diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0775823b..c9b2105b 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,12 +1,10 @@ version: 2 updates: -- package-ecosystem: maven - directory: "/" - schedule: - interval: daily - time: "04:00" - open-pull-requests-limit: 10 - ignore: - - dependency-name: org.apache.maven:maven-compat - versions: - - 3.8.1 + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + - package-ecosystem: "maven" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 18fd939a..ab97ea78 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -15,26 +15,34 @@ name: Java CI -on: [push, pull_request] +on: + pull_request: + push: + branches: + - master jobs: build: runs-on: ubuntu-latest strategy: matrix: - java: [ 8, 11, 17 ] + java: [ '8', '11', '17' ] steps: - - uses: actions/checkout@v2.3.4 - - uses: actions/cache@v2.1.4 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven- - - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v2 - with: - distribution: adopt - java-version: ${{ matrix.java }} - - name: Build with Maven on Java ${{ matrix.java }} - run: mvn -V test -Ddoclint=all --file pom.xml --no-transfer-progress + - uses: actions/checkout@v2.3.4 + - uses: actions/cache@v2.1.4 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v2 + with: + distribution: adopt + java-version: ${{ matrix.java }} + - name: Build with Maven on Java ${{ matrix.java }} + if: matrix.java != '11' + run: mvn -V test -Ddoclint=all --file pom.xml --no-transfer-progress + - name: Code coverage + if: matrix.java == '11' + run: mvn -V test -Ddoclint=all -Pcoverage --file pom.xml --no-transfer-progress diff --git a/docs/DeveloperGuide.md b/docs/DeveloperGuide.md index ccc0f283..2e9a0829 100644 --- a/docs/DeveloperGuide.md +++ b/docs/DeveloperGuide.md @@ -47,15 +47,14 @@ import ognl.Ognl; import ognl.OgnlContext; public class OgnlExpression { - + private Object expression; public OgnlExpression(String expressionString) throws OgnlException { expression = Ognl.parseExpression(expressionString); } - public Object getExpression() - { + public Object getExpression() { return expression; } diff --git a/pom.xml b/pom.xml index eaf4e5c1..2329682d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 @@ -10,7 +11,7 @@ ognl ognl jar - 3.3.4-SNAPSHOT + 3.4.0-SNAPSHOT OGNL - Object Graph Navigation Library OGNL - Object Graph Navigation Library @@ -32,14 +33,9 @@ scm:git:git@github.com:jkuhnert/ognl.git - - OpenSymphony - http://www.opensymphony.com - - - jira - http://jira.opensymphony.com/browse/OGNL + Github Issues + https://github.com/jkuhnert/ognl/issues @@ -99,7 +95,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.2 + 2.22.2 **/*Test.java @@ -151,6 +147,9 @@ true 1.8 + + **/target/generated-sources/**/*.java + https://docs.oracle.com/javase/8/docs/api/ @@ -166,7 +165,32 @@ org.apache.maven.plugins maven-clean-plugin - 3.2.0 + 3.2.0 + + + org.codehaus.mojo + javacc-maven-plugin + 2.6 + + + ognl-jjtree + generate-sources + + ${project.build.directory}/generated-sources/java + ognl + + + + + + javacc + + + @@ -175,39 +199,6 @@ - - javacc-generate - - - - org.apache.maven.plugins - maven-antrun-plugin - - - generate - generate-sources - - run - - - - - - - - - - - - - - - - - - - - jdk17 @@ -232,6 +223,37 @@ + + coverage + + + + org.jacoco + jacoco-maven-plugin + 0.8.7 + + + prepare-agent + + prepare-agent + + + + report + + report + + + + XML + + + + + + + + diff --git a/src/main/java/ognl/ASTAdd.java b/src/main/java/ognl/ASTAdd.java index 3356f263..c599b8cd 100644 --- a/src/main/java/ognl/ASTAdd.java +++ b/src/main/java/ognl/ASTAdd.java @@ -1,33 +1,21 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; @@ -35,45 +23,36 @@ import java.math.BigDecimal; import java.math.BigInteger; +public class ASTAdd extends NumericExpression { -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTAdd extends NumericExpression -{ - public ASTAdd(int id) - { + private static final long serialVersionUID = -7027437312703768232L; + + public ASTAdd(int id) { super(id); } - public ASTAdd(OgnlParser p, int id) - { + public ASTAdd(OgnlParser p, int id) { super(p, id); } - public void jjtClose() - { + public void jjtClose() { flattenTree(); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object result = _children[0].getValue( context, source ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object result = children[0].getValue(context, source); - for ( int i=1; i < _children.length; ++i ) - result = OgnlOps.add( result, _children[i].getValue(context, source) ); + for (int i = 1; i < children.length; ++i) + result = OgnlOps.add(result, children[i].getValue(context, source)); return result; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "+"; } - boolean isWider(NodeType type, NodeType lastType) - { + boolean isWider(NodeType type, NodeType lastType) { if (lastType == null) return true; @@ -85,65 +64,61 @@ boolean isWider(NodeType type, NodeType lastType) if (String.class.isAssignableFrom(type.getGetterClass())) return true; - if (_parent != null && String.class.isAssignableFrom(type.getGetterClass())) + if (parent != null && String.class.isAssignableFrom(type.getGetterClass())) return true; if (String.class.isAssignableFrom(lastType.getGetterClass()) && Object.class == type.getGetterClass()) return false; - if (_parent != null && String.class.isAssignableFrom(lastType.getGetterClass())) + if (parent != null && String.class.isAssignableFrom(lastType.getGetterClass())) return false; - else if (_parent == null && String.class.isAssignableFrom(lastType.getGetterClass())) + else if (parent == null && String.class.isAssignableFrom(lastType.getGetterClass())) return true; - else if (_parent == null && String.class.isAssignableFrom(type.getGetterClass())) + else if (parent == null && String.class.isAssignableFrom(type.getGetterClass())) return false; if (BigDecimal.class.isAssignableFrom(type.getGetterClass()) - || BigInteger.class.isAssignableFrom(type.getGetterClass())) + || BigInteger.class.isAssignableFrom(type.getGetterClass())) return true; if (BigDecimal.class.isAssignableFrom(lastType.getGetterClass()) - || BigInteger.class.isAssignableFrom(lastType.getGetterClass())) + || BigInteger.class.isAssignableFrom(lastType.getGetterClass())) return false; if (Double.class.isAssignableFrom(type.getGetterClass())) return true; if (Integer.class.isAssignableFrom(type.getGetterClass()) - && Double.class.isAssignableFrom(lastType.getGetterClass())) + && Double.class.isAssignableFrom(lastType.getGetterClass())) return false; if (Float.class.isAssignableFrom(type.getGetterClass()) - && Integer.class.isAssignableFrom(lastType.getGetterClass())) + && Integer.class.isAssignableFrom(lastType.getGetterClass())) return true; return true; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { try { - String result = ""; + StringBuilder result = new StringBuilder(); NodeType lastType = null; // go through once to determine the ultimate type - if ((_children != null) && (_children.length > 0)) - { - Class currType = context.getCurrentType(); - Class currAccessor = context.getCurrentAccessor(); + if ((children != null) && (children.length > 0)) { + Class currType = context.getCurrentType(); + Class currAccessor = context.getCurrentAccessor(); Object cast = context.get(ExpressionCompiler.PRE_CAST); - for ( int i = 0; i < _children.length; ++i ) - { - _children[i].toGetSourceString(context, target); + for (Node child : children) { + child.toGetSourceString(context, target); - if (NodeType.class.isInstance(_children[i]) - && ((NodeType)_children[i]).getGetterClass() != null - && isWider((NodeType)_children[i], lastType)) - { - lastType = (NodeType)_children[i]; + if (child instanceof NodeType + && ((NodeType) child).getGetterClass() != null + && isWider((NodeType) child, lastType)) { + lastType = (NodeType) child; } } @@ -157,61 +132,53 @@ && isWider((NodeType)_children[i], lastType)) context.setCurrentObject(target); - if ((_children != null) && (_children.length > 0)) - { + if ((children != null) && (children.length > 0)) { - for ( int i = 0; i < _children.length; ++i ) - { + for (int i = 0; i < children.length; ++i) { if (i > 0) - result += " " + getExpressionOperator(i) + " "; + result.append(" ").append(getExpressionOperator(i)).append(" "); - String expr = _children[i].toGetSourceString(context, target); + String expr = children[i].toGetSourceString(context, target); - if ((expr != null && "null".equals(expr)) - || (!ASTConst.class.isInstance(_children[i]) - && (expr == null || expr.trim().length() <= 0))) - { + if (("null".equals(expr)) + || (!(children[i] instanceof ASTConst) + && (expr == null || expr.trim().length() <= 0))) { expr = "null"; } //System.out.println("astadd child class: " + _children[i].getClass().getName() + " and return expr: " + expr); - if (ASTProperty.class.isInstance(_children[i])) - { - expr = ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context) + expr; + if (children[i] instanceof ASTProperty) { + expr = ExpressionCompiler.getRootExpression(children[i], context.getRoot(), context) + expr; context.setCurrentAccessor(context.getRoot().getClass()); - } else if (ASTMethod.class.isInstance(_children[i])) - { - String chain = (String)context.get("_currentChain"); - String rootExpr = ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context); + } else if (children[i] instanceof ASTMethod) { + String chain = (String) context.get("_currentChain"); + String rootExpr = ExpressionCompiler.getRootExpression(children[i], context.getRoot(), context); //System.out.println("astadd chains is >>" + chain + "<< and rootExpr is >>" + rootExpr + "<<"); // dirty fix for overly aggressive casting dot operations - if (rootExpr.endsWith(".") && chain != null && chain.startsWith(").")) - { - chain = chain.substring(1, chain.length()); + if (rootExpr.endsWith(".") && chain != null && chain.startsWith(").")) { + chain = chain.substring(1); } expr = rootExpr + (chain != null ? chain + "." : "") + expr; context.setCurrentAccessor(context.getRoot().getClass()); - } else if (ExpressionNode.class.isInstance(_children[i])) - { + } else if (children[i] instanceof ExpressionNode) { expr = "(" + expr + ")"; - } else if ((_parent == null || !ASTChain.class.isInstance(_parent)) - && ASTChain.class.isInstance(_children[i])) - { - String rootExpr = ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context); + } else if ((!(parent instanceof ASTChain)) + && children[i] instanceof ASTChain) { + String rootExpr = ExpressionCompiler.getRootExpression(children[i], context.getRoot(), context); - if (!ASTProperty.class.isInstance(_children[i].jjtGetChild(0)) - && rootExpr.endsWith(")") && expr.startsWith(")")) - expr = expr.substring(1, expr.length()); + if (!(children[i].jjtGetChild(0) instanceof ASTProperty) + && rootExpr.endsWith(")") && expr.startsWith(")")) + expr = expr.substring(1); expr = rootExpr + expr; context.setCurrentAccessor(context.getRoot().getClass()); - String cast = (String)context.remove(ExpressionCompiler.PRE_CAST); + String cast = (String) context.remove(ExpressionCompiler.PRE_CAST); if (cast == null) cast = ""; @@ -221,27 +188,24 @@ && isWider((NodeType)_children[i], lastType)) // turn quoted characters into quoted strings if (context.getCurrentType() != null && context.getCurrentType() == Character.class - && ASTConst.class.isInstance(_children[i])) - { + && children[i] instanceof ASTConst) { if (expr.indexOf('\'') >= 0) expr = expr.replaceAll("'", "\""); context.setCurrentType(String.class); } else { - if (!ASTVarRef.class.isAssignableFrom(_children[i].getClass()) - && !ASTProperty.class.isInstance(_children[i]) - && !ASTMethod.class.isInstance(_children[i]) - && !ASTSequence.class.isInstance(_children[i]) - && !ASTChain.class.isInstance(_children[i]) - && !NumericExpression.class.isAssignableFrom(_children[i].getClass()) - && !ASTStaticField.class.isInstance(_children[i]) - && !ASTStaticMethod.class.isInstance(_children[i]) - && !ASTTest.class.isInstance(_children[i])) - { - if (lastType != null && String.class.isAssignableFrom(lastType.getGetterClass())) - { + if (!ASTVarRef.class.isAssignableFrom(children[i].getClass()) + && !(children[i] instanceof ASTProperty) + && !(children[i] instanceof ASTMethod) + && !(children[i] instanceof ASTSequence) + && !(children[i] instanceof ASTChain) + && !NumericExpression.class.isAssignableFrom(children[i].getClass()) + && !(children[i] instanceof ASTStaticField) + && !(children[i] instanceof ASTStaticMethod) + && !(children[i] instanceof ASTTest)) { + if (lastType != null && String.class.isAssignableFrom(lastType.getGetterClass())) { //System.out.println("Input expr >>" + expr + "<<"); - if (expr.indexOf(""") >= 0) + if (expr.contains(""")) expr = expr.replaceAll(""", "\""); if (expr.indexOf('"') >= 0) expr = expr.replaceAll("\"", "'"); @@ -251,23 +215,21 @@ && isWider((NodeType)_children[i], lastType)) } } - result += expr; + result.append(expr); // hanlde addition for numeric types when applicable or just string concatenation - if ( (lastType == null || !String.class.isAssignableFrom(lastType.getGetterClass())) - && !ASTConst.class.isAssignableFrom(_children[i].getClass()) - && !NumericExpression.class.isAssignableFrom(_children[i].getClass())) - { + if ((lastType == null || !String.class.isAssignableFrom(lastType.getGetterClass())) + && !ASTConst.class.isAssignableFrom(children[i].getClass()) + && !NumericExpression.class.isAssignableFrom(children[i].getClass())) { if (context.getCurrentType() != null && Number.class.isAssignableFrom(context.getCurrentType()) - && !ASTMethod.class.isInstance(_children[i])) - { - if (ASTVarRef.class.isInstance(_children[i]) - || ASTProperty.class.isInstance(_children[i]) - || ASTChain.class.isInstance(_children[i])) - result += "."; - - result += OgnlRuntime.getNumericValueGetter(context.getCurrentType()); + && !(children[i] instanceof ASTMethod)) { + if (children[i] instanceof ASTVarRef + || children[i] instanceof ASTProperty + || children[i] instanceof ASTChain) + result.append("."); + + result.append(OgnlRuntime.getNumericValueGetter(context.getCurrentType())); context.setCurrentType(OgnlRuntime.getPrimitiveWrapperClass(context.getCurrentType())); } } @@ -277,28 +239,23 @@ && isWider((NodeType)_children[i], lastType)) } } - if (_parent == null || ASTSequence.class.isAssignableFrom(_parent.getClass())) - { - if (_getterClass != null && String.class.isAssignableFrom(_getterClass)) - _getterClass = Object.class; - } else - { - context.setCurrentType(_getterClass); + if (parent == null || ASTSequence.class.isAssignableFrom(parent.getClass())) { + if (getterClass != null && String.class.isAssignableFrom(getterClass)) + getterClass = Object.class; + } else { + context.setCurrentType(getterClass); } - try - { + try { Object contextObj = getValueBody(context, target); context.setCurrentObject(contextObj); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - return result; + return result.toString(); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } diff --git a/src/main/java/ognl/ASTAnd.java b/src/main/java/ognl/ASTAnd.java index 5102b510..cc4a4596 100644 --- a/src/main/java/ognl/ASTAnd.java +++ b/src/main/java/ognl/ASTAnd.java @@ -1,44 +1,30 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; import ognl.enhance.UnsupportedCompilationException; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTAnd extends BooleanExpression -{ +public class ASTAnd extends BooleanExpression { + + private static final long serialVersionUID = 6696870754345362407L; + public ASTAnd(int id) { super(id); } @@ -51,75 +37,67 @@ public void jjtClose() { flattenTree(); } - protected Object getValueBody( OgnlContext context, Object source ) - throws OgnlException - { + protected Object getValueBody(OgnlContext context, Object source) + throws OgnlException { Object result = null; - int last = _children.length - 1; - for ( int i=0; i <= last; ++i ) - { - result = _children[i].getValue( context, source ); + int last = children.length - 1; + for (int i = 0; i <= last; ++i) { + result = children[i].getValue(context, source); - if ( i != last && ! OgnlOps.booleanValue(result) ) + if (i != last && !OgnlOps.booleanValue(result)) break; } - + return result; } - protected void setValueBody( OgnlContext context, Object target, Object value ) - throws OgnlException - { - int last = _children.length - 1; - - for ( int i=0; i < last; ++i ) - { - Object v = _children[i].getValue( context, target ); - - if ( ! OgnlOps.booleanValue(v) ) + protected void setValueBody(OgnlContext context, Object target, Object value) + throws OgnlException { + int last = children.length - 1; + + for (int i = 0; i < last; ++i) { + Object v = children[i].getValue(context, target); + + if (!OgnlOps.booleanValue(v)) return; } - - _children[last].setValue( context, target, value ); + + children[last].setValue(context, target, value); } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "&&"; } - public Class getGetterClass() - { + public Class getGetterClass() { return null; } - public String toGetSourceString(OgnlContext context, Object target) - { - if (_children.length != 2) + public String toGetSourceString(OgnlContext context, Object target) { + if (children.length != 2) throw new UnsupportedCompilationException("Can only compile boolean expressions with two children."); - + String result = ""; - + try { - String first = OgnlRuntime.getChildSource(context, target, _children[0]); - if (!OgnlOps.booleanValue(context.getCurrentObject())) - { + String first = OgnlRuntime.getChildSource(context, target, children[0]); + if (!OgnlOps.booleanValue(context.getCurrentObject())) { throw new UnsupportedCompilationException("And expression can't be compiled until all conditions are true."); } if (!OgnlRuntime.isBoolean(first) && !context.getCurrentType().isPrimitive()) first = OgnlRuntime.getCompiler().createLocalReference(context, first, context.getCurrentType()); - String second = OgnlRuntime.getChildSource(context, target, _children[1]); + String second = OgnlRuntime.getChildSource(context, target, children[1]); if (!OgnlRuntime.isBoolean(second) && !context.getCurrentType().isPrimitive()) second = OgnlRuntime.getCompiler().createLocalReference(context, second, context.getCurrentType()); result += "(ognl.OgnlOps.booleanValue(" + first + ")"; - + result += " ? "; - result += " ($w) (" + second + ")"; + result += " ($w) (" + second + ")"; result += " : "; result += " ($w) (" + first + ")"; @@ -129,58 +107,54 @@ public String toGetSourceString(OgnlContext context, Object target) context.setCurrentObject(target); context.setCurrentType(Object.class); } catch (NullPointerException e) { - + throw new UnsupportedCompilationException("evaluation resulted in null expression."); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - + return result; } - - public String toSetSourceString(OgnlContext context, Object target) - { - if (_children.length != 2) + + public String toSetSourceString(OgnlContext context, Object target) { + if (children.length != 2) throw new UnsupportedCompilationException("Can only compile boolean expressions with two children."); - - String pre = (String)context.get("_currentChain"); + + String pre = (String) context.get("_currentChain"); if (pre == null) pre = ""; - + String result = ""; - + try { - if (!OgnlOps.booleanValue(_children[0].getValue(context, target))) - { - throw new UnsupportedCompilationException("And expression can't be compiled until all conditions are true."); + if (!OgnlOps.booleanValue(children[0].getValue(context, target))) { + throw new UnsupportedCompilationException("And expression can't be compiled until all conditions are true."); } - - String first = ExpressionCompiler.getRootExpression(_children[0], context.getRoot(), context) - + pre + _children[0].toGetSourceString(context, target); - - _children[1].getValue(context, target); - - String second = ExpressionCompiler.getRootExpression(_children[1], context.getRoot(), context) - + pre + _children[1].toSetSourceString(context, target); + + String first = ExpressionCompiler.getRootExpression(children[0], context.getRoot(), context) + + pre + children[0].toGetSourceString(context, target); + + children[1].getValue(context, target); + + String second = ExpressionCompiler.getRootExpression(children[1], context.getRoot(), context) + + pre + children[1].toSetSourceString(context, target); if (!OgnlRuntime.isBoolean(first)) result += "if(ognl.OgnlOps.booleanValue(" + first + ")){"; else result += "if(" + first + "){"; - + result += second; result += "; } "; - + context.setCurrentObject(target); context.setCurrentType(Object.class); - - } catch (Throwable t) - { + + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - + return result; } } diff --git a/src/main/java/ognl/ASTAssign.java b/src/main/java/ognl/ASTAssign.java index d09aa1ae..9c4bc79c 100644 --- a/src/main/java/ognl/ASTAssign.java +++ b/src/main/java/ognl/ASTAssign.java @@ -1,44 +1,30 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.OrderedReturn; import ognl.enhance.UnsupportedCompilationException; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTAssign extends SimpleNode -{ +public class ASTAssign extends SimpleNode { + + private static final long serialVersionUID = -2036484456563256284L; + public ASTAssign(int id) { super(id); } @@ -47,33 +33,30 @@ public ASTAssign(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object result = _children[1].getValue( context, source ); - _children[0].setValue( context, source, result ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object result = children[1].getValue(context, source); + children[0].setValue(context, source, result); return result; } - public String toString() - { - return _children[0] + " = " + _children[1]; + public String toString() { + return children[0] + " = " + children[1]; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { String result = ""; - String first = _children[0].toGetSourceString(context, target); + String first = children[0].toGetSourceString(context, target); String second = ""; - if (ASTProperty.class.isInstance(_children[1])) { + if (children[1] instanceof ASTProperty) { second += "((" + OgnlRuntime.getCompiler().getClassName(target.getClass()) + ")$2)."; } - second += _children[1].toGetSourceString(context, target); + second += children[1].toGetSourceString(context, target); - if (ASTSequence.class.isAssignableFrom(_children[1].getClass())) { - ASTSequence seq = (ASTSequence)_children[1]; + if (ASTSequence.class.isAssignableFrom(children[1].getClass())) { + ASTSequence seq = (ASTSequence) children[1]; context.setCurrentType(Object.class); @@ -82,19 +65,19 @@ public String toGetSourceString(OgnlContext context, Object target) core = core.substring(0, core.lastIndexOf(";")); second = OgnlRuntime.getCompiler().createLocalReference(context, - "ognl.OgnlOps.returnValue(($w)" + core + ", ($w) " + seq.getLastExpression() + ")", + "ognl.OgnlOps.returnValue(($w)" + core + ", ($w) " + seq.getLastExpression() + ")", Object.class); } - if (NodeType.class.isInstance(_children[1]) - && !ASTProperty.class.isInstance(_children[1]) - && ((NodeType)_children[1]).getGetterClass() != null && !OrderedReturn.class.isInstance(_children[1])) { + if (children[1] instanceof NodeType + && !(children[1] instanceof ASTProperty) + && ((NodeType) children[1]).getGetterClass() != null && !(children[1] instanceof OrderedReturn)) { - second = "new " + ((NodeType)_children[1]).getGetterClass().getName() + "(" + second + ")"; + second = "new " + ((NodeType) children[1]).getGetterClass().getName() + "(" + second + ")"; } - if (OrderedReturn.class.isAssignableFrom(_children[0].getClass()) - && ((OrderedReturn)_children[0]).getCoreExpression() != null) { + if (OrderedReturn.class.isAssignableFrom(children[0].getClass()) + && ((OrderedReturn) children[0]).getCoreExpression() != null) { context.setCurrentType(Object.class); result = first + second + ")"; @@ -102,39 +85,38 @@ public String toGetSourceString(OgnlContext context, Object target) // System.out.println("building ordered ret from child[0] with result of:" + result); result = OgnlRuntime.getCompiler().createLocalReference(context, - "ognl.OgnlOps.returnValue(($w)" + result + ", ($w)" + ((OrderedReturn)_children[0]).getLastExpression() + ")", + "ognl.OgnlOps.returnValue(($w)" + result + ", ($w)" + ((OrderedReturn) children[0]).getLastExpression() + ")", Object.class); } return result; } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { String result = ""; - result += _children[0].toSetSourceString(context, target); + result += children[0].toSetSourceString(context, target); - if (ASTProperty.class.isInstance(_children[1])) { + if (children[1] instanceof ASTProperty) { result += "((" + OgnlRuntime.getCompiler().getClassName(target.getClass()) + ")$2)."; } - String value =_children[1].toSetSourceString(context, target); + String value = children[1].toSetSourceString(context, target); if (value == null) throw new UnsupportedCompilationException("Value for assignment is null, can't enhance statement to bytecode."); - if (ASTSequence.class.isAssignableFrom(_children[1].getClass())) { - ASTSequence seq = (ASTSequence)_children[1]; + if (ASTSequence.class.isAssignableFrom(children[1].getClass())) { + ASTSequence seq = (ASTSequence) children[1]; result = seq.getCoreExpression() + result; value = seq.getLastExpression(); } - if (NodeType.class.isInstance(_children[1]) - && !ASTProperty.class.isInstance(_children[1]) - && ((NodeType)_children[1]).getGetterClass() != null) { + if (children[1] instanceof NodeType + && !(children[1] instanceof ASTProperty) + && ((NodeType) children[1]).getGetterClass() != null) { - value = "new " + ((NodeType)_children[1]).getGetterClass().getName() + "(" + value + ")"; + value = "new " + ((NodeType) children[1]).getGetterClass().getName() + "(" + value + ")"; } return result + value + ")"; diff --git a/src/main/java/ognl/ASTBitAnd.java b/src/main/java/ognl/ASTBitAnd.java index cd2f7bb0..13662503 100644 --- a/src/main/java/ognl/ASTBitAnd.java +++ b/src/main/java/ognl/ASTBitAnd.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTBitAnd extends NumericExpression -{ +public class ASTBitAnd extends NumericExpression { + + private static final long serialVersionUID = -1168821577717290445L; + public ASTBitAnd(int id) { super(id); } @@ -48,21 +34,18 @@ public void jjtClose() { flattenTree(); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object result = _children[0].getValue( context, source ); - for ( int i=1; i < _children.length; ++i ) - result = OgnlOps.binaryAnd( result, _children[i].getValue(context, source) ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object result = children[0].getValue(context, source); + for (int i = 1; i < children.length; ++i) + result = OgnlOps.binaryAnd(result, children[i].getValue(context, source)); return result; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "&"; } - public String coerceToNumeric(String source, OgnlContext context, Node child) - { + public String coerceToNumeric(String source, OgnlContext context, Node child) { return "(long)" + super.coerceToNumeric(source, context, child); } } diff --git a/src/main/java/ognl/ASTBitNegate.java b/src/main/java/ognl/ASTBitNegate.java index 71fc2f19..52234785 100644 --- a/src/main/java/ognl/ASTBitNegate.java +++ b/src/main/java/ognl/ASTBitNegate.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTBitNegate extends NumericExpression -{ +public class ASTBitNegate extends NumericExpression { + + private static final long serialVersionUID = 1889283641910348148L; + public ASTBitNegate(int id) { super(id); } @@ -44,25 +30,20 @@ public ASTBitNegate(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - return OgnlOps.bitNegate( _children[0].getValue(context, source) ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + return OgnlOps.bitNegate(children[0].getValue(context, source)); } - public String toString() - { - return "~" + _children[0]; + public String toString() { + return "~" + children[0]; } - public String toGetSourceString(OgnlContext context, Object target) - { - String source = _children[0].toGetSourceString(context, target); + public String toGetSourceString(OgnlContext context, Object target) { + String source = children[0].toGetSourceString(context, target); - if (!ASTBitNegate.class.isInstance(_children[0])) - { - return "~(" + super.coerceToNumeric(source, context, _children[0]) + ")"; - } else - { + if (!(children[0] instanceof ASTBitNegate)) { + return "~(" + super.coerceToNumeric(source, context, children[0]) + ")"; + } else { return "~(" + source + ")"; } } diff --git a/src/main/java/ognl/ASTBitOr.java b/src/main/java/ognl/ASTBitOr.java index 453a06b7..877ac801 100644 --- a/src/main/java/ognl/ASTBitOr.java +++ b/src/main/java/ognl/ASTBitOr.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTBitOr extends NumericExpression -{ +public class ASTBitOr extends NumericExpression { + + private static final long serialVersionUID = -7692570501162791771L; + public ASTBitOr(int id) { super(id); } @@ -48,16 +34,14 @@ public void jjtClose() { flattenTree(); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object result = _children[0].getValue( context, source ); - for ( int i=1; i < _children.length; ++i ) - result = OgnlOps.binaryOr( result, _children[i].getValue(context, source) ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object result = children[0].getValue(context, source); + for (int i = 1; i < children.length; ++i) + result = OgnlOps.binaryOr(result, children[i].getValue(context, source)); return result; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "|"; } } diff --git a/src/main/java/ognl/ASTChain.java b/src/main/java/ognl/ASTChain.java index c15a5141..b7743b88 100644 --- a/src/main/java/ognl/ASTChain.java +++ b/src/main/java/ognl/ASTChain.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; @@ -36,61 +24,49 @@ import java.lang.reflect.Array; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTChain extends SimpleNode implements NodeType, OrderedReturn -{ - - private Class _getterClass; - private Class _setterClass; +public class ASTChain extends SimpleNode implements NodeType, OrderedReturn { - private String _lastExpression; + private static final long serialVersionUID = 6689037266594707682L; - private String _coreExpression; + private Class getterClass; + private Class setterClass; + private String lastExpression; + private String coreExpression; - public ASTChain(int id) - { + public ASTChain(int id) { super(id); } - public ASTChain(OgnlParser p, int id) - { + public ASTChain(OgnlParser p, int id) { super(p, id); } - public String getLastExpression() - { - return _lastExpression; + public String getLastExpression() { + return lastExpression; } - public String getCoreExpression() - { - return _coreExpression; + public String getCoreExpression() { + return coreExpression; } - public void jjtClose() - { + public void jjtClose() { flattenTree(); } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { + throws OgnlException { Object result = source; - for(int i = 0, ilast = _children.length - 1; i <= ilast; ++i) - { + for (int i = 0, ilast = children.length - 1; i <= ilast; ++i) { boolean handled = false; if (i < ilast) { - if (_children[i] instanceof ASTProperty) { - ASTProperty propertyNode = (ASTProperty) _children[i]; + if (children[i] instanceof ASTProperty) { + ASTProperty propertyNode = (ASTProperty) children[i]; int indexType = propertyNode.getIndexedPropertyType(context, result); - if ((indexType != OgnlRuntime.INDEXED_PROPERTY_NONE) && (_children[i + 1] instanceof ASTProperty)) { - ASTProperty indexNode = (ASTProperty) _children[i + 1]; + if ((indexType != OgnlRuntime.INDEXED_PROPERTY_NONE) && (children[i + 1] instanceof ASTProperty)) { + ASTProperty indexNode = (ASTProperty) children[i + 1]; if (indexNode.isIndexedAccess()) { Object index = indexNode.getProperty(context, result); @@ -100,7 +76,7 @@ protected Object getValueBody(OgnlContext context, Object source) Object array = propertyNode.getValue(context, result); int len = Array.getLength(array); - switch(((DynamicSubscript) index).getFlag()) { + switch (((DynamicSubscript) index).getFlag()) { case DynamicSubscript.ALL: result = Array.newInstance(array.getClass().getComponentType(), len); System.arraycopy(array, 0, result, 0, len); @@ -108,27 +84,28 @@ protected Object getValueBody(OgnlContext context, Object source) i++; break; case DynamicSubscript.FIRST: - index = new Integer((len > 0) ? 0 : -1); + index = (len > 0) ? 0 : -1; break; case DynamicSubscript.MID: - index = new Integer((len > 0) ? (len / 2) : -1); + index = (len > 0) ? (len / 2) : -1; break; case DynamicSubscript.LAST: - index = new Integer((len > 0) ? (len - 1) : -1); + index = (len > 0) ? (len - 1) : -1; break; } } else { - if (indexType == OgnlRuntime.INDEXED_PROPERTY_OBJECT) { throw new OgnlException( - "DynamicSubscript '" + indexNode - + "' not allowed for object indexed property '" + propertyNode - + "'"); } + if (indexType == OgnlRuntime.INDEXED_PROPERTY_OBJECT) { + throw new OgnlException( + "DynamicSubscript '" + indexNode + + "' not allowed for object indexed property '" + propertyNode + + "'"); + } } } - if (!handled) - { + if (!handled) { result = OgnlRuntime.getIndexedProperty(context, result, - propertyNode.getProperty(context, result).toString(), - index); + propertyNode.getProperty(context, result).toString(), + index); handled = true; i++; } @@ -136,108 +113,91 @@ protected Object getValueBody(OgnlContext context, Object source) } } } - if (!handled) - { - result = _children[i].getValue(context, result); + if (!handled) { + result = children[i].getValue(context, result); } } return result; } protected void setValueBody(OgnlContext context, Object target, Object value) - throws OgnlException - { + throws OgnlException { boolean handled = false; - for(int i = 0, ilast = _children.length - 2; i <= ilast; ++i) - { - if (i <= ilast) { - if (_children[i] instanceof ASTProperty) - { - ASTProperty propertyNode = (ASTProperty) _children[i]; - int indexType = propertyNode.getIndexedPropertyType(context, target); - - if ((indexType != OgnlRuntime.INDEXED_PROPERTY_NONE) && (_children[i + 1] instanceof ASTProperty)) - { - ASTProperty indexNode = (ASTProperty) _children[i + 1]; - - if (indexNode.isIndexedAccess()) - { - Object index = indexNode.getProperty(context, target); - - if (index instanceof DynamicSubscript) - { - if (indexType == OgnlRuntime.INDEXED_PROPERTY_INT) - { - Object array = propertyNode.getValue(context, target); - int len = Array.getLength(array); - - switch(((DynamicSubscript) index).getFlag()) - { - case DynamicSubscript.ALL: - System.arraycopy(target, 0, value, 0, len); - handled = true; - i++; - break; - case DynamicSubscript.FIRST: - index = new Integer((len > 0) ? 0 : -1); - break; - case DynamicSubscript.MID: - index = new Integer((len > 0) ? (len / 2) : -1); - break; - case DynamicSubscript.LAST: - index = new Integer((len > 0) ? (len - 1) : -1); - break; - } - } else - { - if (indexType == OgnlRuntime.INDEXED_PROPERTY_OBJECT) - { - throw new OgnlException("DynamicSubscript '" + indexNode - + "' not allowed for object indexed property '" + propertyNode - + "'"); - } + for (int i = 0, ilast = children.length - 2; i <= ilast; ++i) { + if (children[i] instanceof ASTProperty) { + ASTProperty propertyNode = (ASTProperty) children[i]; + int indexType = propertyNode.getIndexedPropertyType(context, target); + + if ((indexType != OgnlRuntime.INDEXED_PROPERTY_NONE) && (children[i + 1] instanceof ASTProperty)) { + ASTProperty indexNode = (ASTProperty) children[i + 1]; + + if (indexNode.isIndexedAccess()) { + Object index = indexNode.getProperty(context, target); + + if (index instanceof DynamicSubscript) { + if (indexType == OgnlRuntime.INDEXED_PROPERTY_INT) { + Object array = propertyNode.getValue(context, target); + int len = Array.getLength(array); + + switch (((DynamicSubscript) index).getFlag()) { + case DynamicSubscript.ALL: + System.arraycopy(target, 0, value, 0, len); + handled = true; + i++; + break; + case DynamicSubscript.FIRST: + index = (len > 0) ? 0 : -1; + break; + case DynamicSubscript.MID: + index = (len > 0) ? (len / 2) : -1; + break; + case DynamicSubscript.LAST: + index = (len > 0) ? (len - 1) : -1; + break; + } + } else { + if (indexType == OgnlRuntime.INDEXED_PROPERTY_OBJECT) { + throw new OgnlException("DynamicSubscript '" + indexNode + + "' not allowed for object indexed property '" + propertyNode + + "'"); } } - if (!handled && i == ilast) - { - OgnlRuntime.setIndexedProperty(context, target, - propertyNode.getProperty(context, target).toString(), - index, value); - handled = true; - i++; - } else if (!handled) { - target = OgnlRuntime.getIndexedProperty(context, target, - propertyNode.getProperty(context, target).toString(), - index); - i++; - continue; - } + } + if (!handled && i == ilast) { + OgnlRuntime.setIndexedProperty(context, target, + propertyNode.getProperty(context, target).toString(), + index, value); + handled = true; + i++; + } else if (!handled) { + target = OgnlRuntime.getIndexedProperty(context, target, + propertyNode.getProperty(context, target).toString(), + index); + i++; + continue; } } } } - if (!handled) - { - target = _children[i].getValue(context, target); + if (!handled) { + target = children[i].getValue(context, target); } } - if (!handled) - { - _children[_children.length - 1].setValue(context, target, value); + if (!handled) { + children[children.length - 1].setValue(context, target, value); } } public boolean isSimpleNavigationChain(OgnlContext context) - throws OgnlException - { + throws OgnlException { boolean result = false; - if ((_children != null) && (_children.length > 0)) { + if ((children != null) && (children.length > 0)) { result = true; - for(int i = 0; result && (i < _children.length); i++) { - if (_children[i] instanceof SimpleNode) { - result = ((SimpleNode) _children[i]).isSimpleProperty(context); + for (int i = 0; result && (i < children.length); i++) { + if (children[i] instanceof SimpleNode) { + result = ((SimpleNode) children[i]).isSimpleProperty(context); } else { result = false; } @@ -246,39 +206,34 @@ public boolean isSimpleNavigationChain(OgnlContext context) return result; } - public Class getGetterClass() - { - return _getterClass; + public Class getGetterClass() { + return getterClass; } - public Class getSetterClass() - { - return _setterClass; + public Class getSetterClass() { + return setterClass; } - public String toString() - { - String result = ""; + public String toString() { + StringBuilder result = new StringBuilder(); - if ((_children != null) && (_children.length > 0)) { - for(int i = 0; i < _children.length; i++) { + if ((children != null) && (children.length > 0)) { + for (int i = 0; i < children.length; i++) { if (i > 0) { - if (!(_children[i] instanceof ASTProperty) || !((ASTProperty) _children[i]).isIndexedAccess()) { - result = result + "."; + if (!(children[i] instanceof ASTProperty) || !((ASTProperty) children[i]).isIndexedAccess()) { + result.append("."); } } - result += _children[i].toString(); + result.append(children[i].toString()); } } - return result; + return result.toString(); } - public String toGetSourceString(OgnlContext context, Object target) - { - String prevChain = (String)context.get("_currentChain"); + public String toGetSourceString(OgnlContext context, Object target) { + String prevChain = (String) context.get("_currentChain"); - if (target != null) - { + if (target != null) { context.setCurrentObject(target); context.setCurrentType(target.getClass()); } @@ -288,84 +243,62 @@ public String toGetSourceString(OgnlContext context, Object target) boolean ordered = false; boolean constructor = false; try { - if ((_children != null) && (_children.length > 0)) - { - for(int i = 0; i < _children.length; i++) - { - /* System.out.println("astchain child: " + _children[i].getClass().getName() - + " with current object target " + context.getCurrentObject() - + " current type: " + context.getCurrentType());*/ + if ((children != null) && (children.length > 0)) { + for (Node child : children) { + String value = child.toGetSourceString(context, context.getCurrentObject()); - String value = _children[i].toGetSourceString(context, context.getCurrentObject()); - -// System.out.println("astchain child returned >> " + value + " <<"); - - if (ASTCtor.class.isInstance(_children[i])) + if (child instanceof ASTCtor) constructor = true; - if (NodeType.class.isInstance(_children[i]) - && ((NodeType)_children[i]).getGetterClass() != null) - { - _lastType = (NodeType)_children[i]; + if (child instanceof NodeType + && ((NodeType) child).getGetterClass() != null) { + _lastType = (NodeType) child; } -// System.out.println("Astchain i: " + i + " currentobj : " + context.getCurrentObject() + " and root: " + context.getRoot()); - if (!ASTVarRef.class.isInstance(_children[i]) && !constructor - && !(OrderedReturn.class.isInstance(_children[i]) && ((OrderedReturn)_children[i]).getLastExpression() != null) - && (_parent == null || !ASTSequence.class.isInstance(_parent))) - { - value = OgnlRuntime.getCompiler().castExpression(context, _children[i], value); + if (!(child instanceof ASTVarRef) && !constructor + && !(child instanceof OrderedReturn && ((OrderedReturn) child).getLastExpression() != null) + && (!(parent instanceof ASTSequence))) { + value = OgnlRuntime.getCompiler().castExpression(context, child, value); } - /*System.out.println("astchain value now : " + value + " with index " + i - + " current type " + context.getCurrentType() + " current accessor " + context.getCurrentAccessor() - + " prev type " + context.getPreviousType() + " prev accessor " + context.getPreviousAccessor());*/ - - if (OrderedReturn.class.isInstance(_children[i]) && ((OrderedReturn)_children[i]).getLastExpression() != null) - { + if (child instanceof OrderedReturn && ((OrderedReturn) child).getLastExpression() != null) { ordered = true; - OrderedReturn or = (OrderedReturn)_children[i]; + OrderedReturn or = (OrderedReturn) child; if (or.getCoreExpression() == null || or.getCoreExpression().trim().length() <= 0) result = ""; else result += or.getCoreExpression(); - _lastExpression = or.getLastExpression(); + lastExpression = or.getLastExpression(); - if (context.get(ExpressionCompiler.PRE_CAST) != null) - { - _lastExpression = context.remove(ExpressionCompiler.PRE_CAST) + _lastExpression; + if (context.get(ExpressionCompiler.PRE_CAST) != null) { + lastExpression = context.remove(ExpressionCompiler.PRE_CAST) + lastExpression; } - } else if (ASTOr.class.isInstance(_children[i]) - || ASTAnd.class.isInstance(_children[i]) - || ASTCtor.class.isInstance(_children[i]) - || (ASTStaticField.class.isInstance(_children[i]) && _parent == null)) - { + } else if (child instanceof ASTOr + || child instanceof ASTAnd + || child instanceof ASTCtor + || (child instanceof ASTStaticField && parent == null)) { context.put("_noRoot", "true"); result = value; - } else - { + } else { result += value; } context.put("_currentChain", result); } } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - if (_lastType != null) - { - _getterClass = _lastType.getGetterClass(); - _setterClass = _lastType.getSetterClass(); + if (_lastType != null) { + getterClass = _lastType.getGetterClass(); + setterClass = _lastType.getSetterClass(); } - if (ordered) - { - _coreExpression = result; + if (ordered) { + coreExpression = result; } context.put("_currentChain", prevChain); @@ -373,16 +306,14 @@ public String toGetSourceString(OgnlContext context, Object target) return result; } - public String toSetSourceString(OgnlContext context, Object target) - { - String prevChain = (String)context.get("_currentChain"); - String prevChild = (String)context.get("_lastChild"); + public String toSetSourceString(OgnlContext context, Object target) { + String prevChain = (String) context.get("_currentChain"); + String prevChild = (String) context.get("_lastChild"); if (prevChain != null) throw new UnsupportedCompilationException("Can't compile nested chain expressions."); - if (target != null) - { + if (target != null) { context.setCurrentObject(target); context.setCurrentType(target.getClass()); } @@ -391,56 +322,36 @@ public String toSetSourceString(OgnlContext context, Object target) NodeType _lastType = null; boolean constructor = false; try { - if ((_children != null) && (_children.length > 0)) - { - if (ASTConst.class.isInstance(_children[0])) - { + if ((children != null) && (children.length > 0)) { + if (children[0] instanceof ASTConst) { throw new UnsupportedCompilationException("Can't modify constant values."); } - for(int i = 0; i < _children.length; i++) - { -// System.out.println("astchain setsource child[" + i + "] : " + _children[i].getClass().getName()); - - if (i == (_children.length -1)) - { + for (int i = 0; i < children.length; i++) { + if (i == (children.length - 1)) { context.put("_lastChild", "true"); } - String value = _children[i].toSetSourceString(context, context.getCurrentObject()); - //if (value == null || value.trim().length() <= 0) - // return ""; - -// System.out.println("astchain setter child returned >> " + value + " <<"); + String value = children[i].toSetSourceString(context, context.getCurrentObject()); - if (ASTCtor.class.isInstance(_children[i])) + if (children[i] instanceof ASTCtor) constructor = true; - if (NodeType.class.isInstance(_children[i]) - && ((NodeType)_children[i]).getGetterClass() != null) - { - _lastType = (NodeType)_children[i]; + if (children[i] instanceof NodeType + && ((NodeType) children[i]).getGetterClass() != null) { + _lastType = (NodeType) children[i]; } - if (!ASTVarRef.class.isInstance(_children[i]) && !constructor - && !(OrderedReturn.class.isInstance(_children[i]) && ((OrderedReturn)_children[i]).getLastExpression() != null) - && (_parent == null || !ASTSequence.class.isInstance(_parent))) - { - value = OgnlRuntime.getCompiler().castExpression(context, _children[i], value); + if (!(children[i] instanceof ASTVarRef) && !constructor + && !(children[i] instanceof OrderedReturn && ((OrderedReturn) children[i]).getLastExpression() != null) + && (!(parent instanceof ASTSequence))) { + value = OgnlRuntime.getCompiler().castExpression(context, children[i], value); } -// System.out.println("astchain setter after cast value is: " + value); - - /*if (!constructor && !OrderedReturn.class.isInstance(_children[i]) - && (_parent == null || !ASTSequence.class.isInstance(_parent))) - { - value = OgnlRuntime.getCompiler().castExpression(context, _children[i], value); - }*/ - - if (ASTOr.class.isInstance(_children[i]) - || ASTAnd.class.isInstance(_children[i]) - || ASTCtor.class.isInstance(_children[i]) - || ASTStaticField.class.isInstance(_children[i])) { + if (children[i] instanceof ASTOr + || children[i] instanceof ASTAnd + || children[i] instanceof ASTCtor + || children[i] instanceof ASTStaticField) { context.put("_noRoot", "true"); result = value; } else @@ -449,8 +360,7 @@ public String toSetSourceString(OgnlContext context, Object target) context.put("_currentChain", result); } } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } @@ -458,7 +368,7 @@ public String toSetSourceString(OgnlContext context, Object target) context.put("_currentChain", prevChain); if (_lastType != null) - _setterClass = _lastType.getSetterClass(); + setterClass = _lastType.getSetterClass(); return result; } diff --git a/src/main/java/ognl/ASTConst.java b/src/main/java/ognl/ASTConst.java index f81dacfc..2d8f7e73 100644 --- a/src/main/java/ognl/ASTConst.java +++ b/src/main/java/ognl/ASTConst.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; @@ -35,104 +23,78 @@ import java.math.BigDecimal; import java.math.BigInteger; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTConst extends SimpleNode implements NodeType -{ +public class ASTConst extends SimpleNode implements NodeType { - private Object value; + private static final long serialVersionUID = 6025967712275552286L; - private Class _getterClass; + private Object value; + private Class getterClass; - public ASTConst(int id) - { + public ASTConst(int id) { super(id); } - public ASTConst(OgnlParser p, int id) - { + public ASTConst(OgnlParser p, int id) { super(p, id); } - /** + /** * Called from parser actions. * * @param value the Object representing the value. */ - public void setValue(Object value) - { + public void setValue(Object value) { this.value = value; } - public Object getValue() - { + public Object getValue() { return value; } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { + throws OgnlException { return this.value; } - public boolean isNodeConstant(OgnlContext context) - throws OgnlException - { + public boolean isNodeConstant(OgnlContext context) throws OgnlException { return true; } - public Class getGetterClass() - { - if (_getterClass == null) + public Class getGetterClass() { + if (getterClass == null) return null; - return _getterClass; + return getterClass; } - public Class getSetterClass() - { + public Class getSetterClass() { return null; } - public String toString() - { + public String toString() { String result; - if (value == null) - { + if (value == null) { result = "null"; - } else - { - if (value instanceof String) - { + } else { + if (value instanceof String) { result = '\"' + OgnlOps.getEscapeString(value.toString()) + '\"'; } else { - if (value instanceof Character) - { - result = '\'' + OgnlOps.getEscapedChar(((Character) value).charValue()) + '\''; - } else - { + if (value instanceof Character) { + result = '\'' + OgnlOps.getEscapedChar((Character) value) + '\''; + } else { result = value.toString(); - if (value instanceof Long) - { + if (value instanceof Long) { result = result + "L"; - } else - { - if (value instanceof BigDecimal) - { + } else { + if (value instanceof BigDecimal) { result = result + "B"; - } else - { - if (value instanceof BigInteger) - { + } else { + if (value instanceof BigInteger) { result = result + "H"; - } else - { - if (value instanceof Node) - { + } else { + if (value instanceof Node) { result = ":[ " + result + " ]"; } } @@ -144,36 +106,28 @@ public String toString() return result; } - public String toGetSourceString(OgnlContext context, Object target) - { - if (value == null && _parent != null && ExpressionNode.class.isInstance(_parent)) - { + public String toGetSourceString(OgnlContext context, Object target) { + if (value == null && parent instanceof ExpressionNode) { context.setCurrentType(null); return "null"; - } else if (value == null) - { + } else if (value == null) { context.setCurrentType(null); return ""; } - _getterClass = value.getClass(); + getterClass = value.getClass(); - Object retval = value; - if (_parent != null && ASTProperty.class.isInstance(_parent)) - { + Object retval; + if (parent instanceof ASTProperty) { context.setCurrentObject(value); return value.toString(); - } else if (value != null && Number.class.isAssignableFrom(value.getClass())) - { + } else if (Number.class.isAssignableFrom(value.getClass())) { context.setCurrentType(OgnlRuntime.getPrimitiveWrapperClass(value.getClass())); context.setCurrentObject(value); return value.toString(); - } else if (!(_parent != null && value != null - && NumericExpression.class.isAssignableFrom(_parent.getClass())) - && String.class.isAssignableFrom(value.getClass())) - { + } else if (!(parent != null && NumericExpression.class.isAssignableFrom(parent.getClass())) && String.class.isAssignableFrom(value.getClass())) { context.setCurrentType(String.class); retval = '\"' + OgnlOps.getEscapeString(value.toString()) + '\"'; @@ -181,24 +135,22 @@ public String toGetSourceString(OgnlContext context, Object target) context.setCurrentObject(retval.toString()); return retval.toString(); - } else if (Character.class.isInstance(value)) - { - Character val = (Character)value; + } else if (value instanceof Character) { + Character val = (Character) value; context.setCurrentType(Character.class); - if (Character.isLetterOrDigit(val.charValue())) - retval = "'" + ((Character) value).charValue() + "'"; + if (Character.isLetterOrDigit(val)) + retval = "'" + value + "'"; else - retval = "'" + OgnlOps.getEscapedChar(((Character) value).charValue()) + "'"; + retval = "'" + OgnlOps.getEscapedChar((Character) value) + "'"; context.setCurrentObject(retval); return retval.toString(); } - if (Boolean.class.isAssignableFrom(value.getClass())) - { - _getterClass = Boolean.TYPE; + if (Boolean.class.isAssignableFrom(value.getClass())) { + getterClass = Boolean.TYPE; context.setCurrentType(Boolean.TYPE); context.setCurrentObject(value); @@ -209,11 +161,10 @@ public String toGetSourceString(OgnlContext context, Object target) return value.toString(); } - public String toSetSourceString(OgnlContext context, Object target) - { - if (_parent == null) + public String toSetSourceString(OgnlContext context, Object target) { + if (parent == null) throw new UnsupportedCompilationException("Can't modify constant values."); - + return toGetSourceString(context, target); } } diff --git a/src/main/java/ognl/ASTCtor.java b/src/main/java/ognl/ASTCtor.java index 7650c32c..4c88f9fe 100644 --- a/src/main/java/ognl/ASTCtor.java +++ b/src/main/java/ognl/ASTCtor.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; @@ -36,142 +24,128 @@ import java.lang.reflect.Constructor; import java.util.List; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTCtor extends SimpleNode -{ +public class ASTCtor extends SimpleNode { + + private static final long serialVersionUID = -218799350410195779L; private String className; private boolean isArray; - public ASTCtor(int id) - { + public ASTCtor(int id) { super(id); } - public ASTCtor(OgnlParser p, int id) - { + public ASTCtor(OgnlParser p, int id) { super(p, id); } - /** Called from parser action. */ - void setClassName(String className) - { + /** + * Called from parser action. + */ + void setClassName(String className) { this.className = className; } - Class getCreatedClass(OgnlContext context) throws ClassNotFoundException { + Class getCreatedClass(OgnlContext context) throws ClassNotFoundException { return OgnlRuntime.classForName(context, className); } - - void setArray(boolean value) - { + void setArray(boolean value) { isArray = value; } - public boolean isArray() - { + public boolean isArray() { return isArray; } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { + throws OgnlException { Object result, root = context.getRoot(); int count = jjtGetNumChildren(); - Object[] args = OgnlRuntime.getObjectArrayPool().create(count); + Object[] args = new Object[count]; - try { - for(int i = 0; i < count; ++i) { - args[i] = _children[i].getValue(context, root); - } - if (isArray) { - if (args.length == 1) { - try { - Class componentClass = OgnlRuntime.classForName(context, className); - List sourceList = null; - int size; - - if (args[0] instanceof List) { - sourceList = (List) args[0]; - size = sourceList.size(); - } else { - size = (int) OgnlOps.longValue(args[0]); - } - result = Array.newInstance(componentClass, size); - if (sourceList != null) { - TypeConverter converter = context.getTypeConverter(); - - for(int i = 0, icount = sourceList.size(); i < icount; i++) { - Object o = sourceList.get(i); - - if ((o == null) || componentClass.isInstance(o)) { - Array.set(result, i, o); - } else { - Array.set(result, i, converter.convertValue(context, null, null, null, o, - componentClass)); - } + for (int i = 0; i < count; ++i) { + args[i] = children[i].getValue(context, root); + } + if (isArray) { + if (args.length == 1) { + try { + Class componentClass = OgnlRuntime.classForName(context, className); + List sourceList = null; + int size; + + if (args[0] instanceof List) { + sourceList = (List) args[0]; + size = sourceList.size(); + } else { + size = (int) OgnlOps.longValue(args[0]); + } + result = Array.newInstance(componentClass, size); + if (sourceList != null) { + TypeConverter converter = context.getTypeConverter(); + + for (int i = 0, icount = sourceList.size(); i < icount; i++) { + Object o = sourceList.get(i); + + if ((o == null) || componentClass.isInstance(o)) { + Array.set(result, i, o); + } else { + Array.set(result, i, converter.convertValue(context, null, null, null, o, + componentClass)); } } - } catch (ClassNotFoundException ex) { - throw new OgnlException("array component class '" + className + "' not found", ex); } - } else { - throw new OgnlException("only expect array size or fixed initializer list"); + } catch (ClassNotFoundException ex) { + throw new OgnlException("array component class '" + className + "' not found", ex); } } else { - result = OgnlRuntime.callConstructor(context, className, args); + throw new OgnlException("only expect array size or fixed initializer list"); } - - return result; - } finally { - OgnlRuntime.getObjectArrayPool().recycle(args); + } else { + result = OgnlRuntime.callConstructor(context, className, args); } + + return result; } - public String toString() - { - String result = "new " + className; + public String toString() { + StringBuilder result = new StringBuilder("new " + className); if (isArray) { - if (_children[0] instanceof ASTConst) { - result = result + "[" + _children[0] + "]"; + if (children[0] instanceof ASTConst) { + result.append("[").append(children[0]).append("]"); } else { - result = result + "[] " + _children[0]; + result.append("[] ").append(children[0]); } } else { - result = result + "("; - if ((_children != null) && (_children.length > 0)) { - for(int i = 0; i < _children.length; i++) { + result.append("("); + if ((children != null) && (children.length > 0)) { + for (int i = 0; i < children.length; i++) { if (i > 0) { - result = result + ", "; + result.append(", "); } - result = result + _children[i]; + result.append(children[i]); } } - result = result + ")"; + result.append(")"); } - return result; + return result.toString(); } - public String toGetSourceString(OgnlContext context, Object target) - { - String result = "new " + className; + public String toGetSourceString(OgnlContext context, Object target) { + StringBuilder result = new StringBuilder("new " + className); - Class clazz = null; - Object ctorValue = null; + Class clazz; + Object ctorValue; try { clazz = OgnlRuntime.classForName(context, className); - + ctorValue = this.getValueBody(context, target); context.setCurrentObject(ctorValue); - - if (clazz != null && ctorValue != null) { - + + if (ctorValue != null) { + context.setCurrentType(ctorValue.getClass()); context.setCurrentAccessor(ctorValue.getClass()); } @@ -179,61 +153,56 @@ public String toGetSourceString(OgnlContext context, Object target) if (isArray) context.put("_ctorClass", clazz); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } try { if (isArray) { - if (_children[0] instanceof ASTConst) { - - result = result + "[" + _children[0].toGetSourceString(context, target) + "]"; - } else if (ASTProperty.class.isInstance(_children[0])) { - - result = result + "[" - + ExpressionCompiler.getRootExpression(_children[0], target, context) - + _children[0].toGetSourceString(context, target) - + "]"; - } else if (ASTChain.class.isInstance(_children[0])) { - - result = result + "[" + _children[0].toGetSourceString(context, target) + "]"; + if (children[0] instanceof ASTConst) { + + result.append("[").append(children[0].toGetSourceString(context, target)).append("]"); + } else if (children[0] instanceof ASTProperty) { + + result.append("[").append(ExpressionCompiler.getRootExpression(children[0], target, context)).append(children[0].toGetSourceString(context, target)).append("]"); + } else if (children[0] instanceof ASTChain) { + + result.append("[").append(children[0].toGetSourceString(context, target)).append("]"); } else { - result = result + "[] "+ _children[0].toGetSourceString(context, target); + result.append("[] ").append(children[0].toGetSourceString(context, target)); } } else { - result = result + "("; + result.append("("); - if ((_children != null) && (_children.length > 0)) { + if ((children != null) && (children.length > 0)) { - Object[] values = new Object[_children.length]; - String[] expressions = new String[_children.length]; - Class[] types = new Class[_children.length]; + Object[] values = new Object[children.length]; + String[] expressions = new String[children.length]; + Class[] types = new Class[children.length]; // first populate arrays with child values - - for(int i = 0; i < _children.length; i++) { - - Object objValue = _children[i].getValue(context, context.getRoot()); - String value = _children[i].toGetSourceString(context, target); - - if (!ASTRootVarRef.class.isInstance(_children[i])) - { - value = ExpressionCompiler.getRootExpression(_children[i], target, context) + value; + + for (int i = 0; i < children.length; i++) { + + Object objValue = children[i].getValue(context, context.getRoot()); + String value = children[i].toGetSourceString(context, target); + + if (!(children[i] instanceof ASTRootVarRef)) { + value = ExpressionCompiler.getRootExpression(children[i], target, context) + value; } String cast = ""; - if (ExpressionCompiler.shouldCast(_children[i])) { + if (ExpressionCompiler.shouldCast(children[i])) { - cast = (String)context.remove(ExpressionCompiler.PRE_CAST); + cast = (String) context.remove(ExpressionCompiler.PRE_CAST); } if (cast == null) cast = ""; - if (!ASTConst.class.isInstance(_children[i])) + if (!(children[i] instanceof ASTConst)) value = cast + value; values[i] = objValue; @@ -242,18 +211,17 @@ public String toGetSourceString(OgnlContext context, Object target) } // now try and find a matching constructor - - Constructor[] cons = clazz.getConstructors(); - Constructor ctor = null; - Class[] ctorParamTypes = null; - - for (int i=0; i < cons.length; i++) - { - Class[] ctorTypes = cons[i].getParameterTypes(); + + Constructor[] cons = clazz.getConstructors(); + Constructor ctor = null; + Class[] ctorParamTypes = null; + + for (Constructor con : cons) { + Class[] ctorTypes = con.getParameterTypes(); if (OgnlRuntime.areArgsCompatible(values, ctorTypes) - && (ctor == null || OgnlRuntime.isMoreSpecific(ctorTypes, ctorParamTypes))) { - ctor = cons[i]; + && (ctor == null || OgnlRuntime.isMoreSpecific(ctorTypes, ctorParamTypes))) { + ctor = con; ctorParamTypes = ctorTypes; } } @@ -268,9 +236,9 @@ public String toGetSourceString(OgnlContext context, Object target) // now loop over child values again and build up the actual source string - for(int i = 0; i < _children.length; i++) { + for (int i = 0; i < children.length; i++) { if (i > 0) { - result = result + ", "; + result.append(", "); } String value = expressions[i]; @@ -285,43 +253,41 @@ public String toGetSourceString(OgnlContext context, Object target) if (ctorParamTypes[i] != types[i]) { if (values[i] != null && !types[i].isPrimitive() - && !values[i].getClass().isArray() && !ASTConst.class.isInstance(_children[i])) { - + && !values[i].getClass().isArray() && !(children[i] instanceof ASTConst)) { + value = "(" + OgnlRuntime.getCompiler().getInterfaceClass(values[i].getClass()).getName() + ")" + value; - } else if (!ASTConst.class.isInstance(_children[i]) - || (ASTConst.class.isInstance(_children[i]) && !types[i].isPrimitive())) { - + } else if (!(children[i] instanceof ASTConst) + || (children[i] instanceof ASTConst && !types[i].isPrimitive())) { + if (!types[i].isArray() - && types[i].isPrimitive() && !ctorParamTypes[i].isPrimitive()) + && types[i].isPrimitive() && !ctorParamTypes[i].isPrimitive()) value = "new " + ExpressionCompiler.getCastString(OgnlRuntime.getPrimitiveWrapperClass(types[i])) + "(" + value + ")"; else value = " ($w) " + value; } } - result += value; + result.append(value); } } - result = result + ")"; + result.append(")"); } context.setCurrentType(ctorValue != null ? ctorValue.getClass() : clazz); context.setCurrentAccessor(clazz); context.setCurrentObject(ctorValue); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } context.remove("_ctorClass"); - return result; + return result.toString(); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { return ""; } } diff --git a/src/main/java/ognl/ASTDivide.java b/src/main/java/ognl/ASTDivide.java index e0baeff7..50a9ea59 100644 --- a/src/main/java/ognl/ASTDivide.java +++ b/src/main/java/ognl/ASTDivide.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTDivide extends NumericExpression -{ +public class ASTDivide extends NumericExpression { + + private static final long serialVersionUID = 3154412889742069891L; + public ASTDivide(int id) { super(id); } @@ -44,15 +30,13 @@ public ASTDivide(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.divide( v1, v2 ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.divide(v1, v2); } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "/"; } diff --git a/src/main/java/ognl/ASTEq.java b/src/main/java/ognl/ASTEq.java index b3d3f097..15da810c 100644 --- a/src/main/java/ognl/ASTEq.java +++ b/src/main/java/ognl/ASTEq.java @@ -1,42 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; +public class ASTEq extends ComparisonExpression { + + private static final long serialVersionUID = -7129666227440957636L; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTEq extends ComparisonExpression -{ public ASTEq(int id) { super(id); } @@ -45,20 +30,17 @@ public ASTEq(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.equal( v1, v2 )? Boolean.TRUE : Boolean.FALSE; + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.equal(v1, v2) ? Boolean.TRUE : Boolean.FALSE; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "=="; } - public String getComparisonFunction() - { + public String getComparisonFunction() { return "ognl.OgnlOps.equal"; } } diff --git a/src/main/java/ognl/ASTEval.java b/src/main/java/ognl/ASTEval.java index cee2fea1..b4413a0b 100644 --- a/src/main/java/ognl/ASTEval.java +++ b/src/main/java/ognl/ASTEval.java @@ -1,61 +1,43 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTEval extends SimpleNode -{ +public class ASTEval extends SimpleNode { + + private static final long serialVersionUID = 3686472873318541923L; - public ASTEval(int id) - { + public ASTEval(int id) { super(id); } - public ASTEval(OgnlParser p, int id) - { + public ASTEval(OgnlParser p, int id) { super(p, id); } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { - Object result, expr = _children[0].getValue(context, source), previousRoot = context.getRoot(); + throws OgnlException { + Object result, expr = children[0].getValue(context, source), previousRoot = context.getRoot(); Node node; - source = _children[1].getValue(context, source); + source = children[1].getValue(context, source); node = (expr instanceof Node) ? (Node) expr : (Node) Ognl.parseExpression(expr.toString()); try { context.setRoot(source); @@ -67,12 +49,11 @@ protected Object getValueBody(OgnlContext context, Object source) } protected void setValueBody(OgnlContext context, Object target, Object value) - throws OgnlException - { - Object expr = _children[0].getValue(context, target), previousRoot = context.getRoot(); + throws OgnlException { + Object expr = children[0].getValue(context, target), previousRoot = context.getRoot(); Node node; - target = _children[1].getValue(context, target); + target = children[1].getValue(context, target); node = (expr instanceof Node) ? (Node) expr : (Node) Ognl.parseExpression(expr.toString()); try { context.setRoot(target); @@ -87,18 +68,15 @@ public boolean isEvalChain(OgnlContext context) throws OgnlException { return true; } - public String toString() - { - return "(" + _children[0] + ")(" + _children[1] + ")"; + public String toString() { + return "(" + children[0] + ")(" + children[1] + ")"; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Eval expressions not supported as native java yet."); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Map expressions not supported as native java yet."); } } diff --git a/src/main/java/ognl/ASTGreater.java b/src/main/java/ognl/ASTGreater.java index d10f4fea..ba59e69c 100644 --- a/src/main/java/ognl/ASTGreater.java +++ b/src/main/java/ognl/ASTGreater.java @@ -1,42 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; +public class ASTGreater extends ComparisonExpression { + + private static final long serialVersionUID = 3544928077296457477L; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTGreater extends ComparisonExpression -{ public ASTGreater(int id) { super(id); } @@ -45,21 +30,18 @@ public ASTGreater(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); - return OgnlOps.greater( v1, v2 )? Boolean.TRUE : Boolean.FALSE; + return OgnlOps.greater(v1, v2) ? Boolean.TRUE : Boolean.FALSE; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return ">"; } - public String getComparisonFunction() - { + public String getComparisonFunction() { return "ognl.OgnlOps.greater"; } } diff --git a/src/main/java/ognl/ASTGreaterEq.java b/src/main/java/ognl/ASTGreaterEq.java index 09550112..b7c107e3 100644 --- a/src/main/java/ognl/ASTGreaterEq.java +++ b/src/main/java/ognl/ASTGreaterEq.java @@ -1,42 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; +public class ASTGreaterEq extends ComparisonExpression { + + private static final long serialVersionUID = -6286160482861838266L; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTGreaterEq extends ComparisonExpression -{ public ASTGreaterEq(int id) { super(id); } @@ -45,20 +30,17 @@ public ASTGreaterEq(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.less( v1, v2 )? Boolean.FALSE : Boolean.TRUE; + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.less(v1, v2) ? Boolean.FALSE : Boolean.TRUE; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return ">="; } - public String getComparisonFunction() - { + public String getComparisonFunction() { return "!ognl.OgnlOps.less"; } } diff --git a/src/main/java/ognl/ASTIn.java b/src/main/java/ognl/ASTIn.java index 32e379a1..4ab1c2de 100644 --- a/src/main/java/ognl/ASTIn.java +++ b/src/main/java/ognl/ASTIn.java @@ -1,43 +1,29 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTIn extends SimpleNode implements NodeType -{ +public class ASTIn extends SimpleNode implements NodeType { + + private static final long serialVersionUID = -6647839788080239625L; + public ASTIn(int id) { super(id); } @@ -46,36 +32,31 @@ public ASTIn(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) - throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); + protected Object getValueBody(OgnlContext context, Object source) + throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); - return OgnlOps.in( v1, v2 )? Boolean.TRUE : Boolean.FALSE; + return OgnlOps.in(v1, v2) ? Boolean.TRUE : Boolean.FALSE; } - public String toString() - { - return _children[0] + " in " + _children[1]; + public String toString() { + return children[0] + " in " + children[1]; } - public Class getGetterClass() - { + public Class getGetterClass() { return Boolean.TYPE; } - public Class getSetterClass() - { + public Class getSetterClass() { return null; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { try { String result = "ognl.OgnlOps.in( ($w) "; - result += OgnlRuntime.getChildSource(context, target, _children[0]) + ", ($w) " + OgnlRuntime.getChildSource(context, target, _children[1]); + result += OgnlRuntime.getChildSource(context, target, children[0]) + ", ($w) " + OgnlRuntime.getChildSource(context, target, children[1]); result += ")"; @@ -88,14 +69,12 @@ public String toGetSourceString(OgnlContext context, Object target) e.printStackTrace(); throw new UnsupportedCompilationException("evaluation resulted in null expression."); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Map expressions not supported as native java yet."); } } diff --git a/src/main/java/ognl/ASTInstanceof.java b/src/main/java/ognl/ASTInstanceof.java index 165229f0..1c9003d4 100644 --- a/src/main/java/ognl/ASTInstanceof.java +++ b/src/main/java/ognl/ASTInstanceof.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2002, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTInstanceof extends SimpleNode implements NodeType -{ +public class ASTInstanceof extends SimpleNode implements NodeType { + + private static final long serialVersionUID = 4988707282372901939L; + private String targetType; public ASTInstanceof(int id) { @@ -46,54 +32,47 @@ public ASTInstanceof(OgnlParser p, int id) { super(p, id); } - void setTargetType( String targetType ) { + void setTargetType(String targetType) { this.targetType = targetType; } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object value = _children[0].getValue( context, source ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object value = children[0].getValue(context, source); return OgnlRuntime.isInstance(context, value, targetType) ? Boolean.TRUE : Boolean.FALSE; } - public String toString() - { - return _children[0] + " instanceof " + targetType; + public String toString() { + return children[0] + " instanceof " + targetType; } - - public Class getGetterClass() - { + + public Class getGetterClass() { return boolean.class; } - - public Class getSetterClass() - { + + public Class getSetterClass() { return null; } - - public String toGetSourceString(OgnlContext context, Object target) - { + + public String toGetSourceString(OgnlContext context, Object target) { try { - String ret = ""; + String ret; - if (ASTConst.class.isInstance(_children[0])) - ret = ((Boolean)getValueBody(context, target)).toString(); + if (children[0] instanceof ASTConst) + ret = ((Boolean) getValueBody(context, target)).toString(); else - ret = _children[0].toGetSourceString(context, target) + " instanceof " + targetType; - + ret = children[0].toGetSourceString(context, target) + " instanceof " + targetType; + context.setCurrentType(Boolean.TYPE); return ret; - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } - - public String toSetSourceString(OgnlContext context, Object target) - { + + public String toSetSourceString(OgnlContext context, Object target) { return toGetSourceString(context, target); } } diff --git a/src/main/java/ognl/ASTKeyValue.java b/src/main/java/ognl/ASTKeyValue.java index cc78375a..b7ae0a8b 100644 --- a/src/main/java/ognl/ASTKeyValue.java +++ b/src/main/java/ognl/ASTKeyValue.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTKeyValue extends SimpleNode -{ +public class ASTKeyValue extends SimpleNode { + + private static final long serialVersionUID = -2039156077201845415L; + public ASTKeyValue(int id) { super(id); } @@ -44,26 +30,22 @@ public ASTKeyValue(OgnlParser p, int id) { super(p, id); } - protected Node getKey() - { - return _children[0]; + protected Node getKey() { + return children[0]; } - protected Node getValue() - { - return (jjtGetNumChildren() > 1) ? _children[1] : null; + protected Node getValue() { + return (jjtGetNumChildren() > 1) ? children[1] : null; } /** - Returns null because this is a parser construct and does not evaluate + * Returns null because this is a parser construct and does not evaluate */ - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { return null; } - public String toString() - { + public String toString() { return getKey() + " -> " + getValue(); } } diff --git a/src/main/java/ognl/ASTLess.java b/src/main/java/ognl/ASTLess.java index 9904469b..0bfcea05 100644 --- a/src/main/java/ognl/ASTLess.java +++ b/src/main/java/ognl/ASTLess.java @@ -1,42 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; +class ASTLess extends ComparisonExpression { + + private static final long serialVersionUID = 7073712002461814213L; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -class ASTLess extends ComparisonExpression -{ public ASTLess(int id) { super(id); } @@ -45,21 +30,18 @@ public ASTLess(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.less( v1, v2 )? Boolean.TRUE : Boolean.FALSE; + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + + Object v2 = children[1].getValue(context, source); + return OgnlOps.less(v1, v2) ? Boolean.TRUE : Boolean.FALSE; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "<"; } - - public String getComparisonFunction() - { + + public String getComparisonFunction() { return "ognl.OgnlOps.less"; } } diff --git a/src/main/java/ognl/ASTLessEq.java b/src/main/java/ognl/ASTLessEq.java index 7e08702d..9cb970c0 100644 --- a/src/main/java/ognl/ASTLessEq.java +++ b/src/main/java/ognl/ASTLessEq.java @@ -1,42 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; +public class ASTLessEq extends ComparisonExpression { + + private static final long serialVersionUID = 7691692576590096450L; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTLessEq extends ComparisonExpression -{ public ASTLessEq(int id) { super(id); } @@ -45,20 +30,17 @@ public ASTLessEq(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.greater( v1, v2 )? Boolean.FALSE : Boolean.TRUE; + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.greater(v1, v2) ? Boolean.FALSE : Boolean.TRUE; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "<="; } - public String getComparisonFunction() - { + public String getComparisonFunction() { return "!ognl.OgnlOps.greater"; } diff --git a/src/main/java/ognl/ASTList.java b/src/main/java/ognl/ASTList.java index fa8915a4..93d0a250 100644 --- a/src/main/java/ognl/ASTList.java +++ b/src/main/java/ognl/ASTList.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; @@ -35,153 +23,122 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTList extends SimpleNode implements NodeType -{ - public ASTList(int id) - { +public class ASTList extends SimpleNode implements NodeType { + + private static final long serialVersionUID = 5819304155523588899L; + + public ASTList(int id) { super(id); } - public ASTList(OgnlParser p, int id) - { + public ASTList(OgnlParser p, int id) { super(p, id); } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { - List answer = new ArrayList(jjtGetNumChildren()); - for(int i = 0; i < jjtGetNumChildren(); ++i) - answer.add(_children[i].getValue(context, source)); + throws OgnlException { + List answer = new ArrayList<>(jjtGetNumChildren()); + for (int i = 0; i < jjtGetNumChildren(); ++i) { + answer.add(children[i].getValue(context, source)); + } return answer; } - public Class getGetterClass() - { + public Class getGetterClass() { return null; } - public Class getSetterClass() - { + public Class getSetterClass() { return null; } - public String toString() - { - String result = "{ "; + public String toString() { + StringBuilder result = new StringBuilder("{ "); - for(int i = 0; i < jjtGetNumChildren(); ++i) { + for (int i = 0; i < jjtGetNumChildren(); ++i) { if (i > 0) { - result = result + ", "; + result.append(", "); } - result = result + _children[i].toString(); + result.append(children[i].toString()); } return result + " }"; } - public String toGetSourceString(OgnlContext context, Object target) - { - String result = ""; - boolean array = false; - - if (_parent != null && ASTCtor.class.isInstance(_parent) - && ((ASTCtor)_parent).isArray()) { - - array = true; - } + public String toGetSourceString(OgnlContext context, Object target) { + StringBuilder result = new StringBuilder(); + boolean array = parent instanceof ASTCtor && ((ASTCtor) parent).isArray(); context.setCurrentType(List.class); context.setCurrentAccessor(List.class); - if (!array) - { + if (!array) { if (jjtGetNumChildren() < 1) return "java.util.Arrays.asList( new Object[0])"; - result += "java.util.Arrays.asList( new Object[] "; + result.append("java.util.Arrays.asList( new Object[] "); } - result += "{ "; + result.append("{ "); try { - for(int i = 0; i < jjtGetNumChildren(); ++i) { + for (int i = 0; i < jjtGetNumChildren(); ++i) { if (i > 0) { - result = result + ", "; + result.append(", "); } - Class prevType = context.getCurrentType(); + Class prevType = context.getCurrentType(); - Object objValue = _children[i].getValue(context, context.getRoot()); - String value = _children[i].toGetSourceString(context, target); + Object objValue = children[i].getValue(context, context.getRoot()); + String value = children[i].toGetSourceString(context, target); // to undo type setting of constants when used as method parameters - if (ASTConst.class.isInstance(_children[i])) { + if (children[i] instanceof ASTConst) { context.setCurrentType(prevType); } - value = ExpressionCompiler.getRootExpression(_children[i], target, context) + value; + value = ExpressionCompiler.getRootExpression(children[i], target, context) + value; String cast = ""; - if (ExpressionCompiler.shouldCast(_children[i])) { + if (ExpressionCompiler.shouldCast(children[i])) { - cast = (String)context.remove(ExpressionCompiler.PRE_CAST); + cast = (String) context.remove(ExpressionCompiler.PRE_CAST); } if (cast == null) cast = ""; - if (!ASTConst.class.isInstance(_children[i])) + if (!(children[i] instanceof ASTConst)) value = cast + value; - Class ctorClass = (Class)context.get("_ctorClass"); + Class ctorClass = (Class) context.get("_ctorClass"); if (array && ctorClass != null && !ctorClass.isPrimitive()) { - Class valueClass = value != null ? value.getClass() : null; - if (NodeType.class.isAssignableFrom(_children[i].getClass())) - valueClass = ((NodeType)_children[i]).getGetterClass(); + Class valueClass = value.getClass(); + if (NodeType.class.isAssignableFrom(children[i].getClass())) + valueClass = ((NodeType) children[i]).getGetterClass(); if (valueClass != null && ctorClass.isArray()) { value = OgnlRuntime.getCompiler().createLocalReference(context, - "(" + ExpressionCompiler.getCastString(ctorClass) - + ")ognl.OgnlOps.toArray(" + value + ", " + ctorClass.getComponentType().getName() - + ".class, true)", - ctorClass - ); - - } else if (ctorClass.isPrimitive()) { - - Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(ctorClass); - - value = OgnlRuntime.getCompiler().createLocalReference(context, - "((" + wrapClass.getName() - + ")ognl.OgnlOps.convertValue(" + value + "," - + wrapClass.getName() + ".class, true))." - + OgnlRuntime.getNumericValueGetter(wrapClass), - ctorClass + "(" + ExpressionCompiler.getCastString(ctorClass) + + ")ognl.OgnlOps.toArray(" + value + ", " + ctorClass.getComponentType().getName() + + ".class, true)", + ctorClass ); } else if (ctorClass != Object.class) { - value = OgnlRuntime.getCompiler().createLocalReference(context, - "(" + ctorClass.getName() + ")ognl.OgnlOps.convertValue(" + value + "," + ctorClass.getName() + ".class)", - ctorClass + "(" + ctorClass.getName() + ")ognl.OgnlOps.convertValue(" + value + "," + ctorClass.getName() + ".class)", + ctorClass ); - - } else if ((NodeType.class.isInstance(_children[i]) - && ((NodeType)_children[i]).getGetterClass() != null - && Number.class.isAssignableFrom(((NodeType)_children[i]).getGetterClass())) - || valueClass.isPrimitive()) { - + } else if ((children[i] instanceof NodeType + && ((NodeType) children[i]).getGetterClass() != null + && Number.class.isAssignableFrom(((NodeType) children[i]).getGetterClass())) + || Objects.requireNonNull(valueClass).isPrimitive()) { value = " ($w) (" + value + ")"; - } else if (valueClass.isPrimitive()) { - value = "($w) (" + value + ")"; } } else if (ctorClass == null || !ctorClass.isPrimitive()) { @@ -192,27 +149,25 @@ public String toGetSourceString(OgnlContext context, Object target) if (objValue == null || value.length() <= 0) value = "null"; - result += value; + result.append(value); } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } context.setCurrentType(List.class); context.setCurrentAccessor(List.class); - result += "}"; + result.append("}"); if (!array) - result += ")"; + result.append(")"); - return result; + return result.toString(); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Can't generate setter for ASTList."); } } diff --git a/src/main/java/ognl/ASTMap.java b/src/main/java/ognl/ASTMap.java index cb4650a9..a93652ef 100644 --- a/src/main/java/ognl/ASTMap.java +++ b/src/main/java/ognl/ASTMap.java @@ -1,97 +1,62 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTMap extends SimpleNode -{ +public class ASTMap extends SimpleNode { - private static Class DEFAULT_MAP_CLASS; - private String className; + private static final long serialVersionUID = -849999202189860682L; - static { - /* Try to get LinkedHashMap; if older JDK than 1.4 use HashMap */ - try { - DEFAULT_MAP_CLASS = Class.forName("java.util.LinkedHashMap"); - } catch (ClassNotFoundException ex) { - DEFAULT_MAP_CLASS = HashMap.class; - } - } + private String className; - public ASTMap(int id) - { + public ASTMap(int id) { super(id); } - public ASTMap(OgnlParser p, int id) - { + public ASTMap(OgnlParser p, int id) { super(p, id); } - protected void setClassName(String value) - { + protected void setClassName(String value) { className = value; } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { - Map answer; + throws OgnlException { + Map answer; if (className == null) { - try { - answer = (Map) DEFAULT_MAP_CLASS.newInstance(); - } catch (Exception ex) { - /* This should never happen */ - throw new OgnlException("Default Map class '" + DEFAULT_MAP_CLASS.getName() + "' instantiation error", - ex); - } + answer = new LinkedHashMap<>(); } else { try { - answer = (Map) OgnlRuntime.classForName(context, className).newInstance(); + answer = (Map) OgnlRuntime.classForName(context, className).newInstance(); } catch (Exception ex) { throw new OgnlException("Map implementor '" + className + "' not found", ex); } } - for(int i = 0; i < jjtGetNumChildren(); ++i) { - ASTKeyValue kv = (ASTKeyValue) _children[i]; + for (int i = 0; i < jjtGetNumChildren(); ++i) { + ASTKeyValue kv = (ASTKeyValue) children[i]; Node k = kv.getKey(), v = kv.getValue(); answer.put(k.getValue(context, source), (v == null) ? null : v.getValue(context, source)); @@ -100,33 +65,30 @@ protected Object getValueBody(OgnlContext context, Object source) return answer; } - public String toString() - { - String result = "#"; + public String toString() { + StringBuilder result = new StringBuilder("#"); if (className != null) { - result = result + "@" + className + "@"; + result.append("@").append(className).append("@"); } - result = result + "{ "; - for(int i = 0; i < jjtGetNumChildren(); ++i) { - ASTKeyValue kv = (ASTKeyValue) _children[i]; + result.append("{ "); + for (int i = 0; i < jjtGetNumChildren(); ++i) { + ASTKeyValue kv = (ASTKeyValue) children[i]; if (i > 0) { - result = result + ", "; + result.append(", "); } - result = result + kv.getKey() + " : " + kv.getValue(); + result.append(kv.getKey()).append(" : ").append(kv.getValue()); } return result + " }"; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Map expressions not supported as native java yet."); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Map expressions not supported as native java yet."); } } diff --git a/src/main/java/ognl/ASTMethod.java b/src/main/java/ognl/ASTMethod.java index ec0785ef..5766ba00 100644 --- a/src/main/java/ognl/ASTMethod.java +++ b/src/main/java/ognl/ASTMethod.java @@ -1,33 +1,21 @@ -//-------------------------------------------------------------------------- -//Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -//All rights reserved. - -//Redistribution and use in source and binary forms, with or without -//modification, are permitted provided that the following conditions are -//met: - -//Redistributions of source code must retain the above copyright notice, -//this list of conditions and the following disclaimer. -//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. -//Neither the name of the Drew Davidson nor the names of its contributors -//may be used to endorse or promote products derived from this software -//without specific prior written permission. - -//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -//"AS IS" AND ANY EXPRESS 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 -//COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; @@ -37,28 +25,20 @@ import java.lang.reflect.Method; import java.util.List; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTMethod extends SimpleNode implements OrderedReturn, NodeType -{ - - private String _methodName; - - private String _lastExpression; +public class ASTMethod extends SimpleNode implements OrderedReturn, NodeType { - private String _coreExpression; + private static final long serialVersionUID = -6108508556131109533L; - private Class _getterClass; + private String methodName; + private String lastExpression; + private String coreExpression; + private Class getterClass; - public ASTMethod(int id) - { + public ASTMethod(int id) { super(id); } - public ASTMethod(OgnlParser p, int id) - { + public ASTMethod(OgnlParser p, int id) { super(p, id); } @@ -67,9 +47,8 @@ public ASTMethod(OgnlParser p, int id) * * @param methodName the method name. */ - public void setMethodName(String methodName) - { - _methodName = methodName; + public void setMethodName(String methodName) { + this.methodName = methodName; } /** @@ -77,286 +56,247 @@ public void setMethodName(String methodName) * * @return the method name. */ - public String getMethodName() - { - return _methodName; + public String getMethodName() { + return methodName; } - protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { - Object[] args = OgnlRuntime.getObjectArrayPool().create(jjtGetNumChildren()); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object[] args = new Object[jjtGetNumChildren()]; - try { - Object result, root = context.getRoot(); + Object result, root = context.getRoot(); - for(int i = 0, icount = args.length; i < icount; ++i) { - args[i] = _children[i].getValue(context, root); - } + for (int i = 0, icount = args.length; i < icount; ++i) { + args[i] = children[i].getValue(context, root); + } - result = OgnlRuntime.callMethod(context, source, _methodName, args); + result = OgnlRuntime.callMethod(context, source, methodName, args); - if (result == null) - { - NullHandler nh = OgnlRuntime.getNullHandler(OgnlRuntime.getTargetClass(source)); - result = nh.nullMethodResult(context, source, _methodName, args); - } + if (result == null) { + NullHandler nh = OgnlRuntime.getNullHandler(OgnlRuntime.getTargetClass(source)); + result = nh.nullMethodResult(context, source, methodName, args); + } - return result; + return result; - } finally { - OgnlRuntime.getObjectArrayPool().recycle(args); - } } - public String getLastExpression() - { - return _lastExpression; + public String getLastExpression() { + return lastExpression; } - public String getCoreExpression() - { - return _coreExpression; + public String getCoreExpression() { + return coreExpression; } - public Class getGetterClass() - { - return _getterClass; + public Class getGetterClass() { + return getterClass; } - public Class getSetterClass() - { - return _getterClass; + public Class getSetterClass() { + return getterClass; } - public String toString() - { - String result = _methodName; + public String toString() { + StringBuilder result = new StringBuilder(methodName); - result = result + "("; - if ((_children != null) && (_children.length > 0)) { - - for(int i = 0; i < _children.length; i++) { + result.append("("); + if ((children != null) && (children.length > 0)) { + for (int i = 0; i < children.length; i++) { if (i > 0) { - result = result + ", "; + result.append(", "); } - - result = result + _children[i]; + result.append(children[i]); } } - result = result + ")"; - return result; + result.append(")"); + return result.toString(); } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { /* System.out.println("methodName is " + _methodName + " for target " + target + " target class: " + (target != null ? target.getClass() : null) + " current type: " + context.getCurrentType());*/ if (target == null) throw new UnsupportedCompilationException("Target object is null."); String post = ""; - String result = null; - Method m = null; + StringBuilder result; + Method m; try { - m = OgnlRuntime.getMethod(context, context.getCurrentType() != null ? context.getCurrentType() : target.getClass(), _methodName, _children, false); - Class[] argumentClasses = getChildrenClasses(context, _children); + m = OgnlRuntime.getMethod(context, context.getCurrentType() != null ? context.getCurrentType() : target.getClass(), methodName, children, false); + Class[] argumentClasses = getChildrenClasses(context, children); if (m == null) - m = OgnlRuntime.getReadMethod(target.getClass(), _methodName, argumentClasses); + m = OgnlRuntime.getReadMethod(target.getClass(), methodName, argumentClasses); if (m == null) { - m = OgnlRuntime.getWriteMethod(target.getClass(), _methodName, argumentClasses); + m = OgnlRuntime.getWriteMethod(target.getClass(), methodName, argumentClasses); if (m != null) { context.setCurrentType(m.getReturnType()); context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); - _coreExpression = toSetSourceString(context, target); - if (_coreExpression == null || _coreExpression.length() < 1) + coreExpression = toSetSourceString(context, target); + if (coreExpression == null || coreExpression.length() < 1) throw new UnsupportedCompilationException("can't find suitable getter method"); - _coreExpression += ";"; - _lastExpression = "null"; + coreExpression += ";"; + lastExpression = "null"; - return _coreExpression; + return coreExpression; } return ""; } else { - _getterClass = m.getReturnType(); + getterClass = m.getReturnType(); } // TODO: This is a hacky workaround until javassist supports varargs method invocations boolean varArgs = m.isVarArgs(); - if (varArgs) - { + if (varArgs) { throw new UnsupportedCompilationException("Javassist does not currently support varargs method calls"); } - result = "." + m.getName() + "("; + result = new StringBuilder("." + m.getName() + "("); - if ((_children != null) && (_children.length > 0)) - { - Class[] parms = m.getParameterTypes(); - String prevCast = (String)context.remove(ExpressionCompiler.PRE_CAST); -/* - System.out.println("before children methodName is " + _methodName + " for target " + target + " target class: " + (target != null ? target.getClass() : null) - + " current type: " + context.getCurrentType() + " and previous type: " + context.getPreviousType());*/ - - for(int i = 0; i < _children.length; i++) - { - if (i > 0) - { - result = result + ", "; + if ((children != null) && (children.length > 0)) { + Class[] parms = m.getParameterTypes(); + String prevCast = (String) context.remove(ExpressionCompiler.PRE_CAST); + + for (int i = 0; i < children.length; i++) { + if (i > 0) { + result.append(", "); } - Class prevType = context.getCurrentType(); + Class prevType = context.getCurrentType(); context.setCurrentObject(context.getRoot()); context.setCurrentType(context.getRoot() != null ? context.getRoot().getClass() : null); context.setCurrentAccessor(null); context.setPreviousType(null); - Object value = _children[i].getValue(context, context.getRoot()); - String parmString = _children[i].toGetSourceString(context, context.getRoot()); + Object value = children[i].getValue(context, context.getRoot()); + String parmString = children[i].toGetSourceString(context, context.getRoot()); if (parmString == null || parmString.trim().length() < 1) parmString = "null"; // to undo type setting of constants when used as method parameters - if (ASTConst.class.isInstance(_children[i])) - { + if (children[i] instanceof ASTConst) { context.setCurrentType(prevType); } - parmString = ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context) + parmString; + parmString = ExpressionCompiler.getRootExpression(children[i], context.getRoot(), context) + parmString; String cast = ""; - if (ExpressionCompiler.shouldCast(_children[i])) - { - cast = (String)context.remove(ExpressionCompiler.PRE_CAST); + if (ExpressionCompiler.shouldCast(children[i])) { + cast = (String) context.remove(ExpressionCompiler.PRE_CAST); } if (cast == null) cast = ""; - if (!ASTConst.class.isInstance(_children[i])) + if (!(children[i] instanceof ASTConst)) parmString = cast + parmString; - Class valueClass = value != null ? value.getClass() : null; - if (NodeType.class.isAssignableFrom(_children[i].getClass())) - valueClass = ((NodeType)_children[i]).getGetterClass(); + Class valueClass = value != null ? value.getClass() : null; + if (NodeType.class.isAssignableFrom(children[i].getClass())) + valueClass = ((NodeType) children[i]).getGetterClass(); - if ((!varArgs || varArgs && (i + 1) < parms.length) && valueClass != parms[i]) - { + if (valueClass != parms[i]) { if (parms[i].isArray()) { parmString = OgnlRuntime.getCompiler().createLocalReference(context, - "(" + ExpressionCompiler.getCastString(parms[i]) - + ")ognl.OgnlOps#toArray(" + parmString + ", " + parms[i].getComponentType().getName() - + ".class, true)", - parms[i] + "(" + ExpressionCompiler.getCastString(parms[i]) + + ")ognl.OgnlOps#toArray(" + parmString + ", " + parms[i].getComponentType().getName() + + ".class, true)", + parms[i] ); - } else if (parms[i].isPrimitive()) { + } else if (parms[i].isPrimitive()) { - Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(parms[i]); + Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(parms[i]); parmString = OgnlRuntime.getCompiler().createLocalReference(context, - "((" + wrapClass.getName() - + ")ognl.OgnlOps#convertValue(" + parmString + "," - + wrapClass.getName() + ".class, true))." - + OgnlRuntime.getNumericValueGetter(wrapClass), - parms[i] + "((" + wrapClass.getName() + + ")ognl.OgnlOps#convertValue(" + parmString + "," + + wrapClass.getName() + ".class, true))." + + OgnlRuntime.getNumericValueGetter(wrapClass), + parms[i] ); } else if (parms[i] != Object.class) { parmString = OgnlRuntime.getCompiler().createLocalReference(context, - "(" + parms[i].getName() + ")ognl.OgnlOps#convertValue(" + parmString + "," + parms[i].getName() + ".class)", - parms[i] + "(" + parms[i].getName() + ")ognl.OgnlOps#convertValue(" + parmString + "," + parms[i].getName() + ".class)", + parms[i] ); - } else if ((NodeType.class.isInstance(_children[i]) - && ((NodeType)_children[i]).getGetterClass() != null - && Number.class.isAssignableFrom(((NodeType)_children[i]).getGetterClass())) - || (valueClass != null && valueClass.isPrimitive())) - { + } else if ((children[i] instanceof NodeType + && ((NodeType) children[i]).getGetterClass() != null + && Number.class.isAssignableFrom(((NodeType) children[i]).getGetterClass())) + || (valueClass != null && valueClass.isPrimitive())) { parmString = " ($w) " + parmString; - } else if (valueClass != null && valueClass.isPrimitive()) - { - parmString = "($w) " + parmString; } } - result += parmString; + result.append(parmString); } - if (prevCast != null) - { + if (prevCast != null) { context.put(ExpressionCompiler.PRE_CAST, prevCast); } } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - try - { + try { Object contextObj = getValueBody(context, target); context.setCurrentObject(contextObj); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - result += ")" + post; + result.append(")").append(post); if (m.getReturnType() == void.class) { - _coreExpression = result + ";"; - _lastExpression = "null"; + coreExpression = result + ";"; + lastExpression = "null"; } context.setCurrentType(m.getReturnType()); context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); - return result; + return result.toString(); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { /*System.out.println("current type: " + context.getCurrentType() + " target:" + target + " " + context.getCurrentObject() + " last child? " + lastChild(context));*/ Method m = OgnlRuntime.getWriteMethod(context.getCurrentType() != null ? - context.getCurrentType() : target.getClass(), - _methodName, getChildrenClasses(context, _children)); - if (m == null) - { - throw new UnsupportedCompilationException("Unable to determine setter method generation for " + _methodName); + context.getCurrentType() : target.getClass(), + methodName, getChildrenClasses(context, children)); + if (m == null) { + throw new UnsupportedCompilationException("Unable to determine setter method generation for " + methodName); } String post = ""; - String result = "." + m.getName() + "("; + StringBuilder result = new StringBuilder("." + m.getName() + "("); - if (m.getReturnType() != void.class && m.getReturnType().isPrimitive() - && (_parent == null || !ASTTest.class.isInstance(_parent))) - { - Class wrapper = OgnlRuntime.getPrimitiveWrapperClass(m.getReturnType()); + if (m.getReturnType() != void.class && m.getReturnType().isPrimitive() && (!(parent instanceof ASTTest))) { + Class wrapper = OgnlRuntime.getPrimitiveWrapperClass(m.getReturnType()); ExpressionCompiler.addCastString(context, "new " + wrapper.getName() + "("); post = ")"; - _getterClass = wrapper; + getterClass = wrapper; } boolean varArgs = m.isVarArgs(); - if (varArgs) - { + if (varArgs) { throw new UnsupportedCompilationException("Javassist does not currently support varargs method calls"); } @@ -364,52 +304,46 @@ public String toSetSourceString(OgnlContext context, Object target) /* if (lastChild(context) && m.getParameterTypes().length > 0 && _children.length <= 0) throw new UnsupportedCompilationException("Unable to determine setter method generation for " + m); */ - if ((_children != null) && (_children.length > 0)) - { - Class[] parms = m.getParameterTypes(); - String prevCast = (String)context.remove(ExpressionCompiler.PRE_CAST); + if ((children != null) && (children.length > 0)) { + Class[] parms = m.getParameterTypes(); + String prevCast = (String) context.remove(ExpressionCompiler.PRE_CAST); - for(int i = 0; i < _children.length; i++) - { - if (i > 0) - { - result += ", "; + for (int i = 0; i < children.length; i++) { + if (i > 0) { + result.append(", "); } - Class prevType = context.getCurrentType(); + Class prevType = context.getCurrentType(); context.setCurrentObject(context.getRoot()); context.setCurrentType(context.getRoot() != null ? context.getRoot().getClass() : null); context.setCurrentAccessor(null); context.setPreviousType(null); - Object value = _children[i].getValue(context, context.getRoot()); - String parmString = _children[i].toSetSourceString(context, context.getRoot()); + Object value = children[i].getValue(context, context.getRoot()); + String parmString = children[i].toSetSourceString(context, context.getRoot()); if (context.getCurrentType() == Void.TYPE || context.getCurrentType() == void.class) throw new UnsupportedCompilationException("Method argument can't be a void type."); - if (parmString == null || parmString.trim().length() < 1) - { - if (ASTProperty.class.isInstance(_children[i]) || ASTMethod.class.isInstance(_children[i]) - || ASTStaticMethod.class.isInstance(_children[i]) || ASTChain.class.isInstance(_children[i])) + if (parmString == null || parmString.trim().length() < 1) { + if (children[i] instanceof ASTProperty || children[i] instanceof ASTMethod + || children[i] instanceof ASTStaticMethod || children[i] instanceof ASTChain) throw new UnsupportedCompilationException("ASTMethod setter child returned null from a sub property expression."); parmString = "null"; } // to undo type setting of constants when used as method parameters - if (ASTConst.class.isInstance(_children[i])) - { + if (children[i] instanceof ASTConst) { context.setCurrentType(prevType); } - parmString = ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context) + parmString; + parmString = ExpressionCompiler.getRootExpression(children[i], context.getRoot(), context) + parmString; String cast = ""; - if (ExpressionCompiler.shouldCast(_children[i])) - { - cast = (String)context.remove(ExpressionCompiler.PRE_CAST); + if (ExpressionCompiler.shouldCast(children[i])) { + cast = (String) context.remove(ExpressionCompiler.PRE_CAST); } if (cast == null) @@ -417,74 +351,62 @@ public String toSetSourceString(OgnlContext context, Object target) parmString = cast + parmString; - Class valueClass = value != null ? value.getClass() : null; - if (NodeType.class.isAssignableFrom(_children[i].getClass())) - valueClass = ((NodeType)_children[i]).getGetterClass(); + Class valueClass = value != null ? value.getClass() : null; + if (NodeType.class.isAssignableFrom(children[i].getClass())) + valueClass = ((NodeType) children[i]).getGetterClass(); - if (valueClass != parms[i]) - { - if (parms[i].isArray()) - { + if (valueClass != parms[i]) { + if (parms[i].isArray()) { parmString = OgnlRuntime.getCompiler().createLocalReference(context, - "(" + ExpressionCompiler.getCastString(parms[i]) - + ")ognl.OgnlOps#toArray(" + parmString + ", " - + parms[i].getComponentType().getName() - + ".class)", - parms[i] + "(" + ExpressionCompiler.getCastString(parms[i]) + + ")ognl.OgnlOps#toArray(" + parmString + ", " + + parms[i].getComponentType().getName() + + ".class)", + parms[i] ); - } else if (parms[i].isPrimitive()) - { - Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(parms[i]); + } else if (parms[i].isPrimitive()) { + Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(parms[i]); parmString = OgnlRuntime.getCompiler().createLocalReference(context, - "((" + wrapClass.getName() - + ")ognl.OgnlOps#convertValue(" + parmString + "," - + wrapClass.getName() + ".class, true))." - + OgnlRuntime.getNumericValueGetter(wrapClass), - parms[i] + "((" + wrapClass.getName() + + ")ognl.OgnlOps#convertValue(" + parmString + "," + + wrapClass.getName() + ".class, true))." + + OgnlRuntime.getNumericValueGetter(wrapClass), + parms[i] ); - } else if (parms[i] != Object.class) - { + } else if (parms[i] != Object.class) { parmString = OgnlRuntime.getCompiler().createLocalReference(context, - "(" + parms[i].getName() + ")ognl.OgnlOps#convertValue(" - + parmString + "," + parms[i].getName() + ".class)", - parms[i] + "(" + parms[i].getName() + ")ognl.OgnlOps#convertValue(" + + parmString + "," + parms[i].getName() + ".class)", + parms[i] ); - } else if ((NodeType.class.isInstance(_children[i]) - && ((NodeType)_children[i]).getGetterClass() != null - && Number.class.isAssignableFrom(((NodeType)_children[i]).getGetterClass())) - || (valueClass != null && valueClass.isPrimitive())) - { + } else if ((children[i] instanceof NodeType + && ((NodeType) children[i]).getGetterClass() != null + && Number.class.isAssignableFrom(((NodeType) children[i]).getGetterClass())) + || (valueClass != null && valueClass.isPrimitive())) { parmString = " ($w) " + parmString; - } else if (valueClass != null && valueClass.isPrimitive()) - { - parmString = "($w) " + parmString; } } - result += parmString; + result.append(parmString); } - if (prevCast != null) - { + if (prevCast != null) { context.put(ExpressionCompiler.PRE_CAST, prevCast); } } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - try - { + try { Object contextObj = getValueBody(context, target); context.setCurrentObject(contextObj); - } catch (Throwable t) - { + } catch (Throwable t) { // ignore } @@ -494,11 +416,10 @@ public String toSetSourceString(OgnlContext context, Object target) return result + ")" + post; } - private static Class getClassMatchingAllChildren(OgnlContext context, Node[] _children) { - Class[] cc = getChildrenClasses(context, _children); - Class componentType = null; - for (int j = 0; j < cc.length; j++) { - Class ic = cc[j]; + private static Class getClassMatchingAllChildren(OgnlContext context, Node[] _children) { + Class[] cc = getChildrenClasses(context, _children); + Class componentType = null; + for (Class ic : cc) { if (ic == null) { componentType = Object.class; // fall back to object... break; @@ -510,7 +431,7 @@ private static Class getClassMatchingAllChildren(OgnlContext context, Node[] _ch if (ic.isAssignableFrom(componentType)) { componentType = ic; // just swap... ic is more generic... } else { - Class pc; + Class pc; while ((pc = componentType.getSuperclass()) != null) { // TODO hmm - it could also be that an interface matches... if (pc.isAssignableFrom(ic)) { componentType = pc; // use this matching parent class @@ -532,28 +453,26 @@ private static Class getClassMatchingAllChildren(OgnlContext context, Node[] _ch return componentType; } - private static Class[] getChildrenClasses(OgnlContext context, Node[] _children) { + private static Class[] getChildrenClasses(OgnlContext context, Node[] _children) { if (_children == null) return null; - Class[] argumentClasses = new Class[_children.length]; + Class[] argumentClasses = new Class[_children.length]; for (int i = 0; i < _children.length; i++) { Node child = _children[i]; - if (child instanceof ASTList) { // special handling for ASTList - it creates a List - //Class componentType = getClassMatchingAllChildren(context, ((ASTList)child)._children); - //argumentClasses[i] = Array.newInstance(componentType, 0).getClass(); + if (child instanceof ASTList) { // special handling for ASTList - it creates a List argumentClasses[i] = List.class; } else if (child instanceof NodeType) { - argumentClasses[i] = ((NodeType)child).getGetterClass(); + argumentClasses[i] = ((NodeType) child).getGetterClass(); } else if (child instanceof ASTCtor) { try { - argumentClasses[i] = ((ASTCtor)child).getCreatedClass(context); + argumentClasses[i] = ((ASTCtor) child).getCreatedClass(context); } catch (ClassNotFoundException nfe) { throw OgnlOps.castToRuntime(nfe); } } else if (child instanceof ASTTest) { - argumentClasses[i] = getClassMatchingAllChildren(context, ((ASTTest)child)._children); + argumentClasses[i] = getClassMatchingAllChildren(context, ((ASTTest) child).children); } else { - throw new UnsupportedOperationException("Don't know how to handle child: "+child); + throw new UnsupportedOperationException("Don't know how to handle child: " + child); } } return argumentClasses; diff --git a/src/main/java/ognl/ASTMultiply.java b/src/main/java/ognl/ASTMultiply.java index 85dd2716..d35cd52f 100644 --- a/src/main/java/ognl/ASTMultiply.java +++ b/src/main/java/ognl/ASTMultiply.java @@ -1,41 +1,26 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTMultiply extends NumericExpression -{ +public class ASTMultiply extends NumericExpression { + + private static final long serialVersionUID = -6495848669307687043L; public ASTMultiply(int id) { super(id); @@ -49,16 +34,14 @@ public void jjtClose() { flattenTree(); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object result = _children[0].getValue( context, source ); - for ( int i=1; i < _children.length; ++i ) - result = OgnlOps.multiply( result, _children[i].getValue(context, source) ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object result = children[0].getValue(context, source); + for (int i = 1; i < children.length; ++i) + result = OgnlOps.multiply(result, children[i].getValue(context, source)); return result; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "*"; } } diff --git a/src/main/java/ognl/ASTNegate.java b/src/main/java/ognl/ASTNegate.java index 482eff12..b0a46f51 100644 --- a/src/main/java/ognl/ASTNegate.java +++ b/src/main/java/ognl/ASTNegate.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTNegate extends NumericExpression -{ +public class ASTNegate extends NumericExpression { + + private static final long serialVersionUID = -541105956940549394L; + public ASTNegate(int id) { super(id); } @@ -44,33 +30,28 @@ public ASTNegate(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - return OgnlOps.negate( _children[0].getValue(context, source) ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + return OgnlOps.negate(children[0].getValue(context, source)); } - public String toString() - { - return "-" + _children[0]; + public String toString() { + return "-" + children[0]; } - public String toGetSourceString(OgnlContext context, Object target) - { - String source = _children[0].toGetSourceString(context, target); + public String toGetSourceString(OgnlContext context, Object target) { + String source = children[0].toGetSourceString(context, target); - if (!ASTNegate.class.isInstance(_children[0])) - { + if (!(children[0] instanceof ASTNegate)) { return "-" + source; - } else - { + } else { return "-(" + source + ")"; } } @Override public boolean isOperation(OgnlContext context) throws OgnlException { - if (_children.length == 1) { - SimpleNode child = (SimpleNode) _children[0]; + if (children.length == 1) { + SimpleNode child = (SimpleNode) children[0]; return child.isOperation(context) || !child.isConstant(context); } return super.isOperation(context); diff --git a/src/main/java/ognl/ASTNot.java b/src/main/java/ognl/ASTNot.java index 15eece89..2ce18337 100644 --- a/src/main/java/ognl/ASTNot.java +++ b/src/main/java/ognl/ASTNot.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTNot extends BooleanExpression -{ +public class ASTNot extends BooleanExpression { + + private static final long serialVersionUID = 6791997588178551336L; + public ASTNot(int id) { super(id); } @@ -44,18 +30,15 @@ public ASTNot(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - return OgnlOps.booleanValue( _children[0].getValue(context, source) ) ? Boolean.FALSE : Boolean.TRUE; + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + return OgnlOps.booleanValue(children[0].getValue(context, source)) ? Boolean.FALSE : Boolean.TRUE; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "!"; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { try { String srcString = super.toGetSourceString(context, target); @@ -67,8 +50,7 @@ public String toGetSourceString(OgnlContext context, Object target) return "(! ognl.OgnlOps.booleanValue(" + srcString + ") )"; - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } diff --git a/src/main/java/ognl/ASTNotEq.java b/src/main/java/ognl/ASTNotEq.java index 3a7ce3e7..a011aaa1 100644 --- a/src/main/java/ognl/ASTNotEq.java +++ b/src/main/java/ognl/ASTNotEq.java @@ -1,42 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; +public class ASTNotEq extends ComparisonExpression { + + private static final long serialVersionUID = -8504319639438982233L; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTNotEq extends ComparisonExpression -{ public ASTNotEq(int id) { super(id); } @@ -45,21 +30,18 @@ public ASTNotEq(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); - return OgnlOps.equal( v1, v2 ) ? Boolean.FALSE : Boolean.TRUE; + return OgnlOps.equal(v1, v2) ? Boolean.FALSE : Boolean.TRUE; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "!="; } - public String getComparisonFunction() - { + public String getComparisonFunction() { return "!ognl.OgnlOps.equal"; } } diff --git a/src/main/java/ognl/ASTNotIn.java b/src/main/java/ognl/ASTNotIn.java index 6dba0c46..0f3b6903 100644 --- a/src/main/java/ognl/ASTNotIn.java +++ b/src/main/java/ognl/ASTNotIn.java @@ -1,43 +1,29 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTNotIn extends SimpleNode implements NodeType -{ +public class ASTNotIn extends SimpleNode implements NodeType { + + private static final long serialVersionUID = -7179506923293705885L; + public ASTNotIn(int id) { super(id); } @@ -46,49 +32,38 @@ public ASTNotIn(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.in( v1, v2 )? Boolean.FALSE : Boolean.TRUE; + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.in(v1, v2) ? Boolean.FALSE : Boolean.TRUE; } - public String toString() - { - return _children[0] + " not in " + _children[1]; + public String toString() { + return children[0] + " not in " + children[1]; } - public Class getGetterClass() - { + public Class getGetterClass() { return Boolean.TYPE; } - public Class getSetterClass() - { + public Class getSetterClass() { return null; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { try { String result = "(! ognl.OgnlOps.in( ($w) "; - - result += OgnlRuntime.getChildSource(context, target, _children[0]) + ", ($w) " + OgnlRuntime.getChildSource(context, target, _children[1]); - + result += OgnlRuntime.getChildSource(context, target, children[0]) + ", ($w) " + OgnlRuntime.getChildSource(context, target, children[1]); result += ") )"; - context.setCurrentType(Boolean.TYPE); - return result; } catch (NullPointerException e) { - // expected to happen in some instances e.printStackTrace(); - throw new UnsupportedCompilationException("evaluation resulted in null expression."); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } + } diff --git a/src/main/java/ognl/ASTOr.java b/src/main/java/ognl/ASTOr.java index 7afd537b..0b53fda6 100644 --- a/src/main/java/ognl/ASTOr.java +++ b/src/main/java/ognl/ASTOr.java @@ -1,141 +1,113 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; import ognl.enhance.UnsupportedCompilationException; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ public class ASTOr extends BooleanExpression { - public ASTOr(int id) - { + + private static final long serialVersionUID = -5221348144886054097L; + + public ASTOr(int id) { super(id); } - public ASTOr(OgnlParser p, int id) - { + public ASTOr(OgnlParser p, int id) { super(p, id); } - public void jjtClose() - { + public void jjtClose() { flattenTree(); } - protected Object getValueBody(OgnlContext context, Object source) throws OgnlException - { + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { Object result = null; - int last = _children.length - 1; + int last = children.length - 1; for (int i = 0; i <= last; ++i) { - result = _children[i].getValue(context, source); + result = children[i].getValue(context, source); if (i != last && OgnlOps.booleanValue(result)) break; } return result; } - protected void setValueBody(OgnlContext context, Object target, Object value) throws OgnlException - { - int last = _children.length - 1; + protected void setValueBody(OgnlContext context, Object target, Object value) throws OgnlException { + int last = children.length - 1; for (int i = 0; i < last; ++i) { - Object v = _children[i].getValue(context, target); + Object v = children[i].getValue(context, target); if (OgnlOps.booleanValue(v)) return; } - _children[last].setValue(context, target, value); + children[last].setValue(context, target, value); } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "||"; } - public Class getGetterClass() - { + public Class getGetterClass() { return null; } - public String toGetSourceString(OgnlContext context, Object target) - { - if (_children.length != 2) + public String toGetSourceString(OgnlContext context, Object target) { + if (children.length != 2) throw new UnsupportedCompilationException("Can only compile boolean expressions with two children."); String result = "("; try { - String first = OgnlRuntime.getChildSource(context, target, _children[0]); + String first = OgnlRuntime.getChildSource(context, target, children[0]); if (!OgnlRuntime.isBoolean(first)) first = OgnlRuntime.getCompiler().createLocalReference(context, first, context.getCurrentType()); - - Class firstType = context.getCurrentType(); - String second = OgnlRuntime.getChildSource(context, target, _children[1]); + Class firstType = context.getCurrentType(); + + String second = OgnlRuntime.getChildSource(context, target, children[1]); if (!OgnlRuntime.isBoolean(second)) second = OgnlRuntime.getCompiler().createLocalReference(context, second, context.getCurrentType()); - Class secondType = context.getCurrentType(); + Class secondType = context.getCurrentType(); boolean mismatched = (firstType.isPrimitive() && !secondType.isPrimitive()) - || (!firstType.isPrimitive() && secondType.isPrimitive()) ? true : false; + || (!firstType.isPrimitive() && secondType.isPrimitive()); result += "ognl.OgnlOps.booleanValue(" + first + ")"; - result += " ? "; - result += (mismatched ? " ($w) " : "") + first; - result += " : "; - result += (mismatched ? " ($w) " : "") + second; - result += ")"; context.setCurrentObject(target); context.setCurrentType(Boolean.TYPE); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } return result; } - public String toSetSourceString(OgnlContext context, Object target) - { - if (_children.length != 2) + public String toSetSourceString(OgnlContext context, Object target) { + if (children.length != 2) throw new UnsupportedCompilationException("Can only compile boolean expressions with two children."); String pre = (String) context.get("_currentChain"); @@ -146,17 +118,17 @@ public String toSetSourceString(OgnlContext context, Object target) try { - _children[0].getValue(context, target); + children[0].getValue(context, target); - String first = ExpressionCompiler.getRootExpression(_children[0], context.getRoot(), context) - + pre + _children[0].toGetSourceString(context, target); + String first = ExpressionCompiler.getRootExpression(children[0], context.getRoot(), context) + + pre + children[0].toGetSourceString(context, target); if (!OgnlRuntime.isBoolean(first)) first = OgnlRuntime.getCompiler().createLocalReference(context, first, Object.class); - _children[1].getValue(context, target); - - String second = ExpressionCompiler.getRootExpression(_children[1], context.getRoot(), context) - + pre + _children[1].toSetSourceString(context, target); + children[1].getValue(context, target); + + String second = ExpressionCompiler.getRootExpression(children[1], context.getRoot(), context) + + pre + children[1].toSetSourceString(context, target); if (!OgnlRuntime.isBoolean(second)) second = OgnlRuntime.getCompiler().createLocalReference(context, second, context.getCurrentType()); @@ -173,8 +145,7 @@ public String toSetSourceString(OgnlContext context, Object target) context.setCurrentType(Boolean.TYPE); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } diff --git a/src/main/java/ognl/ASTProject.java b/src/main/java/ognl/ASTProject.java index 3034b9c9..3ec321cd 100644 --- a/src/main/java/ognl/ASTProject.java +++ b/src/main/java/ognl/ASTProject.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; @@ -36,51 +24,41 @@ import java.util.Enumeration; import java.util.List; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTProject extends SimpleNode -{ +public class ASTProject extends SimpleNode { - public ASTProject(int id) - { + private static final long serialVersionUID = 2768334664377467301L; + + public ASTProject(int id) { super(id); } - public ASTProject(OgnlParser p, int id) - { + public ASTProject(OgnlParser p, int id) { super(p, id); } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { - Node expr = _children[0]; - List answer = new ArrayList(); + throws OgnlException { + Node expr = children[0]; + List answer = new ArrayList<>(); ElementsAccessor elementsAccessor = OgnlRuntime.getElementsAccessor(OgnlRuntime.getTargetClass(source)); - for(Enumeration e = elementsAccessor.getElements(source); e.hasMoreElements();) { - + for (Enumeration e = elementsAccessor.getElements(source); e.hasMoreElements(); ) { answer.add(expr.getValue(context, e.nextElement())); } return answer; } - public String toString() - { - return "{ " + _children[0] + " }"; + public String toString() { + return "{ " + children[0] + " }"; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Projection expressions not supported as native java yet."); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Projection expressions not supported as native java yet."); } } diff --git a/src/main/java/ognl/ASTProperty.java b/src/main/java/ognl/ASTProperty.java index 2e1afa6e..6c309da0 100644 --- a/src/main/java/ognl/ASTProperty.java +++ b/src/main/java/ognl/ASTProperty.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; @@ -38,90 +26,75 @@ import java.lang.reflect.Method; import java.util.Iterator; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTProperty extends SimpleNode implements NodeType -{ - private boolean _indexedAccess = false; +public class ASTProperty extends SimpleNode implements NodeType { + + private static final long serialVersionUID = -7755110504199540734L; - private Class _getterClass; - private Class _setterClass; + private boolean indexedAccess = false; + private Class getterClass; + private Class setterClass; - public ASTProperty(int id) - { + public ASTProperty(int id) { super(id); } - public void setIndexedAccess(boolean value) - { - _indexedAccess = value; + public void setIndexedAccess(boolean value) { + indexedAccess = value; } /** * Returns true if this property is itself an index reference. - * + * * @return true if this property is an index reference, false otherwise. */ - public boolean isIndexedAccess() - { - return _indexedAccess; + public boolean isIndexedAccess() { + return indexedAccess; } /** * Returns true if this property is described by an IndexedPropertyDescriptor and that if * followed by an index specifier it will call the index get/set methods rather than go through * property accessors. - * - * @param context the OgnlContext within which to perform the operation. - * @param source the Object (indexed property) from which to retrieve the indexed property type. + * + * @param context the OgnlContext within which to perform the operation. + * @param source the Object (indexed property) from which to retrieve the indexed property type. * @return the int representing the indexed property type of source. * @throws OgnlException if source is not an indexed property. */ public int getIndexedPropertyType(OgnlContext context, Object source) - throws OgnlException - { - Class type = context.getCurrentType(); - Class prevType = context.getPreviousType(); - try - { - if (!isIndexedAccess()) - { + throws OgnlException { + Class type = context.getCurrentType(); + Class prevType = context.getPreviousType(); + try { + if (!isIndexedAccess()) { Object property = getProperty(context, source); - if (property instanceof String) - { - return OgnlRuntime.getIndexedPropertyType(context, (source == null) + if (property instanceof String) { + return OgnlRuntime.getIndexedPropertyType((source == null) ? null : OgnlRuntime.getCompiler().getInterfaceClass(source.getClass()), (String) property); } } return OgnlRuntime.INDEXED_PROPERTY_NONE; - } finally - { + } finally { context.setCurrentObject(source); context.setCurrentType(type); context.setPreviousType(prevType); } } - public Object getProperty(OgnlContext context, Object source) - throws OgnlException - { - return _children[0].getValue(context, context.getRoot()); + public Object getProperty(OgnlContext context, Object source) throws OgnlException { + return children[0].getValue(context, context.getRoot()); } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { + throws OgnlException { Object property = getProperty(context, source); Object result = OgnlRuntime.getProperty(context, source, property); - if (result == null) - { + if (result == null) { result = OgnlRuntime.getNullHandler(OgnlRuntime.getTargetClass(source)).nullPropertyValue(context, source, property); } @@ -129,43 +102,35 @@ protected Object getValueBody(OgnlContext context, Object source) } protected void setValueBody(OgnlContext context, Object target, Object value) - throws OgnlException - { + throws OgnlException { OgnlRuntime.setProperty(context, target, getProperty(context, target), value); } public boolean isNodeSimpleProperty(OgnlContext context) - throws OgnlException - { - return (_children != null) && (_children.length == 1) && ((SimpleNode) _children[0]).isConstant(context); + throws OgnlException { + return (children != null) && (children.length == 1) && ((SimpleNode) children[0]).isConstant(context); } - public Class getGetterClass() - { - return _getterClass; + public Class getGetterClass() { + return getterClass; } - public Class getSetterClass() - { - return _setterClass; + public Class getSetterClass() { + return setterClass; } - public String toString() - { + public String toString() { String result; - if (isIndexedAccess()) - { - result = "[" + _children[0] + "]"; - } else - { - result = ((ASTConst) _children[0]).getValue().toString(); + if (isIndexedAccess()) { + result = "[" + children[0] + "]"; + } else { + result = ((ASTConst) children[0]).getValue().toString(); } return result; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { if (context.getCurrentObject() == null) throw new UnsupportedCompilationException("Current target is null."); @@ -176,52 +141,48 @@ public String toGetSourceString(OgnlContext context, Object target) /* System.out.println("astproperty is indexed? : " + isIndexedAccess() + " child: " + _children[0].getClass().getName() + " target: " + target.getClass().getName() + " current object: " + context.getCurrentObject().getClass().getName());*/ - if (isIndexedAccess()) - { - Object value = _children[0].getValue(context, context.getRoot()); + if (isIndexedAccess()) { + Object value = children[0].getValue(context, context.getRoot()); if (value == null || DynamicSubscript.class.isAssignableFrom(value.getClass())) throw new UnsupportedCompilationException("Value passed as indexed property was null or not supported."); // Get root cast string if the child is a type that needs it (like a nested ASTProperty) - String srcString = _children[0].toGetSourceString(context, context.getRoot()); - srcString = ExpressionCompiler.getRootExpression(_children[0], context.getRoot(), context) + srcString; + String srcString = children[0].toGetSourceString(context, context.getRoot()); + srcString = ExpressionCompiler.getRootExpression(children[0], context.getRoot(), context) + srcString; - if (ASTChain.class.isInstance(_children[0])) - { - String cast = (String)context.remove(ExpressionCompiler.PRE_CAST); + if (children[0] instanceof ASTChain) { + String cast = (String) context.remove(ExpressionCompiler.PRE_CAST); if (cast != null) srcString = cast + srcString; } - if (ASTConst.class.isInstance(_children[0]) && String.class.isInstance(context.getCurrentObject())) + if (children[0] instanceof ASTConst && context.getCurrentObject() instanceof String) srcString = "\"" + srcString + "\""; // System.out.println("indexed getting with child srcString: " + srcString + " value class: " + value.getClass() + " and child: " + _children[0].getClass()); - if (context.get("_indexedMethod") != null) - { - m = (Method)context.remove("_indexedMethod"); - _getterClass = m.getReturnType(); + if (context.get("_indexedMethod") != null) { + m = (Method) context.remove("_indexedMethod"); + getterClass = m.getReturnType(); Object indexedValue = OgnlRuntime.callMethod(context, target, m.getName(), new Object[]{value}); - context.setCurrentType(_getterClass); + context.setCurrentType(getterClass); context.setCurrentObject(indexedValue); context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); return "." + m.getName() + "(" + srcString + ")"; - } else - { + } else { PropertyAccessor p = OgnlRuntime.getPropertyAccessor(target.getClass()); // System.out.println("child value : " + _children[0].getValue(context, context.getCurrentObject()) + " using propaccessor " + p.getClass().getName() // + " and srcString " + srcString + " on target: " + target); Object currObj = context.getCurrentObject(); - Class currType = context.getCurrentType(); - Class prevType = context.getPreviousType(); + Class currType = context.getCurrentType(); + Class prevType = context.getPreviousType(); Object indexVal = p.getProperty(context, target, value); @@ -231,43 +192,32 @@ public String toGetSourceString(OgnlContext context, Object target) context.setCurrentType(currType); context.setPreviousType(prevType); -/* System.out.println("astprop srcString: " + srcString - + " from child class " + _children[0].getClass().getName() - + " and indexVal " + indexVal - + " propertyAccessor : " + p.getClass().getName() + " context obj " + context.getCurrentObject() - + " context obj is array? : " + context.getCurrentObject().getClass().isArray() - + " current type: " + context.getCurrentType());*/ - - if (ASTConst.class.isInstance(_children[0]) && Number.class.isInstance(context.getCurrentObject())) + if (children[0] instanceof ASTConst && context.getCurrentObject() instanceof Number) context.setCurrentType(OgnlRuntime.getPrimitiveWrapperClass(context.getCurrentObject().getClass())); result = p.getSourceAccessor(context, target, srcString); - _getterClass = context.getCurrentType(); + getterClass = context.getCurrentType(); context.setCurrentObject(indexVal); return result; } } - String name = ((ASTConst) _children[0]).getValue().toString(); + String name = ((ASTConst) children[0]).getValue().toString(); if (!Iterator.class.isAssignableFrom(context.getCurrentObject().getClass()) - || (Iterator.class.isAssignableFrom(context.getCurrentObject().getClass()) && name.indexOf("next") < 0)) - { + || (Iterator.class.isAssignableFrom(context.getCurrentObject().getClass()) && !name.contains("next"))) { Object currObj = target; - try - { + try { target = getValue(context, context.getCurrentObject()); - } catch (NoSuchPropertyException e) - { + } catch (NoSuchPropertyException e) { try { target = getValue(context, context.getRoot()); } catch (NoSuchPropertyException ex) { // ignore } - } finally - { + } finally { context.setCurrentObject(currObj); } } @@ -275,39 +225,32 @@ public String toGetSourceString(OgnlContext context, Object target) PropertyDescriptor pd = OgnlRuntime.getPropertyDescriptor(context.getCurrentObject().getClass(), name); if (pd != null && pd.getReadMethod() != null - && !context.getMemberAccess().isAccessible(context, context.getCurrentObject(), pd.getReadMethod(), name)) - { + && !context.getMemberAccess().isAccessible(context, context.getCurrentObject(), pd.getReadMethod(), name)) { throw new UnsupportedCompilationException("Member access forbidden for property " + name + " on class " + context.getCurrentObject().getClass()); } - if (this.getIndexedPropertyType(context, context.getCurrentObject()) > 0 && pd != null) - { + if (this.getIndexedPropertyType(context, context.getCurrentObject()) > 0 && pd != null) { // if an indexed method accessor need to use special property descriptors to find methods - if (pd instanceof IndexedPropertyDescriptor) - { + if (pd instanceof IndexedPropertyDescriptor) { m = ((IndexedPropertyDescriptor) pd).getIndexedReadMethod(); - } else - { + } else { if (pd instanceof ObjectIndexedPropertyDescriptor) m = ((ObjectIndexedPropertyDescriptor) pd).getIndexedReadMethod(); else throw new OgnlException("property '" + name + "' is not an indexed property"); } - if (_parent == null) - { + if (parent == null) { // the above pd will be the wrong result sometimes, such as methods like getValue(int) vs String[] getValue() m = OgnlRuntime.getReadMethod(context.getCurrentObject().getClass(), name); result = m.getName() + "()"; - _getterClass = m.getReturnType(); - } else - { + getterClass = m.getReturnType(); + } else { context.put("_indexedMethod", m); } - } else - { + } else { /* System.out.println("astproperty trying to get " + name + " on object target: " + context.getCurrentObject().getClass().getName() + " current type " + context.getCurrentType() + " current accessor " + context.getCurrentAccessor() @@ -315,41 +258,34 @@ public String toGetSourceString(OgnlContext context, Object target) PropertyAccessor pa = OgnlRuntime.getPropertyAccessor(context.getCurrentObject().getClass()); - if (context.getCurrentObject().getClass().isArray()) - { - if (pd == null) - { + if (context.getCurrentObject().getClass().isArray()) { + if (pd == null) { pd = OgnlRuntime.getProperty(context.getCurrentObject().getClass(), name); - if (pd != null && pd.getReadMethod() != null) - { + if (pd != null && pd.getReadMethod() != null) { m = pd.getReadMethod(); result = pd.getName(); - } else - { - _getterClass = int.class; + } else { + getterClass = int.class; context.setCurrentAccessor(context.getCurrentObject().getClass()); context.setCurrentType(int.class); result = "." + name; } } - } else - { - if (pd != null && pd.getReadMethod() != null) - { + } else { + if (pd != null && pd.getReadMethod() != null) { m = pd.getReadMethod(); result = "." + m.getName() + "()"; - } else if (pa != null) - { + } else if (pa != null) { Object currObj = context.getCurrentObject(); - Class currType = context.getCurrentType(); - Class prevType = context.getPreviousType(); + Class currType = context.getCurrentType(); + Class prevType = context.getPreviousType(); - String srcString = _children[0].toGetSourceString(context, context.getRoot()); + String srcString = children[0].toGetSourceString(context, context.getRoot()); - if (ASTConst.class.isInstance(_children[0]) && - String.class.isInstance(context.getCurrentObject())) + if (children[0] instanceof ASTConst && context.getCurrentObject() instanceof String) { srcString = "\"" + srcString + "\""; + } context.setCurrentObject(currObj); context.setCurrentType(currType); @@ -357,21 +293,19 @@ public String toGetSourceString(OgnlContext context, Object target) result = pa.getSourceAccessor(context, context.getCurrentObject(), srcString); - _getterClass = context.getCurrentType(); + getterClass = context.getCurrentType(); } } } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } // set known property types for NodeType interface when possible - if (m != null) - { - _getterClass = m.getReturnType(); + if (m != null) { + getterClass = m.getReturnType(); context.setCurrentType(m.getReturnType()); context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); @@ -382,21 +316,17 @@ public String toGetSourceString(OgnlContext context, Object target) return result; } - Method getIndexedWriteMethod(PropertyDescriptor pd) - { - if (IndexedPropertyDescriptor.class.isInstance(pd)) - { - return ((IndexedPropertyDescriptor)pd).getIndexedWriteMethod(); - } else if (ObjectIndexedPropertyDescriptor.class.isInstance(pd)) - { - return ((ObjectIndexedPropertyDescriptor)pd).getIndexedWriteMethod(); + Method getIndexedWriteMethod(PropertyDescriptor pd) { + if (pd instanceof IndexedPropertyDescriptor) { + return ((IndexedPropertyDescriptor) pd).getIndexedWriteMethod(); + } else if (pd instanceof ObjectIndexedPropertyDescriptor) { + return ((ObjectIndexedPropertyDescriptor) pd).getIndexedWriteMethod(); } return null; } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { String result = ""; Method m = null; @@ -408,67 +338,60 @@ public String toSetSourceString(OgnlContext context, Object target) try { - if (isIndexedAccess()) - { - Object value = _children[0].getValue(context, context.getRoot()); + if (isIndexedAccess()) { + Object value = children[0].getValue(context, context.getRoot()); if (value == null) throw new UnsupportedCompilationException("Value passed as indexed property is null, can't enhance statement to bytecode."); - String srcString = _children[0].toGetSourceString(context, context.getRoot()); - srcString = ExpressionCompiler.getRootExpression(_children[0], context.getRoot(), context) + srcString; + String srcString = children[0].toGetSourceString(context, context.getRoot()); + srcString = ExpressionCompiler.getRootExpression(children[0], context.getRoot(), context) + srcString; - if (ASTChain.class.isInstance(_children[0])) - { - String cast = (String)context.remove(ExpressionCompiler.PRE_CAST); + if (children[0] instanceof ASTChain) { + String cast = (String) context.remove(ExpressionCompiler.PRE_CAST); if (cast != null) srcString = cast + srcString; } - if (ASTConst.class.isInstance(_children[0]) && String.class.isInstance(context.getCurrentObject())) - { + if (children[0] instanceof ASTConst && context.getCurrentObject() instanceof String) { srcString = "\"" + srcString + "\""; } // System.out.println("astproperty setter using indexed value " + value + " and srcString: " + srcString); - if (context.get("_indexedMethod") != null) - { - m = (Method)context.remove("_indexedMethod"); - PropertyDescriptor pd = (PropertyDescriptor)context.remove("_indexedDescriptor"); + if (context.get("_indexedMethod") != null) { + m = (Method) context.remove("_indexedMethod"); + PropertyDescriptor pd = (PropertyDescriptor) context.remove("_indexedDescriptor"); boolean lastChild = lastChild(context); - if (lastChild) - { + if (lastChild) { m = getIndexedWriteMethod(pd); if (m == null) throw new UnsupportedCompilationException("Indexed property has no corresponding write method."); } - _setterClass = m.getParameterTypes()[0]; + setterClass = m.getParameterTypes()[0]; Object indexedValue = null; if (!lastChild) indexedValue = OgnlRuntime.callMethod(context, target, m.getName(), new Object[]{value}); - context.setCurrentType(_setterClass); + context.setCurrentType(setterClass); context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); - if (!lastChild) - { + if (!lastChild) { context.setCurrentObject(indexedValue); return "." + m.getName() + "(" + srcString + ")"; } else { return "." + m.getName() + "(" + srcString + ", $3)"; } - } else - { + } else { PropertyAccessor p = OgnlRuntime.getPropertyAccessor(target.getClass()); Object currObj = context.getCurrentObject(); - Class currType = context.getCurrentType(); - Class prevType = context.getPreviousType(); + Class currType = context.getCurrentType(); + Class prevType = context.getPreviousType(); Object indexVal = p.getProperty(context, target, value); @@ -478,39 +401,24 @@ public String toSetSourceString(OgnlContext context, Object target) context.setCurrentType(currType); context.setPreviousType(prevType); - if (ASTConst.class.isInstance(_children[0]) && Number.class.isInstance(context.getCurrentObject())) + if (children[0] instanceof ASTConst && context.getCurrentObject() instanceof Number) context.setCurrentType(OgnlRuntime.getPrimitiveWrapperClass(context.getCurrentObject().getClass())); result = lastChild(context) ? p.getSourceSetter(context, target, srcString) : p.getSourceAccessor(context, target, srcString); - /*System.out.println("ASTProperty using propertyaccessor and isLastChild? " + lastChild(context) - + " generated source of: " + result + " using accessor class: " + p.getClass().getName());*/ - - //result = p.getSourceAccessor(context, target, srcString); - _getterClass = context.getCurrentType(); + getterClass = context.getCurrentType(); context.setCurrentObject(indexVal); - /* PropertyAccessor p = OgnlRuntime.getPropertyAccessor(target.getClass()); - - if (ASTConst.class.isInstance(_children[0]) && Number.class.isInstance(context.getCurrentObject())) - { - context.setCurrentType(OgnlRuntime.getPrimitiveWrapperClass(context.getCurrentObject().getClass())); - } - - result = p.getSourceSetter(context, target, srcString); - - context.setCurrentObject(value); - context.setCurrentType(_getterClass);*/ return result; } } - String name = ((ASTConst) _children[0]).getValue().toString(); + String name = ((ASTConst) children[0]).getValue().toString(); // System.out.println(" astprop(setter) : trying to set " + name + " on object target " + context.getCurrentObject().getClass().getName()); if (!Iterator.class.isAssignableFrom(context.getCurrentObject().getClass()) - || (Iterator.class.isAssignableFrom(context.getCurrentObject().getClass()) && name.indexOf("next") < 0)) { + || (Iterator.class.isAssignableFrom(context.getCurrentObject().getClass()) && !name.contains("next"))) { Object currObj = target; @@ -518,10 +426,9 @@ public String toSetSourceString(OgnlContext context, Object target) target = getValue(context, context.getCurrentObject()); } catch (NoSuchPropertyException e) { try { - target = getValue(context, context.getRoot()); - - } catch (NoSuchPropertyException ex) { } + } catch (NoSuchPropertyException ignored) { + } } finally { context.setCurrentObject(currObj); @@ -530,49 +437,40 @@ public String toSetSourceString(OgnlContext context, Object target) PropertyDescriptor pd = OgnlRuntime.getPropertyDescriptor(OgnlRuntime.getCompiler().getInterfaceClass(context.getCurrentObject().getClass()), name); - if (pd != null) - { + if (pd != null) { Method pdMethod = lastChild(context) ? pd.getWriteMethod() : pd.getReadMethod(); - if (pdMethod != null && !context.getMemberAccess().isAccessible(context, context.getCurrentObject(), pdMethod, name)) - { + if (pdMethod != null && !context.getMemberAccess().isAccessible(context, context.getCurrentObject(), pdMethod, name)) { throw new UnsupportedCompilationException("Member access forbidden for property " + name + " on class " + context.getCurrentObject().getClass()); } } - if (pd != null && this.getIndexedPropertyType(context, context.getCurrentObject()) > 0) - { + if (pd != null && this.getIndexedPropertyType(context, context.getCurrentObject()) > 0) { // if an indexed method accessor need to use special property descriptors to find methods - if (pd instanceof IndexedPropertyDescriptor) - { - IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor)pd; + if (pd instanceof IndexedPropertyDescriptor) { + IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd; m = lastChild(context) ? ipd.getIndexedWriteMethod() : ipd.getIndexedReadMethod(); - } else - { - if (pd instanceof ObjectIndexedPropertyDescriptor) - { - ObjectIndexedPropertyDescriptor opd = (ObjectIndexedPropertyDescriptor)pd; + } else { + if (pd instanceof ObjectIndexedPropertyDescriptor) { + ObjectIndexedPropertyDescriptor opd = (ObjectIndexedPropertyDescriptor) pd; m = lastChild(context) ? opd.getIndexedWriteMethod() : opd.getIndexedReadMethod(); - } else - { + } else { throw new OgnlException("property '" + name + "' is not an indexed property"); } } - if (_parent == null) - { - // the above pd will be the wrong result sometimes, such as methods like getValue(int) vs String[] getValue() + if (parent == null) { + // the above pd will be the wrong result sometimes, such as methods like getValue(int) vs String[] getValue() m = OgnlRuntime.getWriteMethod(context.getCurrentObject().getClass(), name); - Class parm = m.getParameterTypes()[0]; + Class parm = m.getParameterTypes()[0]; String cast = parm.isArray() ? ExpressionCompiler.getCastString(parm) : parm.getName(); result = m.getName() + "((" + cast + ")$3)"; - _setterClass = parm; - } else - { + setterClass = parm; + } else { context.put("_indexedMethod", m); context.put("_indexedDescriptor", pd); } @@ -584,27 +482,22 @@ public String toSetSourceString(OgnlContext context, Object target) + " using propertyaccessor type: " + pa);*/ if (target != null) - _setterClass = target.getClass(); + setterClass = target.getClass(); - if (_parent != null && pd != null && pa == null) - { + if (parent != null && pd != null && pa == null) { m = pd.getReadMethod(); result = m.getName() + "()"; - } else - { - if (context.getCurrentObject().getClass().isArray()) - { + } else { + if (context.getCurrentObject().getClass().isArray()) { result = ""; - } else if (pa != null) - { + } else if (pa != null) { Object currObj = context.getCurrentObject(); //Class currType = context.getCurrentType(); //Class prevType = context.getPreviousType(); - String srcString = _children[0].toGetSourceString(context, context.getRoot()); + String srcString = children[0].toGetSourceString(context, context.getRoot()); - if (ASTConst.class.isInstance(_children[0]) && String.class.isInstance(context.getCurrentObject())) - { + if (children[0] instanceof ASTConst && context.getCurrentObject() instanceof String) { srcString = "\"" + srcString + "\""; } @@ -612,28 +505,24 @@ public String toSetSourceString(OgnlContext context, Object target) //context.setCurrentType(currType); //context.setPreviousType(prevType); - if (!lastChild(context)) - { + if (!lastChild(context)) { result = pa.getSourceAccessor(context, context.getCurrentObject(), srcString); - } else - { + } else { result = pa.getSourceSetter(context, context.getCurrentObject(), srcString); } - _getterClass = context.getCurrentType(); + getterClass = context.getCurrentType(); } } } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } context.setCurrentObject(target); - if (m != null) - { + if (m != null) { context.setCurrentType(m.getReturnType()); context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); } diff --git a/src/main/java/ognl/ASTRemainder.java b/src/main/java/ognl/ASTRemainder.java index 999bd799..65e6f80e 100644 --- a/src/main/java/ognl/ASTRemainder.java +++ b/src/main/java/ognl/ASTRemainder.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTRemainder extends NumericExpression -{ +public class ASTRemainder extends NumericExpression { + + private static final long serialVersionUID = -7872347798983239086L; + public ASTRemainder(int id) { super(id); } @@ -44,15 +30,13 @@ public ASTRemainder(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.remainder( v1, v2 ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.remainder(v1, v2); } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "%"; } } diff --git a/src/main/java/ognl/ASTRootVarRef.java b/src/main/java/ognl/ASTRootVarRef.java index 48106457..8a91604b 100644 --- a/src/main/java/ognl/ASTRootVarRef.java +++ b/src/main/java/ognl/ASTRootVarRef.java @@ -1,89 +1,68 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTRootVarRef extends ASTVarRef -{ - public ASTRootVarRef(int id) - { +public class ASTRootVarRef extends ASTVarRef { + + private static final long serialVersionUID = 5015348645898451815L; + + public ASTRootVarRef(int id) { super(id); } - public ASTRootVarRef(OgnlParser p, int id) - { + public ASTRootVarRef(OgnlParser p, int id) { super(p, id); } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { + throws OgnlException { return context.getRoot(); } protected void setValueBody(OgnlContext context, Object target, Object value) - throws OgnlException - { + throws OgnlException { context.setRoot(value); } - public String toString() - { + public String toString() { return "#root"; } - - public String toGetSourceString(OgnlContext context, Object target) - { + + public String toGetSourceString(OgnlContext context, Object target) { if (target != null) - _getterClass = target.getClass(); - - if (_getterClass != null) { - - context.setCurrentType(_getterClass); + getterClass = target.getClass(); + + if (getterClass != null) { + + context.setCurrentType(getterClass); } - if (_parent == null || (_getterClass != null && _getterClass.isArray())) + if (parent == null || (getterClass != null && getterClass.isArray())) return ""; else return ExpressionCompiler.getRootExpression(this, target, context); } - - public String toSetSourceString(OgnlContext context, Object target) - { - if (_parent == null || (_getterClass != null && _getterClass.isArray())) + + public String toSetSourceString(OgnlContext context, Object target) { + if (parent == null || (getterClass != null && getterClass.isArray())) return ""; else return "$3"; diff --git a/src/main/java/ognl/ASTSelect.java b/src/main/java/ognl/ASTSelect.java index d2590de1..827e0612 100644 --- a/src/main/java/ognl/ASTSelect.java +++ b/src/main/java/ognl/ASTSelect.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; @@ -36,52 +24,44 @@ import java.util.Enumeration; import java.util.List; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTSelect extends SimpleNode -{ - public ASTSelect(int id) - { +public class ASTSelect extends SimpleNode { + + private static final long serialVersionUID = 7036346554394321967L; + + public ASTSelect(int id) { super(id); } - public ASTSelect(OgnlParser p, int id) - { + public ASTSelect(OgnlParser p, int id) { super(p, id); } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { - Node expr = _children[0]; - List answer = new ArrayList(); + throws OgnlException { + Node expr = children[0]; + List answer = new ArrayList<>(); ElementsAccessor elementsAccessor = OgnlRuntime.getElementsAccessor(OgnlRuntime.getTargetClass(source)); - for(Enumeration e = elementsAccessor.getElements(source); e.hasMoreElements();) { + for (Enumeration e = elementsAccessor.getElements(source); e.hasMoreElements(); ) { Object next = e.nextElement(); - - if (OgnlOps.booleanValue(expr.getValue(context, next))) + if (OgnlOps.booleanValue(expr.getValue(context, next))) { answer.add(next); + } } return answer; } - public String toString() - { - return "{? " + _children[0] + " }"; + public String toString() { + return "{? " + children[0] + " }"; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Eval expressions not supported as native java yet."); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Eval expressions not supported as native java yet."); } } diff --git a/src/main/java/ognl/ASTSelectFirst.java b/src/main/java/ognl/ASTSelectFirst.java index 9d8c7fb5..d9e2d7b4 100644 --- a/src/main/java/ognl/ASTSelectFirst.java +++ b/src/main/java/ognl/ASTSelectFirst.java @@ -1,33 +1,21 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; @@ -36,12 +24,10 @@ import java.util.Enumeration; import java.util.List; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTSelectFirst extends SimpleNode -{ +public class ASTSelectFirst extends SimpleNode { + + private static final long serialVersionUID = -2454450963927873461L; + public ASTSelectFirst(int id) { super(id); } @@ -50,15 +36,13 @@ public ASTSelectFirst(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Node expr = _children[0]; - List answer = new ArrayList(); - ElementsAccessor elementsAccessor = OgnlRuntime.getElementsAccessor( OgnlRuntime.getTargetClass(source) ); - - for (Enumeration e = elementsAccessor.getElements(source); e.hasMoreElements(); ) { - Object next = e.nextElement(); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Node expr = children[0]; + List answer = new ArrayList<>(); + ElementsAccessor elementsAccessor = OgnlRuntime.getElementsAccessor(OgnlRuntime.getTargetClass(source)); + for (Enumeration e = elementsAccessor.getElements(source); e.hasMoreElements(); ) { + Object next = e.nextElement(); if (OgnlOps.booleanValue(expr.getValue(context, next))) { answer.add(next); break; @@ -67,18 +51,15 @@ protected Object getValueBody( OgnlContext context, Object source ) throws OgnlE return answer; } - public String toString() - { - return "{^ " + _children[0] + " }"; + public String toString() { + return "{^ " + children[0] + " }"; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Eval expressions not supported as native java yet."); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Eval expressions not supported as native java yet."); } } diff --git a/src/main/java/ognl/ASTSelectLast.java b/src/main/java/ognl/ASTSelectLast.java index a1ed057f..b2b12711 100644 --- a/src/main/java/ognl/ASTSelectLast.java +++ b/src/main/java/ognl/ASTSelectLast.java @@ -1,33 +1,21 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; @@ -36,12 +24,10 @@ import java.util.Enumeration; import java.util.List; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTSelectLast extends SimpleNode -{ +public class ASTSelectLast extends SimpleNode { + + private static final long serialVersionUID = 2555624711061241877L; + public ASTSelectLast(int id) { super(id); } @@ -50,14 +36,13 @@ public ASTSelectLast(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Node expr = _children[0]; - List answer = new ArrayList(); - ElementsAccessor elementsAccessor = OgnlRuntime.getElementsAccessor( OgnlRuntime.getTargetClass(source) ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Node expr = children[0]; + List answer = new ArrayList<>(); + ElementsAccessor elementsAccessor = OgnlRuntime.getElementsAccessor(OgnlRuntime.getTargetClass(source)); - for ( Enumeration e = elementsAccessor.getElements(source); e.hasMoreElements(); ) { - Object next = e.nextElement(); + for (Enumeration e = elementsAccessor.getElements(source); e.hasMoreElements(); ) { + Object next = e.nextElement(); if (OgnlOps.booleanValue(expr.getValue(context, next))) { answer.clear(); @@ -67,18 +52,15 @@ protected Object getValueBody( OgnlContext context, Object source ) throws OgnlE return answer; } - public String toString() - { - return "{$ " + _children[0] + " }"; + public String toString() { + return "{$ " + children[0] + " }"; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Eval expressions not supported as native java yet."); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Eval expressions not supported as native java yet."); } } diff --git a/src/main/java/ognl/ASTSequence.java b/src/main/java/ognl/ASTSequence.java index 0e848783..5d4f7ea6 100644 --- a/src/main/java/ognl/ASTSequence.java +++ b/src/main/java/ognl/ASTSequence.java @@ -1,47 +1,33 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; import ognl.enhance.OrderedReturn; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTSequence extends SimpleNode implements NodeType, OrderedReturn -{ - private Class _getterClass; - private String _lastExpression; - private String _coreExpression; +public class ASTSequence extends SimpleNode implements NodeType, OrderedReturn { + + private static final long serialVersionUID = 7862664419715024875L; + + private Class getterClass; + private String lastExpression; + private String coreExpression; public ASTSequence(int id) { super(id); @@ -55,110 +41,94 @@ public void jjtClose() { flattenTree(); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { Object result = null; - for ( int i=0; i < _children.length; ++i ) - { - result = _children[i].getValue( context, source ); + for (Node child : children) { + result = child.getValue(context, source); } - return result; // The result is just the last one we saw. } - protected void setValueBody( OgnlContext context, Object target, Object value ) throws OgnlException { - int last = _children.length - 1; - for ( int i=0; i < last; ++i ) { - _children[i].getValue( context, target ); + protected void setValueBody(OgnlContext context, Object target, Object value) throws OgnlException { + int last = children.length - 1; + for (int i = 0; i < last; ++i) { + children[i].getValue(context, target); } - _children[last].setValue( context, target, value ); + children[last].setValue(context, target, value); } - public Class getGetterClass() - { - return _getterClass; + public Class getGetterClass() { + return getterClass; } - public Class getSetterClass() - { + public Class getSetterClass() { return null; } - public String getLastExpression() - { - return _lastExpression; + public String getLastExpression() { + return lastExpression; } - public String getCoreExpression() - { - return _coreExpression; + public String getCoreExpression() { + return coreExpression; } - public String toString() - { - String result = ""; + public String toString() { + StringBuilder result = new StringBuilder(); - for ( int i=0; i < _children.length; ++i ) { + for (int i = 0; i < children.length; ++i) { if (i > 0) { - result = result + ", "; + result.append(", "); } - result = result + _children[i]; + result.append(children[i]); } - return result; + return result.toString(); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { return ""; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { String result = ""; NodeType _lastType = null; - for (int i = 0; i < _children.length; ++i) - { - //System.out.println("astsequence child : " + _children[i].getClass().getName()); - String seqValue = _children[i].toGetSourceString(context, target); + for (int i = 0; i < children.length; ++i) { + String seqValue = children[i].toGetSourceString(context, target); - if ((i + 1) < _children.length - && ASTOr.class.isInstance(_children[i])) { + if ((i + 1) < children.length && children[i] instanceof ASTOr) { seqValue = "(" + seqValue + ")"; } - if (i > 0 && ASTProperty.class.isInstance(_children[i]) - && seqValue != null && seqValue.trim().length() > 0) - { - String pre = (String)context.get("_currentChain"); - if (pre == null) + if (i > 0 && children[i] instanceof ASTProperty && seqValue != null && seqValue.trim().length() > 0) { + String pre = (String) context.get("_currentChain"); + if (pre == null) { pre = ""; - - seqValue = ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context) + pre + seqValue; + } + seqValue = ExpressionCompiler.getRootExpression(children[i], context.getRoot(), context) + pre + seqValue; context.setCurrentAccessor(context.getRoot().getClass()); } - if ((i + 1) >= _children.length) - { - _coreExpression = result; - _lastExpression = seqValue; + if ((i + 1) >= children.length) { + coreExpression = result; + lastExpression = seqValue; } - if (seqValue != null && seqValue.trim().length() > 0 && (i + 1) < _children.length) + if (seqValue != null && seqValue.trim().length() > 0 && (i + 1) < children.length) { result += seqValue + ";"; - else if (seqValue != null && seqValue.trim().length() > 0) + } else if (seqValue != null && seqValue.trim().length() > 0) { result += seqValue; + } // set last known type from last child with a type - - if (NodeType.class.isInstance(_children[i]) && ((NodeType)_children[i]).getGetterClass() != null) - _lastType = (NodeType)_children[i]; + if (children[i] instanceof NodeType && ((NodeType) children[i]).getGetterClass() != null) { + _lastType = (NodeType) children[i]; + } } - if (_lastType != null) - { - _getterClass = _lastType.getGetterClass(); + if (_lastType != null) { + getterClass = _lastType.getGetterClass(); } return result; diff --git a/src/main/java/ognl/ASTShiftLeft.java b/src/main/java/ognl/ASTShiftLeft.java index 6b58c8a9..d90df75d 100644 --- a/src/main/java/ognl/ASTShiftLeft.java +++ b/src/main/java/ognl/ASTShiftLeft.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTShiftLeft extends NumericExpression -{ +public class ASTShiftLeft extends NumericExpression { + + private static final long serialVersionUID = 7590620928636478693L; + public ASTShiftLeft(int id) { super(id); } @@ -44,15 +30,13 @@ public ASTShiftLeft(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.shiftLeft( v1, v2 ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.shiftLeft(v1, v2); } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "<<"; } } diff --git a/src/main/java/ognl/ASTShiftRight.java b/src/main/java/ognl/ASTShiftRight.java index a5b7ec40..1ad84dcf 100644 --- a/src/main/java/ognl/ASTShiftRight.java +++ b/src/main/java/ognl/ASTShiftRight.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTShiftRight extends NumericExpression -{ +public class ASTShiftRight extends NumericExpression { + + private static final long serialVersionUID = -8536847221411673601L; + public ASTShiftRight(int id) { super(id); } @@ -44,15 +30,13 @@ public ASTShiftRight(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.shiftRight( v1, v2 ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.shiftRight(v1, v2); } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return ">>"; } } diff --git a/src/main/java/ognl/ASTStaticField.java b/src/main/java/ognl/ASTStaticField.java index b2a3ddea..c2c99f0b 100644 --- a/src/main/java/ognl/ASTStaticField.java +++ b/src/main/java/ognl/ASTStaticField.java @@ -1,94 +1,71 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.lang.reflect.Field; import java.lang.reflect.Modifier; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTStaticField extends SimpleNode implements NodeType -{ +public class ASTStaticField extends SimpleNode implements NodeType { + + private static final long serialVersionUID = -6421261547066021884L; private String className; private String fieldName; + private Class getterClass; - private Class _getterClass; - - public ASTStaticField(int id) - { + public ASTStaticField(int id) { super(id); } - public ASTStaticField(OgnlParser p, int id) - { + public ASTStaticField(OgnlParser p, int id) { super(p, id); } - /** Called from parser action. */ - void init(String className, String fieldName) - { + /** + * Called from parser action. + */ + void init(String className, String fieldName) { this.className = className; this.fieldName = fieldName; } - protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { return OgnlRuntime.getStaticField(context, className, fieldName); } public boolean isNodeConstant(OgnlContext context) - throws OgnlException - { + throws OgnlException { boolean result = false; Exception reason = null; try { - Class c = OgnlRuntime.classForName(context, className); + Class c = OgnlRuntime.classForName(context, className); /* - * Check for virtual static field "class"; this cannot interfere with normal static - * fields because it is a reserved word. It is considered constant. - */ - if (fieldName.equals("class")) - { + * Check for virtual static field "class"; this cannot interfere with normal static + * fields because it is a reserved word. It is considered constant. + */ + if (fieldName.equals("class")) { result = true; - } else if (c.isEnum()) - { + } else if (c.isEnum()) { result = true; - } else - { + } else { Field f = OgnlRuntime.getField(c, fieldName); if (f == null) { throw new NoSuchFieldException(fieldName); @@ -99,108 +76,73 @@ public boolean isNodeConstant(OgnlContext context) result = Modifier.isFinal(f.getModifiers()); } - } catch (ClassNotFoundException e) { - reason = e; - } catch (NoSuchFieldException e) { - reason = e; - } catch (SecurityException e) { + } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) { reason = e; } if (reason != null) throw new OgnlException("Could not get static field " + fieldName - + " from class " + className, reason); + + " from class " + className, reason); return result; } - Class getFieldClass(OgnlContext context) - throws OgnlException - { - Exception reason = null; - + private Class getFieldClass(OgnlContext context) throws OgnlException { + Exception reason; try { - Class c = OgnlRuntime.classForName(context, className); + Class c = OgnlRuntime.classForName(context, className); /* - * Check for virtual static field "class"; this cannot interfere with normal static - * fields because it is a reserved word. It is considered constant. - */ - if (fieldName.equals("class")) - { + * Check for virtual static field "class"; this cannot interfere with normal static + * fields because it is a reserved word. It is considered constant. + */ + if (fieldName.equals("class")) { return c; - } else if (c.isEnum()) - { + } else if (c.isEnum()) { return c; - } else - { + } else { Field f = c.getField(fieldName); return f.getType(); } - } catch (ClassNotFoundException e) { - reason = e; - } catch (NoSuchFieldException e) { - reason = e; - } catch (SecurityException e) { + } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) { reason = e; } - if (reason != null) { throw new OgnlException("Could not get static field " + fieldName + " from class " - + className, reason); } - - return null; + throw new OgnlException("Could not get static field " + fieldName + " from class " + className, reason); } - public Class getGetterClass() - { - return _getterClass; + public Class getGetterClass() { + return getterClass; } - public Class getSetterClass() - { - return _getterClass; + public Class getSetterClass() { + return getterClass; } - public String toString() - { + public String toString() { return "@" + className + "@" + fieldName; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { try { - Object obj = OgnlRuntime.getStaticField(context, className, fieldName); - context.setCurrentObject(obj); - - _getterClass = getFieldClass(context); - - context.setCurrentType(_getterClass); - - } catch (Throwable t) - { + getterClass = getFieldClass(context); + context.setCurrentType(getterClass); + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - return className + "." + fieldName; } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { try { - Object obj = OgnlRuntime.getStaticField(context, className, fieldName); - context.setCurrentObject(obj); - - _getterClass = getFieldClass(context); - - context.setCurrentType(_getterClass); - - } catch (Throwable t) - { + getterClass = getFieldClass(context); + context.setCurrentType(getterClass); + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } diff --git a/src/main/java/ognl/ASTStaticMethod.java b/src/main/java/ognl/ASTStaticMethod.java index f27bf1d5..3c487d0e 100644 --- a/src/main/java/ognl/ASTStaticMethod.java +++ b/src/main/java/ognl/ASTStaticMethod.java @@ -1,248 +1,204 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; import ognl.enhance.UnsupportedCompilationException; import java.lang.reflect.Method; +import java.util.Objects; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTStaticMethod extends SimpleNode implements NodeType -{ +public class ASTStaticMethod extends SimpleNode implements NodeType { - private String _className; - private String _methodName; + private static final long serialVersionUID = -116222026971367049L; - private Class _getterClass; + private String className; + private String methodName; + private Class getterClass; - public ASTStaticMethod(int id) - { + public ASTStaticMethod(int id) { super(id); } - public ASTStaticMethod(OgnlParser p, int id) - { + public ASTStaticMethod(OgnlParser p, int id) { super(p, id); } - /** Called from parser action. */ - void init(String className, String methodName) - { - _className = className; - _methodName = methodName; + /** + * Called from parser action. + */ + void init(String className, String methodName) { + this.className = className; + this.methodName = methodName; } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { - Object[] args = OgnlRuntime.getObjectArrayPool().create(jjtGetNumChildren()); + throws OgnlException { + Object[] args = new Object[jjtGetNumChildren()]; Object root = context.getRoot(); - try { - for(int i = 0, icount = args.length; i < icount; ++i) - args[i] = _children[i].getValue(context, root); - - return OgnlRuntime.callStaticMethod(context, _className, _methodName, args); - } finally { - OgnlRuntime.getObjectArrayPool().recycle(args); + for (int i = 0, icount = args.length; i < icount; ++i) { + args[i] = children[i].getValue(context, root); } + + return OgnlRuntime.callStaticMethod(context, className, methodName, args); } - public Class getGetterClass() - { - return _getterClass; + public Class getGetterClass() { + return getterClass; } - public Class getSetterClass() - { - return _getterClass; + public Class getSetterClass() { + return getterClass; } - public String toString() - { - String result = "@" + _className + "@" + _methodName; + public String toString() { + StringBuilder result = new StringBuilder("@" + className + "@" + methodName); - result = result + "("; - if ((_children != null) && (_children.length > 0)) { - for(int i = 0; i < _children.length; i++) { + result.append("("); + if ((children != null) && (children.length > 0)) { + for (int i = 0; i < children.length; i++) { if (i > 0) { - result = result + ", "; + result.append(", "); } - result = result + _children[i]; + result.append(children[i]); } } - result = result + ")"; - return result; + result.append(")"); + return result.toString(); } - public String toGetSourceString(OgnlContext context, Object target) - { - String result = _className + "#" + _methodName + "("; + public String toGetSourceString(OgnlContext context, Object target) { + StringBuilder result = new StringBuilder(className + "#" + methodName + "("); try { - Class clazz = OgnlRuntime.classForName(context, _className); - Method m = OgnlRuntime.getMethod(context, clazz, _methodName, _children, true); + Class clazz = OgnlRuntime.classForName(context, className); + Method m = OgnlRuntime.getMethod(context, clazz, methodName, children, true); - if (clazz == null || m == null) - throw new UnsupportedCompilationException("Unable to find class/method combo " + _className + " / " + _methodName); + if (m == null) { + throw new UnsupportedCompilationException("Unable to find class/method combo " + className + " / " + methodName); + } - if (!context.getMemberAccess().isAccessible(context, clazz, m, _methodName)) - { + if (!context.getMemberAccess().isAccessible(context, clazz, m, methodName)) { throw new UnsupportedCompilationException("Method is not accessible, check your jvm runtime security settings. " + - "For static class method " + _className + " / " + _methodName); + "For static class method " + className + " / " + methodName); } - if ((_children != null) && (_children.length > 0)) - { - Class[] parms = m.getParameterTypes(); + if ((children != null) && (children.length > 0)) { + Class[] parms = m.getParameterTypes(); - for(int i = 0; i < _children.length; i++) - { - if (i > 0) - { - result = result + ", "; + for (int i = 0; i < children.length; i++) { + if (i > 0) { + result.append(", "); } - Class prevType = context.getCurrentType(); + Class prevType = context.getCurrentType(); - Object value = _children[i].getValue(context, context.getRoot()); - String parmString = _children[i].toGetSourceString(context, context.getRoot()); + Object value = children[i].getValue(context, context.getRoot()); + String parmString = children[i].toGetSourceString(context, context.getRoot()); if (parmString == null || parmString.trim().length() < 1) parmString = "null"; // to undo type setting of constants when used as method parameters - if (ASTConst.class.isInstance(_children[i])) - { + if (children[i] instanceof ASTConst) { context.setCurrentType(prevType); } - parmString = ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context) + parmString; + parmString = ExpressionCompiler.getRootExpression(children[i], context.getRoot(), context) + parmString; String cast = ""; - if (ExpressionCompiler.shouldCast(_children[i])) - { - cast = (String)context.remove(ExpressionCompiler.PRE_CAST); + if (ExpressionCompiler.shouldCast(children[i])) { + cast = (String) context.remove(ExpressionCompiler.PRE_CAST); } if (cast == null) cast = ""; - if (!ASTConst.class.isInstance(_children[i])) + if (!(children[i] instanceof ASTConst)) parmString = cast + parmString; - Class valueClass = value != null ? value.getClass() : null; - if (NodeType.class.isAssignableFrom(_children[i].getClass())) - valueClass = ((NodeType)_children[i]).getGetterClass(); + Class valueClass = value != null ? value.getClass() : null; + if (NodeType.class.isAssignableFrom(children[i].getClass())) + valueClass = ((NodeType) children[i]).getGetterClass(); - if (valueClass != parms[i]) - { - if (parms[i].isArray()) - { + if (valueClass != parms[i]) { + if (parms[i].isArray()) { parmString = OgnlRuntime.getCompiler() .createLocalReference(context, - "(" + ExpressionCompiler.getCastString(parms[i]) - + ")ognl.OgnlOps.toArray(" + parmString + ", " + parms[i].getComponentType().getName() - + ".class, true)", - parms[i] + "(" + ExpressionCompiler.getCastString(parms[i]) + + ")ognl.OgnlOps.toArray(" + parmString + ", " + parms[i].getComponentType().getName() + + ".class, true)", + parms[i] ); - } else if (parms[i].isPrimitive()) - { - Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(parms[i]); + } else if (parms[i].isPrimitive()) { + Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(parms[i]); parmString = OgnlRuntime.getCompiler().createLocalReference(context, - "((" + wrapClass.getName() - + ")ognl.OgnlOps.convertValue(" + parmString + "," - + wrapClass.getName() + ".class, true))." - + OgnlRuntime.getNumericValueGetter(wrapClass), - parms[i] + "((" + wrapClass.getName() + + ")ognl.OgnlOps.convertValue(" + parmString + "," + + wrapClass.getName() + ".class, true))." + + OgnlRuntime.getNumericValueGetter(wrapClass), + parms[i] ); - } else if (parms[i] != Object.class) - { + } else if (parms[i] != Object.class) { parmString = OgnlRuntime.getCompiler() .createLocalReference(context, - "(" + parms[i].getName() + ")ognl.OgnlOps.convertValue(" + parmString + "," + parms[i].getName() + ".class)", - parms[i] + "(" + parms[i].getName() + ")ognl.OgnlOps.convertValue(" + parmString + "," + parms[i].getName() + ".class)", + parms[i] ); - } else if ((NodeType.class.isInstance(_children[i]) - && ((NodeType)_children[i]).getGetterClass() != null - && Number.class.isAssignableFrom(((NodeType)_children[i]).getGetterClass())) - || valueClass.isPrimitive()) - { + } else if ((children[i] instanceof NodeType + && ((NodeType) children[i]).getGetterClass() != null + && Number.class.isAssignableFrom(((NodeType) children[i]).getGetterClass())) + || Objects.requireNonNull(valueClass).isPrimitive()) { parmString = " ($w) " + parmString; - } else if (valueClass.isPrimitive()) - { - parmString = "($w) " + parmString; } } - result += parmString; + result.append(parmString); } } - result += ")"; + result.append(")"); - try - { + try { Object contextObj = getValueBody(context, target); context.setCurrentObject(contextObj); - } catch (Throwable t) - { + } catch (Throwable t) { // ignore } - if (m != null) - { - _getterClass = m.getReturnType(); + getterClass = m.getReturnType(); - context.setCurrentType(m.getReturnType()); - context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); - } + context.setCurrentType(m.getReturnType()); + context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - return result; + return result.toString(); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { return toGetSourceString(context, target); } } diff --git a/src/main/java/ognl/ASTSubtract.java b/src/main/java/ognl/ASTSubtract.java index 7dc4e96b..351bb929 100644 --- a/src/main/java/ognl/ASTSubtract.java +++ b/src/main/java/ognl/ASTSubtract.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTSubtract extends NumericExpression -{ +public class ASTSubtract extends NumericExpression { + + private static final long serialVersionUID = -6236738073110752982L; + public ASTSubtract(int id) { super(id); } @@ -44,15 +30,13 @@ public ASTSubtract(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.subtract( v1, v2 ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.subtract(v1, v2); } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "-"; } } diff --git a/src/main/java/ognl/ASTTest.java b/src/main/java/ognl/ASTTest.java index dbd0800a..e90e5417 100644 --- a/src/main/java/ognl/ASTTest.java +++ b/src/main/java/ognl/ASTTest.java @@ -1,43 +1,29 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTTest extends ExpressionNode -{ +public class ASTTest extends ExpressionNode { + + private static final long serialVersionUID = -6924826770978283631L; + public ASTTest(int id) { super(id); } @@ -46,90 +32,77 @@ public ASTTest(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object test = _children[0].getValue( context, source ); - int branch = OgnlOps.booleanValue(test)? 1 : 2; - return _children[branch].getValue( context, source ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object test = children[0].getValue(context, source); + int branch = OgnlOps.booleanValue(test) ? 1 : 2; + return children[branch].getValue(context, source); } - protected void setValueBody( OgnlContext context, Object target, Object value ) throws OgnlException - { - Object test = _children[0].getValue( context, target ); - int branch = OgnlOps.booleanValue(test)? 1 : 2; - _children[branch].setValue( context, target, value ); + protected void setValueBody(OgnlContext context, Object target, Object value) throws OgnlException { + Object test = children[0].getValue(context, target); + int branch = OgnlOps.booleanValue(test) ? 1 : 2; + children[branch].setValue(context, target, value); } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return (index == 1) ? "?" : ":"; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { if (target == null) throw new UnsupportedCompilationException("evaluation resulted in null expression."); - if (_children.length != 3) - throw new UnsupportedCompilationException("Can only compile test expressions with two children." + _children.length); + if (children.length != 3) + throw new UnsupportedCompilationException("Can only compile test expressions with two children." + children.length); String result = ""; try { - String first = OgnlRuntime.getChildSource(context, target, _children[0]); + String first = OgnlRuntime.getChildSource(context, target, children[0]); if (!OgnlRuntime.isBoolean(first) && !context.getCurrentType().isPrimitive()) first = OgnlRuntime.getCompiler().createLocalReference(context, first, context.getCurrentType()); - if (ExpressionNode.class.isInstance(_children[0])) - { + if (children[0] instanceof ExpressionNode) { first = "(" + first + ")"; } - String second = OgnlRuntime.getChildSource(context, target, _children[1]); - Class secondType = context.getCurrentType(); + String second = OgnlRuntime.getChildSource(context, target, children[1]); + Class secondType = context.getCurrentType(); if (!OgnlRuntime.isBoolean(second) && !context.getCurrentType().isPrimitive()) second = OgnlRuntime.getCompiler().createLocalReference(context, second, context.getCurrentType()); - if (ExpressionNode.class.isInstance(_children[1])) - { + if (children[1] instanceof ExpressionNode) { second = "(" + second + ")"; } - String third = OgnlRuntime.getChildSource(context, target, _children[2]); - Class thirdType = context.getCurrentType(); + String third = OgnlRuntime.getChildSource(context, target, children[2]); + Class thirdType = context.getCurrentType(); if (!OgnlRuntime.isBoolean(third) && !context.getCurrentType().isPrimitive()) third = OgnlRuntime.getCompiler().createLocalReference(context, third, context.getCurrentType()); - if (ExpressionNode.class.isInstance(_children[2])) - { + if (children[2] instanceof ExpressionNode) { third = "(" + third + ")"; } boolean mismatched = (secondType.isPrimitive() && !thirdType.isPrimitive()) - || (!secondType.isPrimitive() && thirdType.isPrimitive()) ? true : false; + || (!secondType.isPrimitive() && thirdType.isPrimitive()); result += "ognl.OgnlOps.booleanValue(" + first + ")"; - result += " ? "; - result += (mismatched ? " ($w) " : "") + second; result += " : "; - result += (mismatched ? " ($w) " : "") + third; context.setCurrentObject(target); context.setCurrentType(mismatched ? Object.class : secondType); return result; - } catch (NullPointerException e) { - // expected to happen in some instances throw new UnsupportedCompilationException("evaluation resulted in null expression."); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } diff --git a/src/main/java/ognl/ASTThisVarRef.java b/src/main/java/ognl/ASTThisVarRef.java index f097c7d0..16eaf967 100644 --- a/src/main/java/ognl/ASTThisVarRef.java +++ b/src/main/java/ognl/ASTThisVarRef.java @@ -1,78 +1,54 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTThisVarRef extends ASTVarRef -{ +public class ASTThisVarRef extends ASTVarRef { + + private static final long serialVersionUID = 5225752191165475979L; - public ASTThisVarRef(int id) - { + public ASTThisVarRef(int id) { super(id); } - public ASTThisVarRef(OgnlParser p, int id) - { + public ASTThisVarRef(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { return context.getCurrentObject(); } - protected void setValueBody(OgnlContext context, Object target, Object value) - throws OgnlException - { + protected void setValueBody(OgnlContext context, Object target, Object value) throws OgnlException { context.setCurrentObject(value); } - public String toString() - { + public String toString() { return "#this"; } - - public String toGetSourceString(OgnlContext context, Object target) - { + + public String toGetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Unable to compile this references."); } - - public String toSetSourceString(OgnlContext context, Object target) - { + + public String toSetSourceString(OgnlContext context, Object target) { throw new UnsupportedCompilationException("Unable to compile this references."); } } diff --git a/src/main/java/ognl/ASTUnsignedShiftRight.java b/src/main/java/ognl/ASTUnsignedShiftRight.java index 8a1d0183..fa5ef85a 100644 --- a/src/main/java/ognl/ASTUnsignedShiftRight.java +++ b/src/main/java/ognl/ASTUnsignedShiftRight.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTUnsignedShiftRight extends NumericExpression -{ +public class ASTUnsignedShiftRight extends NumericExpression { + + private static final long serialVersionUID = 7787910329305946213L; + public ASTUnsignedShiftRight(int id) { super(id); } @@ -44,35 +30,30 @@ public ASTUnsignedShiftRight(OgnlParser p, int id) { super(p, id); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object v1 = _children[0].getValue( context, source ); - Object v2 = _children[1].getValue( context, source ); - return OgnlOps.unsignedShiftRight( v1, v2 ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object v1 = children[0].getValue(context, source); + Object v2 = children[1].getValue(context, source); + return OgnlOps.unsignedShiftRight(v1, v2); } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return ">>>"; } - public String toGetSourceString(OgnlContext context, Object target) - { - String result = ""; + public String toGetSourceString(OgnlContext context, Object target) { + String result; try { + String child1 = OgnlRuntime.getChildSource(context, target, children[0]); + child1 = coerceToNumeric(child1, context, children[0]); - String child1 = OgnlRuntime.getChildSource(context, target, _children[0]); - child1 = coerceToNumeric(child1, context, _children[0]); - - String child2 = OgnlRuntime.getChildSource(context, target, _children[1]); - child2 = coerceToNumeric(child2, context, _children[1]); + String child2 = OgnlRuntime.getChildSource(context, target, children[1]); + child2 = coerceToNumeric(child2, context, children[1]); - Object v1 = _children[0].getValue(context, target); + Object v1 = children[0].getValue(context, target); int type = OgnlOps.getNumericType(v1); - if (type <= OgnlOps.INT) - { + if (type <= OgnlOps.INT) { child1 = "(int)" + child1; child2 = "(int)" + child2; } @@ -81,9 +62,7 @@ public String toGetSourceString(OgnlContext context, Object target) context.setCurrentType(Integer.TYPE); context.setCurrentObject(getValueBody(context, target)); - - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } diff --git a/src/main/java/ognl/ASTVarRef.java b/src/main/java/ognl/ASTVarRef.java index e3f4b2a4..47d44167 100644 --- a/src/main/java/ognl/ASTVarRef.java +++ b/src/main/java/ognl/ASTVarRef.java @@ -1,120 +1,93 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.OrderedReturn; import ognl.enhance.UnsupportedCompilationException; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ public class ASTVarRef extends SimpleNode implements NodeType, OrderedReturn { - private String _name; + private static final long serialVersionUID = -4497407745162564648L; - protected Class _getterClass; + private String name; - protected String _core; - protected String _last; + protected Class getterClass; + protected String core; + protected String last; - public ASTVarRef(int id) - { + public ASTVarRef(int id) { super(id); } - public ASTVarRef(OgnlParser p, int id) - { + public ASTVarRef(OgnlParser p, int id) { super(p, id); } - void setName(String name) - { - this._name = name; + void setName(String name) { + this.name = name; } protected Object getValueBody(OgnlContext context, Object source) - throws OgnlException - { - return context.get(_name); + throws OgnlException { + return context.get(name); } protected void setValueBody(OgnlContext context, Object target, Object value) - throws OgnlException - { - context.put(_name, value); + throws OgnlException { + context.put(name, value); } - public Class getGetterClass() - { - return _getterClass; + public Class getGetterClass() { + return getterClass; } - public Class getSetterClass() - { + public Class getSetterClass() { return null; } - public String getCoreExpression() - { - return _core; + public String getCoreExpression() { + return core; } - public String getLastExpression() - { - return _last; + public String getLastExpression() { + return last; } - public String toString() - { - return "#" + _name; + public String toString() { + return "#" + name; } - public String toGetSourceString(OgnlContext context, Object target) - { - Object value = context.get(_name); + public String toGetSourceString(OgnlContext context, Object target) { + Object value = context.get(name); if (value != null) { - - _getterClass = value.getClass(); + getterClass = value.getClass(); } - context.setCurrentType(_getterClass); + context.setCurrentType(getterClass); context.setCurrentAccessor(context.getClass()); context.setCurrentObject(value); - //context.setRoot(context.get(_name)); - if (context.getCurrentObject() == null) + if (context.getCurrentObject() == null) { throw new UnsupportedCompilationException("Current context object is null, can't compile var reference."); + } String pre = ""; String post = ""; @@ -123,18 +96,17 @@ public String toGetSourceString(OgnlContext context, Object target) post = ")"; } - if (_parent != null && ASTAssign.class.isInstance(_parent)) { - _core = "$1.put(\"" + _name + "\","; - _last = pre + "$1.get(\"" + _name + "\")" + post; + if (parent instanceof ASTAssign) { + core = "$1.put(\"" + name + "\","; + last = pre + "$1.get(\"" + name + "\")" + post; - return _core; + return core; } - return pre + "$1.get(\"" + _name + "\")" + post; + return pre + "$1.get(\"" + name + "\")" + post; } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { return toGetSourceString(context, target); } } diff --git a/src/main/java/ognl/ASTXor.java b/src/main/java/ognl/ASTXor.java index 95a3ce46..fc40a962 100644 --- a/src/main/java/ognl/ASTXor.java +++ b/src/main/java/ognl/ASTXor.java @@ -1,41 +1,27 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public class ASTXor extends NumericExpression -{ +public class ASTXor extends NumericExpression { + + private static final long serialVersionUID = 6774627095887209111L; + public ASTXor(int id) { super(id); } @@ -48,16 +34,14 @@ public void jjtClose() { flattenTree(); } - protected Object getValueBody( OgnlContext context, Object source ) throws OgnlException - { - Object result = _children[0].getValue( context, source ); - for ( int i=1; i < _children.length; ++i ) - result = OgnlOps.binaryXor( result, _children[i].getValue(context, source) ); + protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { + Object result = children[0].getValue(context, source); + for (int i = 1; i < children.length; ++i) + result = OgnlOps.binaryXor(result, children[i].getValue(context, source)); return result; } - public String getExpressionOperator(int index) - { + public String getExpressionOperator(int index) { return "^"; } } diff --git a/src/main/java/ognl/AbstractMemberAccess.java b/src/main/java/ognl/AbstractMemberAccess.java index 1e1ecc14..9bc0b3dc 100644 --- a/src/main/java/ognl/AbstractMemberAccess.java +++ b/src/main/java/ognl/AbstractMemberAccess.java @@ -19,18 +19,17 @@ package ognl; import java.lang.reflect.Member; -import java.util.Map; /** * Used as a based class */ abstract public class AbstractMemberAccess implements MemberAccess { - public Object setup(Map context, Object target, Member member, String propertyName) { + public Object setup(OgnlContext context, Object target, Member member, String propertyName) { return null; } - public void restore(Map context, Object target, Member member, String propertyName, Object state) { + public void restore(OgnlContext context, Object target, Member member, String propertyName, Object state) { } } diff --git a/src/main/java/ognl/AccessibleObjectHandler.java b/src/main/java/ognl/AccessibleObjectHandler.java index 57c75f6d..ffe4738e 100644 --- a/src/main/java/ognl/AccessibleObjectHandler.java +++ b/src/main/java/ognl/AccessibleObjectHandler.java @@ -22,18 +22,17 @@ /** * This interface provides a mechanism for indirect reflection access processing - * of AccessibleObject instances by OGNL. It can be used to provide different - * behaviour as JDK reflection mechanisms evolve. + * of AccessibleObject instances by OGNL. It can be used to provide different + * behaviour as JDK reflection mechanisms evolve. * * @since 3.1.24 */ -public abstract interface AccessibleObjectHandler -{ +public interface AccessibleObjectHandler { /** * Provides an appropriate implementation to change the accessibility of accessibleObject. * * @param accessibleObject the AccessibleObject upon which to apply the flag. - * @param flag the new accessible flag value. + * @param flag the new accessible flag value. */ void setAccessible(AccessibleObject accessibleObject, boolean flag); } diff --git a/src/main/java/ognl/AccessibleObjectHandlerJDK9Plus.java b/src/main/java/ognl/AccessibleObjectHandlerJDK9Plus.java index 2fbe9a4a..80de6107 100644 --- a/src/main/java/ognl/AccessibleObjectHandlerJDK9Plus.java +++ b/src/main/java/ognl/AccessibleObjectHandlerJDK9Plus.java @@ -24,47 +24,47 @@ /** * Utilizes a JDK 9 and later mechanism for changing the accessibility level of a given - * AccessibleObject. - * + * AccessibleObject. + *

* If the JDK 9+ mechanism fails, this class will fall back to a standard pre-JDK 9 reflection mechanism. - * Note: That may cause "WARNING: Illegal reflective access" output to be generated to stdout/stderr. - * + * Note: That may cause "WARNING: Illegal reflective access" output to be generated to stdout/stderr. + *

* For reference, this class draws on information from the following locations: - * - Post about Illegal Reflective Access what is an illegal reflective access - * - Blog on Unsafe Java Magic. Part 4: sun.misc.Unsafe - * - Blog on Unsafe Guide to sun.misc.Unsafe - * - JEP about access to Unsafe being retained in JDK 9 JEP 260: Encapsulate Most Internal APIs - * + * - Post about Illegal Reflective Access what is an illegal reflective access + * - Blog on Unsafe Java Magic. Part 4: sun.misc.Unsafe + * - Blog on Unsafe Guide to sun.misc.Unsafe + * - JEP about access to Unsafe being retained in JDK 9 JEP 260: Encapsulate Most Internal APIs + *

* In addition to the above, inspiration was drawn from Gson: PR 1218, - * PR 1306. - * + * PR 1306. + *

* Appreciation and credit to the authors, contributors and commenters for the information contained in the preceding links. * * @since 3.1.24 */ -class AccessibleObjectHandlerJDK9Plus implements AccessibleObjectHandler -{ - private static final Class _clazzUnsafe = instantiateClazzUnsafe(); - private static final Object _unsafeInstance = instantiateUnsafeInstance(_clazzUnsafe); - private static final Method _unsafeObjectFieldOffsetMethod = instantiateUnsafeObjectFieldOffsetMethod(_clazzUnsafe); - private static final Method _unsafePutBooleanMethod = instantiateUnsafePutBooleanMethod(_clazzUnsafe); - private static final Field _accessibleObjectOverrideField = instantiateAccessibleObjectOverrideField(); - private static final long _accessibleObjectOverrideFieldOffset = determineAccessibleObjectOverrideFieldOffset(); +class AccessibleObjectHandlerJDK9Plus implements AccessibleObjectHandler { + private static final Class CLAZZ_UNSAFE = instantiateClazzUnsafe(); + private static final Object UNSAFE_INSTANCE = instantiateUnsafeInstance(); + private static final Method UNSAFE_OBJECT_FIELD_OFFSET_METHOD = instantiateUnsafeObjectFieldOffsetMethod(); + private static final Method UNSAFE_PUT_BOOLEAN_METHOD = instantiateUnsafePutBooleanMethod(); + private static final Field ACCESSIBLE_OBJECT_OVERRIDE_FIELD = instantiateAccessibleObjectOverrideField(); + private static final long ACCESSIBLE_OBJECT_OVERRIDE_FIELD_OFFSET = determineAccessibleObjectOverrideFieldOffset(); /** * Private constructor */ - private AccessibleObjectHandlerJDK9Plus() {} + private AccessibleObjectHandlerJDK9Plus() { + } /** * Package-accessible method to determine if a given class is Unsafe or a descendant - * of Unsafe. + * of Unsafe. * * @param clazz the Class upon which to perform the unsafe check. * @return true if parameter is Unsafe or a descendant, false otherwise */ - static boolean unsafeOrDescendant(final Class clazz) { - return (_clazzUnsafe != null ? _clazzUnsafe.isAssignableFrom(clazz) : false); + static boolean unsafeOrDescendant(final Class clazz) { + return (CLAZZ_UNSAFE != null && CLAZZ_UNSAFE.isAssignableFrom(clazz)); } /** @@ -72,8 +72,8 @@ static boolean unsafeOrDescendant(final Class clazz) { * * @return class if available, null otherwise */ - private static Class instantiateClazzUnsafe() { - Class clazz; + private static Class instantiateClazzUnsafe() { + Class clazz; try { clazz = Class.forName("sun.misc.Unsafe"); @@ -87,16 +87,15 @@ private static Class instantiateClazzUnsafe() { /** * Instantiate an instance of Unsafe object. * - * @param clazz (expected to be an Unsafe instance) * @return instance if available, null otherwise */ - private static Object instantiateUnsafeInstance(Class clazz) { + private static Object instantiateUnsafeInstance() { Object unsafe; - if (clazz != null) { + if (AccessibleObjectHandlerJDK9Plus.CLAZZ_UNSAFE != null) { Field field = null; try { - field = clazz.getDeclaredField("theUnsafe"); + field = AccessibleObjectHandlerJDK9Plus.CLAZZ_UNSAFE.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = field.get(null); } catch (Throwable t) { @@ -120,15 +119,14 @@ private static Object instantiateUnsafeInstance(Class clazz) { /** * Instantiate an Unsafe.objectFieldOffset() method instance. * - * @param clazz (expected to be an Unsafe instance) * @return method if available, null otherwise */ - private static Method instantiateUnsafeObjectFieldOffsetMethod(Class clazz) { + private static Method instantiateUnsafeObjectFieldOffsetMethod() { Method method; - if (clazz != null) { + if (AccessibleObjectHandlerJDK9Plus.CLAZZ_UNSAFE != null) { try { - method = clazz.getMethod("objectFieldOffset", Field.class); + method = AccessibleObjectHandlerJDK9Plus.CLAZZ_UNSAFE.getMethod("objectFieldOffset", Field.class); } catch (Throwable t) { method = null; } @@ -142,15 +140,14 @@ private static Method instantiateUnsafeObjectFieldOffsetMethod(Class clazz) { /** * Instantiate an Unsafe.putBoolean() method instance. * - * @param clazz (expected to be an Unsafe instance) * @return method if available, null otherwise */ - private static Method instantiateUnsafePutBooleanMethod(Class clazz) { + private static Method instantiateUnsafePutBooleanMethod() { Method method; - if (clazz != null) { + if (AccessibleObjectHandlerJDK9Plus.CLAZZ_UNSAFE != null) { try { - method = clazz.getMethod("putBoolean", Object.class, long.class, boolean.class); + method = AccessibleObjectHandlerJDK9Plus.CLAZZ_UNSAFE.getMethod("putBoolean", Object.class, long.class, boolean.class); } catch (Throwable t) { method = null; } @@ -179,16 +176,16 @@ private static Field instantiateAccessibleObjectOverrideField() { } /** - * Attempt to determined the AccessibleObject override field offset. + * Attempt to determine the AccessibleObject override field offset. * * @return field offset if available, -1 otherwise */ private static long determineAccessibleObjectOverrideFieldOffset() { long offset = -1; - if (_accessibleObjectOverrideField != null && _unsafeObjectFieldOffsetMethod != null && _unsafeInstance != null) { + if (ACCESSIBLE_OBJECT_OVERRIDE_FIELD != null && UNSAFE_OBJECT_FIELD_OFFSET_METHOD != null && UNSAFE_INSTANCE != null) { try { - offset = (Long) _unsafeObjectFieldOffsetMethod.invoke(_unsafeInstance, _accessibleObjectOverrideField); + offset = (Long) UNSAFE_OBJECT_FIELD_OFFSET_METHOD.invoke(UNSAFE_INSTANCE, ACCESSIBLE_OBJECT_OVERRIDE_FIELD); } catch (Throwable t) { // Don't care (offset already -1) } @@ -199,19 +196,18 @@ private static long determineAccessibleObjectOverrideFieldOffset() { /** * Package-level generator of an AccessibleObjectHandlerJDK9Plus instance. - * + *

* Not intended for use outside of the package. - * + *

* Note: An AccessibleObjectHandlerJDK9Plus will only be created if running on a - * JDK9+ and the environment flag is set. Otherwise this method will return - * an AccessibleHandlerPreJDK9 instance instead, + * JDK9+ and the environment flag is set. Otherwise this method will return + * an AccessibleHandlerPreJDK9 instance instead, * * @return an AccessibleObjectHandler instance - * * @since 3.1.24 */ static AccessibleObjectHandler createHandler() { - if (OgnlRuntime.usingJDK9PlusAccessHandler()){ + if (OgnlRuntime.usingJDK9PlusAccessHandler()) { return new AccessibleObjectHandlerJDK9Plus(); } else { return AccessibleObjectHandlerPreJDK9.createHandler(); @@ -220,17 +216,17 @@ static AccessibleObjectHandler createHandler() { /** * Utilize accessibility modification mechanism for JDK 9 (Java Major Version 9) and later. - * Should that mechanism fail, attempt a standard pre-JDK9 accessibility modification. + * Should that mechanism fail, attempt a standard pre-JDK9 accessibility modification. * * @param accessibleObject the AccessibleObject upon which to apply the flag. - * @param flag the new accessible flag value. + * @param flag the new accessible flag value. */ public void setAccessible(AccessibleObject accessibleObject, boolean flag) { boolean operationComplete = false; - if (_unsafeInstance != null && _unsafePutBooleanMethod != null && _accessibleObjectOverrideFieldOffset != -1) { + if (UNSAFE_INSTANCE != null && UNSAFE_PUT_BOOLEAN_METHOD != null && ACCESSIBLE_OBJECT_OVERRIDE_FIELD_OFFSET != -1) { try { - _unsafePutBooleanMethod.invoke(_unsafeInstance, accessibleObject, _accessibleObjectOverrideFieldOffset, flag); + UNSAFE_PUT_BOOLEAN_METHOD.invoke(UNSAFE_INSTANCE, accessibleObject, ACCESSIBLE_OBJECT_OVERRIDE_FIELD_OFFSET, flag); operationComplete = true; } catch (Throwable t) { // Don't care (operationComplete already false) diff --git a/src/main/java/ognl/AccessibleObjectHandlerPreJDK9.java b/src/main/java/ognl/AccessibleObjectHandlerPreJDK9.java index 123010ec..b8bcdabe 100644 --- a/src/main/java/ognl/AccessibleObjectHandlerPreJDK9.java +++ b/src/main/java/ognl/AccessibleObjectHandlerPreJDK9.java @@ -22,25 +22,24 @@ /** * Utilizes a standard pre-JDK 9 reflection mechanism for changing the accessibility level of - * a given AccessibleObject. + * a given AccessibleObject. * * @since 3.1.24 */ -class AccessibleObjectHandlerPreJDK9 implements AccessibleObjectHandler -{ +class AccessibleObjectHandlerPreJDK9 implements AccessibleObjectHandler { /** * Private constructor */ - private AccessibleObjectHandlerPreJDK9() {} + private AccessibleObjectHandlerPreJDK9() { + } /** * Package-level generator of an AccessibleObjectHandlerJDK9Plus instance. - * + *

* Not intended for use outside of the package. * * @return an AccessibleObjectHandler instance - * * @since 3.1.24 */ static AccessibleObjectHandler createHandler() { @@ -49,10 +48,10 @@ static AccessibleObjectHandler createHandler() { /** * Utilize accessibility modification mechanism for JDK 8 (Java Major Version 8) and earlier. - * It is also the default modification mechanism for JDK 9+. + * It is also the default modification mechanism for JDK 9+. * * @param accessibleObject the AccessibleObject upon which to apply the flag. - * @param flag the new accessible flag value. + * @param flag the new accessible flag value. */ public void setAccessible(AccessibleObject accessibleObject, boolean flag) { accessibleObject.setAccessible(flag); diff --git a/src/main/java/ognl/ArrayElementsAccessor.java b/src/main/java/ognl/ArrayElementsAccessor.java index dcf0ccdc..872f9ed4 100644 --- a/src/main/java/ognl/ArrayElementsAccessor.java +++ b/src/main/java/ognl/ArrayElementsAccessor.java @@ -1,33 +1,21 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.lang.reflect.Array; @@ -35,25 +23,19 @@ /** * Implementation of ElementsAccessor that returns an iterator over a Java array. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class ArrayElementsAccessor implements ElementsAccessor -{ - public Enumeration getElements( final Object target ) - { - return new Enumeration() { - private int count = Array.getLength( target ); +public class ArrayElementsAccessor implements ElementsAccessor { + public Enumeration getElements(final Object target) { + return new Enumeration() { + private final int count = Array.getLength(target); private int index = 0; - public boolean hasMoreElements() - { + public boolean hasMoreElements() { return index < count; } - public Object nextElement() - { - return Array.get( target, index++ ); + public Object nextElement() { + return Array.get(target, index++); } }; } diff --git a/src/main/java/ognl/ArrayPropertyAccessor.java b/src/main/java/ognl/ArrayPropertyAccessor.java index 3f435f82..6b568515 100644 --- a/src/main/java/ognl/ArrayPropertyAccessor.java +++ b/src/main/java/ognl/ArrayPropertyAccessor.java @@ -1,96 +1,68 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.lang.reflect.Array; -import java.util.Map; /** * Implementation of PropertyAccessor that uses numbers and dynamic subscripts as properties to * index into Java arrays. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class ArrayPropertyAccessor extends ObjectPropertyAccessor implements PropertyAccessor -{ +public class ArrayPropertyAccessor extends ObjectPropertyAccessor implements PropertyAccessor { - public Object getProperty(Map context, Object target, Object name) - throws OgnlException - { + public Object getProperty(OgnlContext context, Object target, Object name) throws OgnlException { Object result = null; - if (name instanceof String) - { - if (name.equals("length")) - { - result = new Integer(Array.getLength(target)); - } else - { + if (name instanceof String) { + if (name.equals("length")) { + result = Array.getLength(target); + } else { result = super.getProperty(context, target, name); } - } else - { + } else { Object index = name; - if (index instanceof DynamicSubscript) - { + if (index instanceof DynamicSubscript) { int len = Array.getLength(target); - switch(((DynamicSubscript) index).getFlag()) - { + switch (((DynamicSubscript) index).getFlag()) { case DynamicSubscript.ALL: result = Array.newInstance(target.getClass().getComponentType(), len); System.arraycopy(target, 0, result, 0, len); break; case DynamicSubscript.FIRST: - index = new Integer((len > 0) ? 0 : -1); + index = (len > 0) ? 0 : -1; break; case DynamicSubscript.MID: - index = new Integer((len > 0) ? (len / 2) : -1); + index = (len > 0) ? (len / 2) : -1; break; case DynamicSubscript.LAST: - index = new Integer((len > 0) ? (len - 1) : -1); + index = (len > 0) ? (len - 1) : -1; break; } } - if (result == null) - { - if (index instanceof Number) - { + if (result == null) { + if (index instanceof Number) { int i = ((Number) index).intValue(); result = (i >= 0) ? Array.get(target, i) : null; - } else - { + } else { throw new NoSuchPropertyException(target, index); } } @@ -98,61 +70,47 @@ public Object getProperty(Map context, Object target, Object name) return result; } - public void setProperty(Map context, Object target, Object name, Object value) - throws OgnlException - { + public void setProperty(OgnlContext context, Object target, Object name, Object value) throws OgnlException { Object index = name; boolean isNumber = (index instanceof Number); - if (isNumber || (index instanceof DynamicSubscript)) - { - TypeConverter converter = ((OgnlContext) context).getTypeConverter(); - Object convertedValue; - - convertedValue = - converter.convertValue(context, target, null, name.toString(), - value, target.getClass().getComponentType()); - if (isNumber) - { + if (isNumber || (index instanceof DynamicSubscript)) { + TypeConverter converter = context.getTypeConverter(); + Object convertedValue = converter.convertValue(context, target, null, name.toString(), value, target.getClass().getComponentType()); + if (isNumber) { int i = ((Number) index).intValue(); - if (i >= 0) - { + if (i >= 0) { Array.set(target, i, convertedValue); } - } else - { + } else { int len = Array.getLength(target); - switch(((DynamicSubscript) index).getFlag()) - { + switch (((DynamicSubscript) index).getFlag()) { case DynamicSubscript.ALL: System.arraycopy(target, 0, convertedValue, 0, len); return; case DynamicSubscript.FIRST: - index = new Integer((len > 0) ? 0 : -1); + index = (len > 0) ? 0 : -1; break; case DynamicSubscript.MID: - index = new Integer((len > 0) ? (len / 2) : -1); + index = (len > 0) ? (len / 2) : -1; break; case DynamicSubscript.LAST: - index = new Integer((len > 0) ? (len - 1) : -1); + index = (len > 0) ? (len - 1) : -1; break; } } } else { - if (name instanceof String) - { + if (name instanceof String) { super.setProperty(context, target, name, value); - } else - { + } else { throw new NoSuchPropertyException(target, index); } } } - public String getSourceAccessor(OgnlContext context, Object target, Object index) - { + public String getSourceAccessor(OgnlContext context, Object target, Object index) { String indexStr = index.toString(); // need to convert to primitive for list index access @@ -160,16 +118,12 @@ public String getSourceAccessor(OgnlContext context, Object target, Object index // System.out.println("index class " + index.getClass() + " current type " + context.getCurrentType() + " current object class " + context.getCurrentObject().getClass()); if (context.getCurrentType() != null && !context.getCurrentType().isPrimitive() - && Number.class.isAssignableFrom(context.getCurrentType())) - { + && Number.class.isAssignableFrom(context.getCurrentType())) { indexStr += "." + OgnlRuntime.getNumericValueGetter(context.getCurrentType()); } else if (context.getCurrentObject() != null && Number.class.isAssignableFrom(context.getCurrentObject().getClass()) - && !context.getCurrentType().isPrimitive()) - { + && !context.getCurrentType().isPrimitive()) { // means it needs to be cast first as well - - String toString = String.class.isInstance(index) && context.getCurrentType() != Object.class ? "" : ".toString()"; - + String toString = index instanceof String && context.getCurrentType() != Object.class ? "" : ".toString()"; indexStr = "ognl.OgnlOps#getIntValue(" + indexStr + toString + ")"; } @@ -179,39 +133,31 @@ public String getSourceAccessor(OgnlContext context, Object target, Object index return "[" + indexStr + "]"; } - public String getSourceSetter(OgnlContext context, Object target, Object index) - { + public String getSourceSetter(OgnlContext context, Object target, Object index) { String indexStr = index.toString(); // need to convert to primitive for list index access if (context.getCurrentType() != null && !context.getCurrentType().isPrimitive() - && Number.class.isAssignableFrom(context.getCurrentType())) - { + && Number.class.isAssignableFrom(context.getCurrentType())) { indexStr += "." + OgnlRuntime.getNumericValueGetter(context.getCurrentType()); } else if (context.getCurrentObject() != null && Number.class.isAssignableFrom(context.getCurrentObject().getClass()) - && !context.getCurrentType().isPrimitive()) - { + && !context.getCurrentType().isPrimitive()) { // means it needs to be cast first as well - - String toString = String.class.isInstance(index) && context.getCurrentType() != Object.class ? "" : ".toString()"; - + String toString = index instanceof String && context.getCurrentType() != Object.class ? "" : ".toString()"; indexStr = "ognl.OgnlOps#getIntValue(" + indexStr + toString + ")"; } - Class type = target.getClass().isArray() ? target.getClass().getComponentType() : target.getClass(); + Class type = target.getClass().isArray() ? target.getClass().getComponentType() : target.getClass(); context.setCurrentAccessor(target.getClass()); context.setCurrentType(target.getClass().getComponentType()); - if (type.isPrimitive()) - { - Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(type); - - return "[" + indexStr + "]=((" + wrapClass.getName() + ")ognl.OgnlOps.convertValue($3," + wrapClass.getName() - + ".class, true))." + OgnlRuntime.getNumericValueGetter(wrapClass); - } else - { + if (type.isPrimitive()) { + Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(type); + return "[" + indexStr + "]=((" + wrapClass.getName() + ")ognl.OgnlOps.convertValue($3," + wrapClass.getName() + + ".class, true))." + OgnlRuntime.getNumericValueGetter(wrapClass); + } else { return "[" + indexStr + "]=ognl.OgnlOps.convertValue($3," + type.getName() + ".class)"; } } diff --git a/src/main/java/ognl/BooleanExpression.java b/src/main/java/ognl/BooleanExpression.java index 1d2da420..1747519d 100644 --- a/src/main/java/ognl/BooleanExpression.java +++ b/src/main/java/ognl/BooleanExpression.java @@ -1,21 +1,34 @@ -/** - * +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package ognl; import ognl.enhance.UnsupportedCompilationException; - /** * Base class for boolean expressions. - * - * @author jkuhnert */ -public abstract class BooleanExpression extends ExpressionNode implements NodeType -{ - - protected Class _getterClass; - +public abstract class BooleanExpression extends ExpressionNode implements NodeType { + + private static final long serialVersionUID = 8933433183011657435L; + + protected Class getterClass; + public BooleanExpression(int id) { super(id); } @@ -24,47 +37,43 @@ public BooleanExpression(OgnlParser p, int id) { super(p, id); } - public Class getGetterClass() - { - return _getterClass; + public Class getGetterClass() { + return getterClass; } - - public Class getSetterClass() - { + + public Class getSetterClass() { return null; } - - public String toGetSourceString(OgnlContext context, Object target) - { + + public String toGetSourceString(OgnlContext context, Object target) { try { - Object value = getValueBody(context, target); - - if (value != null && Boolean.class.isAssignableFrom(value.getClass())) - _getterClass = Boolean.TYPE; - else if (value != null) - _getterClass = value.getClass(); - else - _getterClass = Boolean.TYPE; + + if (value != null && Boolean.class.isAssignableFrom(value.getClass())) { + getterClass = Boolean.TYPE; + } else if (value != null) { + getterClass = value.getClass(); + } else { + getterClass = Boolean.TYPE; + } String ret = super.toGetSourceString(context, target); - if ("(false)".equals(ret)) + if ("(false)".equals(ret)) { return "false"; - else if ("(true)".equals(ret)) + } else if ("(true)".equals(ret)) { return "true"; - + } + return ret; - + } catch (NullPointerException e) { - // expected to happen in some instances e.printStackTrace(); - throw new UnsupportedCompilationException("evaluation resulted in null expression."); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } + } diff --git a/src/main/java/ognl/ClassCacheInspector.java b/src/main/java/ognl/ClassCacheInspector.java index d32ece50..708b92e6 100644 --- a/src/main/java/ognl/ClassCacheInspector.java +++ b/src/main/java/ognl/ClassCacheInspector.java @@ -1,18 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; /** - * Optional interface that may be registered with {@link OgnlRuntime#setClassCacheInspector(ClassCacheInspector)} as - * a means to disallow caching of specific class types. + * Optional interface that may be registered with {@link OgnlRuntime#setClassCacheInspector(ClassCacheInspector)} + * as a means to disallow caching of specific class types. */ public interface ClassCacheInspector { /** * Invoked just before storing a class type within a cache instance. * - * @param type - * The class that is to be stored. - * + * @param type The class that is to be stored. * @return True if the class can be cached, false otherwise. */ - boolean shouldCache(Class type); + boolean shouldCache(Class type); + } diff --git a/src/main/java/ognl/ClassResolver.java b/src/main/java/ognl/ClassResolver.java index ecf49456..0403d511 100644 --- a/src/main/java/ognl/ClassResolver.java +++ b/src/main/java/ognl/ClassResolver.java @@ -1,44 +1,29 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.Map; - /** * This interface defines an object that will resolve a class from a string * and a ognl context table. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public interface ClassResolver -{ - public Class classForName(String className, Map context) throws ClassNotFoundException; +public interface ClassResolver { + + Class classForName(String className, OgnlContext context) throws ClassNotFoundException; + } diff --git a/src/main/java/ognl/CollectionElementsAccessor.java b/src/main/java/ognl/CollectionElementsAccessor.java index e1f2b481..ad1803a6 100644 --- a/src/main/java/ognl/CollectionElementsAccessor.java +++ b/src/main/java/ognl/CollectionElementsAccessor.java @@ -1,46 +1,33 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; +import java.util.Collection; +import java.util.Enumeration; /** * Implementation of ElementsAccessor that returns a collection's iterator. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class CollectionElementsAccessor implements ElementsAccessor -{ - public Enumeration getElements( Object target ) - { - return new IteratorEnumeration( ((Collection)target).iterator() ); +public class CollectionElementsAccessor implements ElementsAccessor { + + public Enumeration getElements(Object target) { + return new IteratorEnumeration(((Collection) target).iterator()); } + } diff --git a/src/main/java/ognl/ComparisonExpression.java b/src/main/java/ognl/ComparisonExpression.java index f673c228..6a8f7066 100644 --- a/src/main/java/ognl/ComparisonExpression.java +++ b/src/main/java/ognl/ComparisonExpression.java @@ -1,16 +1,31 @@ -/** - * +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package ognl; import ognl.enhance.UnsupportedCompilationException; - /** - * Base class for types that compare values. + * Base class for types that compare values. */ -public abstract class ComparisonExpression extends BooleanExpression -{ +public abstract class ComparisonExpression extends BooleanExpression { + + private static final long serialVersionUID = -687171907698242382L; public ComparisonExpression(int id) { super(id); @@ -19,41 +34,40 @@ public ComparisonExpression(int id) { public ComparisonExpression(OgnlParser p, int id) { super(p, id); } - + public abstract String getComparisonFunction(); - - public String toGetSourceString(OgnlContext context, Object target) - { + + public String toGetSourceString(OgnlContext context, Object target) { if (target == null) throw new UnsupportedCompilationException("Current target is null, can't compile."); - + try { - + Object value = getValueBody(context, target); - + if (value != null && Boolean.class.isAssignableFrom(value.getClass())) - _getterClass = Boolean.TYPE; + getterClass = Boolean.TYPE; else if (value != null) - _getterClass = value.getClass(); + getterClass = value.getClass(); else - _getterClass = Boolean.TYPE; - + getterClass = Boolean.TYPE; + // iterate over children to make numeric type detection work properly - - OgnlRuntime.getChildSource(context, target, _children[0]); - OgnlRuntime.getChildSource(context, target, _children[1]); - + + OgnlRuntime.getChildSource(context, target, children[0]); + OgnlRuntime.getChildSource(context, target, children[1]); + // System.out.println("comparison expression currentType: " + context.getCurrentType() + " previousType: " + context.getPreviousType()); boolean conversion = OgnlRuntime.shouldConvertNumericTypes(context); String result = conversion ? "(" + getComparisonFunction() + "( ($w) (" : "("; - - result += OgnlRuntime.getChildSource(context, target, _children[0], conversion) - + " " - + (conversion ? "), ($w) " : getExpressionOperator(0)) + " " - + OgnlRuntime.getChildSource(context, target, _children[1], conversion); - + + result += OgnlRuntime.getChildSource(context, target, children[0]) + + " " + + (conversion ? "), ($w) " : getExpressionOperator(0)) + " " + + OgnlRuntime.getChildSource(context, target, children[1]); + result += conversion ? ")" : ""; context.setCurrentType(Boolean.TYPE); @@ -62,12 +76,11 @@ else if (value != null) return result; } catch (NullPointerException e) { - + // expected to happen in some instances - + throw new UnsupportedCompilationException("evaluation resulted in null expression."); - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } diff --git a/src/main/java/ognl/DefaultClassResolver.java b/src/main/java/ognl/DefaultClassResolver.java index 7ec2d36f..a8eb76a4 100644 --- a/src/main/java/ognl/DefaultClassResolver.java +++ b/src/main/java/ognl/DefaultClassResolver.java @@ -1,59 +1,42 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Default class resolution. Uses Class.forName() to look up classes by name. * It also looks in the "java.lang" package if the class named does not give * a package specifier, allowing easier usage of these classes. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class DefaultClassResolver extends Object implements ClassResolver -{ - private final ConcurrentHashMap classes = new ConcurrentHashMap<>(101); +public class DefaultClassResolver implements ClassResolver { + + private final ConcurrentHashMap> classes = new ConcurrentHashMap<>(101); - public DefaultClassResolver() - { + public DefaultClassResolver() { super(); } - public Class classForName(String className, Map context) throws ClassNotFoundException - { - Class result = classes.get(className); + public Class classForName(String className, OgnlContext context) throws ClassNotFoundException { + Class result = classes.get(className); if (result != null) { - return result; + return (Class) result; } try { result = toClassForName(className); @@ -71,10 +54,10 @@ public Class classForName(String className, Map context) throws ClassNotFoundExc } } classes.putIfAbsent(className, result); - return result; + return (Class) result; } - protected Class toClassForName(String className) throws ClassNotFoundException { + protected Class toClassForName(String className) throws ClassNotFoundException { return Class.forName(className); } diff --git a/src/main/java/ognl/DefaultTypeConverter.java b/src/main/java/ognl/DefaultTypeConverter.java index 06d239ce..24132406 100644 --- a/src/main/java/ognl/DefaultTypeConverter.java +++ b/src/main/java/ognl/DefaultTypeConverter.java @@ -1,58 +1,41 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.lang.reflect.Member; -import java.util.Map; /** * Default type conversion. Converts among numeric types and also strings. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class DefaultTypeConverter implements TypeConverter -{ - public DefaultTypeConverter() - { +public class DefaultTypeConverter implements TypeConverter { + + public DefaultTypeConverter() { super(); } - public Object convertValue(Map context, Object value, Class toType) - { + public Object convertValue(OgnlContext context, Object value, Class toType) { return OgnlOps.convertValue(value, toType); } - public Object convertValue(Map context, Object target, Member member, String propertyName, Object value, Class toType) - { + public Object convertValue(OgnlContext context, Object target, Member member, String propertyName, Object value, Class toType) { return convertValue(context, value, toType); } + } diff --git a/src/main/java/ognl/DynamicSubscript.java b/src/main/java/ognl/DynamicSubscript.java index a12ad843..7fcaef8c 100644 --- a/src/main/java/ognl/DynamicSubscript.java +++ b/src/main/java/ognl/DynamicSubscript.java @@ -1,77 +1,63 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; - /** * This class has predefined instances that stand for OGNL's special "dynamic subscripts" * for getting at the first, middle, or last elements of a list. In OGNL expressions, * these subscripts look like special kinds of array indexes: [^] means the first element, * [$] means the last, [|] means the middle, and [*] means the whole list. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class DynamicSubscript -{ - public static final int FIRST = 0; - public static final int MID = 1; - public static final int LAST = 2; - public static final int ALL = 3; +public class DynamicSubscript { + + public static final int FIRST = 0; + public static final int MID = 1; + public static final int LAST = 2; + public static final int ALL = 3; - public static final DynamicSubscript first = new DynamicSubscript(FIRST); - public static final DynamicSubscript mid = new DynamicSubscript(MID); - public static final DynamicSubscript last = new DynamicSubscript(LAST); - public static final DynamicSubscript all = new DynamicSubscript(ALL); + public static final DynamicSubscript first = new DynamicSubscript(FIRST); + public static final DynamicSubscript mid = new DynamicSubscript(MID); + public static final DynamicSubscript last = new DynamicSubscript(LAST); + public static final DynamicSubscript all = new DynamicSubscript(ALL); - private int flag; + private final int flag; - private DynamicSubscript( int flag ) - { + private DynamicSubscript(int flag) { this.flag = flag; } - public int getFlag() - { + public int getFlag() { return flag; } - public String toString() - { - switch (flag) - { - case FIRST: return "^"; - case MID: return "|"; - case LAST: return "$"; - case ALL: return "*"; - default: return "?"; // Won't happen - } + public String toString() { + switch (flag) { + case FIRST: + return "^"; + case MID: + return "|"; + case LAST: + return "$"; + case ALL: + return "*"; + default: + return "?"; // Won't happen + } } } diff --git a/src/main/java/ognl/ElementsAccessor.java b/src/main/java/ognl/ElementsAccessor.java index 90d86380..46c1c358 100644 --- a/src/main/java/ognl/ElementsAccessor.java +++ b/src/main/java/ognl/ElementsAccessor.java @@ -1,33 +1,21 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.util.Enumeration; @@ -41,16 +29,14 @@ *

An implementation of this interface will often require that its target objects all * be of some particular type. For example, the MapElementsAccessor class requires that * its targets all implement the Map interface. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public interface ElementsAccessor -{ - /** - * Returns an iterator over the elements of the given target object. - * @param target the object to get the elements of - * @return an iterator over the elements of the given object - * @exception OgnlException if there is an error getting the given object's elements - */ - public Enumeration getElements( Object target ) throws OgnlException; +public interface ElementsAccessor { + /** + * Returns an iterator over the elements of the given target object. + * + * @param target the object to get the elements of + * @return an iterator over the elements of the given object + * @throws OgnlException if there is an error getting the given object's elements + */ + Enumeration getElements(Object target) throws OgnlException; } diff --git a/src/main/java/ognl/EnumerationElementsAccessor.java b/src/main/java/ognl/EnumerationElementsAccessor.java index ca3f4858..58fbae40 100644 --- a/src/main/java/ognl/EnumerationElementsAccessor.java +++ b/src/main/java/ognl/EnumerationElementsAccessor.java @@ -1,48 +1,33 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.util.Enumeration; - /** * Implementation of the ElementsAccessor interface for Enumerations, which returns an * iterator that passes its calls through to the target Enumeration. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class EnumerationElementsAccessor implements ElementsAccessor -{ - public Enumeration getElements( Object target ) - { - return (Enumeration)target; +public class EnumerationElementsAccessor implements ElementsAccessor { + + public Enumeration getElements(Object target) { + return (Enumeration) target; } + } diff --git a/src/main/java/ognl/EnumerationIterator.java b/src/main/java/ognl/EnumerationIterator.java index f65fd78b..9a3b3a0c 100644 --- a/src/main/java/ognl/EnumerationIterator.java +++ b/src/main/java/ognl/EnumerationIterator.java @@ -1,64 +1,47 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; +import java.util.Enumeration; +import java.util.Iterator; /** * Object that implements Iterator from an Enumeration - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class EnumerationIterator implements Iterator -{ - private Enumeration e; +public class EnumerationIterator implements Iterator { + + private Enumeration enumeration; + + public EnumerationIterator(Enumeration enumeration) { + this.enumeration = enumeration; + } - public EnumerationIterator(Enumeration e) - { - super(); - this.e = e; - } + public boolean hasNext() { + return enumeration.hasMoreElements(); + } - public boolean hasNext() - { - return e.hasMoreElements(); - } + public T next() { + return enumeration.nextElement(); + } - public Object next() - { - return e.nextElement(); - } + public void remove() { + throw new UnsupportedOperationException("remove() not supported by Enumeration"); + } - public void remove() - { - throw new UnsupportedOperationException("remove() not supported by Enumeration"); - } } diff --git a/src/main/java/ognl/EnumerationPropertyAccessor.java b/src/main/java/ognl/EnumerationPropertyAccessor.java index cb0313dd..20c359c6 100644 --- a/src/main/java/ognl/EnumerationPropertyAccessor.java +++ b/src/main/java/ognl/EnumerationPropertyAccessor.java @@ -1,60 +1,44 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; +import java.util.Enumeration; /** * Implementation of PropertyAccessor that provides "property" reference to * "nextElement" (aliases to "next" also) and "hasMoreElements" (also aliased * to "hasNext"). - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class EnumerationPropertyAccessor extends ObjectPropertyAccessor - implements PropertyAccessor // This is here to make javadoc show this class as an implementor -{ - public Object getProperty( Map context, Object target, Object name ) throws OgnlException - { - Object result; - Enumeration e = (Enumeration)target; +public class EnumerationPropertyAccessor extends ObjectPropertyAccessor implements PropertyAccessor { + + public Object getProperty(OgnlContext context, Object target, Object name) throws OgnlException { + Object result; + Enumeration e = (Enumeration) target; - if ( name instanceof String ) { + if (name instanceof String) { if (name.equals("next") || name.equals("nextElement")) { result = e.nextElement(); } else { if (name.equals("hasNext") || name.equals("hasMoreElements")) { result = e.hasMoreElements() ? Boolean.TRUE : Boolean.FALSE; } else { - result = super.getProperty( context, target, name ); + result = super.getProperty(context, target, name); } } } else { @@ -63,8 +47,7 @@ public Object getProperty( Map context, Object target, Object name ) throws Ognl return result; } - public void setProperty( Map context, Object target, Object name, Object value ) throws OgnlException - { - throw new IllegalArgumentException( "can't set property " + name + " on Enumeration" ); + public void setProperty(OgnlContext context, Object target, Object name, Object value) throws OgnlException { + throw new IllegalArgumentException("can't set property " + name + " on Enumeration"); } } diff --git a/src/main/java/ognl/Evaluation.java b/src/main/java/ognl/Evaluation.java index 23b6328a..192064ca 100644 --- a/src/main/java/ognl/Evaluation.java +++ b/src/main/java/ognl/Evaluation.java @@ -1,256 +1,226 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; /** - An Evaluation is and object that holds a node being evaluated - and the source from which that node will take extract its - value. It refers to child evaluations that occur as - a result of the nodes' evaluation. + * An Evaluation is and object that holds a node being evaluated + * and the source from which that node will take extract its + * value. It refers to child evaluations that occur as + * a result of the nodes' evaluation. */ -public class Evaluation extends Object -{ - private SimpleNode node; - private Object source; - private boolean setOperation; - private Object result; - private Throwable exception; - private Evaluation parent; - private Evaluation next; - private Evaluation previous; - private Evaluation firstChild; - private Evaluation lastChild; +public class Evaluation { + + private SimpleNode node; + private Object source; + private boolean setOperation; + private Object result; + private Throwable exception; + private Evaluation parent; + private Evaluation next; + private Evaluation previous; + private Evaluation firstChild; + private Evaluation lastChild; /** - Constructs a new "get" Evaluation from the node and source given. + * Constructs a new "get" Evaluation from the node and source given. * - * @param node a SimpleNode for this Evaluation. + * @param node a SimpleNode for this Evaluation. * @param source a source Object for this Evaluation. */ - public Evaluation(SimpleNode node, Object source) - { + public Evaluation(SimpleNode node, Object source) { super(); this.node = node; this.source = source; } /** - Constructs a new Evaluation from the node and source given. - If setOperation is true this Evaluation represents - a "set" as opposed to a "get". + * Constructs a new Evaluation from the node and source given. + * If setOperation is true this Evaluation represents + * a "set" as opposed to a "get". * - * @param node a SimpleNode for this Evaluation. - * @param source a source Object for this Evaluation. + * @param node a SimpleNode for this Evaluation. + * @param source a source Object for this Evaluation. * @param setOperation true to identify this Evaluation as a set operation, false to identify it as a get operation. */ - public Evaluation(SimpleNode node, Object source, boolean setOperation) - { + public Evaluation(SimpleNode node, Object source, boolean setOperation) { this(node, source); this.setOperation = setOperation; } /** - Returns the SimpleNode for this Evaluation + * Returns the SimpleNode for this Evaluation * * @return the SimpleNode for this Evaluation. */ - public SimpleNode getNode() - { + public SimpleNode getNode() { return node; } /** - Sets the node of the evaluation. Normally applications do not need to - set this. Notable exceptions to this rule are custom evaluators that - choose between navigable objects (as in a multi-root evaluator where - the navigable node is chosen at runtime). + * Sets the node of the evaluation. Normally applications do not need to + * set this. Notable exceptions to this rule are custom evaluators that + * choose between navigable objects (as in a multi-root evaluator where + * the navigable node is chosen at runtime). * * @param value the SimpleNode to set for this Evaluation. */ - public void setNode(SimpleNode value) - { + public void setNode(SimpleNode value) { node = value; } /** - Returns the source object on which this Evaluation operated. + * Returns the source object on which this Evaluation operated. * * @return the source Object operated upon by this Evaluation. */ - public Object getSource() - { + public Object getSource() { return source; } /** - Sets the source of the evaluation. Normally applications do not need to - set this. Notable exceptions to this rule are custom evaluators that - choose between navigable objects (as in a multi-root evaluator where - the navigable node is chosen at runtime). + * Sets the source of the evaluation. Normally applications do not need to + * set this. Notable exceptions to this rule are custom evaluators that + * choose between navigable objects (as in a multi-root evaluator where + * the navigable node is chosen at runtime). * * @param value the source Object to be set for this Evaluation. */ - public void setSource(Object value) - { + public void setSource(Object value) { source = value; } /** - Returns true if this Evaluation represents a set operation. + * Returns true if this Evaluation represents a set operation. * * @return true if this Evaluation represents a set operation, false otherwise. */ - public boolean isSetOperation() - { + public boolean isSetOperation() { return setOperation; } /** - Marks the Evaluation as a set operation if the value is true, else - marks it as a get operation. + * Marks the Evaluation as a set operation if the value is true, else + * marks it as a get operation. * * @param value true to identify this Evaluation as a set operation, false to identify it as a get operation. */ - public void setSetOperation(boolean value) - { + public void setSetOperation(boolean value) { setOperation = value; } /** - Returns the result of the Evaluation, or null if it was a set operation. + * Returns the result of the Evaluation, or null if it was a set operation. * * @return the result of the Evaluation (for a get operation), or null (for a set operation). */ - public Object getResult() - { + public Object getResult() { return result; } /** - Sets the result of the Evaluation. This method is normally only used - interally and should not be set without knowledge of what you are doing. + * Sets the result of the Evaluation. This method is normally only used + * interally and should not be set without knowledge of what you are doing. * * @param value the result Object for this Evaluation. */ - public void setResult(Object value) - { + public void setResult(Object value) { result = value; } /** - Returns the exception that occurred as a result of evaluating the - Evaluation, or null if no exception occurred. - * + * Returns the exception that occurred as a result of evaluating the + * Evaluation, or null if no exception occurred. + * * @return an exception if one occurred during evaluation, or null (no exception) otherwise. */ - public Throwable getException() - { + public Throwable getException() { return exception; } /** - Sets the exception that occurred as a result of evaluating the - Evaluation. This method is normally only used interally and - should not be set without knowledge of what you are doing. + * Sets the exception that occurred as a result of evaluating the + * Evaluation. This method is normally only used interally and + * should not be set without knowledge of what you are doing. * * @param value the Throwable exception that occurred during the evaluation of this Evaluation. */ - public void setException(Throwable value) - { + public void setException(Throwable value) { exception = value; } /** - Returns the parent evaluation of this evaluation. If this returns - null then it is is the root evaluation of a tree. + * Returns the parent evaluation of this evaluation. If this returns + * null then it is is the root evaluation of a tree. * * @return the parent Evaluation of the current Evaluation, or null if no parent exists. */ - public Evaluation getParent() - { + public Evaluation getParent() { return parent; } /** - Returns the next sibling of this evaluation. Returns null if - this is the last in a chain of evaluations. + * Returns the next sibling of this evaluation. Returns null if + * this is the last in a chain of evaluations. * * @return the next sibling Evaluation of the current Evaluation, or null if this is the last Evaluation in a chain. */ - public Evaluation getNext() - { + public Evaluation getNext() { return next; } /** - Returns the previous sibling of this evaluation. Returns null if - this is the first in a chain of evaluations. + * Returns the previous sibling of this evaluation. Returns null if + * this is the first in a chain of evaluations. * * @return the previous sibling Evaluation of the current Evaluation, or null if this is the first Evaluation in a chain. */ - public Evaluation getPrevious() - { + public Evaluation getPrevious() { return previous; } /** - Returns the first child of this evaluation. Returns null if - there are no children. + * Returns the first child of this evaluation. Returns null if + * there are no children. * * @return the first child Evaluation of the current Evaluation, or null if no children exist. */ - public Evaluation getFirstChild() - { + public Evaluation getFirstChild() { return firstChild; } /** - Returns the last child of this evaluation. Returns null if - there are no children. + * Returns the last child of this evaluation. Returns null if + * there are no children. * * @return the last child Evaluation of the current Evaluation, or null if no children exist. */ - public Evaluation getLastChild() - { + public Evaluation getLastChild() { return lastChild; } /** - Gets the first descendent. In any Evaluation tree this will the - Evaluation that was first executed. + * Gets the first descendent. In any Evaluation tree this will the + * Evaluation that was first executed. * * @return the first descendant Evaluation (first Evaluation executed in the tree). */ - public Evaluation getFirstDescendant() - { + public Evaluation getFirstDescendant() { if (firstChild != null) { return firstChild.getFirstDescendant(); } @@ -258,13 +228,12 @@ public Evaluation getFirstDescendant() } /** - Gets the last descendent. In any Evaluation tree this will the - Evaluation that was most recently executing. + * Gets the last descendent. In any Evaluation tree this will the + * Evaluation that was most recently executing. * - * @return the last descendant Evaluation (most recent Evaluation executed in the tree). + * @return the last descendant Evaluation (most recent Evaluation executed in the tree). */ - public Evaluation getLastDescendant() - { + public Evaluation getLastDescendant() { if (lastChild != null) { return lastChild.getLastDescendant(); } @@ -272,16 +241,15 @@ public Evaluation getLastDescendant() } /** - Adds a child to the list of children of this evaluation. The - parent of the child is set to the receiver and the children - references are modified in the receiver to reflect the new child. - The lastChild of the receiver is set to the child, and the - firstChild is set also if child is the first (or only) child. + * Adds a child to the list of children of this evaluation. The + * parent of the child is set to the receiver and the children + * references are modified in the receiver to reflect the new child. + * The lastChild of the receiver is set to the child, and the + * firstChild is set also if child is the first (or only) child. * * @param child an Evaluation to add as a child to the current Evaluation. */ - public void addChild(Evaluation child) - { + public void addChild(Evaluation child) { if (firstChild == null) { firstChild = lastChild = child; } else { @@ -299,14 +267,13 @@ public void addChild(Evaluation child) } /** - Reinitializes this Evaluation to the parameters specified. + * Reinitializes this Evaluation to the parameters specified. * - * @param node a SimpleNode for this Evaluation. - * @param source a source Object for this Evaluation. + * @param node a SimpleNode for this Evaluation. + * @param source a source Object for this Evaluation. * @param setOperation true to identify this Evaluation as a set operation, false to identify it as a get operation. */ - public void init(SimpleNode node, Object source, boolean setOperation) - { + public void init(SimpleNode node, Object source, boolean setOperation) { this.node = node; this.source = source; this.setOperation = setOperation; @@ -320,73 +287,69 @@ public void init(SimpleNode node, Object source, boolean setOperation) } /** - Resets this Evaluation to the initial state. + * Resets this Evaluation to the initial state. */ - public void reset() - { + public void reset() { init(null, null, false); } /** - Produces a String value for the Evaluation. If compact is - true then a more compact form of the description only including - the node type and unique identifier is shown, else a full - description including source and result are shown. If showChildren - is true the child evaluations are printed using the depth string - given as a prefix. + * Produces a String value for the Evaluation. If compact is + * true then a more compact form of the description only including + * the node type and unique identifier is shown, else a full + * description including source and result are shown. If showChildren + * is true the child evaluations are printed using the depth string + * given as a prefix. * - * @param compact true to generate a compact form of the description for this Evaluation, false for a full form. + * @param compact true to generate a compact form of the description for this Evaluation, false for a full form. * @param showChildren true to generate descriptions for child Evaluation elements of this Evaluation. - * @param depth prefix String to use in front of child Evaluation description output - used when showChildren is true. + * @param depth prefix String to use in front of child Evaluation description output - used when showChildren is true. * @return the description of this Evaluation as a String. */ - public String toString(boolean compact, boolean showChildren, String depth) - { - String stringResult; + public String toString(boolean compact, boolean showChildren, String depth) { + StringBuilder stringResult; if (compact) { - stringResult = depth + "<" + node.getClass().getName() + " " + System.identityHashCode(this) + ">"; + stringResult = new StringBuilder(depth + "<" + node.getClass().getName() + " " + System.identityHashCode(this) + ">"); } else { - String ss = (source != null) ? source.getClass().getName() : "null", - rs = (result != null) ? result.getClass().getName() : "null"; + String ss = (source != null) ? source.getClass().getName() : "null", + rs = (result != null) ? result.getClass().getName() : "null"; - stringResult = depth + "<" + node.getClass().getName() + ": [" + (setOperation ? "set" : "get") + "] source = " + ss + ", result = " + result + " [" + rs + "]>"; + stringResult = new StringBuilder(depth + "<" + node.getClass().getName() + ": [" + (setOperation ? "set" : "get") + "] source = " + ss + ", result = " + result + " [" + rs + "]>"); } if (showChildren) { - Evaluation child = firstChild; + Evaluation child = firstChild; - stringResult += "\n"; + stringResult.append("\n"); while (child != null) { - stringResult += child.toString(compact, depth + " "); + stringResult.append(child.toString(compact, depth + " ")); child = child.next; } } - return stringResult; + return stringResult.toString(); } /** - Produces a String value for the Evaluation. If compact is - true then a more compact form of the description only including - the node type and unique identifier is shown, else a full - description including source and result are shown. Child - evaluations are printed using the depth string given as a prefix. + * Produces a String value for the Evaluation. If compact is + * true then a more compact form of the description only including + * the node type and unique identifier is shown, else a full + * description including source and result are shown. Child + * evaluations are printed using the depth string given as a prefix. * * @param compact true to generate a compact form of the description for this Evaluation, false for a full form. - * @param depth prefix String to use in front of child Evaluation description output - used when showChildren is true. + * @param depth prefix String to use in front of child Evaluation description output - used when showChildren is true. * @return the description of this Evaluation as a String. */ - public String toString(boolean compact, String depth) - { + public String toString(boolean compact, String depth) { return toString(compact, true, depth); } /** - Returns a String description of the Evaluation. + * Returns a String description of the Evaluation. * * @return the description of this Evaluation as a String. */ - public String toString() - { + public String toString() { return toString(false, ""); } } diff --git a/src/main/java/ognl/EvaluationPool.java b/src/main/java/ognl/EvaluationPool.java index 2605f64d..e933a39c 100644 --- a/src/main/java/ognl/EvaluationPool.java +++ b/src/main/java/ognl/EvaluationPool.java @@ -1,157 +1,92 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; - -public final class EvaluationPool extends Object -{ - public EvaluationPool() - { - this(0); - } - - public EvaluationPool(int initialSize) - { - super(); - // do not init object pooling - } +public final class EvaluationPool { /** - Returns an Evaluation that contains the node, source and whether it - is a set operation. If there are no Evaluation objects in the - pool one is created and returned. + * Returns an Evaluation that contains the node, source and whether it + * is a set operation. If there are no Evaluation objects in the + * pool one is created and returned. * - * @param node a SimpleNode for an Evaluation to be created. + * @param node a SimpleNode for an Evaluation to be created. * @param source a source Object for an Evaluation to be created. * @return an Evaluation based on the parameters. */ - public Evaluation create(SimpleNode node, Object source) - { + public Evaluation create(SimpleNode node, Object source) { return create(node, source, false); } /** - Returns an Evaluation that contains the node, source and whether it - is a set operation. + * Returns an Evaluation that contains the node, source and whether it + * is a set operation. * - * @param node a SimpleNode for an Evaluation to be created. - * @param source a source Object for an Evaluation to be created. + * @param node a SimpleNode for an Evaluation to be created. + * @param source a source Object for an Evaluation to be created. * @param setOperation true to identify the Evaluation to be created as a set operation, false to identify it as a get operation. * @return an Evaluation based on the parameters. */ - public Evaluation create(SimpleNode node, Object source, boolean setOperation) - { + public Evaluation create(SimpleNode node, Object source, boolean setOperation) { // synchronization is removed as we do not rely anymore on the in-house object pooling return new Evaluation(node, source, setOperation); } /** - Recycles an Evaluation - * - * @param value an Evaluation to be recycled (not used). - * @deprecated object-pooling now relies on the jvm garbage collection - */ - public void recycle(Evaluation value) - { - // no need of recycling, we rely on the garbage collection efficiency - } - - /** - Recycles an of Evaluation and all of it's siblings - and children. - * - * @param value an Evaluation to be recycled along with its siblings (not used). - * @deprecated object-pooling now relies on the jvm garbage collection - */ - public void recycleAll(Evaluation value) - { - // no need of recycling, we rely on the garbage collection efficiency - } - - /** - Recycles a List of Evaluation objects - * - * @param value a List of Evaluation objects to be recycled (not used). - * @deprecated object-pooling now relies on the jvm garbage collection - */ - public void recycleAll(List value) - { - // no need of recycling, we rely on the garbage collection efficiency - } - - /** - Returns the number of items in the pool + * Returns the number of items in the pool * * @return the size of the Evaluation pool (always 0). * @deprecated object-pooling now relies on the jvm garbage collection */ - public int getSize() - { + public int getSize() { return 0; } /** - Returns the number of items this pool has created since - it's construction. + * Returns the number of items this pool has created since + * it's construction. * * @return the creation count for the Evaluation pool (always 0). * @deprecated object-pooling now relies on the jvm garbage collection */ - public int getCreatedCount() - { + public int getCreatedCount() { return 0; } /** - Returns the number of items this pool has recovered from - the pool since its construction. + * Returns the number of items this pool has recovered from + * the pool since its construction. * * @return the recovered count for the Evaluation pool (always 0). * @deprecated object-pooling now relies on the jvm garbage collection */ - public int getRecoveredCount() - { + public int getRecoveredCount() { return 0; } /** - Returns the number of items this pool has recycled since - it's construction. + * Returns the number of items this pool has recycled since + * it's construction. * * @return the recycled count for the Evaluation pool (always 0). * @deprecated object-pooling now relies on the jvm garbage collection */ - public int getRecycledCount() - { + public int getRecycledCount() { return 0; } } diff --git a/src/main/java/ognl/ExpressionNode.java b/src/main/java/ognl/ExpressionNode.java index 235d5006..67345037 100644 --- a/src/main/java/ognl/ExpressionNode.java +++ b/src/main/java/ognl/ExpressionNode.java @@ -1,43 +1,29 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ -public abstract class ExpressionNode extends SimpleNode -{ +public abstract class ExpressionNode extends SimpleNode { + + private static final long serialVersionUID = 4880029588563407661L; + public ExpressionNode(int i) { super(i); } @@ -45,23 +31,22 @@ public ExpressionNode(int i) { public ExpressionNode(OgnlParser p, int i) { super(p, i); } + /** - Returns true iff this node is constant without respect to the children. + * Returns true iff this node is constant without respect to the children. */ - public boolean isNodeConstant( OgnlContext context ) throws OgnlException - { + public boolean isNodeConstant(OgnlContext context) throws OgnlException { return false; } - public boolean isConstant( OgnlContext context ) throws OgnlException - { - boolean result = isNodeConstant(context); + public boolean isConstant(OgnlContext context) throws OgnlException { + boolean result = isNodeConstant(context); - if ((_children != null) && (_children.length > 0)) { + if ((children != null) && (children.length > 0)) { result = true; - for ( int i=0; result && (i < _children.length); ++i ) { - if (_children[i] instanceof SimpleNode) { - result = ((SimpleNode)_children[i]).isConstant( context ); + for (int i = 0; result && (i < children.length); ++i) { + if (children[i] instanceof SimpleNode) { + result = ((SimpleNode) children[i]).isConstant(context); } else { result = false; } @@ -70,90 +55,85 @@ public boolean isConstant( OgnlContext context ) throws OgnlException return result; } - public String getExpressionOperator(int index) - { - throw new RuntimeException("unknown operator for " + OgnlParserTreeConstants.jjtNodeName[_id]); + public String getExpressionOperator(int index) { + throw new RuntimeException("unknown operator for " + OgnlParserTreeConstants.jjtNodeName[id]); } - public String toString() - { - String result = (_parent == null) ? "" : "("; - - if ((_children != null) && (_children.length > 0)) { - for ( int i = 0; i < _children.length; ++i ) { + public String toString() { + StringBuilder result = new StringBuilder((parent == null) ? "" : "("); + + if ((children != null) && (children.length > 0)) { + for (int i = 0; i < children.length; ++i) { if (i > 0) { - result += " " + getExpressionOperator(i) + " "; + result.append(" ").append(getExpressionOperator(i)).append(" "); } - result += _children[i].toString(); + result.append(children[i].toString()); } } - if (_parent != null) { - result = result + ")"; + if (parent != null) { + result.append(")"); } - return result; + return result.toString(); } - - public String toGetSourceString(OgnlContext context, Object target) - { - String result = (_parent == null || NumericExpression.class.isAssignableFrom(_parent.getClass())) ? "" : "("; - if ((_children != null) && (_children.length > 0)) { - for ( int i = 0; i < _children.length; ++i ) { + public String toGetSourceString(OgnlContext context, Object target) { + StringBuilder result = new StringBuilder((parent == null || NumericExpression.class.isAssignableFrom(parent.getClass())) ? "" : "("); + + if ((children != null) && (children.length > 0)) { + for (int i = 0; i < children.length; ++i) { if (i > 0) { - result += " " + getExpressionOperator(i) + " "; + result.append(" ").append(getExpressionOperator(i)).append(" "); } - - String value = _children[i].toGetSourceString(context, target); - if ((ASTProperty.class.isInstance(_children[i]) || ASTMethod.class.isInstance(_children[i]) - || ASTSequence.class.isInstance(_children[i]) || ASTChain.class.isInstance(_children[i])) - && value != null && value.trim().length() > 0) { + String value = children[i].toGetSourceString(context, target); + + if ((children[i] instanceof ASTProperty || children[i] instanceof ASTMethod + || children[i] instanceof ASTSequence || children[i] instanceof ASTChain) + && value != null && value.trim().length() > 0) { String pre = null; - if (ASTMethod.class.isInstance(_children[i])) - { - pre = (String)context.get("_currentChain"); + if (children[i] instanceof ASTMethod) { + pre = (String) context.get("_currentChain"); } if (pre == null) pre = ""; - String cast = (String)context.remove(ExpressionCompiler.PRE_CAST); + String cast = (String) context.remove(ExpressionCompiler.PRE_CAST); if (cast == null) cast = ""; - value = cast + ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context) + pre + value; - } + value = cast + ExpressionCompiler.getRootExpression(children[i], context.getRoot(), context) + pre + value; + } - result += value; + result.append(value); } } - if (_parent != null && !NumericExpression.class.isAssignableFrom(_parent.getClass())) { - result = result + ")"; + if (parent != null && !NumericExpression.class.isAssignableFrom(parent.getClass())) { + result.append(")"); } - - return result; + + return result.toString(); } - - public String toSetSourceString(OgnlContext context, Object target) - { - String result = (_parent == null) ? "" : "("; - - if ((_children != null) && (_children.length > 0)) { - for ( int i = 0; i < _children.length; ++i ) { + + public String toSetSourceString(OgnlContext context, Object target) { + StringBuilder result = new StringBuilder((parent == null) ? "" : "("); + + if ((children != null) && (children.length > 0)) { + for (int i = 0; i < children.length; ++i) { if (i > 0) { - result += " " + getExpressionOperator(i) + " "; + result.append(" ").append(getExpressionOperator(i)).append(" "); } - - result += _children[i].toSetSourceString(context, target); + + result.append(children[i].toSetSourceString(context, target)); } } - if (_parent != null) { - result = result + ")"; + if (parent != null) { + result.append(")"); } - - return result; + + return result.toString(); } @Override diff --git a/src/main/java/ognl/ExpressionSyntaxException.java b/src/main/java/ognl/ExpressionSyntaxException.java index 4062169b..6007b580 100644 --- a/src/main/java/ognl/ExpressionSyntaxException.java +++ b/src/main/java/ognl/ExpressionSyntaxException.java @@ -1,46 +1,31 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; - /** * Exception thrown if a malformed OGNL expression is encountered. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class ExpressionSyntaxException extends OgnlException -{ - public ExpressionSyntaxException( String expression, Throwable reason ) - { - super( "Malformed OGNL expression: " + expression, reason ); +public class ExpressionSyntaxException extends OgnlException { + + private static final long serialVersionUID = 3219409775304901172L; + + public ExpressionSyntaxException(String expression, Throwable reason) { + super("Malformed OGNL expression: " + expression, reason); } } diff --git a/src/main/java/ognl/InappropriateExpressionException.java b/src/main/java/ognl/InappropriateExpressionException.java index 41f0644d..e02f3a59 100644 --- a/src/main/java/ognl/InappropriateExpressionException.java +++ b/src/main/java/ognl/InappropriateExpressionException.java @@ -1,47 +1,33 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; - /** * Exception thrown if an OGNL expression is evaluated in the wrong context; the usual * case is when an expression that does not end in a property reference is passed to * setValue. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class InappropriateExpressionException extends OgnlException -{ - public InappropriateExpressionException( Node tree ) - { - super( "Inappropriate OGNL expression: " + tree ); +public class InappropriateExpressionException extends OgnlException { + + private static final long serialVersionUID = 1976942828887727759L; + + public InappropriateExpressionException(Node tree) { + super("Inappropriate OGNL expression: " + tree); } } diff --git a/src/main/java/ognl/IntHashMap.java b/src/main/java/ognl/IntHashMap.java deleted file mode 100644 index bcd93960..00000000 --- a/src/main/java/ognl/IntHashMap.java +++ /dev/null @@ -1,355 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package ognl; - -import java.util.*; - -/** - * A Map that uses ints as the keys. - *

Use just like any java.util.Map, except that the keys must be ints. - * This is much faster than creating a new Integer for each access.

- *

For non-Map access (faster) use the put(int, Object) method.

- *

This class implements Map for convenience, but this is not the most - * efficient usage.

- * @see java.util.HashMap - * @see java.util.Map -*/ -public class IntHashMap extends Object implements Map -{ - private Entry table[]; - private int count; - private int threshold; - private float loadFactor; - - /*=================================================================== - Private static classes - ===================================================================*/ - private static class IntHashMapIterator implements Iterator - { - boolean keys; - int index; - Entry table[]; - Entry entry; - - IntHashMapIterator(Entry table[], boolean keys) - { - super(); - this.table = table; - this.keys = keys; - this.index = table.length; - } - - /*=================================================================== - Iterator interface - ===================================================================*/ - public boolean hasNext() - { - if (entry != null) { - return true; - } - while (index-- > 0) { - if ((entry = table[index]) != null) { - return true; - } - } - return false; - } - - public Object next() - { - if (entry == null) { - while ((index-- > 0) && ((entry = table[index]) == null)) { - /* do nothing */ - } - } - if (entry != null) { - Entry e = entry; - - entry = e.next; - return keys ? new Integer(e.key) : e.value; - } - throw new NoSuchElementException("IntHashMapIterator"); - } - - public void remove() - { - throw new UnsupportedOperationException("remove"); - } - } - - /*=================================================================== - Public static classes - ===================================================================*/ - public static class Entry extends Object - { - int hash; - int key; - Object value; - Entry next; - - public Entry() - { - super(); - } - } - - /*=================================================================== - Constructors - ===================================================================*/ - public IntHashMap(int initialCapacity, float loadFactor) - { - super(); - if (initialCapacity <= 0 || loadFactor <= 0.0) { - throw new IllegalArgumentException(); - } - this.loadFactor = loadFactor; - table = new Entry[initialCapacity]; - threshold = (int)(initialCapacity * loadFactor); - } - - public IntHashMap(int initialCapacity) - { - this(initialCapacity, 0.75f); - } - - public IntHashMap() - { - this(101, 0.75f); - } - - /*=================================================================== - Protected methods - ===================================================================*/ - protected void rehash() - { - int oldCapacity = table.length; - Entry oldTable[] = table; - int newCapacity = oldCapacity * 2 + 1; - Entry newTable[] = new Entry[newCapacity]; - - threshold = (int)(newCapacity * loadFactor); - table = newTable; - for (int i = oldCapacity ; i-- > 0 ;) { - for (Entry old = oldTable[i] ; old != null;) { - Entry e = old; - int index = ( e.hash & 0x7FFFFFFF ) % newCapacity; - - old = old.next; - e.next = newTable[index]; - newTable[index] = e; - } - } - } - - /*=================================================================== - Public methods - ===================================================================*/ - public final boolean containsKey(int key) - { - int index = (key & 0x7FFFFFFF) % table.length; - - for (Entry e = table[index] ; e != null ; e = e.next) { - if ((e.hash == key) && (e.key == key)) { - return true; - } - } - return false; - } - - public final Object get(int key) - { - int index = (key & 0x7FFFFFFF) % table.length; - - for (Entry e = table[index] ; e != null ; e = e.next) { - if ((e.hash == key) && (e.key == key)) { - return e.value; - } - } - return null; - } - - public final Object put(int key, Object value) - { - int index = ( key & 0x7FFFFFFF ) % table.length; - - if (value == null) { - throw new IllegalArgumentException(); - } - for (Entry e = table[index] ; e != null ; e = e.next) { - if ((e.hash == key) && (e.key == key)) { - Object old = e.value; - - e.value = value; - return old; - } - } - - if (count >= threshold) { - // Rehash the table if the threshold is exceeded. - rehash(); - return put(key, value); - } - - Entry e = new Entry(); - - e.hash = key; - e.key = key; - e.value = value; - e.next = table[index]; - table[index] = e; - ++count; - return null; - } - - public final Object remove(int key) - { - int index = (key & 0x7FFFFFFF) % table.length; - - for (Entry e = table[index], prev = null ; e != null ; prev = e, e = e.next) { - if ((e.hash == key) && (e.key == key)) { - if ( prev != null ) { - prev.next = e.next; - } else { - table[index] = e.next; - } - --count; - return e.value; - } - } - return null; - } - - /*=================================================================== - Map interface - ===================================================================*/ - public int size() - { - return count; - } - - public boolean isEmpty() - { - return count == 0; - } - - public Object get(Object key) - { - if (!(key instanceof Number)) { - throw new IllegalArgumentException("key is not an Number subclass"); - } - return get(((Number)key).intValue()); - } - - public Object put(Object key, Object value) - { - if (!(key instanceof Number)) { - throw new IllegalArgumentException( "key cannot be null" ); - } - return put(((Number)key).intValue(), value ); - } - - public void putAll(Map otherMap) - { - for (Iterator it = otherMap.keySet().iterator(); it.hasNext();) { - Object k = it.next(); - - put(k, otherMap.get(k)); - } - } - - public Object remove(Object key) - { - if (!(key instanceof Number)) { - throw new IllegalArgumentException("key cannot be null"); - } - return remove(((Number)key).intValue()); - } - - public void clear() - { - Entry tab[] = table; - - for (int index = tab.length; --index >= 0;) { - tab[index] = null; - } - count = 0; - } - - public boolean containsKey(Object key) - { - if (!(key instanceof Number)) { - throw new InternalError( "key is not an Number subclass" ); - } - return containsKey(((Number)key).intValue()); - } - - public boolean containsValue(Object value) - { - Entry tab[] = table; - - if (value == null) { - throw new IllegalArgumentException(); - } - for (int i = tab.length ; i-- > 0;) { - for (Entry e = tab[i] ; e != null ; e = e.next ) { - if (e.value.equals(value)) { - return true; - } - } - } - return false; - } - - public Set keySet() - { - Set result = new HashSet(); - - for (Iterator it = new IntHashMapIterator(table, true); it.hasNext();) { - result.add(it.next()); - } - return result; - } - - public Collection values() - { - List result = new ArrayList(); - - for (Iterator it = new IntHashMapIterator(table, false); it.hasNext();) { - result.add(it.next()); - } - return result; - } - - public Set entrySet() - { - throw new UnsupportedOperationException("entrySet"); - } -} diff --git a/src/main/java/ognl/IteratorElementsAccessor.java b/src/main/java/ognl/IteratorElementsAccessor.java index 65238c47..88f596fc 100644 --- a/src/main/java/ognl/IteratorElementsAccessor.java +++ b/src/main/java/ognl/IteratorElementsAccessor.java @@ -1,47 +1,34 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; +import java.util.Enumeration; +import java.util.Iterator; /** * Implementation of the ElementsAccessor interface for Iterators, which simply returns * the target iterator itself. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class IteratorElementsAccessor implements ElementsAccessor -{ - public Enumeration getElements( Object target ) - { - return new IteratorEnumeration( (Iterator)target ); +public class IteratorElementsAccessor implements ElementsAccessor { + + public Enumeration getElements(Object target) { + return new IteratorEnumeration((Iterator) target); } + } diff --git a/src/main/java/ognl/IteratorEnumeration.java b/src/main/java/ognl/IteratorEnumeration.java index ae470041..1f3783d3 100644 --- a/src/main/java/ognl/IteratorEnumeration.java +++ b/src/main/java/ognl/IteratorEnumeration.java @@ -1,51 +1,37 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; +import java.util.Enumeration; +import java.util.Iterator; /** * Maps an Iterator to an Enumeration - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class IteratorEnumeration extends Object implements Enumeration -{ - private Iterator it; +public class IteratorEnumeration implements Enumeration { + + private final Iterator it; - public IteratorEnumeration(Iterator it) - { - super(); - this.it = it; - } + public IteratorEnumeration(Iterator it) { + super(); + this.it = it; + } public boolean hasMoreElements() { return it.hasNext(); diff --git a/src/main/java/ognl/IteratorPropertyAccessor.java b/src/main/java/ognl/IteratorPropertyAccessor.java index b5d35bfc..0480d3f4 100644 --- a/src/main/java/ognl/IteratorPropertyAccessor.java +++ b/src/main/java/ognl/IteratorPropertyAccessor.java @@ -1,59 +1,43 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; +import java.util.Iterator; /** * Implementation of PropertyAccessor that provides "property" reference to * "next" and "hasNext". - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class IteratorPropertyAccessor extends ObjectPropertyAccessor - implements PropertyAccessor // This is here to make javadoc show this class as an implementor -{ - public Object getProperty( Map context, Object target, Object name ) throws OgnlException - { - Object result; - Iterator iterator = (Iterator)target; +public class IteratorPropertyAccessor extends ObjectPropertyAccessor implements PropertyAccessor { + + public Object getProperty(OgnlContext context, Object target, Object name) throws OgnlException { + Object result; + Iterator iterator = (Iterator) target; - if ( name instanceof String ) { + if (name instanceof String) { if (name.equals("next")) { result = iterator.next(); } else { if (name.equals("hasNext")) { result = iterator.hasNext() ? Boolean.TRUE : Boolean.FALSE; } else { - result = super.getProperty( context, target, name ); + result = super.getProperty(context, target, name); } } } else { @@ -62,8 +46,8 @@ public Object getProperty( Map context, Object target, Object name ) throws Ognl return result; } - public void setProperty( Map context, Object target, Object name, Object value ) throws OgnlException - { - throw new IllegalArgumentException( "can't set property " + name + " on Iterator" ); + public void setProperty(OgnlContext context, Object target, Object name, Object value) throws OgnlException { + throw new IllegalArgumentException("can't set property " + name + " on Iterator"); } + } diff --git a/src/main/java/ognl/JJTOgnlParserState.java b/src/main/java/ognl/JJTOgnlParserState.java index 30b3059d..a4c0ca93 100644 --- a/src/main/java/ognl/JJTOgnlParserState.java +++ b/src/main/java/ognl/JJTOgnlParserState.java @@ -2,122 +2,122 @@ package ognl; public class JJTOgnlParserState { - private java.util.List nodes; - private java.util.List marks; - - private int sp; // number of nodes on stack - private int mk; // current mark - private boolean node_created; - - public JJTOgnlParserState() { - nodes = new java.util.ArrayList(); - marks = new java.util.ArrayList(); - 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. */ - public boolean nodeCreated() { - return node_created; - } - - /* Call this to reinitialize the node stack. It is called - automatically by the parser's ReInit() method. */ - public 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. */ - public Node rootNode() { - return (Node)nodes.get(0); - } - - /* Pushes a node on to the stack. */ - public void pushNode(Node n) { - nodes.add(n); - ++sp; - } - - /* Returns the node on the top of the stack, and remove it from the - stack. */ - public Node popNode() { - if (--sp < mk) { - mk = ((Integer)marks.remove(marks.size()-1)).intValue(); + private java.util.List nodes; + private java.util.List marks; + + private int sp; // number of nodes on stack + private int mk; // current mark + private boolean node_created; + + public JJTOgnlParserState() { + nodes = new java.util.ArrayList(); + marks = new java.util.ArrayList(); + sp = 0; + mk = 0; } - return (Node)nodes.remove(nodes.size()-1); - } - /* Returns the node currently on the top of the stack. */ - public Node peekNode() { - return (Node)nodes.get(nodes.size()-1); - } + /* Determines whether the current node was actually closed and + pushed. This should only be called in the final user action of a + node scope. */ + public boolean nodeCreated() { + return node_created; + } + + /* Call this to reinitialize the node stack. It is called + automatically by the parser's ReInit() method. */ + public 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. */ + public Node rootNode() { + return (Node) nodes.get(0); + } - /* Returns the number of children on the stack in the current node - scope. */ - public int nodeArity() { - return sp - mk; - } + /* Pushes a node on to the stack. */ + public void pushNode(Node n) { + nodes.add(n); + ++sp; + } + /* Returns the node on the top of the stack, and remove it from the + stack. */ + public Node popNode() { + if (--sp < mk) { + mk = ((Integer) marks.remove(marks.size() - 1)).intValue(); + } + return (Node) nodes.remove(nodes.size() - 1); + } - public void clearNodeScope(Node n) { - while (sp > mk) { - popNode(); + /* Returns the node currently on the top of the stack. */ + public Node peekNode() { + return (Node) nodes.get(nodes.size() - 1); } - mk = ((Integer)marks.remove(marks.size()-1)).intValue(); - } - - - public void openNodeScope(Node n) { - marks.add(new Integer(mk)); - 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. */ - public void closeNodeScope(Node n, int num) { - mk = ((Integer)marks.remove(marks.size()-1)).intValue(); - while (num-- > 0) { - Node c = popNode(); - c.jjtSetParent(n); - n.jjtAddChild(c, num); + + /* Returns the number of children on the stack in the current node + scope. */ + public int nodeArity() { + return sp - mk; } - 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 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. */ - public void closeNodeScope(Node n, boolean condition) { - if (condition) { - int a = nodeArity(); - mk = ((Integer)marks.remove(marks.size()-1)).intValue(); - while (a-- > 0) { - Node c = popNode(); - c.jjtSetParent(n); - n.jjtAddChild(c, a); - } - n.jjtClose(); - pushNode(n); - node_created = true; - } else { - mk = ((Integer)marks.remove(marks.size()-1)).intValue(); - node_created = false; + + + public void clearNodeScope(Node n) { + while (sp > mk) { + popNode(); + } + mk = ((Integer) marks.remove(marks.size() - 1)).intValue(); + } + + + public void openNodeScope(Node n) { + marks.add(new Integer(mk)); + 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. */ + public void closeNodeScope(Node n, int num) { + mk = ((Integer) marks.remove(marks.size() - 1)).intValue(); + while (num-- > 0) { + Node 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 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. */ + public void closeNodeScope(Node n, boolean condition) { + if (condition) { + int a = nodeArity(); + mk = ((Integer) marks.remove(marks.size() - 1)).intValue(); + while (a-- > 0) { + Node c = popNode(); + c.jjtSetParent(n); + n.jjtAddChild(c, a); + } + n.jjtClose(); + pushNode(n); + node_created = true; + } else { + mk = ((Integer) marks.remove(marks.size() - 1)).intValue(); + node_created = false; + } } - } } /* JavaCC - OriginalChecksum=61071c68a05e7c9104307c34a2e37165 (do not edit this line) */ diff --git a/src/main/java/ognl/JavaCharStream.java b/src/main/java/ognl/JavaCharStream.java deleted file mode 100644 index 65846d17..00000000 --- a/src/main/java/ognl/JavaCharStream.java +++ /dev/null @@ -1,769 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. JavaCharStream.java Version 4.1 */ -/* JavaCCOptions:STATIC=false */ -package ognl; - -/** - * An implementation of interface CharStream, where the stream is assumed to - * contain only ASCII characters (with java-like unicode escape processing). - */ - -public class JavaCharStream -{ -/** Whether parser is static. */ - public static final boolean staticFlag = false; - static final int hexval(char c) throws java.io.IOException { - switch(c) - { - case '0' : - return 0; - case '1' : - return 1; - case '2' : - return 2; - case '3' : - return 3; - case '4' : - return 4; - case '5' : - return 5; - case '6' : - return 6; - case '7' : - return 7; - case '8' : - return 8; - case '9' : - return 9; - - case 'a' : - case 'A' : - return 10; - case 'b' : - case 'B' : - return 11; - case 'c' : - case 'C' : - return 12; - case 'd' : - case 'D' : - return 13; - case 'e' : - case 'E' : - return 14; - case 'f' : - case 'F' : - return 15; - } - - throw new java.io.IOException(); // Should never come here - } - -/** Position in buffer. */ - public int bufpos = -1; - int bufsize; - int available; - int tokenBegin; - protected int bufline[]; - protected int bufcolumn[]; - - protected int column = 0; - protected int line = 1; - - protected boolean prevCharIsCR = false; - protected boolean prevCharIsLF = false; - - protected java.io.Reader inputStream; - - protected char[] nextCharBuf; - protected char[] buffer; - protected int maxNextCharInd = 0; - protected int nextCharInd = -1; - protected int inBuf = 0; - protected int tabSize = 8; - - protected void setTabSize(int i) { tabSize = i; } - protected int getTabSize(int i) { return tabSize; } - - protected void ExpandBuff(boolean wrapAround) - { - char[] newbuffer = new char[bufsize + 2048]; - int newbufline[] = new int[bufsize + 2048]; - int newbufcolumn[] = new int[bufsize + 2048]; - - try - { - if (wrapAround) - { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - System.arraycopy(buffer, 0, newbuffer, - bufsize - tokenBegin, bufpos); - buffer = newbuffer; - - System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); - System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); - bufline = newbufline; - - System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); - System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); - bufcolumn = newbufcolumn; - - bufpos += (bufsize - tokenBegin); - } - else - { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - buffer = newbuffer; - - System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); - bufline = newbufline; - - System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); - bufcolumn = newbufcolumn; - - bufpos -= tokenBegin; - } - } - catch (Throwable t) - { - throw new Error(t.getMessage()); - } - - available = (bufsize += 2048); - tokenBegin = 0; - } - - protected void FillBuff() throws java.io.IOException - { - int i; - if (maxNextCharInd == 4096) - maxNextCharInd = nextCharInd = 0; - - try { - if ((i = inputStream.read(nextCharBuf, maxNextCharInd, - 4096 - maxNextCharInd)) == -1) - { - inputStream.close(); - throw new java.io.IOException(); - } - else - maxNextCharInd += i; - return; - } - catch(java.io.IOException e) { - if (bufpos != 0) - { - --bufpos; - backup(0); - } - else - { - bufline[bufpos] = line; - bufcolumn[bufpos] = column; - } - throw e; - } - } - - protected char ReadByte() throws java.io.IOException - { - if (++nextCharInd >= maxNextCharInd) - FillBuff(); - - return nextCharBuf[nextCharInd]; - } - - /** - * Begin processing a new token, returning the starting character for the token. - * - * @return starting character for token. - * @throws java.io.IOException if the operation fails a read operation. - */ - public char BeginToken() throws java.io.IOException - { - if (inBuf > 0) - { - --inBuf; - - if (++bufpos == bufsize) - bufpos = 0; - - tokenBegin = bufpos; - return buffer[bufpos]; - } - - tokenBegin = 0; - bufpos = -1; - - return readChar(); - } - - protected void AdjustBuffSize() - { - if (available == bufsize) - { - if (tokenBegin > 2048) - { - bufpos = 0; - available = tokenBegin; - } - else - ExpandBuff(false); - } - else if (available > tokenBegin) - available = bufsize; - else if ((tokenBegin - available) < 2048) - ExpandBuff(true); - else - available = tokenBegin; - } - - protected 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 += (tabSize - (column % tabSize)); - break; - default : - break; - } - - bufline[bufpos] = line; - bufcolumn[bufpos] = column; - } - - /** - * Read a character. - * - * @return the character that was read for processing. - * @throws java.io.IOException if the operation fails a read operation. - */ - public char readChar() throws java.io.IOException - { - if (inBuf > 0) - { - --inBuf; - - if (++bufpos == bufsize) - bufpos = 0; - - return buffer[bufpos]; - } - - char c; - - if (++bufpos == available) - AdjustBuffSize(); - - if ((buffer[bufpos] = c = ReadByte()) == '\\') - { - UpdateLineColumn(c); - - int backSlashCnt = 1; - - for (;;) // Read all the backslashes - { - if (++bufpos == available) - AdjustBuffSize(); - - try - { - if ((buffer[bufpos] = c = ReadByte()) != '\\') - { - UpdateLineColumn(c); - // found a non-backslash char. - if ((c == 'u') && ((backSlashCnt & 1) == 1)) - { - if (--bufpos < 0) - bufpos = bufsize - 1; - - break; - } - - backup(backSlashCnt); - return '\\'; - } - } - catch(java.io.IOException e) - { - if (backSlashCnt > 1) - backup(backSlashCnt-1); - - return '\\'; - } - - UpdateLineColumn(c); - backSlashCnt++; - } - - // Here, we have seen an odd number of backslash's followed by a 'u' - try - { - while ((c = ReadByte()) == 'u') - ++column; - - buffer[bufpos] = c = (char)(hexval(c) << 12 | - hexval(ReadByte()) << 8 | - hexval(ReadByte()) << 4 | - hexval(ReadByte())); - - column += 4; - } - catch(java.io.IOException e) - { - throw new Error("Invalid escape character at line " + line + - " column " + column + "."); - } - - if (backSlashCnt == 1) - return c; - else - { - backup(backSlashCnt - 1); - return '\\'; - } - } - else - { - UpdateLineColumn(c); - return c; - } - } - - /** - * Get the current column number. - * - * @return the current column number. - * @deprecated - * @see #getEndColumn - */ - public int getColumn() { - return bufcolumn[bufpos]; - } - - /** - * Get the current line number. - * - * @return the current line number. - * @deprecated - * @see #getEndLine - */ - public int getLine() { - return bufline[bufpos]; - } - - /** - * Get end column. - * - * @return the end column number. - */ - public int getEndColumn() { - return bufcolumn[bufpos]; - } - - /** - * Get end line. - * - * @return the end line number. - */ - public int getEndLine() { - return bufline[bufpos]; - } - - /** @return column of token start */ - public int getBeginColumn() { - return bufcolumn[tokenBegin]; - } - - /** @return line number of token start */ - public int getBeginLine() { - return bufline[tokenBegin]; - } - - /** - * Retreat. - * - * @param amount the amount to backup (retreat) in the stream. - */ - public void backup(int amount) { - - inBuf += amount; - if ((bufpos -= amount) < 0) - bufpos += bufsize; - } - - /** - * Constructor. - * - * @param dstream the datastream to read from. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - * @param buffersize the size of the initial buffer to use to process the dstream. - */ - public JavaCharStream(java.io.Reader 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]; - nextCharBuf = new char[4096]; - } - - /** - * Constructor. - * - * @param dstream the datastream to read from. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - */ - public JavaCharStream(java.io.Reader dstream, - int startline, int startcolumn) - { - this(dstream, startline, startcolumn, 4096); - } - - /** - * Constructor. - * - * @param dstream the datastream to read from. - */ - public JavaCharStream(java.io.Reader dstream) - { - this(dstream, 1, 1, 4096); - } - - /** - * Reinitialise. - * - * @param dstream the datastream to read from. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - * @param buffersize the size of the initial buffer to use to process the dstream. - */ - public void ReInit(java.io.Reader 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]; - nextCharBuf = new char[4096]; - } - prevCharIsLF = prevCharIsCR = false; - tokenBegin = inBuf = maxNextCharInd = 0; - nextCharInd = bufpos = -1; - } - - /** - * Reinitialise. - * - * @param dstream the datastream to read from. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - */ - public void ReInit(java.io.Reader dstream, - int startline, int startcolumn) - { - ReInit(dstream, startline, startcolumn, 4096); - } - - /** - * Reinitialise. - * - * @param dstream the datastream to read from. - */ - public void ReInit(java.io.Reader dstream) - { - ReInit(dstream, 1, 1, 4096); - } - - /** - * Constructor. - * - * @param dstream the datastream to read from. - * @param encoding the encoding to use for the dstream. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - * @param buffersize the size of the initial buffer to use to process the dstream. - * @throws java.io.UnsupportedEncodingException if the chosen encoding is not supported. - */ - public JavaCharStream(java.io.InputStream dstream, String encoding, int startline, - int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException - { - this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); - } - - /** - * Constructor. - * - * @param dstream the datastream to read from. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - * @param buffersize the size of the initial buffer to use to process the dstream. - */ - public JavaCharStream(java.io.InputStream dstream, int startline, - int startcolumn, int buffersize) - { - this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); - } - - /** - * Constructor. - * - * @param dstream the datastream to read from. - * @param encoding the encoding to use for the dstream. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - * @throws java.io.UnsupportedEncodingException if the chosen encoding is not supported. - */ - public JavaCharStream(java.io.InputStream dstream, String encoding, int startline, - int startcolumn) throws java.io.UnsupportedEncodingException - { - this(dstream, encoding, startline, startcolumn, 4096); - } - - /** - * Constructor. - * - * @param dstream the datastream to read from. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - */ - public JavaCharStream(java.io.InputStream dstream, int startline, - int startcolumn) - { - this(dstream, startline, startcolumn, 4096); - } - - /** - * Constructor. - * - * @param dstream the datastream to read from. - * @param encoding the encoding to use for the dstream. - * @throws java.io.UnsupportedEncodingException if the chosen encoding is not supported. - */ - public JavaCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException - { - this(dstream, encoding, 1, 1, 4096); - } - - /** - * Constructor. - * - * @param dstream the datastream to read from. - */ - public JavaCharStream(java.io.InputStream dstream) - { - this(dstream, 1, 1, 4096); - } - - /** - * Reinitialise. - * - * @param dstream the datastream to read from. - * @param encoding the encoding to use for the dstream. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - * @param buffersize the size of the initial buffer to use to process the dstream. - * @throws java.io.UnsupportedEncodingException if the chosen encoding is not supported. - */ - public void ReInit(java.io.InputStream dstream, String encoding, int startline, - int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException - { - ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); - } - - /** - * Reinitialise. - * - * @param dstream the datastream to read from. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - * @param buffersize the size of the initial buffer to use to process the dstream. - */ - public void ReInit(java.io.InputStream dstream, int startline, - int startcolumn, int buffersize) - { - ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); - } - - /** - * Reinitialise. - * - * @param dstream the datastream to read from. - * @param encoding the encoding to use for the dstream. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - * @throws java.io.UnsupportedEncodingException if the chosen encoding is not supported. - */ - public void ReInit(java.io.InputStream dstream, String encoding, int startline, - int startcolumn) throws java.io.UnsupportedEncodingException - { - ReInit(dstream, encoding, startline, startcolumn, 4096); - } - - /** - * Reinitialise. - * - * @param dstream the datastream to read from. - * @param startline the line number to start processing from. - * @param startcolumn the column number to start processing from. - */ - public void ReInit(java.io.InputStream dstream, int startline, - int startcolumn) - { - ReInit(dstream, startline, startcolumn, 4096); - } - - /** - * Reinitialise. - * - * @param dstream the datastream to read from. - * @param encoding the encoding to use for the dstream. - * @throws java.io.UnsupportedEncodingException if the chosen encoding is not supported. - */ - public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException - { - ReInit(dstream, encoding, 1, 1, 4096); - } - - /** - * Reinitialise. - * - * @param dstream the datastream to read from. - */ - public void ReInit(java.io.InputStream dstream) - { - ReInit(dstream, 1, 1, 4096); - } - - /** @return token image as String */ - public String GetImage() - { - if (bufpos >= tokenBegin) - return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); - else - return new String(buffer, tokenBegin, bufsize - tokenBegin) + - new String(buffer, 0, bufpos + 1); - } - - /** - * Get the suffix of the specified length. - * - * @param len the length of the suffix to get. - * @return suffix - */ - public char[] GetSuffix(int len) - { - char[] ret = new char[len]; - - if ((bufpos + 1) >= len) - System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); - else - { - System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, - len - bufpos - 1); - System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); - } - - return ret; - } - - /** Set buffers back to null when finished. */ - public void Done() - { - nextCharBuf = null; - buffer = null; - bufline = null; - bufcolumn = null; - } - - /** - * Method to adjust line and column numbers for the start of a token. - * - * @param newLine the new line number for the start of a token. - * @param newCol the new column number for the start of a token. - */ - 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]; - } - -} -/* JavaCC - OriginalChecksum=7ef64849e2b59fe6d1ffdca3bf0ddd2b (do not edit this line) */ diff --git a/src/main/java/ognl/JavaSource.java b/src/main/java/ognl/JavaSource.java index e3af0d19..75195e6a 100644 --- a/src/main/java/ognl/JavaSource.java +++ b/src/main/java/ognl/JavaSource.java @@ -1,5 +1,20 @@ -/** - * +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package ognl; @@ -8,30 +23,29 @@ /** * Defines an object that can return a representation of itself and any objects it contains * in the form of a {@link String} embedded with literal java statements. - * + * * @author jkuhnert */ -public interface JavaSource -{ - +public interface JavaSource { + /** - * Expected to return a java source representation of itself such that + * Expected to return a java source representation of itself such that * it could be turned into a literal java expression to be compiled and * executed for {@link ExpressionAccessor#get(OgnlContext, Object)} calls. - * + * * @param context the OgnlContext within which to perform the operation. - * @param target the Object from which to retrieve the get source string. + * @param target the Object from which to retrieve the get source string. * @return Literal java string representation of an object get. */ String toGetSourceString(OgnlContext context, Object target); - + /** - * Expected to return a java source representation of itself such that + * Expected to return a java source representation of itself such that * it could be turned into a literal java expression to be compiled and * executed for {@link ExpressionAccessor#get(OgnlContext, Object)} calls. - * + * * @param context the OgnlContext within which to perform the operation. - * @param target the Object from which to retrieve the set source string. + * @param target the Object from which to retrieve the set source string. * @return Literal java string representation of an object set. */ String toSetSourceString(OgnlContext context, Object target); diff --git a/src/main/java/ognl/ListPropertyAccessor.java b/src/main/java/ognl/ListPropertyAccessor.java index 9c675781..685dad02 100644 --- a/src/main/java/ognl/ListPropertyAccessor.java +++ b/src/main/java/ognl/ListPropertyAccessor.java @@ -1,58 +1,43 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; /** * Implementation of PropertyAccessor that uses numbers and dynamic subscripts as properties to * index into Lists. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class ListPropertyAccessor extends ObjectPropertyAccessor implements PropertyAccessor -{ +public class ListPropertyAccessor extends ObjectPropertyAccessor implements PropertyAccessor { - public Object getProperty(Map context, Object target, Object name) - throws OgnlException - { - List list = (List) target; + public Object getProperty(OgnlContext context, Object target, Object name) throws OgnlException { + List list = (List) target; if (name instanceof String) { - Object result = null; + Object result; if (name.equals("size")) { - result = new Integer(list.size()); + result = list.size(); } else { if (name.equals("iterator")) { result = list.iterator(); @@ -73,7 +58,7 @@ public Object getProperty(Map context, Object target, Object name) if (name instanceof DynamicSubscript) { int len = list.size(); - switch(((DynamicSubscript) name).getFlag()) { + switch (((DynamicSubscript) name).getFlag()) { case DynamicSubscript.FIRST: return len > 0 ? list.get(0) : null; case DynamicSubscript.MID: @@ -81,22 +66,21 @@ public Object getProperty(Map context, Object target, Object name) case DynamicSubscript.LAST: return len > 0 ? list.get(len - 1) : null; case DynamicSubscript.ALL: - return new ArrayList(list); + return new ArrayList<>(list); } } throw new NoSuchPropertyException(target, name); } - public void setProperty(Map context, Object target, Object name, Object value) - throws OgnlException - { - if (name instanceof String && ((String)name).indexOf("$") < 0) { + public void setProperty(OgnlContext context, Object target, Object name, Object value) + throws OgnlException { + if (name instanceof String && !((String) name).contains("$")) { super.setProperty(context, target, name, value); return; } - List list = (List) target; + List list = (List) target; if (name instanceof Number) { list.set(((Number) name).intValue(), value); @@ -105,7 +89,7 @@ public void setProperty(Map context, Object target, Object name, Object value) if (name instanceof DynamicSubscript) { int len = list.size(); - switch(((DynamicSubscript) name).getFlag()) { + switch (((DynamicSubscript) name).getFlag()) { case DynamicSubscript.FIRST: if (len > 0) list.set(0, value); return; @@ -115,11 +99,10 @@ public void setProperty(Map context, Object target, Object name, Object value) case DynamicSubscript.LAST: if (len > 0) list.set(len - 1, value); return; - case DynamicSubscript.ALL: - { + case DynamicSubscript.ALL: { if (!(value instanceof Collection)) throw new OgnlException("Value must be a collection"); list.clear(); - list.addAll((Collection) value); + list.addAll((Collection) value); return; } } @@ -128,11 +111,10 @@ public void setProperty(Map context, Object target, Object name, Object value) throw new NoSuchPropertyException(target, name); } - public Class getPropertyClass(OgnlContext context, Object target, Object index) - { + public Class getPropertyClass(OgnlContext context, Object target, Object index) { if (index instanceof String) { - String indexStr = (String)index; - String key = (indexStr.indexOf('"') >= 0? indexStr.replaceAll("\"", "") : indexStr); + String indexStr = (String) index; + String key = (indexStr.indexOf('"') >= 0 ? indexStr.replaceAll("\"", "") : indexStr); if (key.equals("size")) { return int.class; } else { @@ -154,30 +136,23 @@ public Class getPropertyClass(OgnlContext context, Object target, Object index) return null; } - public String getSourceAccessor(OgnlContext context, Object target, Object index) - { + public String getSourceAccessor(OgnlContext context, Object target, Object index) { String indexStr = index.toString(); if (indexStr.indexOf('"') >= 0) indexStr = indexStr.replaceAll("\"", ""); - if (String.class.isInstance(index)) - { - if (indexStr.equals("size")) - { + if (index instanceof String) { + if (indexStr.equals("size")) { context.setCurrentAccessor(List.class); context.setCurrentType(int.class); return ".size()"; - } else - { - if (indexStr.equals("iterator")) - { + } else { + if (indexStr.equals("iterator")) { context.setCurrentAccessor(List.class); context.setCurrentType(Iterator.class); return ".iterator()"; - } else - { - if (indexStr.equals("isEmpty") || indexStr.equals("empty")) - { + } else { + if (indexStr.equals("isEmpty") || indexStr.equals("empty")) { context.setCurrentAccessor(List.class); context.setCurrentType(boolean.class); return ".isEmpty()"; @@ -188,17 +163,13 @@ public String getSourceAccessor(OgnlContext context, Object target, Object index // TODO: This feels really inefficient, must be some better way // check if the index string represents a method on a custom class implementing java.util.List instead.. - - if (context.getCurrentObject() != null && !Number.class.isInstance(context.getCurrentObject())) - { + if (context.getCurrentObject() != null && !(context.getCurrentObject() instanceof Number)) { try { Method m = OgnlRuntime.getReadMethod(target.getClass(), indexStr); - - if (m != null) + if (m != null) { return super.getSourceAccessor(context, target, index); - - } catch (Throwable t) - { + } + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } @@ -208,15 +179,13 @@ public String getSourceAccessor(OgnlContext context, Object target, Object index // need to convert to primitive for list index access // System.out.println("Curent type: " + context.getCurrentType() + " current object type " + context.getCurrentObject().getClass()); - if (!context.getCurrentType().isPrimitive() && Number.class.isAssignableFrom(context.getCurrentType())) - { + if (!context.getCurrentType().isPrimitive() && Number.class.isAssignableFrom(context.getCurrentType())) { indexStr += "." + OgnlRuntime.getNumericValueGetter(context.getCurrentType()); - } else if (context.getCurrentObject() != null && Number.class.isAssignableFrom(context.getCurrentObject().getClass()) - && !context.getCurrentType().isPrimitive()) - { + } else if (context.getCurrentObject() != null && Number.class.isAssignableFrom(context.getCurrentObject().getClass()) + && !context.getCurrentType().isPrimitive()) { // means it needs to be cast first as well - String toString = String.class.isInstance(index) && context.getCurrentType() != Object.class ? "" : ".toString()"; + String toString = index instanceof String && context.getCurrentType() != Object.class ? "" : ".toString()"; indexStr = "ognl.OgnlOps#getIntValue(" + indexStr + toString + ")"; } @@ -226,8 +195,7 @@ public String getSourceAccessor(OgnlContext context, Object target, Object index return ".get(" + indexStr + ")"; } - public String getSourceSetter(OgnlContext context, Object target, Object index) - { + public String getSourceSetter(OgnlContext context, Object target, Object index) { String indexStr = index.toString(); if (indexStr.indexOf('"') >= 0) indexStr = indexStr.replaceAll("\"", ""); @@ -236,47 +204,32 @@ public String getSourceSetter(OgnlContext context, Object target, Object index) // check if the index string represents a method on a custom class implementing java.util.List instead.. /* System.out.println("Listpropertyaccessor setter using index: " + index + " and current object: " + context.getCurrentObject() + " number is current object? " + Number.class.isInstance(context.getCurrentObject()));*/ - - if (context.getCurrentObject() != null && !Number.class.isInstance(context.getCurrentObject())) - { + + if (context.getCurrentObject() != null && !(context.getCurrentObject() instanceof Number)) { try { Method m = OgnlRuntime.getWriteMethod(target.getClass(), indexStr); - - if (m != null || !context.getCurrentType().isPrimitive()) - { + + if (m != null || !context.getCurrentType().isPrimitive()) { // System.out.println("super source setter returned: " + super.getSourceSetter(context, target, index)); return super.getSourceSetter(context, target, index); } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } - /* if (String.class.isInstance(index)) - { - context.setCurrentAccessor(List.class); - return ""; - }*/ - context.setCurrentAccessor(List.class); // need to convert to primitive for list index access - if (!context.getCurrentType().isPrimitive() && Number.class.isAssignableFrom(context.getCurrentType())) - { + if (!context.getCurrentType().isPrimitive() && Number.class.isAssignableFrom(context.getCurrentType())) { indexStr += "." + OgnlRuntime.getNumericValueGetter(context.getCurrentType()); - } else if (context.getCurrentObject() != null && Number.class.isAssignableFrom(context.getCurrentObject().getClass()) - && !context.getCurrentType().isPrimitive()) - { + } else if (context.getCurrentObject() != null && Number.class.isAssignableFrom(context.getCurrentObject().getClass()) && !context.getCurrentType().isPrimitive()) { // means it needs to be cast first as well - - String toString = String.class.isInstance(index) && context.getCurrentType() != Object.class ? "" : ".toString()"; - + String toString = index instanceof String && context.getCurrentType() != Object.class ? "" : ".toString()"; indexStr = "ognl.OgnlOps#getIntValue(" + indexStr + toString + ")"; } - context.setCurrentType(Object.class); return ".set(" + indexStr + ", $3)"; diff --git a/src/main/java/ognl/MapElementsAccessor.java b/src/main/java/ognl/MapElementsAccessor.java index f4c96806..05ffdc3b 100644 --- a/src/main/java/ognl/MapElementsAccessor.java +++ b/src/main/java/ognl/MapElementsAccessor.java @@ -1,46 +1,33 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; +import java.util.Enumeration; +import java.util.Map; /** * Implementation of ElementsAccessor that returns an iterator over the map's values. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class MapElementsAccessor implements ElementsAccessor -{ - public Enumeration getElements( Object target ) - { - return new IteratorEnumeration( ((Map)target).values().iterator() ); +public class MapElementsAccessor implements ElementsAccessor { + + public Enumeration getElements(Object target) { + return new IteratorEnumeration(((Map) target).values().iterator()); } + } diff --git a/src/main/java/ognl/MapPropertyAccessor.java b/src/main/java/ognl/MapPropertyAccessor.java index 011234f9..feab17f2 100644 --- a/src/main/java/ognl/MapPropertyAccessor.java +++ b/src/main/java/ognl/MapPropertyAccessor.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.util.Collection; @@ -37,22 +25,19 @@ /** * Implementation of PropertyAccessor that sets and gets properties by storing and looking up values * in Maps. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class MapPropertyAccessor implements PropertyAccessor -{ +public class MapPropertyAccessor implements PropertyAccessor { - public Object getProperty(Map context, Object target, Object name) - throws OgnlException - { + public Object getProperty(OgnlContext context, Object target, Object name) + throws OgnlException { Object result; - Map map = (Map) target; - Node currentNode = ((OgnlContext) context).getCurrentNode().jjtGetParent(); + Map map = (Map) target; + Node currentNode = context.getCurrentNode().jjtGetParent(); boolean indexedAccess = false; - if (currentNode == null) { throw new OgnlException("node is null for '" + name + "'"); } + if (currentNode == null) { + throw new OgnlException("node is null for '" + name + "'"); + } if (!(currentNode instanceof ASTProperty)) { currentNode = currentNode.jjtGetParent(); } @@ -62,7 +47,7 @@ public Object getProperty(Map context, Object target, Object name) if ((name instanceof String) && !indexedAccess) { if (name.equals("size")) { - result = new Integer(map.size()); + result = map.size(); } else { if (name.equals("keys") || name.equals("keySet")) { result = map.keySet(); @@ -85,16 +70,13 @@ public Object getProperty(Map context, Object target, Object name) return result; } - public void setProperty(Map context, Object target, Object name, Object value) - throws OgnlException - { - Map map = (Map) target; + public void setProperty(OgnlContext context, Object target, Object name, Object value) throws OgnlException { + Map map = (Map) target; map.put(name, value); } - public String getSourceAccessor(OgnlContext context, Object target, Object index) - { - Node currentNode = ((OgnlContext) context).getCurrentNode().jjtGetParent(); + public String getSourceAccessor(OgnlContext context, Object target, Object index) { + Node currentNode = context.getCurrentNode().jjtGetParent(); boolean indexedAccess = false; if (currentNode == null) @@ -110,48 +92,50 @@ public String getSourceAccessor(OgnlContext context, Object target, Object index context.setCurrentAccessor(Map.class); context.setCurrentType(Object.class); - - if (String.class.isInstance(index) && !indexedAccess) - { - String key = (indexStr.indexOf('"') >= 0? indexStr.replaceAll("\"", "") : indexStr); - - if (key.equals("size")) { - context.setCurrentType(int.class); - return ".size()"; - } else if (key.equals("keys") || key.equals("keySet")) { - context.setCurrentType(Set.class); - return ".keySet()"; - } else if (key.equals("values")) { - context.setCurrentType(Collection.class); - return ".values()"; - } else if (key.equals("isEmpty")) { - context.setCurrentType(boolean.class); - return ".isEmpty()"; + + if (index instanceof String && !indexedAccess) { + String key = (indexStr.indexOf('"') >= 0 ? indexStr.replaceAll("\"", "") : indexStr); + + switch (key) { + case "size": + context.setCurrentType(int.class); + return ".size()"; + case "keys": + case "keySet": + context.setCurrentType(Set.class); + return ".keySet()"; + case "values": + context.setCurrentType(Collection.class); + return ".values()"; + case "isEmpty": + context.setCurrentType(boolean.class); + return ".isEmpty()"; } } - + return ".get(" + indexStr + ")"; } - public String getSourceSetter(OgnlContext context, Object target, Object index) - { + public String getSourceSetter(OgnlContext context, Object target, Object index) { context.setCurrentAccessor(Map.class); context.setCurrentType(Object.class); String indexStr = index.toString(); - if (String.class.isInstance(index)) - { - String key = (indexStr.indexOf('"') >= 0? indexStr.replaceAll("\"", "") : indexStr); - - if (key.equals("size")) - return ""; - else if (key.equals("keys") || key.equals("keySet")) - return ""; - else if (key.equals("values")) - return ""; - else if (key.equals("isEmpty")) - return ""; + if (index instanceof String) { + String key = (indexStr.indexOf('"') >= 0 ? indexStr.replaceAll("\"", "") : indexStr); + + switch (key) { + case "size": + return ""; + case "keys": + case "keySet": + return ""; + case "values": + return ""; + case "isEmpty": + return ""; + } } return ".put(" + indexStr + ", $3)"; diff --git a/src/main/java/ognl/MemberAccess.java b/src/main/java/ognl/MemberAccess.java index 7e63ed67..2be4b951 100644 --- a/src/main/java/ognl/MemberAccess.java +++ b/src/main/java/ognl/MemberAccess.java @@ -1,80 +1,62 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.lang.reflect.Member; -import java.util.Map; /** * This interface provides a hook for preparing for accessing members * of objects. The Java2 version of this method can allow access - * to otherwise inaccessable members, such as private fields. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - * @version 15 October 1999 + * to otherwise inaccessible members, such as private fields. */ -public interface MemberAccess -{ +public interface MemberAccess { /** * Sets the member up for accessibility - * - * @param context the current execution context. - * @param target the Object upon which to perform the setup operation. - * @param member the Member upon which to perform the setup operation. + * + * @param context the current execution context. + * @param target the Object upon which to perform the setup operation. + * @param member the Member upon which to perform the setup operation. * @param propertyName the property upon which to perform the setup operation. * @return the Object representing the original accessibility state of the target prior to the setup operation. */ - public Object setup(Map context, Object target, Member member, String propertyName); + Object setup(OgnlContext context, Object target, Member member, String propertyName); /** * Restores the member from the previous setup call. - * - * @param context the current execution context. - * @param target the Object upon which to perform the setup operation. - * @param member the Member upon which to perform the setup operation. + * + * @param context the current execution context. + * @param target the Object upon which to perform the setup operation. + * @param member the Member upon which to perform the setup operation. * @param propertyName the property upon which to perform the setup operation. - * @param state the Object holding the state to restore (target state prior to the setup operation). + * @param state the Object holding the state to restore (target state prior to the setup operation). */ - public void restore(Map context, Object target, Member member, String propertyName, Object state); + void restore(OgnlContext context, Object target, Member member, String propertyName, Object state); /** - Returns true if the given member is accessible or can be made accessible - by this object. - * - * @param context the current execution context. - * @param target the Object to test accessibility for. - * @param member the Member to test accessibility for. + * Returns true if the given member is accessible or can be made accessible + * by this object. + * + * @param context the current execution context. + * @param target the Object to test accessibility for. + * @param member the Member to test accessibility for. * @param propertyName the property to test accessibility for. * @return true if the target/member/propertyName is accessible in the context, false otherwise. */ - public boolean isAccessible(Map context, Object target, Member member, String propertyName); + boolean isAccessible(OgnlContext context, Object target, Member member, String propertyName); } diff --git a/src/main/java/ognl/MethodAccessor.java b/src/main/java/ognl/MethodAccessor.java index 70547778..4e145f87 100644 --- a/src/main/java/ognl/MethodAccessor.java +++ b/src/main/java/ognl/MethodAccessor.java @@ -1,69 +1,50 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.Map; - /** * This interface defines methods for calling methods in a target object. * Methods are broken up into static and instance methods for convenience. * indexes into the target object, which must be an array. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public interface MethodAccessor -{ +public interface MethodAccessor { /** * Calls the static method named with the arguments given on the class given. + * * @param context expression context in which the method should be called * @param targetClass the object in which the method exists * @param methodName the name of the method * @param args the arguments to the method - * - * @return result of calling the method - * @exception MethodFailedException if there is an error calling the method + * @return result of calling the method + * @throws MethodFailedException if there is an error calling the method */ - Object callStaticMethod( Map context, Class targetClass, String methodName, Object[] args ) - throws MethodFailedException; + Object callStaticMethod(OgnlContext context, Class targetClass, String methodName, Object[] args) throws MethodFailedException; /** * Calls the method named with the arguments given. - * @param context expression context in which the method should be called - * @param target the object in which the method exists - * @param methodName the name of the method - * @param args the arguments to the method - * @return result of calling the method - * @exception MethodFailedException if there is an error calling the method + * + * @param context expression context in which the method should be called + * @param target the object in which the method exists + * @param methodName the name of the method + * @param args the arguments to the method + * @return result of calling the method + * @throws MethodFailedException if there is an error calling the method */ - Object callMethod( Map context, Object target, String methodName, Object[] args ) - throws MethodFailedException; + Object callMethod(OgnlContext context, Object target, String methodName, Object[] args) throws MethodFailedException; } diff --git a/src/main/java/ognl/MethodFailedException.java b/src/main/java/ognl/MethodFailedException.java index f4986d8f..534c43bd 100644 --- a/src/main/java/ognl/MethodFailedException.java +++ b/src/main/java/ognl/MethodFailedException.java @@ -1,50 +1,35 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; /** * Exception thrown if a method or constructor call fails. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class MethodFailedException extends OgnlException -{ - public MethodFailedException( Object source, String name) - { - super( "Method \"" + name + "\" failed for object " + source); +public class MethodFailedException extends OgnlException { + + private static final long serialVersionUID = 2490616172311289862L; + + public MethodFailedException(Object source, String name) { + super("Method \"" + name + "\" failed for object " + source); } - public MethodFailedException( Object source, String name, Throwable reason ) - { - super( "Method \"" + name + "\" failed for object " + source, reason ); + public MethodFailedException(Object source, String name, Throwable reason) { + super("Method \"" + name + "\" failed for object " + source, reason); } } diff --git a/src/main/java/ognl/NoSuchPropertyException.java b/src/main/java/ognl/NoSuchPropertyException.java index 26c99bc1..ea0ec983 100644 --- a/src/main/java/ognl/NoSuchPropertyException.java +++ b/src/main/java/ognl/NoSuchPropertyException.java @@ -1,68 +1,51 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; - /** * Exception thrown if a property is attempted to be extracted from an object that does - * not have such a property. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) + * not have such a property.* */ -public class NoSuchPropertyException extends OgnlException -{ - private Object target; - private Object name; +public class NoSuchPropertyException extends OgnlException { + + private static final long serialVersionUID = -4394252641910997725L; + + private Object target; + private Object name; - public NoSuchPropertyException( Object target, Object name ) - { - super( getReason(target, name) ); + public NoSuchPropertyException(Object target, Object name) { + super(getReason(target, name)); } - public NoSuchPropertyException( Object target, Object name, Throwable reason ) - { - super( getReason(target, name), reason ); - this.target = target; - this.name = name; + public NoSuchPropertyException(Object target, Object name, Throwable reason) { + super(getReason(target, name), reason); + this.target = target; + this.name = name; } - static String getReason(Object target, Object name) - { - String ret = null; + static String getReason(Object target, Object name) { + String ret; if (target == null) ret = "null"; else if (target instanceof Class) - ret = ((Class)target).getName(); + ret = ((Class) target).getName(); else ret = target.getClass().getName(); @@ -71,13 +54,11 @@ else if (target instanceof Class) return ret; } - public Object getTarget() - { - return target; + public Object getTarget() { + return target; } - public Object getName() - { - return name; + public Object getName() { + return name; } } diff --git a/src/main/java/ognl/Node.java b/src/main/java/ognl/Node.java index b012119a..5b0603a3 100644 --- a/src/main/java/ognl/Node.java +++ b/src/main/java/ognl/Node.java @@ -1,124 +1,116 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionAccessor; /** - JJTree interface for AST nodes, as modified to handle the OGNL operations getValue and - setValue. JJTree's original comment: + * JJTree interface for AST nodes, as modified to handle the OGNL operations getValue and + * setValue. JJTree's original comment: + *

+ * All AST nodes must implement this interface. It provides basic + * machinery for constructing the parent and child relationships + * between nodes. + */ +public interface Node extends JavaSource { - All AST nodes must implement this interface. It provides basic - machinery for constructing the parent and child relationships - between nodes. - - @author Luke Blanshard (blanshlu@netscape.net) - @author Drew Davidson (drew@ognl.org) -*/ -public interface Node extends JavaSource -{ - - /** This method is called after the node has been made the current - node. It indicates that child nodes can now be added to it. */ - public void jjtOpen(); + /** + * This method is called after the node has been made the current + * node. It indicates that child nodes can now be added to it. + */ + void jjtOpen(); - /** This method is called after all the child nodes have been - added. */ - public void jjtClose(); + /** + * This method is called after all the child nodes have been + * added. + */ + void jjtClose(); - /** This pair of methods are used to inform the node of its - parent. + /** + * This pair of methods are used to inform the node of its + * parent. * * @param n the Node to make the parent of this node. */ - public void jjtSetParent(Node n); - public Node jjtGetParent(); + void jjtSetParent(Node n); - /** This method tells the node to add its argument to the node's - list of children. + Node jjtGetParent(); + + /** + * This method tells the node to add its argument to the node's + * list of children. * * @param n the Node to add as a child of this node. * @param i the position at which to add the child node. */ - public void jjtAddChild(Node n, int i); + void jjtAddChild(Node n, int i); - /** This method returns a child node. The children are numbered - from zero, left to right. + /** + * This method returns a child node. The children are numbered + * from zero, left to right. * * @param i the position from which to get the child node. * @return the child Node at position i. */ - public Node jjtGetChild(int i); + Node jjtGetChild(int i); - /** Return the number of children the node has. + /** + * Return the number of children the node has. * * @return the number of children for this node. */ - public int jjtGetNumChildren(); + int jjtGetNumChildren(); + // OGNL additions to Node: -// OGNL additions to Node: - /** * Extracts the value from the given source object that is appropriate for this node * within the given context. - * + * * @param context the OgnlContext within which to perform the operation. - * @param source the Object from which to get the value. + * @param source the Object from which to get the value. * @return the value from the source (as appropriate within the provided context). * @throws OgnlException if the value get fails. */ - public Object getValue( OgnlContext context, Object source ) throws OgnlException; + Object getValue(OgnlContext context, Object source) throws OgnlException; /** * Sets the given value in the given target as appropriate for this node within the * given context. - * + * * @param context the OgnlContext within which to perform the operation. - * @param target the Object upon which to set the value. - * @param value the Object representing the value to apply to the target. + * @param target the Object upon which to set the value. + * @param value the Object representing the value to apply to the target. * @throws OgnlException if the value set fails. */ - public void setValue( OgnlContext context, Object target, Object value ) throws OgnlException; - + void setValue(OgnlContext context, Object target, Object value) throws OgnlException; + /** * Gets the compiled bytecode enhanced expression accessor for getting/setting values. - * + * * @return The accessor for this node, or null if none has been compiled for it. */ ExpressionAccessor getAccessor(); - + /** * Sets a new compiled accessor for this node expression. - * + * * @param accessor The compiled representation of this node. */ void setAccessor(ExpressionAccessor accessor); diff --git a/src/main/java/ognl/NodeType.java b/src/main/java/ognl/NodeType.java index 8e631973..9b62ea4b 100644 --- a/src/main/java/ognl/NodeType.java +++ b/src/main/java/ognl/NodeType.java @@ -1,26 +1,43 @@ -/** - * +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package ognl; +import ognl.enhance.OgnlExpressionCompiler; /** - * Used by some of the {@link ognl.enhance.OgnlExpressionCompiler} logic to determine the object + * Used by some of the {@link OgnlExpressionCompiler} logic to determine the object * type of {@link Node}s during expression evaluation. */ -public interface NodeType -{ +public interface NodeType { + /** * The type returned from the expression - if any. * * @return The type. */ - Class getGetterClass(); + Class getGetterClass(); /** * The type used to set the value - if any. * * @return The type. */ - Class getSetterClass(); + Class getSetterClass(); + } diff --git a/src/main/java/ognl/NullHandler.java b/src/main/java/ognl/NullHandler.java index c5407e69..0db4c5b4 100644 --- a/src/main/java/ognl/NullHandler.java +++ b/src/main/java/ognl/NullHandler.java @@ -1,66 +1,49 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.Map; - /** * Interface for handling null results from Chains. * Object has the opportunity to substitute an object for the * null and continue. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public interface NullHandler -{ +public interface NullHandler { /** - Method called on target returned null. + * Method called on target returned null. * - * @param context the current execution context. - * @param target the Object on which the method was called. + * @param context the current execution context. + * @param target the Object on which the method was called. * @param methodName the name of the method which was called. - * @param args the arguments to the method that was called. + * @param args the arguments to the method that was called. * @return the result Object containing the state of the method call that returned null. */ - public Object nullMethodResult(Map context, Object target, String methodName, Object[] args); + Object nullMethodResult(OgnlContext context, Object target, String methodName, Object[] args); /** - Property in target evaluated to null. Property can be a constant - String property name or a DynamicSubscript. + * Property in target evaluated to null. Property can be a constant + * String property name or a DynamicSubscript. * - * @param context the current execution context. - * @param target the Object to which the property belongs. + * @param context the current execution context. + * @param target the Object to which the property belongs. * @param property the property whose value evaluated to null. * @return the result Object containing the state of the property that evaluated to null. */ - public Object nullPropertyValue(Map context, Object target, Object property); + Object nullPropertyValue(OgnlContext context, Object target, Object property); } diff --git a/src/main/java/ognl/NumberElementsAccessor.java b/src/main/java/ognl/NumberElementsAccessor.java index eb407c55..bc0a2029 100644 --- a/src/main/java/ognl/NumberElementsAccessor.java +++ b/src/main/java/ognl/NumberElementsAccessor.java @@ -1,60 +1,46 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; +import java.util.Enumeration; +import java.util.NoSuchElementException; /** * Implementation of ElementsAccessor that returns an iterator over integers from 0 up to * the given target. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class NumberElementsAccessor implements ElementsAccessor, NumericTypes -{ - public Enumeration getElements( final Object target ) - { - return new Enumeration() { - private int type = OgnlOps.getNumericType( target ); +public class NumberElementsAccessor implements ElementsAccessor, NumericTypes { + + public Enumeration getElements(final Object target) { + return new Enumeration() { + private final int type = OgnlOps.getNumericType(target); + private final long finish = OgnlOps.longValue(target); private long next = 0; - private long finish = OgnlOps.longValue( target ); public boolean hasMoreElements() { return next < finish; } public Object nextElement() { - if ( next >= finish ) + if (next >= finish) throw new NoSuchElementException(); - return OgnlOps.newInteger( type, next++ ); + return OgnlOps.newInteger(type, next++); } }; } diff --git a/src/main/java/ognl/NumericCasts.java b/src/main/java/ognl/NumericCasts.java new file mode 100644 index 00000000..087f149f --- /dev/null +++ b/src/main/java/ognl/NumericCasts.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + +/** + * Constant strings for casting different primitive types. + */ +class NumericCasts { + + private final Map, String> NUMERIC_CASTS = new HashMap<>(6); + + NumericCasts() { + NUMERIC_CASTS.put(Double.class, "(double)"); + NUMERIC_CASTS.put(Float.class, "(float)"); + NUMERIC_CASTS.put(Integer.class, "(int)"); + NUMERIC_CASTS.put(Long.class, "(long)"); + NUMERIC_CASTS.put(BigDecimal.class, "(double)"); + NUMERIC_CASTS.put(BigInteger.class, ""); + } + + String get(Class cls) { + return NUMERIC_CASTS.get(cls); + } + +} diff --git a/src/main/java/ognl/NumericDefaults.java b/src/main/java/ognl/NumericDefaults.java new file mode 100644 index 00000000..0cd7b861 --- /dev/null +++ b/src/main/java/ognl/NumericDefaults.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + +class NumericDefaults { + + private final Map, Object> NUMERIC_DEFAULTS = new HashMap<>(10); + + NumericDefaults() { + NUMERIC_DEFAULTS.put(Boolean.class, Boolean.FALSE); + NUMERIC_DEFAULTS.put(Byte.class, (byte) 0); + NUMERIC_DEFAULTS.put(Short.class, (short) 0); + NUMERIC_DEFAULTS.put(Character.class, (char) 0); + NUMERIC_DEFAULTS.put(Integer.class, 0); + NUMERIC_DEFAULTS.put(Long.class, 0L); + NUMERIC_DEFAULTS.put(Float.class, 0.0f); + NUMERIC_DEFAULTS.put(Double.class, 0.0); + + NUMERIC_DEFAULTS.put(BigInteger.class, BigInteger.ZERO); + NUMERIC_DEFAULTS.put(BigDecimal.class, BigDecimal.ZERO); + } + + Object get(Class cls) { + return NUMERIC_DEFAULTS.get(cls); + } + +} diff --git a/src/main/java/ognl/NumericExpression.java b/src/main/java/ognl/NumericExpression.java index 2e29a1d6..f4fee44b 100644 --- a/src/main/java/ognl/NumericExpression.java +++ b/src/main/java/ognl/NumericExpression.java @@ -1,97 +1,102 @@ -/** - * +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package ognl; import ognl.enhance.ExpressionCompiler; - /** - * Base class for numeric expressions. + * Base class for numeric expressions. */ -public abstract class NumericExpression extends ExpressionNode implements NodeType -{ - protected Class _getterClass; - +public abstract class NumericExpression extends ExpressionNode implements NodeType { + + private static final long serialVersionUID = 411246929049244018L; + + protected Class getterClass; + public NumericExpression(int id) { super(id); } - + public NumericExpression(OgnlParser p, int id) { super(p, id); } - - public Class getGetterClass() - { - if (_getterClass != null) - return _getterClass; - + + public Class getGetterClass() { + if (getterClass != null) + return getterClass; + return Double.TYPE; } - - public Class getSetterClass() - { + + public Class getSetterClass() { return null; } - - public String toGetSourceString(OgnlContext context, Object target) - { - Object value = null; - String result = ""; - try { + public String toGetSourceString(OgnlContext context, Object target) { + Object value; + StringBuilder result = new StringBuilder(); + try { value = getValueBody(context, target); - - if (value != null) - _getterClass = value.getClass(); - - for (int i=0; i < _children.length; i++) - { - if (i > 0) - result += " " + getExpressionOperator(i) + " "; - String str = OgnlRuntime.getChildSource(context, target, _children[i]); + if (value != null) { + getterClass = value.getClass(); + } - result += coerceToNumeric(str, context, _children[i]); + for (int i = 0; i < children.length; i++) { + if (i > 0) { + result.append(" ").append(getExpressionOperator(i)).append(" "); + } + String str = OgnlRuntime.getChildSource(context, target, children[i]); + result.append(coerceToNumeric(str, context, children[i])); } - - } catch (Throwable t) - { + + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - return result; + return result.toString(); } - public String coerceToNumeric(String source, OgnlContext context, Node child) - { + public String coerceToNumeric(String source, OgnlContext context, Node child) { String ret = source; Object value = context.getCurrentObject(); - if (ASTConst.class.isInstance(child) && value != null) - { + if (child instanceof ASTConst && value != null) { return value.toString(); } if (context.getCurrentType() != null && !context.getCurrentType().isPrimitive() - && context.getCurrentObject() != null && Number.class.isInstance(context.getCurrentObject())) - { + && context.getCurrentObject() != null && context.getCurrentObject() instanceof Number) { ret = "((" + ExpressionCompiler.getCastString(context.getCurrentObject().getClass()) + ")" + ret + ")"; ret += "." + OgnlRuntime.getNumericValueGetter(context.getCurrentObject().getClass()); } else if (context.getCurrentType() != null && context.getCurrentType().isPrimitive() - && (ASTConst.class.isInstance(child) || NumericExpression.class.isInstance(child))) - { + && (child instanceof ASTConst || child instanceof NumericExpression)) { ret += OgnlRuntime.getNumericLiteral(context.getCurrentType()); - } else if (context.getCurrentType() != null && String.class.isAssignableFrom(context.getCurrentType())) - { + } else if (context.getCurrentType() != null && String.class.isAssignableFrom(context.getCurrentType())) { ret = "Double.parseDouble(" + ret + ")"; context.setCurrentType(Double.TYPE); } - if (NumericExpression.class.isInstance(child)) + if (child instanceof NumericExpression) ret = "(" + ret + ")"; - + return ret; } } diff --git a/src/main/java/ognl/NumericLiterals.java b/src/main/java/ognl/NumericLiterals.java new file mode 100644 index 00000000..a1cc6e40 --- /dev/null +++ b/src/main/java/ognl/NumericLiterals.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + +/** + * Numeric primitive literal string expressions. + */ +class NumericLiterals { + + private final Map, String> NUMERIC_LITERALS = new HashMap<>(10); + + NumericLiterals() { + NUMERIC_LITERALS.put(Integer.class, ""); + NUMERIC_LITERALS.put(Integer.TYPE, ""); + NUMERIC_LITERALS.put(Long.class, "l"); + NUMERIC_LITERALS.put(Long.TYPE, "l"); + NUMERIC_LITERALS.put(Float.class, "f"); + NUMERIC_LITERALS.put(Float.TYPE, "f"); + NUMERIC_LITERALS.put(Double.class, "d"); + NUMERIC_LITERALS.put(Double.TYPE, "d"); + + NUMERIC_LITERALS.put(BigInteger.class, "d"); + NUMERIC_LITERALS.put(BigDecimal.class, "d"); + } + + String get(Class clazz) { + return NUMERIC_LITERALS.get(clazz); + } + +} diff --git a/src/main/java/ognl/NumericTypes.java b/src/main/java/ognl/NumericTypes.java index 59f57f2a..85d2ae76 100644 --- a/src/main/java/ognl/NumericTypes.java +++ b/src/main/java/ognl/NumericTypes.java @@ -1,75 +1,81 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; - /** * This interface defines some useful constants for describing the various possible * numeric types of OGNL. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public interface NumericTypes -{ - // Order does matter here... see the getNumericType methods in ognl.g. +public interface NumericTypes { + // Order does matter here... see the getNumericType methods in ognl.g. - /** Type tag meaning boolean. */ - int BOOL = 0; - /** Type tag meaning byte. */ - int BYTE = 1; - /** Type tag meaning char. */ - int CHAR = 2; - /** Type tag meaning short. */ - int SHORT = 3; - /** Type tag meaning int. */ - int INT = 4; - /** Type tag meaning long. */ - int LONG = 5; - /** Type tag meaning java.math.BigInteger. */ - int BIGINT = 6; - /** Type tag meaning float. */ - int FLOAT = 7; - /** Type tag meaning double. */ - int DOUBLE = 8; - /** Type tag meaning java.math.BigDecimal. */ - int BIGDEC = 9; - /** Type tag meaning something other than a number. */ + /** + * Type tag meaning boolean. + */ + int BOOL = 0; + /** + * Type tag meaning byte. + */ + int BYTE = 1; + /** + * Type tag meaning char. + */ + int CHAR = 2; + /** + * Type tag meaning short. + */ + int SHORT = 3; + /** + * Type tag meaning int. + */ + int INT = 4; + /** + * Type tag meaning long. + */ + int LONG = 5; + /** + * Type tag meaning java.math.BigInteger. + */ + int BIGINT = 6; + /** + * Type tag meaning float. + */ + int FLOAT = 7; + /** + * Type tag meaning double. + */ + int DOUBLE = 8; + /** + * Type tag meaning java.math.BigDecimal. + */ + int BIGDEC = 9; + /** + * Type tag meaning something other than a number. + */ int NONNUMERIC = 10; - /** - * The smallest type tag that represents reals as opposed to integers. You can see - * whether a type tag represents reals or integers by comparing the tag to this - * constant: all tags less than this constant represent integers, and all tags - * greater than or equal to this constant represent reals. Of course, you must also - * check for NONNUMERIC, which means it is not a number at all. - */ + /** + * The smallest type tag that represents reals as opposed to integers. You can see + * whether a type tag represents reals or integers by comparing the tag to this + * constant: all tags less than this constant represent integers, and all tags + * greater than or equal to this constant represent reals. Of course, you must also + * check for NONNUMERIC, which means it is not a number at all. + */ int MIN_REAL_TYPE = FLOAT; } diff --git a/src/main/java/ognl/NumericValues.java b/src/main/java/ognl/NumericValues.java new file mode 100644 index 00000000..ddc7dea5 --- /dev/null +++ b/src/main/java/ognl/NumericValues.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + +/** + * Constant strings for getting the primitive value of different native types on the generic {@link Number} object + * interface. (or the less generic BigDecimal/BigInteger types) + */ +class NumericValues { + + private final Map, String> NUMERIC_VALUES = new HashMap<>(9); + + NumericValues() { + NUMERIC_VALUES.put(Double.class, "doubleValue()"); + NUMERIC_VALUES.put(Float.class, "floatValue()"); + NUMERIC_VALUES.put(Integer.class, "intValue()"); + NUMERIC_VALUES.put(Long.class, "longValue()"); + NUMERIC_VALUES.put(Short.class, "shortValue()"); + NUMERIC_VALUES.put(Byte.class, "byteValue()"); + NUMERIC_VALUES.put(BigDecimal.class, "doubleValue()"); + NUMERIC_VALUES.put(BigInteger.class, "doubleValue()"); + NUMERIC_VALUES.put(Boolean.class, "booleanValue()"); + } + + String get(Class cls) { + return NUMERIC_VALUES.get(cls); + } + +} diff --git a/src/main/java/ognl/ObjectArrayPool.java b/src/main/java/ognl/ObjectArrayPool.java deleted file mode 100644 index 15fb756f..00000000 --- a/src/main/java/ognl/ObjectArrayPool.java +++ /dev/null @@ -1,111 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package ognl; - -/** - * This class was previously intended to produce performance improvment.
- * This hand-made object pooling is now a bottleneck under high load.
- * We now rely on the new jvm garbage collection improvments to handle object allocation efficiently. - * @deprecated object-pooling now relies on the jvm garbage collection - */ -public final class ObjectArrayPool extends Object -{ - public ObjectArrayPool() - { - super(); - } - - public Object[] create(int arraySize) - { - return new Object[arraySize]; - } - - public Object[] create(Object singleton) - { - Object[] result = create(1); - - result[0] = singleton; - return result; - } - - public Object[] create(Object object1, Object object2) - { - Object[] result = create(2); - - result[0] = object1; - result[1] = object2; - return result; - } - - public Object[] create(Object object1, Object object2, Object object3) - { - Object[] result = create(3); - - result[0] = object1; - result[1] = object2; - result[2] = object3; - return result; - } - - public Object[] create(Object object1, Object object2, Object object3, Object object4) - { - Object[] result = create(4); - - result[0] = object1; - result[1] = object2; - result[2] = object3; - result[3] = object4; - return result; - } - - public Object[] create(Object object1, Object object2, Object object3, Object object4, Object object5) - { - Object[] result = create(5); - - result[0] = object1; - result[1] = object2; - result[2] = object3; - result[3] = object4; - result[4] = object5; - return result; - } - - /** - * Recycle an array of Objects. - * - * @param value an Object array to recycle (not used). - * @deprecated object-pooling now relies on the jvm garbage collection - */ - public void recycle(Object[] value) - { - // no need of recycling, we rely on the garbage collection efficiency - } -} diff --git a/src/main/java/ognl/ObjectElementsAccessor.java b/src/main/java/ognl/ObjectElementsAccessor.java index 2ae14c2b..9b0cf46e 100644 --- a/src/main/java/ognl/ObjectElementsAccessor.java +++ b/src/main/java/ognl/ObjectElementsAccessor.java @@ -1,65 +1,51 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; +import java.util.Enumeration; /** * Implementation of ElementsAccessor that returns a single-element iterator, containing * the original target object. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class ObjectElementsAccessor implements ElementsAccessor -{ - public Enumeration getElements( Object target ) - { - final Object object = target; +public class ObjectElementsAccessor implements ElementsAccessor { + + public Enumeration getElements(Object target) { + + final Object object = target; - return new Enumeration() { - private boolean seen = false; + return new Enumeration() { + private boolean seen = false; - public boolean hasMoreElements() { - return !seen; - } + public boolean hasMoreElements() { + return !seen; + } - public Object nextElement() { - Object result = null; + public Object nextElement() { + Object result = null; - if (!seen) { - result = object; - seen = true; - } - return result; - } - }; + if (!seen) { + result = object; + seen = true; + } + return result; + } + }; } } diff --git a/src/main/java/ognl/ObjectIndexedPropertyDescriptor.java b/src/main/java/ognl/ObjectIndexedPropertyDescriptor.java index eebd3cc7..5121bdbb 100644 --- a/src/main/java/ognl/ObjectIndexedPropertyDescriptor.java +++ b/src/main/java/ognl/ObjectIndexedPropertyDescriptor.java @@ -1,37 +1,26 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.beans.*; -import java.lang.reflect.*; +import java.beans.IntrospectionException; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Method; /** *

PropertyDescriptor subclass that describes an indexed set of read/write @@ -39,32 +28,32 @@ * the "key" to be an arbitrary object rather than just an int. Consequently * it does not have a "readMethod" or "writeMethod" because it only expects * a pattern like:

- *
+ * 
  *    public void setProperty(KeyType, ValueType);
  *    public ValueType getProperty(KeyType);
- *
+ *
*

and does not require the methods that access it as an array. OGNL can * get away with this without losing functionality because if the object * does expose the properties they are most probably in a Map and that case * is handled by the normal OGNL property accessors. - *

- *

For example, if an object were to have methods that accessed and "attributes" + *

+ *

For example, if an object were to have methods that accessed and "attributes" * property it would be natural to index them by String rather than by integer * and expose the attributes as a map with a different property name: - *

+ * 
  *    public void setAttribute(String name, Object value);
  *    public Object getAttribute(String name);
  *    public Map getAttributes();
- *
- *

Note that the index get/set is called get/set Attribute + *

+ *

Note that the index get/set is called get/set Attribute * whereas the collection getter is called Attributes. This * case is handled unambiguously by the OGNL property accessors because the * set/getAttribute methods are detected by this object and the * "attributes" case is handled by the MapPropertyAccessor. * Therefore OGNL expressions calling this code would be handled in the * following way: - *

- * + *

+ *
* * * @@ -90,35 +79,29 @@ * * *
OGNL Expression
OGNL ExpressionHandling
- * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class ObjectIndexedPropertyDescriptor extends PropertyDescriptor -{ - private Method indexedReadMethod; - private Method indexedWriteMethod; - private Class propertyType; +public class ObjectIndexedPropertyDescriptor extends PropertyDescriptor { + + private final Method indexedReadMethod; + private final Method indexedWriteMethod; + private final Class propertyType; - public ObjectIndexedPropertyDescriptor(String propertyName, Class propertyType, Method indexedReadMethod, Method indexedWriteMethod) throws IntrospectionException - { + public ObjectIndexedPropertyDescriptor(String propertyName, Class propertyType, Method indexedReadMethod, Method indexedWriteMethod) throws IntrospectionException { super(propertyName, null, null); this.propertyType = propertyType; this.indexedReadMethod = indexedReadMethod; this.indexedWriteMethod = indexedWriteMethod; } - public Method getIndexedReadMethod() - { + public Method getIndexedReadMethod() { return indexedReadMethod; } - public Method getIndexedWriteMethod() - { + public Method getIndexedWriteMethod() { return indexedWriteMethod; } - public Class getPropertyType() - { + public synchronized Class getPropertyType() { return propertyType; } } diff --git a/src/main/java/ognl/ObjectMethodAccessor.java b/src/main/java/ognl/ObjectMethodAccessor.java index e612e0d7..05dae080 100644 --- a/src/main/java/ognl/ObjectMethodAccessor.java +++ b/src/main/java/ognl/ObjectMethodAccessor.java @@ -1,71 +1,46 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; +import java.lang.reflect.Method; import java.util.List; -import java.util.Map; /** * Implementation of PropertyAccessor that uses reflection on the target object's class to find a * field or a pair of set/get methods with the given property name. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class ObjectMethodAccessor implements MethodAccessor -{ +public class ObjectMethodAccessor implements MethodAccessor { - /* MethodAccessor interface */ - public Object callStaticMethod(Map context, Class targetClass, String methodName, Object[] args) - throws MethodFailedException - { - List methods = OgnlRuntime.getMethods(targetClass, methodName, true); + public Object callStaticMethod(OgnlContext context, Class targetClass, String methodName, Object[] args) throws MethodFailedException { + List methods = OgnlRuntime.getMethods(targetClass, methodName, true); - return OgnlRuntime.callAppropriateMethod((OgnlContext) context, targetClass, - null, methodName, null, methods, args); + return OgnlRuntime.callAppropriateMethod(context, targetClass, null, methodName, null, methods, args); } - public Object callMethod(Map context, Object target, String methodName, Object[] args) - throws MethodFailedException - { - Class targetClass = (target == null) ? null : target.getClass(); - List methods = OgnlRuntime.getMethods(targetClass, methodName, false); + public Object callMethod(OgnlContext context, Object target, String methodName, Object[] args) throws MethodFailedException { + Class targetClass = (target == null) ? null : target.getClass(); + List methods = OgnlRuntime.getMethods(targetClass, methodName, false); - if ((methods == null) || (methods.size() == 0)) - { + if ((methods == null) || (methods.size() == 0)) { methods = OgnlRuntime.getMethods(targetClass, methodName, true); - } - return OgnlRuntime.callAppropriateMethod((OgnlContext) context, target, - target, methodName, null, methods, args); + return OgnlRuntime.callAppropriateMethod(context, target, target, methodName, null, methods, args); } } diff --git a/src/main/java/ognl/ObjectNullHandler.java b/src/main/java/ognl/ObjectNullHandler.java index 97563bfc..f2fafaed 100644 --- a/src/main/java/ognl/ObjectNullHandler.java +++ b/src/main/java/ognl/ObjectNullHandler.java @@ -1,53 +1,33 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.*; - /** * Implementation of NullHandler that returns null in all cases, * so that NullPointerException will be thrown by the caller. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class ObjectNullHandler implements NullHandler -{ - /* NullHandler interface */ - public Object nullMethodResult(Map context, Object target, String methodName, Object[] args) - { +public class ObjectNullHandler implements NullHandler { + public Object nullMethodResult(OgnlContext context, Object target, String methodName, Object[] args) { return null; } - public Object nullPropertyValue(Map context, Object target, Object property) - { + public Object nullPropertyValue(OgnlContext context, Object target, Object property) { return null; } } diff --git a/src/main/java/ognl/ObjectPropertyAccessor.java b/src/main/java/ognl/ObjectPropertyAccessor.java index 377df8cd..caf056bb 100644 --- a/src/main/java/ognl/ObjectPropertyAccessor.java +++ b/src/main/java/ognl/ObjectPropertyAccessor.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; @@ -36,39 +24,29 @@ import java.beans.IntrospectionException; import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.util.Map; /** * Implementation of PropertyAccessor that uses reflection on the target object's class to find a * field or a pair of set/get methods with the given property name. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ public class ObjectPropertyAccessor implements PropertyAccessor { /** * Returns OgnlRuntime.NotFound if the property does not exist. - * + * * @param context the current execution context. - * @param target the object to get the property from. - * @param name the name of the property to get. + * @param target the object to get the property from. + * @param name the name of the property to get. * @return the current value of the given property in the given object. * @throws OgnlException if there is an error locating the property in the given object. */ - public Object getPossibleProperty(Map context, Object target, String name) - throws OgnlException - { + public Object getPossibleProperty(OgnlContext context, Object target, String name) throws OgnlException { Object result; - OgnlContext ognlContext = (OgnlContext) context; try { - if ((result = OgnlRuntime.getMethodValue(ognlContext, target, name, true)) == OgnlRuntime.NotFound) - { - result = OgnlRuntime.getFieldValue(ognlContext, target, name, true); + if ((result = OgnlRuntime.getMethodValue(context, target, name, true)) == OgnlRuntime.NotFound) { + result = OgnlRuntime.getFieldValue(context, target, name, true); } - } catch (IntrospectionException ex) { - throw new OgnlException(name, ex); } catch (OgnlException ex) { throw ex; } catch (Exception ex) { @@ -80,36 +58,28 @@ public Object getPossibleProperty(Map context, Object target, String name) /** * Returns OgnlRuntime.NotFound if the property does not exist. - * + * * @param context the current execution context. - * @param target the object to set the property in. - * @param name the name of the property to set. - * @param value the new value for the property. + * @param target the object to set the property in. + * @param name the name of the property to set. + * @param value the new value for the property. * @return the Object result of the property set operation. * @throws OgnlException if there is an error setting the property in the given object. */ - public Object setPossibleProperty(Map context, Object target, String name, Object value) - throws OgnlException - { + public Object setPossibleProperty(OgnlContext context, Object target, String name, Object value) + throws OgnlException { Object result = null; - OgnlContext ognlContext = (OgnlContext) context; - try { - if (!OgnlRuntime.setMethodValue(ognlContext, target, name, value, true)) - { - result = OgnlRuntime.setFieldValue(ognlContext, target, name, value) ? null : OgnlRuntime.NotFound; + if (!OgnlRuntime.setMethodValue(context, target, name, value, true)) { + result = OgnlRuntime.setFieldValue(context, target, name, value) ? null : OgnlRuntime.NotFound; } - if (result == OgnlRuntime.NotFound) - { + if (result == OgnlRuntime.NotFound) { Method m = OgnlRuntime.getWriteMethod(target.getClass(), name); - if (m != null) - { - result = m.invoke(target, new Object[] { value}); + if (m != null) { + result = m.invoke(target, value); } } - } catch (IntrospectionException ex) { - throw new OgnlException(name, ex); } catch (OgnlException ex) { throw ex; } catch (Exception ex) { @@ -119,9 +89,7 @@ public Object setPossibleProperty(Map context, Object target, String name, Objec return result; } - public boolean hasGetProperty(OgnlContext context, Object target, Object oname) - throws OgnlException - { + public boolean hasGetProperty(OgnlContext context, Object target, Object oname) throws OgnlException { try { return OgnlRuntime.hasGetProperty(context, target, oname); } catch (IntrospectionException ex) { @@ -129,15 +97,7 @@ public boolean hasGetProperty(OgnlContext context, Object target, Object oname) } } - public boolean hasGetProperty(Map context, Object target, Object oname) - throws OgnlException - { - return hasGetProperty((OgnlContext) context, target, oname); - } - - public boolean hasSetProperty(OgnlContext context, Object target, Object oname) - throws OgnlException - { + public boolean hasSetProperty(OgnlContext context, Object target, Object oname) throws OgnlException { try { return OgnlRuntime.hasSetProperty(context, target, oname); } catch (IntrospectionException ex) { @@ -145,110 +105,71 @@ public boolean hasSetProperty(OgnlContext context, Object target, Object oname) } } - public boolean hasSetProperty(Map context, Object target, Object oname) - throws OgnlException - { - return hasSetProperty((OgnlContext) context, target, oname); - } - - public Object getProperty(Map context, Object target, Object oname) - throws OgnlException - { - Object result = null; + public Object getProperty(OgnlContext context, Object target, Object oname) throws OgnlException { String name = oname.toString(); + Object result = getPossibleProperty(context, target, name); - result = getPossibleProperty(context, target, name); - - if (result == OgnlRuntime.NotFound) - { + if (result == OgnlRuntime.NotFound) { throw new NoSuchPropertyException(target, name); } return result; } - public void setProperty(Map context, Object target, Object oname, Object value) - throws OgnlException - { + public void setProperty(OgnlContext context, Object target, Object oname, Object value) throws OgnlException { String name = oname.toString(); - Object result = setPossibleProperty(context, target, name, value); - - if (result == OgnlRuntime.NotFound) - { + if (result == OgnlRuntime.NotFound) { throw new NoSuchPropertyException(target, name); } } - public Class getPropertyClass(OgnlContext context, Object target, Object index) - { + public Class getPropertyClass(OgnlContext context, Object target, Object index) { try { Method m = OgnlRuntime.getReadMethod(target.getClass(), index.toString()); - if (m == null) { - if (String.class.isAssignableFrom(index.getClass()) && !target.getClass().isArray()) { - String indexStr = (String)index; - String key = (indexStr.indexOf('"') >= 0)? indexStr.replaceAll("\"", "") : indexStr; + String indexStr = (String) index; + String key = (indexStr.indexOf('"') >= 0) ? indexStr.replaceAll("\"", "") : indexStr; try { Field f = target.getClass().getField(key); - if (f != null) { - - return f.getType(); - } + return f.getType(); } catch (NoSuchFieldException e) { return null; } } - return null; } - return m.getReturnType(); - - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } - public String getSourceAccessor(OgnlContext context, Object target, Object index) - { + public String getSourceAccessor(OgnlContext context, Object target, Object index) { try { String indexStr = index.toString(); - String methodName = (indexStr.indexOf('"') >= 0? indexStr.replaceAll("\"", "") : indexStr); + String methodName = (indexStr.indexOf('"') >= 0 ? indexStr.replaceAll("\"", "") : indexStr); Method m = OgnlRuntime.getReadMethod(target.getClass(), methodName); // try last ditch effort of checking if they were trying to do reflection via a return method value - - if (m == null && context.getCurrentObject() != null) - { + if (m == null && context.getCurrentObject() != null) { String currentObjectStr = context.getCurrentObject().toString(); - m = OgnlRuntime.getReadMethod(target.getClass(), (currentObjectStr.indexOf('"') >= 0? currentObjectStr.replaceAll("\"", "") : currentObjectStr)); + m = OgnlRuntime.getReadMethod(target.getClass(), (currentObjectStr.indexOf('"') >= 0 ? currentObjectStr.replaceAll("\"", "") : currentObjectStr)); } - //System.out.println("tried to get read method from target: " + target.getClass() + " with methodName:" + methodName + " result: " + m); - // try to get field if no method could be found - - if (m == null) - { - try - { - if (String.class.isAssignableFrom(index.getClass()) && !target.getClass().isArray()) - { + if (m == null) { + try { + if (String.class.isAssignableFrom(index.getClass()) && !target.getClass().isArray()) { Field f = target.getClass().getField(methodName); - if (f != null) - { - context.setCurrentType(f.getType()); - context.setCurrentAccessor(f.getDeclaringClass()); + context.setCurrentType(f.getType()); + context.setCurrentAccessor(f.getDeclaringClass()); - return "." + f.getName(); - } + return "." + f.getName(); } - } - catch (NoSuchFieldException e) { + } catch (NoSuchFieldException e) { // ignore } @@ -260,60 +181,55 @@ public String getSourceAccessor(OgnlContext context, Object target, Object index return "." + m.getName() + "()"; - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } - public String getSourceSetter(OgnlContext context, Object target, Object index) - { + public String getSourceSetter(OgnlContext context, Object target, Object index) { try { String indexStr = index.toString(); - String methodName = (indexStr.indexOf('"') >= 0? indexStr.replaceAll("\"", "") : indexStr); + String methodName = (indexStr.indexOf('"') >= 0 ? indexStr.replaceAll("\"", "") : indexStr); Method m = OgnlRuntime.getWriteMethod(target.getClass(), methodName); if (m == null && context.getCurrentObject() != null - && context.getCurrentObject().toString() != null) - { + && context.getCurrentObject().toString() != null) { String currentObjectStr = context.getCurrentObject().toString(); - m = OgnlRuntime.getWriteMethod(target.getClass(), (currentObjectStr.indexOf('"') >= 0? currentObjectStr.replaceAll("\"", "") : currentObjectStr)); + m = OgnlRuntime.getWriteMethod(target.getClass(), (currentObjectStr.indexOf('"') >= 0 ? currentObjectStr.replaceAll("\"", "") : currentObjectStr)); } - if (m == null || m.getParameterTypes() == null || m.getParameterTypes().length <= 0) + if (m == null || m.getParameterTypes().length <= 0) { throw new UnsupportedCompilationException("Unable to determine setting expression on " + context.getCurrentObject() - + " with index of " + index); + + " with index of " + index); + } - Class parm = m.getParameterTypes()[0]; + Class param = m.getParameterTypes()[0]; String conversion; if (m.getParameterTypes().length > 1) throw new UnsupportedCompilationException("Object property accessors can only support single parameter setters."); - if (parm.isPrimitive()) - { - Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(parm); + if (param.isPrimitive()) { + Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(param); conversion = OgnlRuntime.getCompiler().createLocalReference(context, - "((" + wrapClass.getName() + ")ognl.OgnlOps#convertValue($3," + wrapClass.getName() - + ".class, true))." + OgnlRuntime.getNumericValueGetter(wrapClass), - parm); + "((" + wrapClass.getName() + ")ognl.OgnlOps#convertValue($3," + wrapClass.getName() + + ".class, true))." + OgnlRuntime.getNumericValueGetter(wrapClass), + param); - } else if (parm.isArray()) - { + } else if (param.isArray()) { conversion = OgnlRuntime.getCompiler().createLocalReference(context, - "(" + ExpressionCompiler.getCastString(parm) + ")ognl.OgnlOps#toArray($3," - + parm.getComponentType().getName() + ".class)", - parm); + "(" + ExpressionCompiler.getCastString(param) + ")ognl.OgnlOps#toArray($3," + + param.getComponentType().getName() + ".class)", + param); - } else - { + } else { conversion = OgnlRuntime.getCompiler().createLocalReference(context, - "(" + parm.getName()+ ")ognl.OgnlOps#convertValue($3," - + parm.getName() - + ".class)", - parm); + "(" + param.getName() + ")ognl.OgnlOps#convertValue($3," + + param.getName() + + ".class)", + param); } context.setCurrentType(m.getReturnType()); @@ -321,8 +237,7 @@ public String getSourceSetter(OgnlContext context, Object target, Object index) return "." + m.getName() + "(" + conversion + ")"; - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } } diff --git a/src/main/java/ognl/Ognl.java b/src/main/java/ognl/Ognl.java index 05ac9ba4..327879cf 100644 --- a/src/main/java/ognl/Ognl.java +++ b/src/main/java/ognl/Ognl.java @@ -1,36 +1,25 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionAccessor; +import ognl.enhance.OgnlExpressionCompiler; import ognl.security.OgnlSecurityManager; import java.io.StringReader; @@ -39,59 +28,40 @@ import java.util.Map; /** - *

* This class provides static methods for parsing and interpreting OGNL expressions. - *

- *

* The simplest use of the Ognl class is to get the value of an expression from an object, without * extra context or pre-parsing. - *

- * - *
- *
+ * 
  * import ognl.Ognl; import ognl.OgnlException; try { result = Ognl.getValue(expression, root); }
  * catch (OgnlException ex) { // Report error or recover }
- *
- * 
- * - *

+ *

+ *

* This will parse the expression given and evaluate it against the root object given, returning the * result. If there is an error in the expression, such as the property is not found, the exception - * is encapsulated into an {@link ognl.OgnlException OgnlException}. - *

- *

+ * is encapsulated into an {@link OgnlException OgnlException}. + *

* Other more sophisticated uses of Ognl can pre-parse expressions. This provides two advantages: in * the case of user-supplied expressions it allows you to catch parse errors before evaluation and * it allows you to cache parsed expressions into an AST for better speed during repeated use. The - * pre-parsed expression is always returned as an Object to simplify use for programs + * pre-parsed expression is always returned as an Object to simplify use for programs * that just wish to store the value for repeated use and do not care that it is an AST. If it does - * care it can always safely cast the value to an AST type. - *

- *

- * The Ognl class also takes a context map as one of the parameters to the set and get + * care it can always safely cast the value to an AST type. + *

+ * The Ognl class also takes a context map as one of the parameters to the set and get * methods. This allows you to put your own variables into the available namespace for OGNL - * expressions. The default context contains only the #root and #context - * keys, which are required to be present. The addDefaultContext(Object, Map) method - * will alter an existing Map to put the defaults in. Here is an example that shows - * how to extract the documentName property out of the root object and append a + * expressions. The default context contains only the #root and #context + * keys, which are required to be present. The addDefaultContext(Object, Map) method + * will alter an existing Map to put the defaults in. Here is an example that shows + * how to extract the documentName property out of the root object and append a * string with the current user name in parens: - *

- * - *
- *
+ * 
  * private Map context = new HashMap(); public void setUserName(String value) {
  * context.put("userName", value); } try { // get value using our own custom context map result =
  * Ognl.getValue("documentName + \" (\" + ((#userName == null) ? \"<nobody>\" : #userName) +
  * \")\"", context, root); } catch (OgnlException ex) { // Report error or recover }
- *
- * 
- * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - * @version 27 June 1999 + *
*/ -public abstract class Ognl -{ +public abstract class Ognl { private static volatile Integer expressionMaxLength = null; private static volatile Boolean expressionMaxLengthFrozen = Boolean.FALSE; @@ -99,14 +69,10 @@ public abstract class Ognl /** * Applies a maximum allowed length on OGNL expressions for security reasons. * - * @param expressionMaxLength - * the OGNL expressions maximum allowed length. Use null (default) to disable this functionality. - * @throws SecurityException - * if the caller is inside OGNL expression itself. - * @throws IllegalStateException - * if the expression maximum allowed length is frozen. - * @throws IllegalArgumentException - * if the provided expressionMaxLength is < 0. + * @param expressionMaxLength the OGNL expressions maximum allowed length. Use null (default) to disable this functionality. + * @throws SecurityException if the caller is inside OGNL expression itself. + * @throws IllegalStateException if the expression maximum allowed length is frozen. + * @throws IllegalArgumentException if the provided expressionMaxLength is < 0. * @since 3.1.26 */ public static synchronized void applyExpressionMaxLength(Integer expressionMaxLength) { @@ -117,9 +83,8 @@ public static synchronized void applyExpressionMaxLength(Integer expressionMaxLe throw new IllegalStateException("The OGNL expression maximum allowed length has been frozen and cannot be changed."); } if (expressionMaxLength != null && expressionMaxLength < 0) { - throw new IllegalArgumentException("The provided OGNL expression maximum allowed length, " + expressionMaxLength + ", is illegal." ); - } - else { + throw new IllegalArgumentException("The provided OGNL expression maximum allowed length, " + expressionMaxLength + ", is illegal."); + } else { Ognl.expressionMaxLength = expressionMaxLength; } } @@ -128,8 +93,7 @@ public static synchronized void applyExpressionMaxLength(Integer expressionMaxLe * Freezes (prevents updates to) the maximum allowed length on OGNL expressions at the current value. * This makes it clear to other OGNL callers that the value should not be changed. * - * @throws SecurityException - * if the caller is inside OGNL expression itself. + * @throws SecurityException if the caller is inside OGNL expression itself. * @since 3.1.26 */ public static synchronized void freezeExpressionMaxLength() { @@ -143,11 +107,10 @@ public static synchronized void freezeExpressionMaxLength() { * Thaws (allows updates to) the maximum allowed length on OGNL expressions. * This makes it clear to other OGNL callers that the value can (again) be changed. * - * @throws SecurityException - * if the caller is inside OGNL expression itself. + * @throws SecurityException if the caller is inside OGNL expression itself. * @since 3.1.26 */ - public static final synchronized void thawExpressionMaxLength() { + public static synchronized void thawExpressionMaxLength() { if (System.getSecurityManager() instanceof OgnlSecurityManager) { throw new SecurityException("Thawing the OGNL expressions maximum allowed length is not accessible inside expression itself!"); } @@ -158,54 +121,42 @@ public static final synchronized void thawExpressionMaxLength() { * Parses the given OGNL expression and returns a tree representation of the expression that can * be used by Ognl static methods. * - * @param expression - * the OGNL expression to be parsed + * @param expression the OGNL expression to be parsed * @return a tree representation of the expression - * @throws ExpressionSyntaxException - * if the expression is malformed - * @throws OgnlException - * if there is a pathological environmental problem + * @throws ExpressionSyntaxException if the expression is malformed + * @throws OgnlException if there is a pathological environmental problem */ - public static Object parseExpression(String expression) - throws OgnlException - { + public static Object parseExpression(String expression) throws OgnlException { final Integer currentExpressionMaxLength = Ognl.expressionMaxLength; // Limit access to the volatile variable to a single operation if (currentExpressionMaxLength != null && expression != null && expression.length() > currentExpressionMaxLength) { throw new OgnlException("Parsing blocked due to security reasons!", new SecurityException("This expression exceeded maximum allowed length: " + expression)); } try { + assert expression != null; OgnlParser parser = new OgnlParser(new StringReader(expression)); return parser.topLevelExpression(); - } catch (ParseException e) { - throw new ExpressionSyntaxException(expression, e); - } catch (TokenMgrError e) { + } catch (ParseException | TokenMgrError e) { throw new ExpressionSyntaxException(expression, e); } } /** - * Parses and compiles the given expression using the {@link ognl.enhance.OgnlExpressionCompiler} returned - * from {@link ognl.OgnlRuntime#getCompiler()}. - * - * @param context - * The context to use. - * @param root - * The root object for the given expression. - * @param expression - * The expression to compile. - * - * @return The node with a compiled accessor set on {@link ognl.Node#getAccessor()} if compilation - * was successfull. In instances where compilation wasn't possible because of a partially null - * expression the {@link ExpressionAccessor} instance may be null and the compilation of this expression - * still possible at some as yet indertermined point in the future. + * Parses and compiles the given expression using the {@link OgnlExpressionCompiler} returned + * from {@link OgnlRuntime#getCompiler()}. * + * @param context The context to use. + * @param root The root object for the given expression. + * @param expression The expression to compile. + * @return The node with a compiled accessor set on {@link Node#getAccessor()} if compilation + * was successfull. In instances where compilation wasn't possible because of a partially null + * expression the {@link ExpressionAccessor} instance may be null and the compilation of this expression + * still possible at some as yet indertermined point in the future. * @throws Exception If a compilation error occurs. */ public static Node compileExpression(OgnlContext context, Object root, String expression) - throws Exception - { - Node expr = (Node)Ognl.parseExpression(expression); + throws Exception { + Node expr = (Node) Ognl.parseExpression(expression); OgnlRuntime.compileExpression(context, expr, root); @@ -215,16 +166,14 @@ public static Node compileExpression(OgnlContext context, Object root, String ex /** * Creates and returns a new standard naming context for evaluating an OGNL expression. * - * @param root - * the root of the object graph + * @param root the root of the object graph * @return a new Map with the keys root and context set - * appropriately + * appropriately */ - public static Map createDefaultContext(Object root) - { + public static OgnlContext createDefaultContext(Object root) { MemberAccess memberAccess = new AbstractMemberAccess() { @Override - public boolean isAccessible(Map context, Object target, Member member, String propertyName) { + public boolean isAccessible(OgnlContext context, Object target, Member member, String propertyName) { int modifiers = member.getModifiers(); return Modifier.isPublic(modifiers); } @@ -235,19 +184,15 @@ public boolean isAccessible(Map context, Object target, Member member, String pr /** * Creates and returns a new standard naming context for evaluating an OGNL expression. * - * @param root - * The root of the object graph. - * @param classResolver - * The resolver used to instantiate {@link Class} instances referenced in the expression. - * + * @param root The root of the object graph. + * @param classResolver The resolver used to instantiate {@link Class} instances referenced in the expression. * @return a new OgnlContext with the keys root and context set - * appropriately + * appropriately */ - public static Map createDefaultContext(Object root, ClassResolver classResolver) - { + public static OgnlContext createDefaultContext(Object root, ClassResolver classResolver) { MemberAccess memberAccess = new AbstractMemberAccess() { @Override - public boolean isAccessible(Map context, Object target, Member member, String propertyName) { + public boolean isAccessible(OgnlContext context, Object target, Member member, String propertyName) { int modifiers = member.getModifiers(); return Modifier.isPublic(modifiers); } @@ -258,21 +203,16 @@ public boolean isAccessible(Map context, Object target, Member member, String pr /** * Creates and returns a new standard naming context for evaluating an OGNL expression. * - * @param root - * The root of the object graph. - * @param classResolver - * The resolver used to instantiate {@link Class} instances referenced in the expression. - * @param converter - * Converter used to convert return types of an expression in to their desired types. - * + * @param root The root of the object graph. + * @param classResolver The resolver used to instantiate {@link Class} instances referenced in the expression. + * @param converter Converter used to convert return types of an expression in to their desired types. * @return a new Map with the keys root and context set - * appropriately + * appropriately */ - public static Map createDefaultContext(Object root, ClassResolver classResolver, TypeConverter converter) - { + public static OgnlContext createDefaultContext(Object root, ClassResolver classResolver, TypeConverter converter) { MemberAccess memberAccess = new AbstractMemberAccess() { @Override - public boolean isAccessible(Map context, Object target, Member member, String propertyName) { + public boolean isAccessible(OgnlContext context, Object target, Member member, String propertyName) { int modifiers = member.getModifiers(); return Modifier.isPublic(modifiers); } @@ -283,37 +223,28 @@ public boolean isAccessible(Map context, Object target, Member member, String pr /** * Creates and returns a new standard naming context for evaluating an OGNL expression. * - * @param root - * The root of the object graph. - * @param memberAccess - * Java security handling object to determine semantics for accessing normally private/protected - * methods / fields. - * @param classResolver - * The resolver used to instantiate {@link Class} instances referenced in the expression. - * @param converter - * Converter used to convert return types of an expression in to their desired types. + * @param root The root of the object graph. + * @param memberAccess Java security handling object to determine semantics for accessing normally private/protected + * methods / fields. + * @param classResolver The resolver used to instantiate {@link Class} instances referenced in the expression. + * @param converter Converter used to convert return types of an expression in to their desired types. * @return a new Map with the keys root and context set - * appropriately + * appropriately */ - public static Map createDefaultContext(Object root, MemberAccess memberAccess, ClassResolver classResolver, - TypeConverter converter) - { + public static OgnlContext createDefaultContext(Object root, MemberAccess memberAccess, ClassResolver classResolver, TypeConverter converter) { return addDefaultContext(root, memberAccess, classResolver, converter, new OgnlContext(classResolver, converter, memberAccess)); } /** * Creates and returns a new standard naming context for evaluating an OGNL expression. * - * @param root - * The root of the object graph. - * @param memberAccess - * Java security handling object to determine semantics for accessing normally private/protected - * methods / fields. + * @param root The root of the object graph. + * @param memberAccess Java security handling object to determine semantics for accessing normally private/protected + * methods / fields. * @return a new Map with the keys root and context set - * appropriately + * appropriately */ - public static Map createDefaultContext(Object root, MemberAccess memberAccess) - { + public static OgnlContext createDefaultContext(Object root, MemberAccess memberAccess) { return addDefaultContext(root, memberAccess, null, null, new OgnlContext(null, null, memberAccess)); } @@ -321,18 +252,15 @@ public static Map createDefaultContext(Object root, MemberAccess memberAccess) * Appends the standard naming context for evaluating an OGNL expression into the context given * so that cached maps can be used as a context. * - * @param root - * the root of the object graph - * @param context - * the context to which OGNL context will be added. + * @param root the root of the object graph + * @param context the context to which OGNL context will be added. * @return Context Map with the keys root and context set - * appropriately + * appropriately */ - public static Map addDefaultContext(Object root, Map context) - { + public static OgnlContext addDefaultContext(Object root, Map context) { MemberAccess memberAccess = new AbstractMemberAccess() { @Override - public boolean isAccessible(Map context, Object target, Member member, String propertyName) { + public boolean isAccessible(OgnlContext context, Object target, Member member, String propertyName) { int modifiers = member.getModifiers(); return Modifier.isPublic(modifiers); } @@ -344,21 +272,16 @@ public boolean isAccessible(Map context, Object target, Member member, String pr * Appends the standard naming context for evaluating an OGNL expression into the context given * so that cached maps can be used as a context. * - * @param root - * The root of the object graph. - * @param classResolver - * The resolver used to instantiate {@link Class} instances referenced in the expression. - * @param context - * The context to which OGNL context will be added. - * + * @param root The root of the object graph. + * @param classResolver The resolver used to instantiate {@link Class} instances referenced in the expression. + * @param context The context to which OGNL context will be added. * @return Context Map with the keys root and context set - * appropriately + * appropriately */ - public static Map addDefaultContext(Object root, ClassResolver classResolver, Map context) - { + public static OgnlContext addDefaultContext(Object root, ClassResolver classResolver, OgnlContext context) { MemberAccess memberAccess = new AbstractMemberAccess() { @Override - public boolean isAccessible(Map context, Object target, Member member, String propertyName) { + public boolean isAccessible(OgnlContext context, Object target, Member member, String propertyName) { int modifiers = member.getModifiers(); return Modifier.isPublic(modifiers); } @@ -370,21 +293,14 @@ public boolean isAccessible(Map context, Object target, Member member, String pr * Appends the standard naming context for evaluating an OGNL expression into the context given * so that cached maps can be used as a context. * - * @param root - * The root of the object graph. - * @param classResolver - * The resolver used to instantiate {@link Class} instances referenced in the expression. - * @param converter - * Converter used to convert return types of an expression in to their desired types. - * @param context - * The context to which OGNL context will be added. - * + * @param root The root of the object graph. + * @param classResolver The resolver used to instantiate {@link Class} instances referenced in the expression. + * @param converter Converter used to convert return types of an expression in to their desired types. + * @param context The context to which OGNL context will be added. * @return Context Map with the keys root and context set - * appropriately + * appropriately */ - public static Map addDefaultContext(Object root, ClassResolver classResolver, - TypeConverter converter, Map context) - { + public static OgnlContext addDefaultContext(Object root, ClassResolver classResolver, TypeConverter converter, OgnlContext context) { return addDefaultContext(root, null, classResolver, converter, context); } @@ -392,23 +308,16 @@ public static Map addDefaultContext(Object root, ClassResolver classResolver, * Appends the standard naming context for evaluating an OGNL expression into the context given * so that cached maps can be used as a context. * - * @param root - * the root of the object graph - * @param memberAccess - * Definition for handling private/protected access. - * @param classResolver - * The class loading resolver that should be used to resolve class references. - * @param converter - * The type converter to be used by default. - * @param context - * Default context to use, if not an {@link OgnlContext} will be dumped into - * a new {@link OgnlContext} object. + * @param root the root of the object graph + * @param memberAccess Definition for handling private/protected access. + * @param classResolver The class loading resolver that should be used to resolve class references. + * @param converter The type converter to be used by default. + * @param context Default context to use, if not an {@link OgnlContext} will be dumped into + * a new {@link OgnlContext} object. * @return Context Map with the keys root and context set - * appropriately + * appropriately */ - public static Map addDefaultContext(Object root, MemberAccess memberAccess, ClassResolver classResolver, - TypeConverter converter, Map context) - { + public static OgnlContext addDefaultContext(Object root, MemberAccess memberAccess, ClassResolver classResolver, TypeConverter converter, Map context) { OgnlContext result; if (context instanceof OgnlContext) { @@ -421,65 +330,15 @@ public static Map addDefaultContext(Object root, MemberAccess memberAccess, Clas return result; } - /** - * Configures the {@link ClassResolver} to use for the given context. Will be used during - * expression parsing / execution to resolve class names. - * - * @param context - * The context to place the resolver. - * @param classResolver - * The resolver to use to resolve classes. - * @deprecated it ignores any attempts to modify ClassResolver, ClassResolver can be defined - * only when creating a new context - */ - public static void setClassResolver(Map context, ClassResolver classResolver) - { - // noop - } - - /** - * Gets the previously stored {@link ClassResolver} for the given context - if any. - * - * @param context - * The context to get the configured resolver from. - * - * @return The resolver instance, or null if none found. - * @deprecated it always return null, access to class resolver was prohibited - */ - public static ClassResolver getClassResolver(Map context) - { - return null; - } - - /** - * Configures the type converter to use for a given context. This will be used - * to convert into / out of various java class types. - * - * @param context - * The context to configure it for. - * @param converter - * The converter to use. - * - * @deprecated do not use - */ - @Deprecated - public static void setTypeConverter(Map context, TypeConverter converter) - { - // no-op - } - /** * Gets the currently configured {@link TypeConverter} for the given context - if any. * - * @param context - * The context to get the converter from. - * + * @param context The context to get the converter from. * @return The converter - or null if none found. */ - public static TypeConverter getTypeConverter(Map context) - { - if (context instanceof OgnlContext) { - return ((OgnlContext) context).getTypeConverter(); + public static TypeConverter getTypeConverter(OgnlContext context) { + if (context != null) { + return context.getTypeConverter(); } return null; } @@ -488,39 +347,30 @@ public static TypeConverter getTypeConverter(Map context) * Sets the root object to use for all expressions in the given context - doesn't necessarily replace * root object instances explicitly passed in to other expression resolving methods on this class. * - * @param context - * The context to store the root object in. - * @param root - * The root object. + * @param context The context to store the root object in. + * @param root The root object. */ - public static void setRoot(Map context, Object root) - { + public static void setRoot(OgnlContext context, Object root) { context.put(OgnlContext.ROOT_CONTEXT_KEY, root); } /** * Gets the stored root object for the given context - if any. * - * @param context - * The context to get the root object from. - * + * @param context The context to get the root object from. * @return The root object - or null if none found. */ - public static Object getRoot(Map context) - { + public static Object getRoot(OgnlContext context) { return context.get(OgnlContext.ROOT_CONTEXT_KEY); } /** * Gets the last {@link Evaluation} executed on the given context. * - * @param context - * The context to get the evaluation from. - * + * @param context The context to get the evaluation from. * @return The {@link Evaluation} - or null if none was found. */ - public static Evaluation getLastEvaluation(Map context) - { + public static Evaluation getLastEvaluation(OgnlContext context) { return (Evaluation) context.get(OgnlContext.LAST_EVALUATION_CONTEXT_KEY); } @@ -528,25 +378,16 @@ public static Evaluation getLastEvaluation(Map context) * Evaluates the given OGNL expression tree to extract a value from the given root object. The * default context is set for the given context and root via addDefaultContext(). * - * @param tree - * the OGNL expression tree to evaluate, as returned by parseExpression() - * @param context - * the naming context for the evaluation - * @param root - * the root object for the OGNL expression + * @param tree the OGNL expression tree to evaluate, as returned by parseExpression() + * @param context the naming context for the evaluation + * @param root the root object for the OGNL expression * @return the result of evaluating the expression - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem */ - public static Object getValue(Object tree, Map context, Object root) - throws OgnlException - { + public static Object getValue(Object tree, OgnlContext context, Object root) throws OgnlException { return getValue(tree, context, root, null); } @@ -554,34 +395,24 @@ public static Object getValue(Object tree, Map context, Object root) * Evaluates the given OGNL expression tree to extract a value from the given root object. The * default context is set for the given context and root via addDefaultContext(). * - * @param tree - * the OGNL expression tree to evaluate, as returned by parseExpression() - * @param context - * the naming context for the evaluation - * @param root - * the root object for the OGNL expression - * @param resultType - * the converted type of the resultant object, using the context's type converter + * @param tree the OGNL expression tree to evaluate, as returned by parseExpression() + * @param context the naming context for the evaluation + * @param root the root object for the OGNL expression + * @param resultType the converted type of the resultant object, using the context's type converter * @return the result of evaluating the expression - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem */ - public static Object getValue(Object tree, Map context, Object root, Class resultType) - throws OgnlException - { + public static Object getValue(Object tree, OgnlContext context, Object root, Class resultType) throws OgnlException { Object result; - OgnlContext ognlContext = (OgnlContext) addDefaultContext(root, context); + OgnlContext ognlContext = addDefaultContext(root, context); - Node node = (Node)tree; + Node node = (Node) tree; if (node.getAccessor() != null) - result = node.getAccessor().get(ognlContext, root); + result = node.getAccessor().get(ognlContext, root); else result = node.getValue(ognlContext, root); @@ -595,17 +426,12 @@ public static Object getValue(Object tree, Map context, Object root, Class resul * Gets the value represented by the given pre-compiled expression on the specified root * object. * - * @param expression - * The pre-compiled expression, as found in {@link Node#getAccessor()}. - * @param context - * The ognl context. - * @param root - * The object to retrieve the expression value from. - * @return - * The value. + * @param expression The pre-compiled expression, as found in {@link Node#getAccessor()}. + * @param context The ognl context. + * @param root The object to retrieve the expression value from. + * @return The value. */ - public static Object getValue(ExpressionAccessor expression, OgnlContext context, Object root) - { + public static Object getValue(ExpressionAccessor expression, OgnlContext context, Object root) { return expression.get(context, root); } @@ -613,20 +439,13 @@ public static Object getValue(ExpressionAccessor expression, OgnlContext context * Gets the value represented by the given pre-compiled expression on the specified root * object. * - * @param expression - * The pre-compiled expression, as found in {@link Node#getAccessor()}. - * @param context - * The ognl context. - * @param root - * The object to retrieve the expression value from. - * @param resultType - * The desired object type that the return value should be converted to using the {@link #getTypeConverter(java.util.Map)} }. - * @return - * The value. + * @param expression The pre-compiled expression, as found in {@link Node#getAccessor()}. + * @param context The ognl context. + * @param root The object to retrieve the expression value from. + * @param resultType The desired object type that the return value should be converted to using the {@link #getTypeConverter(OgnlContext)} }. + * @return The value. */ - public static Object getValue(ExpressionAccessor expression, OgnlContext context, - Object root, Class resultType) - { + public static Object getValue(ExpressionAccessor expression, OgnlContext context, Object root, Class resultType) { return getTypeConverter(context).convertValue(context, root, null, null, expression.get(context, root), resultType); } @@ -634,27 +453,18 @@ public static Object getValue(ExpressionAccessor expression, OgnlContext context * Evaluates the given OGNL expression to extract a value from the given root object in a given * context * - * @see #parseExpression(String) - * @see #getValue(Object,Object) - * @param expression - * the OGNL expression to be parsed - * @param context - * the naming context for the evaluation - * @param root - * the root object for the OGNL expression + * @param expression the OGNL expression to be parsed + * @param context the naming context for the evaluation + * @param root the root object for the OGNL expression * @return the result of evaluating the expression - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem + * @see #parseExpression(String) + * @see #getValue(Object, Object) */ - public static Object getValue(String expression, Map context, Object root) - throws OgnlException - { + public static Object getValue(String expression, OgnlContext context, Object root) throws OgnlException { return getValue(expression, context, root, null); } @@ -662,77 +472,51 @@ public static Object getValue(String expression, Map context, Object root) * Evaluates the given OGNL expression to extract a value from the given root object in a given * context * - * @see #parseExpression(String) - * @see #getValue(Object,Object) - * @param expression - * the OGNL expression to be parsed - * @param context - * the naming context for the evaluation - * @param root - * the root object for the OGNL expression - * @param resultType - * the converted type of the resultant object, using the context's type converter + * @param expression the OGNL expression to be parsed + * @param context the naming context for the evaluation + * @param root the root object for the OGNL expression + * @param resultType the converted type of the resultant object, using the context's type converter * @return the result of evaluating the expression - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem + * @see #parseExpression(String) + * @see #getValue(Object, Object) */ - public static Object getValue(String expression, Map context, Object root, Class resultType) - throws OgnlException - { + public static Object getValue(String expression, OgnlContext context, Object root, Class resultType) throws OgnlException { return getValue(parseExpression(expression), context, root, resultType); } /** * Evaluates the given OGNL expression tree to extract a value from the given root object. * - * @param tree - * the OGNL expression tree to evaluate, as returned by parseExpression() - * @param root - * the root object for the OGNL expression + * @param tree the OGNL expression tree to evaluate, as returned by parseExpression() + * @param root the root object for the OGNL expression * @return the result of evaluating the expression - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem */ public static Object getValue(Object tree, Object root) - throws OgnlException - { + throws OgnlException { return getValue(tree, root, null); } /** * Evaluates the given OGNL expression tree to extract a value from the given root object. * - * @param tree - * the OGNL expression tree to evaluate, as returned by parseExpression() - * @param root - * the root object for the OGNL expression - * @param resultType - * the converted type of the resultant object, using the context's type converter + * @param tree the OGNL expression tree to evaluate, as returned by parseExpression() + * @param root the root object for the OGNL expression + * @param resultType the converted type of the resultant object, using the context's type converter * @return the result of evaluating the expression - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem */ - public static Object getValue(Object tree, Object root, Class resultType) - throws OgnlException - { + public static Object getValue(Object tree, Object root, Class resultType) throws OgnlException { return getValue(tree, createDefaultContext(root), root, resultType); } @@ -740,27 +524,18 @@ public static Object getValue(Object tree, Object root, Class resultType) * Convenience method that combines calls to parseExpression and * getValue. * - * @see #parseExpression(String) - * @see #getValue(Object,Object) - * @param expression - * the OGNL expression to be parsed - * @param root - * the root object for the OGNL expression + * @param expression the OGNL expression to be parsed + * @param root the root object for the OGNL expression * @return the result of evaluating the expression - * @throws ExpressionSyntaxException - * if the expression is malformed - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @throws ExpressionSyntaxException if the expression is malformed + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem + * @see #parseExpression(String) + * @see #getValue(Object, Object) */ - public static Object getValue(String expression, Object root) - throws OgnlException - { + public static Object getValue(String expression, Object root) throws OgnlException { return getValue(expression, root, null); } @@ -768,29 +543,19 @@ public static Object getValue(String expression, Object root) * Convenience method that combines calls to parseExpression and * getValue. * - * @see #parseExpression(String) - * @see #getValue(Object,Object) - * @param expression - * the OGNL expression to be parsed - * @param root - * the root object for the OGNL expression - * @param resultType - * the converted type of the resultant object, using the context's type converter + * @param expression the OGNL expression to be parsed + * @param root the root object for the OGNL expression + * @param resultType the converted type of the resultant object, using the context's type converter * @return the result of evaluating the expression - * @throws ExpressionSyntaxException - * if the expression is malformed - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @throws ExpressionSyntaxException if the expression is malformed + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem + * @see #parseExpression(String) + * @see #getValue(Object, Object) */ - public static Object getValue(String expression, Object root, Class resultType) - throws OgnlException - { + public static Object getValue(String expression, Object root, Class resultType) throws OgnlException { return getValue(parseExpression(expression), root, resultType); } @@ -798,27 +563,17 @@ public static Object getValue(String expression, Object root, Class resultType) * Evaluates the given OGNL expression tree to insert a value into the object graph rooted at * the given root object. The default context is set for the given context and root via addDefaultContext(). * - * @param tree - * the OGNL expression tree to evaluate, as returned by parseExpression() - * @param context - * the naming context for the evaluation - * @param root - * the root object for the OGNL expression - * @param value - * the value to insert into the object graph - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem - */ - public static void setValue(Object tree, Map context, Object root, Object value) - throws OgnlException - { - OgnlContext ognlContext = (OgnlContext) addDefaultContext(root, context); + * @param tree the OGNL expression tree to evaluate, as returned by parseExpression() + * @param context the naming context for the evaluation + * @param root the root object for the OGNL expression + * @param value the value to insert into the object graph + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem + */ + public static void setValue(Object tree, Map context, Object root, Object value) throws OgnlException { + OgnlContext ognlContext = addDefaultContext(root, context); Node n = (Node) tree; if (n.getAccessor() != null) { @@ -830,21 +585,16 @@ public static void setValue(Object tree, Map context, Object root, Object value) } /** - * Sets the value given using the pre-compiled expression on the specified root + * Sets the value given using the pre-compiled expression on the specified root * object. * - * @param expression - * The pre-compiled expression, as found in {@link Node#getAccessor()}. - * @param context - * The ognl context. - * @param root - * The object to set the expression value on. - * @param value - * The value to set. + * @param expression The pre-compiled expression, as found in {@link Node#getAccessor()}. + * @param context The ognl context. + * @param root The object to set the expression value on. + * @param value The value to set. */ public static void setValue(ExpressionAccessor expression, OgnlContext context, - Object root, Object value) - { + Object root, Object value) { expression.set(context, root, value); } @@ -852,26 +602,16 @@ public static void setValue(ExpressionAccessor expression, OgnlContext context, * Evaluates the given OGNL expression to insert a value into the object graph rooted at the * given root object given the context. * - * @param expression - * the OGNL expression to be parsed - * @param root - * the root object for the OGNL expression - * @param context - * the naming context for the evaluation - * @param value - * the value to insert into the object graph - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @param expression the OGNL expression to be parsed + * @param root the root object for the OGNL expression + * @param context the naming context for the evaluation + * @param value the value to insert into the object graph + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem */ - public static void setValue(String expression, Map context, Object root, Object value) - throws OgnlException - { + public static void setValue(String expression, Map context, Object root, Object value) throws OgnlException { setValue(parseExpression(expression), context, root, value); } @@ -879,24 +619,16 @@ public static void setValue(String expression, Map context, Object root, Object * Evaluates the given OGNL expression tree to insert a value into the object graph rooted at * the given root object. * - * @param tree - * the OGNL expression tree to evaluate, as returned by parseExpression() - * @param root - * the root object for the OGNL expression - * @param value - * the value to insert into the object graph - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @param tree the OGNL expression tree to evaluate, as returned by parseExpression() + * @param root the root object for the OGNL expression + * @param value the value to insert into the object graph + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem */ public static void setValue(Object tree, Object root, Object value) - throws OgnlException - { + throws OgnlException { setValue(tree, createDefaultContext(root), root, value); } @@ -904,28 +636,19 @@ public static void setValue(Object tree, Object root, Object value) * Convenience method that combines calls to parseExpression and * setValue. * + * @param expression the OGNL expression to be parsed + * @param root the root object for the OGNL expression + * @param value the value to insert into the object graph + * @throws ExpressionSyntaxException if the expression is malformed + * @throws MethodFailedException if the expression called a method which failed + * @throws NoSuchPropertyException if the expression referred to a nonexistent property + * @throws InappropriateExpressionException if the expression can't be used in this context + * @throws OgnlException if there is a pathological environmental problem * @see #parseExpression(String) - * @see #setValue(Object,Object,Object) - * @param expression - * the OGNL expression to be parsed - * @param root - * the root object for the OGNL expression - * @param value - * the value to insert into the object graph - * @throws ExpressionSyntaxException - * if the expression is malformed - * @throws MethodFailedException - * if the expression called a method which failed - * @throws NoSuchPropertyException - * if the expression referred to a nonexistent property - * @throws InappropriateExpressionException - * if the expression can't be used in this context - * @throws OgnlException - * if there is a pathological environmental problem + * @see #setValue(Object, Object, Object) */ public static void setValue(String expression, Object root, Object value) - throws OgnlException - { + throws OgnlException { setValue(parseExpression(expression), root, value); } @@ -933,34 +656,24 @@ public static void setValue(String expression, Object root, Object value) * Checks if the specified {@link Node} instance represents a constant * expression. * - * @param tree - * The {@link Node} to check. - * @param context - * The context to use. - * + * @param tree The {@link Node} to check. + * @param context The context to use. * @return True if the node is a constant - false otherwise. - * @throws OgnlException If an error occurs checking the expression. + * @throws OgnlException If an error occurs checking the expression. */ - public static boolean isConstant(Object tree, Map context) - throws OgnlException - { - return ((SimpleNode) tree).isConstant((OgnlContext) addDefaultContext(null, context)); + public static boolean isConstant(Object tree, Map context) throws OgnlException { + return ((SimpleNode) tree).isConstant(addDefaultContext(null, context)); } - /** + /** * Checks if the specified expression represents a constant expression. * - * @param expression - * The expression to check. - * @param context - * The context to use. - * + * @param expression The expression to check. + * @param context The context to use. * @return True if the node is a constant - false otherwise. - * @throws OgnlException If an error occurs checking the expression. + * @throws OgnlException If an error occurs checking the expression. */ - public static boolean isConstant(String expression, Map context) - throws OgnlException - { + public static boolean isConstant(String expression, Map context) throws OgnlException { return isConstant(parseExpression(expression), context); } @@ -968,15 +681,11 @@ public static boolean isConstant(String expression, Map context) * Same as {@link #isConstant(Object, java.util.Map)} - only the {@link Map} context * is created for you. * - * @param tree - * The {@link Node} to check. - * + * @param tree The {@link Node} to check. * @return True if the node represents a constant expression - false otherwise. * @throws OgnlException If an exception occurs. */ - public static boolean isConstant(Object tree) - throws OgnlException - { + public static boolean isConstant(Object tree) throws OgnlException { return isConstant(tree, createDefaultContext(null)); } @@ -984,68 +693,49 @@ public static boolean isConstant(Object tree) * Same as {@link #isConstant(String, java.util.Map)} - only the {@link Map} * instance is created for you. * - * @param expression - * The expression to check. - * + * @param expression The expression to check. * @return True if the expression represents a constant - false otherwise. * @throws OgnlException If an exception occurs. */ - public static boolean isConstant(String expression) - throws OgnlException - { + public static boolean isConstant(String expression) throws OgnlException { return isConstant(parseExpression(expression), createDefaultContext(null)); } - public static boolean isSimpleProperty(Object tree, Map context) - throws OgnlException - { - return ((SimpleNode) tree).isSimpleProperty((OgnlContext) addDefaultContext(null, context)); + public static boolean isSimpleProperty(Object tree, Map context) throws OgnlException { + return ((SimpleNode) tree).isSimpleProperty(addDefaultContext(null, context)); } - public static boolean isSimpleProperty(String expression, Map context) - throws OgnlException - { + public static boolean isSimpleProperty(String expression, Map context) throws OgnlException { return isSimpleProperty(parseExpression(expression), context); } - public static boolean isSimpleProperty(Object tree) - throws OgnlException - { + public static boolean isSimpleProperty(Object tree) throws OgnlException { return isSimpleProperty(tree, createDefaultContext(null)); } - public static boolean isSimpleProperty(String expression) - throws OgnlException - { + public static boolean isSimpleProperty(String expression) throws OgnlException { return isSimpleProperty(parseExpression(expression), createDefaultContext(null)); } - public static boolean isSimpleNavigationChain(Object tree, Map context) - throws OgnlException - { - return ((SimpleNode) tree).isSimpleNavigationChain((OgnlContext) addDefaultContext(null, context)); + public static boolean isSimpleNavigationChain(Object tree, Map context) throws OgnlException { + return ((SimpleNode) tree).isSimpleNavigationChain(addDefaultContext(null, context)); } - public static boolean isSimpleNavigationChain(String expression, Map context) - throws OgnlException - { + public static boolean isSimpleNavigationChain(String expression, Map context) throws OgnlException { return isSimpleNavigationChain(parseExpression(expression), context); } - public static boolean isSimpleNavigationChain(Object tree) - throws OgnlException - { + public static boolean isSimpleNavigationChain(Object tree) throws OgnlException { return isSimpleNavigationChain(tree, createDefaultContext(null)); } - public static boolean isSimpleNavigationChain(String expression) - throws OgnlException - { + public static boolean isSimpleNavigationChain(String expression) throws OgnlException { return isSimpleNavigationChain(parseExpression(expression), createDefaultContext(null)); } - /** You can't make one of these. */ - private Ognl() - { + /** + * You can't make one of these. + */ + private Ognl() { } } diff --git a/src/main/java/ognl/OgnlCache.java b/src/main/java/ognl/OgnlCache.java new file mode 100644 index 00000000..d835d052 --- /dev/null +++ b/src/main/java/ognl/OgnlCache.java @@ -0,0 +1,280 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl; + +import ognl.internal.Cache; +import ognl.internal.CacheException; +import ognl.internal.CacheFactory; +import ognl.internal.ClassCache; +import ognl.internal.ClassCacheHandler; +import ognl.internal.HashMapCacheFactory; +import ognl.internal.entry.DeclaredMethodCacheEntry; +import ognl.internal.entry.DeclaredMethodCacheEntryFactory; +import ognl.internal.entry.FieldCacheEntryFactory; +import ognl.internal.entry.GenericMethodParameterTypeCacheEntry; +import ognl.internal.entry.GenericMethodParameterTypeFactory; +import ognl.internal.entry.MethodAccessCacheEntryFactory; +import ognl.internal.entry.MethodAccessEntryValue; +import ognl.internal.entry.MethodPermCacheEntryFactory; +import ognl.internal.entry.PermissionCacheEntry; +import ognl.internal.entry.PermissionCacheEntryFactory; +import ognl.internal.entry.PropertyDescriptorCacheEntryFactory; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.security.Permission; +import java.util.Arrays; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * This class takes care of all the internal caching for OGNL. + */ +public class OgnlCache { + + private final CacheFactory cacheFactory = new HashMapCacheFactory(); + + private final ClassCache methodAccessors = cacheFactory.createClassCache(); + + { + MethodAccessor methodAccessor = new ObjectMethodAccessor(); + setMethodAccessor(Object.class, methodAccessor); + setMethodAccessor(byte[].class, methodAccessor); + setMethodAccessor(short[].class, methodAccessor); + setMethodAccessor(char[].class, methodAccessor); + setMethodAccessor(int[].class, methodAccessor); + setMethodAccessor(long[].class, methodAccessor); + setMethodAccessor(float[].class, methodAccessor); + setMethodAccessor(double[].class, methodAccessor); + setMethodAccessor(Object[].class, methodAccessor); + } + + private final ClassCache propertyAccessors = cacheFactory.createClassCache(); + + { + PropertyAccessor propertyAccessor = new ArrayPropertyAccessor(); + setPropertyAccessor(Object.class, new ObjectPropertyAccessor()); + setPropertyAccessor(byte[].class, propertyAccessor); + setPropertyAccessor(short[].class, propertyAccessor); + setPropertyAccessor(char[].class, propertyAccessor); + setPropertyAccessor(int[].class, propertyAccessor); + setPropertyAccessor(long[].class, propertyAccessor); + setPropertyAccessor(float[].class, propertyAccessor); + setPropertyAccessor(double[].class, propertyAccessor); + setPropertyAccessor(Object[].class, propertyAccessor); + setPropertyAccessor(List.class, new ListPropertyAccessor()); + setPropertyAccessor(Map.class, new MapPropertyAccessor()); + setPropertyAccessor(Set.class, new SetPropertyAccessor()); + setPropertyAccessor(Iterator.class, new IteratorPropertyAccessor()); + setPropertyAccessor(Enumeration.class, new EnumerationPropertyAccessor()); + } + + private final ClassCache elementsAccessors = cacheFactory.createClassCache(); + + { + ElementsAccessor elementsAccessor = new ArrayElementsAccessor(); + setElementsAccessor(Object.class, new ObjectElementsAccessor()); + setElementsAccessor(byte[].class, elementsAccessor); + setElementsAccessor(short[].class, elementsAccessor); + setElementsAccessor(char[].class, elementsAccessor); + setElementsAccessor(int[].class, elementsAccessor); + setElementsAccessor(long[].class, elementsAccessor); + setElementsAccessor(float[].class, elementsAccessor); + setElementsAccessor(double[].class, elementsAccessor); + setElementsAccessor(Object[].class, elementsAccessor); + setElementsAccessor(Collection.class, new CollectionElementsAccessor()); + setElementsAccessor(Map.class, new MapElementsAccessor()); + setElementsAccessor(Iterator.class, new IteratorElementsAccessor()); + setElementsAccessor(Enumeration.class, new EnumerationElementsAccessor()); + setElementsAccessor(Number.class, new NumberElementsAccessor()); + } + + private final ClassCache nullHandlers = cacheFactory.createClassCache(); + + { + NullHandler nullHandler = new ObjectNullHandler(); + setNullHandler(Object.class, nullHandler); + setNullHandler(byte[].class, nullHandler); + setNullHandler(short[].class, nullHandler); + setNullHandler(char[].class, nullHandler); + setNullHandler(int[].class, nullHandler); + setNullHandler(long[].class, nullHandler); + setNullHandler(float[].class, nullHandler); + setNullHandler(double[].class, nullHandler); + setNullHandler(Object[].class, nullHandler); + } + + final ClassCache> propertyDescriptorCache = + cacheFactory.createClassCache(new PropertyDescriptorCacheEntryFactory()); + + private final ClassCache>> constructorCache = + cacheFactory.createClassCache(key -> Arrays.asList(key.getConstructors())); + + private final Cache>> methodCache = + cacheFactory.createCache(new DeclaredMethodCacheEntryFactory()); + + private final Cache invokePermissionCache = + cacheFactory.createCache(new PermissionCacheEntryFactory()); + + private final ClassCache> fieldCache = + cacheFactory.createClassCache(new FieldCacheEntryFactory()); + + private final Cache[]> methodParameterTypesCache = + cacheFactory.createCache(Method::getParameterTypes); + + final Cache[]> genericMethodParameterTypesCache = + cacheFactory.createCache(new GenericMethodParameterTypeFactory()); + + private final Cache, Class[]> ctorParameterTypesCache = + cacheFactory.createCache(Constructor::getParameterTypes); + + private final Cache methodAccessCache = + cacheFactory.createCache(new MethodAccessCacheEntryFactory()); + + private final MethodPermCacheEntryFactory methodPermCacheEntryFactory = + new MethodPermCacheEntryFactory(System.getSecurityManager()); + + private final Cache methodPermCache = cacheFactory.createCache(methodPermCacheEntryFactory); + + public Class[] getMethodParameterTypes(Method method) throws CacheException { + return methodParameterTypesCache.get(method); + } + + public Class[] getParameterTypes(Constructor constructor) throws CacheException { + return ctorParameterTypesCache.get(constructor); + } + + public List> getConstructor(Class clazz) throws CacheException { + return constructorCache.get(clazz); + } + + public Map getField(Class clazz) throws CacheException { + return fieldCache.get(clazz); + } + + public Map> getMethod(DeclaredMethodCacheEntry declaredMethodCacheEntry) throws CacheException { + return methodCache.get(declaredMethodCacheEntry); + } + + public Map getPropertyDescriptor(Class clazz) throws CacheException { + return propertyDescriptorCache.get(clazz); + } + + public Permission getInvokePermission(PermissionCacheEntry permissionCacheEntry) throws CacheException { + return invokePermissionCache.get(permissionCacheEntry); + } + + public MethodAccessor getMethodAccessor(Class clazz) throws OgnlException { + MethodAccessor methodAccessor = ClassCacheHandler.getHandler(clazz, methodAccessors); + if (methodAccessor != null) { + return methodAccessor; + } + throw new OgnlException("No method accessor for " + clazz); + } + + public void setMethodAccessor(Class clazz, MethodAccessor accessor) { + methodAccessors.put(clazz, accessor); + } + + public void setPropertyAccessor(Class clazz, PropertyAccessor accessor) { + propertyAccessors.put(clazz, accessor); + } + + public PropertyAccessor getPropertyAccessor(Class clazz) throws OgnlException { + PropertyAccessor propertyAccessor = ClassCacheHandler.getHandler(clazz, propertyAccessors); + if (propertyAccessor != null) { + return propertyAccessor; + } + throw new OgnlException("No property accessor for class " + clazz); + } + + /** + * Registers the specified {@link ClassCacheInspector} with all class reflection based internal caches. This may + * have a significant performance impact so be careful using this in production scenarios. + * + * @param inspector The inspector instance that will be registered with all internal cache instances. + */ + public void setClassCacheInspector(ClassCacheInspector inspector) { + propertyDescriptorCache.setClassInspector(inspector); + constructorCache.setClassInspector(inspector); + //TODO: methodCache and invokePC should allow to use classCacheInsecptor +// _methodCache.setClassInspector( inspector ); +// _invokePermissionCache.setClassInspector( inspector ); + fieldCache.setClassInspector(inspector); + } + + public Class[] getGenericMethodParameterTypes(GenericMethodParameterTypeCacheEntry key) throws CacheException { + return genericMethodParameterTypesCache.get(key); + } + + public boolean getMethodPerm(Method method) throws CacheException { + return methodPermCache.get(method); + } + + public MethodAccessEntryValue getMethodAccess(Method method) throws CacheException { + return methodAccessCache.get(method); + } + + public void clear() { + methodParameterTypesCache.clear(); + ctorParameterTypesCache.clear(); + propertyDescriptorCache.clear(); + genericMethodParameterTypesCache.clear(); + constructorCache.clear(); + methodCache.clear(); + invokePermissionCache.clear(); + fieldCache.clear(); + methodAccessCache.clear(); + } + + public ElementsAccessor getElementsAccessor(Class clazz) throws OgnlException { + ElementsAccessor answer = ClassCacheHandler.getHandler(clazz, elementsAccessors); + if (answer != null) { + return answer; + } + throw new OgnlException("No elements accessor for class " + clazz); + } + + public void setElementsAccessor(Class clazz, ElementsAccessor accessor) { + elementsAccessors.put(clazz, accessor); + } + + public NullHandler getNullHandler(Class clazz) throws OgnlException { + NullHandler answer = ClassCacheHandler.getHandler(clazz, nullHandlers); + if (answer != null) { + return answer; + } + throw new OgnlException("No null handler for class " + clazz); + } + + public void setNullHandler(Class clazz, NullHandler handler) { + nullHandlers.put(clazz, handler); + } + + public void setSecurityManager(SecurityManager securityManager) { + methodPermCacheEntryFactory.setSecurityManager(securityManager); + } + +} diff --git a/src/main/java/ognl/OgnlContext.java b/src/main/java/ognl/OgnlContext.java index 5f1315d7..591aa2dd 100644 --- a/src/main/java/ognl/OgnlContext.java +++ b/src/main/java/ognl/OgnlContext.java @@ -1,47 +1,37 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.LocalReference; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; /** * This class defines the execution context for an OGNL expression - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class OgnlContext extends Object implements Map -{ +public class OgnlContext implements Map { public static final String ROOT_CONTEXT_KEY = "root"; public static final String THIS_CONTEXT_KEY = "this"; @@ -57,7 +47,7 @@ public class OgnlContext extends Object implements Map private static boolean DEFAULT_KEEP_LAST_EVALUATION = false; private static final Map RESERVED_KEYS = new HashMap<>(6); - + private Object _root; private Object _currentObject; private Node _currentNode; @@ -66,15 +56,14 @@ public class OgnlContext extends Object implements Map private Evaluation _currentEvaluation; private Evaluation _lastEvaluation; private boolean _keepLastEvaluation = DEFAULT_KEEP_LAST_EVALUATION; - - private final Map _values; - + + private final Map _values; + private final ClassResolver _classResolver; private final TypeConverter _typeConverter; private final MemberAccess _memberAccess; - + static { - String s; RESERVED_KEYS.put(ROOT_CONTEXT_KEY, null); RESERVED_KEYS.put(THIS_CONTEXT_KEY, null); @@ -83,11 +72,12 @@ public class OgnlContext extends Object implements Map RESERVED_KEYS.put(KEEP_LAST_EVALUATION_CONTEXT_KEY, null); try { - if ((s = System.getProperty(PROPERTY_KEY_PREFIX + ".traceEvaluations")) != null) { - DEFAULT_TRACE_EVALUATIONS = Boolean.valueOf(s.trim()); + String property; + if ((property = System.getProperty(PROPERTY_KEY_PREFIX + ".traceEvaluations")) != null) { + DEFAULT_TRACE_EVALUATIONS = Boolean.parseBoolean(property.trim()); } - if ((s = System.getProperty(PROPERTY_KEY_PREFIX + ".keepLastEvaluation")) != null) { - DEFAULT_KEEP_LAST_EVALUATION = Boolean.valueOf(s.trim()); + if ((property = System.getProperty(PROPERTY_KEY_PREFIX + ".keepLastEvaluation")) != null) { + DEFAULT_KEEP_LAST_EVALUATION = Boolean.parseBoolean(property.trim()); } } catch (SecurityException ex) { // restricted access environment, just keep defaults @@ -103,33 +93,31 @@ public class OgnlContext extends Object implements Map /** * Constructs a new OgnlContext with the given class resolver, type converter and member access. * If any of these parameters is null the default will be used, except memberAccess which must be non-null. - * + * * @param classResolver the ClassResolver for a new OgnlContext. * @param typeConverter the TypeConverter for a new OgnlContext. - * @param memberAccess the MemberAccess for a new OgnlContext. Must be non-null. + * @param memberAccess the MemberAccess for a new OgnlContext. Must be non-null. */ - public OgnlContext(ClassResolver classResolver, TypeConverter typeConverter, MemberAccess memberAccess) - { + public OgnlContext(ClassResolver classResolver, TypeConverter typeConverter, MemberAccess memberAccess) { // No 'values' map has been specified, so we create one of the default size: 23 entries - this(memberAccess, classResolver, typeConverter, new HashMap(23)); + this(memberAccess, classResolver, typeConverter, new HashMap<>(23)); } /** * Constructs a new OgnlContext with the given member access, class resolver, type converter and values. * If any of these parameters is null the default will be used, except memberAccess which must be non-null. - * - * @param memberAccess the MemberAccess for a new OgnlContext. Must be non-null. + * + * @param memberAccess the MemberAccess for a new OgnlContext. Must be non-null. * @param classResolver the ClassResolver for a new OgnlContext. * @param typeConverter the TypeConverter for a new OgnlContext. - * @param values the Map of values to provide for a new OgnlContext. + * @param values the Map of values to provide for a new OgnlContext. */ - public OgnlContext(MemberAccess memberAccess, ClassResolver classResolver, TypeConverter typeConverter, Map values) - { + public OgnlContext(MemberAccess memberAccess, ClassResolver classResolver, TypeConverter typeConverter, Map values) { super(); if (values != null) { this._values = values; } else { - this._values = new HashMap(23); // No 'values' map has been specified, so we create one of the default size: 23 entries + this._values = new HashMap<>(23); // No 'values' map has been specified, so we create one of the default size: 23 entries } if (classResolver != null) { this._classResolver = classResolver; @@ -150,23 +138,21 @@ public OgnlContext(MemberAccess memberAccess, ClassResolver classResolver, TypeC /** * Set (put) the provided value map content into the existing values Map for this OgnlContext. - * - * @param value a Map of additional values to put into this OgnlContext. + * + * @param values a Map of additional values to put into this OgnlContext. */ - public void setValues(Map value) - { - for (Object k : value.keySet()) { - _values.put(k, value.get(k)); + public void setValues(Map values) { + for (Object k : values.keySet()) { + _values.put(k.toString(), values.get(k)); } } /** * Get the values Map for this OgnlContext. - * + * * @return Map of values for this OgnlContext. */ - public Map getValues() - { + public Map getValues() { return _values; } @@ -175,68 +161,56 @@ public void setClassResolver(ClassResolver ignore) { // no-op } - public ClassResolver getClassResolver() - { + public ClassResolver getClassResolver() { return _classResolver; } @Deprecated - public void setTypeConverter(TypeConverter ignore) - { + public void setTypeConverter(TypeConverter ignore) { // no-op } - public TypeConverter getTypeConverter() - { + public TypeConverter getTypeConverter() { return _typeConverter; } @Deprecated - public void setMemberAccess(MemberAccess ignore) - { + public void setMemberAccess(MemberAccess ignore) { // no-op } - public MemberAccess getMemberAccess() - { + public MemberAccess getMemberAccess() { return _memberAccess; } - public void setRoot(Object value) - { + public void setRoot(Object value) { _root = value; _accessorStack.clear(); _typeStack.clear(); _currentObject = value; - if (_currentObject != null) - { + if (_currentObject != null) { setCurrentType(_currentObject.getClass()); } } - public Object getRoot() - { + public Object getRoot() { return _root; } - public boolean getTraceEvaluations() - { + public boolean getTraceEvaluations() { return _traceEvaluations; } - public void setTraceEvaluations(boolean value) - { + public void setTraceEvaluations(boolean value) { _traceEvaluations = value; } - public Evaluation getLastEvaluation() - { + public Evaluation getLastEvaluation() { return _lastEvaluation; } - public void setLastEvaluation(Evaluation value) - { + public void setLastEvaluation(Evaluation value) { _lastEvaluation = value; } @@ -249,59 +223,50 @@ public void setLastEvaluation(Evaluation value) * @deprecated since 3.2 */ @Deprecated - public void recycleLastEvaluation() - { - OgnlRuntime.getEvaluationPool().recycleAll(_lastEvaluation); + public void recycleLastEvaluation() { _lastEvaluation = null; } /** * Returns true if the last evaluation that was done on this context is retained and available * through getLastEvaluation(). The default is true. - * + * * @return true if the last evaluation for this context is retained and available through getLastEvaluation(), false otherwise. */ - public boolean getKeepLastEvaluation() - { + public boolean getKeepLastEvaluation() { return _keepLastEvaluation; } /** * Sets whether the last evaluation that was done on this context is retained and available * through getLastEvaluation(). The default is true. - * + * * @param value true if the last evaluation for this context should be retained and available through getLastEvaluation(), false otherwise. */ - public void setKeepLastEvaluation(boolean value) - { + public void setKeepLastEvaluation(boolean value) { _keepLastEvaluation = value; } - public void setCurrentObject(Object value) - { + public void setCurrentObject(Object value) { _currentObject = value; } - - public Object getCurrentObject() - { + + public Object getCurrentObject() { return _currentObject; } - - public void setCurrentAccessor(Class type) - { - _accessorStack.add(type); + + public void setCurrentAccessor(Class type) { + _accessorStack.add(type); } - - public Class getCurrentAccessor() - { + + public Class getCurrentAccessor() { if (_accessorStack.isEmpty()) return null; - + return _accessorStack.get(_accessorStack.size() - 1); } - - public Class getPreviousAccessor() - { + + public Class getPreviousAccessor() { if (_accessorStack.isEmpty()) return null; @@ -311,8 +276,7 @@ public Class getPreviousAccessor() return null; } - public Class getFirstAccessor() - { + public Class getFirstAccessor() { if (_accessorStack.isEmpty()) return null; @@ -321,30 +285,27 @@ public Class getFirstAccessor() /** * Gets the current class type being evaluated on the stack, as set by {@link #setCurrentType(Class)}. - * + * * @return The current object type, may be null. */ - public Class getCurrentType() - { + public Class getCurrentType() { if (_typeStack.isEmpty()) return null; - return (Class) _typeStack.get(_typeStack.size() - 1); + return _typeStack.get(_typeStack.size() - 1); } - - public void setCurrentType(Class type) - { + + public void setCurrentType(Class type) { _typeStack.add(type); } - + /** * Represents the last known object type on the evaluation stack, will be the value of * the last known {@link #getCurrentType()}. - * + * * @return The previous type of object on the stack, may be null. */ - public Class getPreviousType() - { + public Class getPreviousType() { if (_typeStack.isEmpty()) return null; @@ -353,62 +314,54 @@ public Class getPreviousType() else return null; } - - public void setPreviousType(Class type) - { + + public void setPreviousType(Class type) { if (_typeStack.isEmpty() || _typeStack.size() < 2) return; _typeStack.set(_typeStack.size() - 2, type); } - public Class getFirstType() - { + public Class getFirstType() { if (_typeStack.isEmpty()) return null; return _typeStack.get(0); } - public void setCurrentNode(Node value) - { + public void setCurrentNode(Node value) { _currentNode = value; } - public Node getCurrentNode() - { + public Node getCurrentNode() { return _currentNode; } /** * Gets the current Evaluation from the top of the stack. This is the Evaluation that is in * process of evaluating. - * + * * @return the current Evaluation from the top of the stack (being evaluated). */ - public Evaluation getCurrentEvaluation() - { + public Evaluation getCurrentEvaluation() { return _currentEvaluation; } - public void setCurrentEvaluation(Evaluation value) - { + public void setCurrentEvaluation(Evaluation value) { _currentEvaluation = value; } /** * Gets the root of the evaluation stack. This Evaluation contains the node representing the * root expression and the source is the root source object. - * + * * @return the root Evaluation from the stack (the root expression node). */ - public Evaluation getRootEvaluation() - { + public Evaluation getRootEvaluation() { return _rootEvaluation; } - public void setRootEvaluation(Evaluation value) - { + public void setRootEvaluation(Evaluation value) { _rootEvaluation = value; } @@ -416,17 +369,16 @@ public void setRootEvaluation(Evaluation value) * Returns the Evaluation at the relative index given. This should be zero or a negative number * as a relative reference back up the evaluation stack. Therefore getEvaluation(0) returns the * current Evaluation. - * + * * @param relativeIndex the relative index for the Evaluation to retrieve from the stack (with 0 being the current Evaluation). relativeIndex should be <= 0. * @return the Evaluation at relativeIndex, or null if relativeIndex is > 0. */ - public Evaluation getEvaluation(int relativeIndex) - { + public Evaluation getEvaluation(int relativeIndex) { Evaluation result = null; if (relativeIndex <= 0) { result = _currentEvaluation; - while((++relativeIndex < 0) && (result != null)) { + while ((++relativeIndex < 0) && (result != null)) { result = result.getParent(); } } @@ -436,11 +388,10 @@ public Evaluation getEvaluation(int relativeIndex) /** * Pushes a new Evaluation onto the stack. This is done before a node evaluates. When evaluation * is complete it should be popped from the stack via popEvaluation(). - * + * * @param value the Evaluation to push onto the stack. */ - public void pushEvaluation(Evaluation value) - { + public void pushEvaluation(Evaluation value) { if (_currentEvaluation != null) { _currentEvaluation.addChild(value); } else { @@ -452,11 +403,10 @@ public void pushEvaluation(Evaluation value) /** * Pops the current Evaluation off of the top of the stack. This is done after a node has * completed its evaluation. - * + * * @return the Evaluation popped from the top of the stack. */ - public Evaluation popEvaluation() - { + public Evaluation popEvaluation() { Evaluation result; result = _currentEvaluation; @@ -469,54 +419,45 @@ public Evaluation popEvaluation() return result; } - public int incrementLocalReferenceCounter() - { + public int incrementLocalReferenceCounter() { return ++_localReferenceCounter; } - public void addLocalReference(String key, LocalReference reference) - { - if (_localReferenceMap == null) - { + public void addLocalReference(String key, LocalReference reference) { + if (_localReferenceMap == null) { _localReferenceMap = new LinkedHashMap<>(); } _localReferenceMap.put(key, reference); } - public Map getLocalReferences() - { + public Map getLocalReferences() { return _localReferenceMap; } /* ================= Map interface ================= */ @Override - public int size() - { + public int size() { return _values.size(); } @Override - public boolean isEmpty() - { + public boolean isEmpty() { return _values.isEmpty(); } @Override - public boolean containsKey(Object key) - { + public boolean containsKey(Object key) { return _values.containsKey(key); } @Override - public boolean containsValue(Object value) - { + public boolean containsValue(Object value) { return _values.containsValue(value); } @Override - public Object get(Object key) - { + public Object get(Object key) { Object result; if (RESERVED_KEYS.containsKey(key)) { @@ -548,10 +489,9 @@ public Object get(Object key) } @Override - public Object put(Object key, Object value) - { + public Object put(Object key, Object value) { Object result; - + if (RESERVED_KEYS.containsKey(key)) { if (key.equals(OgnlContext.THIS_CONTEXT_KEY)) { result = getCurrentObject(); @@ -582,13 +522,12 @@ public Object put(Object key, Object value) } else { result = _values.put(key, value); } - + return result; } @Override - public Object remove(Object key) - { + public Object remove(Object key) { Object result; if (RESERVED_KEYS.containsKey(key)) { @@ -625,23 +564,20 @@ public Object remove(Object key) } @Override - public void putAll(Map t) - { + public void putAll(Map t) { for (Object k : t.keySet()) { put(k, t.get(k)); } } @Override - public void clear() - { + public void clear() { _values.clear(); _typeStack.clear(); _accessorStack.clear(); _localReferenceCounter = 0; - if (_localReferenceMap != null) - { + if (_localReferenceMap != null) { _localReferenceMap.clear(); } @@ -654,35 +590,31 @@ public void clear() } @Override - public Set keySet() - { + public Set keySet() { /* Should root, currentObject, classResolver, typeConverter & memberAccess be included here? */ return _values.keySet(); } @Override - public Collection values() - { + public Collection values() { /* Should root, currentObject, classResolver, typeConverter & memberAccess be included here? */ return _values.values(); } @Override - public Set entrySet() - { + public Set> entrySet() { /* Should root, currentObject, classResolver, typeConverter & memberAccess be included here? */ return _values.entrySet(); } @Override - public boolean equals(Object o) - { + public boolean equals(Object o) { return _values.equals(o); } @Override - public int hashCode() - { + public int hashCode() { return _values.hashCode(); } + } diff --git a/src/main/java/ognl/OgnlException.java b/src/main/java/ognl/OgnlException.java index f7c216ef..5066bf05 100644 --- a/src/main/java/ognl/OgnlException.java +++ b/src/main/java/ognl/OgnlException.java @@ -1,77 +1,70 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; /** * Superclass for OGNL exceptions, incorporating an optional encapsulated exception. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class OgnlException extends Exception -{ - /** +public class OgnlException extends Exception { + + private static final long serialVersionUID = 1225801032966287635L; + + /** * The root evaluation of the expression when the exception was thrown */ private Evaluation _evaluation; - /** Constructs an OgnlException with no message or encapsulated exception. */ - public OgnlException() - { - this( null, null ); + /** + * Constructs an OgnlException with no message or encapsulated exception. + */ + public OgnlException() { + this(null, null); } /** * Constructs an OgnlException with the given message but no encapsulated exception. + * * @param msg the exception's detail message */ - public OgnlException( String msg ) - { - this( msg, null ); + public OgnlException(String msg) { + this(msg, null); } /** * Constructs an OgnlException with the given message and encapsulated exception. - * @param msg the exception's detail message - * @param reason the encapsulated exception + * + * @param msg the exception's detail message + * @param reason the encapsulated exception */ - public OgnlException( String msg, Throwable reason ) - { - super( msg , reason, true, false); + public OgnlException(String msg, Throwable reason) { + super(msg, reason, true, false); } /** * Constructs an OgnlException with the given message and encapsulated exception, * with control on exception suppression and stack trace collection. - * See {@code java.lang.Throwable.Throwable(String, Throwable, boolean, boolean)} for more info. + * + * @param message the exception's detail message + * @param reason the encapsulated exception + * @param enableSuppression whether suppression is enabled or disabled + * @param writableStackTrace whether the stack trace should be writable + * See {@link java.lang.Throwable#Throwable(String, Throwable, boolean, boolean)} for more info. */ protected OgnlException(String message, Throwable reason, boolean enableSuppression, boolean writableStackTrace) { super(message, reason, enableSuppression, writableStackTrace); @@ -79,20 +72,20 @@ protected OgnlException(String message, Throwable reason, boolean enableSuppress /** * Returns the encapsulated exception, or null if there is none. + * * @return the encapsulated exception */ - public Throwable getReason() - { + public Throwable getReason() { return getCause(); } /** * Returns the Evaluation that was the root evaluation when the exception was * thrown. + * * @return The {@link Evaluation}. */ - public Evaluation getEvaluation() - { + public Evaluation getEvaluation() { return _evaluation; } @@ -101,20 +94,21 @@ public Evaluation getEvaluation() * * @param value The {@link Evaluation}. */ - public void setEvaluation(Evaluation value) - { + public void setEvaluation(Evaluation value) { _evaluation = value; } /** * Returns a string representation of this exception. + * * @return a string representation of this exception */ - public String toString() - { - if ( getCause() == null ) + public String toString() { + if (getCause() == null) { return super.toString(); + } return super.toString() + " [" + getCause() + "]"; } + } diff --git a/src/main/java/ognl/OgnlInvokePermission.java b/src/main/java/ognl/OgnlInvokePermission.java index 94f3490a..46a22690 100644 --- a/src/main/java/ognl/OgnlInvokePermission.java +++ b/src/main/java/ognl/OgnlInvokePermission.java @@ -1,36 +1,24 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.security.*; +import java.security.BasicPermission; /** * BasicPermission subclass that defines a permission token for invoking @@ -38,18 +26,16 @@ * constructors) and does not implement actions. It is similar in spirit * to the {@link java.lang.reflect.ReflectPermission} class in that it * guards access to methods. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class OgnlInvokePermission extends BasicPermission -{ - public OgnlInvokePermission(String name) - { +public class OgnlInvokePermission extends BasicPermission { + + private static final long serialVersionUID = -1075128617667321761L; + + public OgnlInvokePermission(String name) { super(name); } - public OgnlInvokePermission(String name, String actions) - { + public OgnlInvokePermission(String name, String actions) { super(name, actions); } } diff --git a/src/main/java/ognl/OgnlOps.java b/src/main/java/ognl/OgnlOps.java index 38230978..8c14f2ee 100644 --- a/src/main/java/ognl/OgnlOps.java +++ b/src/main/java/ognl/OgnlOps.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.UnsupportedCompilationException; @@ -35,17 +23,14 @@ import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; +import java.math.RoundingMode; import java.util.Collection; import java.util.Enumeration; /** * This is an abstract class with static methods that define the operations of OGNL. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public abstract class OgnlOps implements NumericTypes -{ +public abstract class OgnlOps implements NumericTypes { /** * Compares two objects for equality, even if it has to convert one of them to the other type. @@ -55,19 +40,15 @@ public abstract class OgnlOps implements NumericTypes * (i.e. v1 is of the same or superclass of v2's type) they are compared with * Comparable.compareTo(). If both values are non-numeric and not Comparable or of incompatible * classes this will throw and IllegalArgumentException. - * - * @param v1 - * First value to compare - * @param v2 - * second value to compare + * + * @param v1 First value to compare + * @param v2 second value to compare * @return integer describing the comparison between the two objects. A negative number - * indicates that v1 < v2. Positive indicates that v1 > v2. Zero indicates v1 == v2. - * @throws IllegalArgumentException - * if the objects are both non-numeric yet of incompatible types or do not implement - * Comparable. + * indicates that v1 < v2. Positive indicates that v1 > v2. Zero indicates v1 == v2. + * @throws IllegalArgumentException if the objects are both non-numeric yet of incompatible types or do not implement + * Comparable. */ - public static int compareWithConversion(Object v1, Object v2) - { + public static int compareWithConversion(Object v1, Object v2) { int result; if (v1 == v2) { @@ -75,42 +56,42 @@ public static int compareWithConversion(Object v1, Object v2) } else { int t1 = getNumericType(v1), t2 = getNumericType(v2), type = getNumericType(t1, t2, true); - switch(type) { - case BIGINT: - result = bigIntValue(v1).compareTo(bigIntValue(v2)); - break; - - case BIGDEC: - result = bigDecValue(v1).compareTo(bigDecValue(v2)); - break; - - case NONNUMERIC: - if ((t1 == NONNUMERIC) && (t2 == NONNUMERIC)) { - if ((v1 instanceof Comparable) && v1.getClass().isAssignableFrom(v2.getClass())) { - result = ((Comparable) v1).compareTo(v2); - break; - } else if ((v1 instanceof Enum && v2 instanceof Enum) && - (v1.getClass() == v2.getClass() || ((Enum) v1).getDeclaringClass() == ((Enum) v2).getDeclaringClass())) { - result = ((Enum) v1).compareTo((Enum) v2); - break; - } else { - throw new IllegalArgumentException("invalid comparison: " + v1.getClass().getName() + " and " - + v2.getClass().getName()); + switch (type) { + case BIGINT: + result = bigIntValue(v1).compareTo(bigIntValue(v2)); + break; + + case BIGDEC: + result = bigDecValue(v1).compareTo(bigDecValue(v2)); + break; + + case NONNUMERIC: + if ((t1 == NONNUMERIC) && (t2 == NONNUMERIC)) { + if ((v1 instanceof Comparable) && v1.getClass().isAssignableFrom(v2.getClass())) { + result = ((Comparable) v1).compareTo(v2); + break; + } else if ((v1 instanceof Enum && v2 instanceof Enum) && + (v1.getClass() == v2.getClass() || ((Enum) v1).getDeclaringClass() == ((Enum) v2).getDeclaringClass())) { + result = ((Enum) v1).compareTo((Enum) v2); + break; + } else { + throw new IllegalArgumentException("invalid comparison: " + v1.getClass().getName() + " and " + + v2.getClass().getName()); + } } - } - // else fall through - case FLOAT: - case DOUBLE: - double dv1 = doubleValue(v1), - dv2 = doubleValue(v2); + // else fall through + case FLOAT: + case DOUBLE: + double dv1 = doubleValue(v1), + dv2 = doubleValue(v2); - return (dv1 == dv2) ? 0 : ((dv1 < dv2) ? -1 : 1); + return (dv1 == dv2) ? 0 : ((dv1 < dv2) ? -1 : 1); - default: - long lv1 = longValue(v1), - lv2 = longValue(v2); + default: + long lv1 = longValue(v1), + lv2 = longValue(v2); - return (lv1 == lv2) ? 0 : ((lv1 < lv2) ? -1 : 1); + return (lv1 == lv2) ? 0 : ((lv1 < lv2) ? -1 : 1); } } return result; @@ -119,15 +100,12 @@ public static int compareWithConversion(Object v1, Object v2) /** * Returns true if object1 is equal to object2 in either the sense that they are the same object * or, if both are non-null if they are equal in the equals() sense. - * - * @param object1 - * First object to compare - * @param object2 - * Second object to compare + * + * @param object1 First object to compare + * @param object2 Second object to compare * @return true if v1 == v2 */ - public static boolean isEqual(Object object1, Object object2) - { + public static boolean isEqual(Object object1, Object object2) { boolean result = false; if (object1 == object2) { @@ -137,7 +115,7 @@ public static boolean isEqual(Object object1, Object object2) if (object2.getClass().isArray() && (object2.getClass() == object1.getClass())) { result = (Array.getLength(object1) == Array.getLength(object2)); if (result) { - for(int i = 0, icount = Array.getLength(object1); result && (i < icount); i++) { + for (int i = 0, icount = Array.getLength(object1); result && (i < icount); i++) { result = isEqual(Array.get(object1, i), Array.get(object2, i)); } } @@ -156,98 +134,89 @@ public static boolean isEqual(Object object1, Object object2) } return result; } - - public static boolean booleanValue(boolean value) - { + + public static boolean booleanValue(boolean value) { return value; } - - public static boolean booleanValue(int value) - { + + public static boolean booleanValue(int value) { return value > 0; } - - public static boolean booleanValue(float value) - { + + public static boolean booleanValue(float value) { return value > 0; } - - public static boolean booleanValue(long value) - { + + public static boolean booleanValue(long value) { return value > 0; } - - public static boolean booleanValue(double value) - { + + public static boolean booleanValue(double value) { return value > 0; } - + /** * Evaluates the given object as a boolean: if it is a Boolean object, it's easy; if it's a * Number or a Character, returns true for non-zero objects; and otherwise returns true for * non-null objects. - * - * @param value - * an object to interpret as a boolean + * + * @param value an object to interpret as a boolean * @return the boolean value implied by the given object */ - public static boolean booleanValue(Object value) - { - if (value == null) + public static boolean booleanValue(Object value) { + if (value == null) { return false; - Class c = value.getClass(); + } - if (c == Boolean.class) - return ((Boolean) value).booleanValue(); + Class c = value.getClass(); - if ( c == String.class ) + if (c == Boolean.class) { + return (Boolean) value; + } + if (c == String.class) { return Boolean.parseBoolean(String.valueOf(value)); - - if (c == Character.class) - return ((Character) value).charValue() != 0; - if (value instanceof Number) + } + if (c == Character.class) { + return (Character) value != 0; + } + if (value instanceof Number) { return ((Number) value).doubleValue() != 0; - + } + return true; // non-null } /** * Evaluates the given object as a long integer. - * - * @param value - * an object to interpret as a long integer + * + * @param value an object to interpret as a long integer * @return the long integer value implied by the given object - * @throws NumberFormatException - * if the given object can't be understood as a long integer + * @throws NumberFormatException if the given object can't be understood as a long integer */ public static long longValue(Object value) - throws NumberFormatException - { + throws NumberFormatException { if (value == null) return 0L; - Class c = value.getClass(); + Class c = value.getClass(); if (c.getSuperclass() == Number.class) return ((Number) value).longValue(); - if (c == Boolean.class) return ((Boolean) value).booleanValue() ? 1 : 0; - if (c == Character.class) return ((Character) value).charValue(); + if (c == Boolean.class) return (Boolean) value ? 1 : 0; + if (c == Character.class) return (Character) value; return Long.parseLong(stringValue(value, true)); } /** * Evaluates the given object as a double-precision floating-point number. - * - * @param value - * an object to interpret as a double + * + * @param value an object to interpret as a double * @return the double value implied by the given object - * @throws NumberFormatException - * if the given object can't be understood as a double + * @throws NumberFormatException if the given object can't be understood as a double */ public static double doubleValue(Object value) - throws NumberFormatException - { + throws NumberFormatException { if (value == null) return 0.0; - Class c = value.getClass(); + Class c = value.getClass(); if (c.getSuperclass() == Number.class) return ((Number) value).doubleValue(); - if (c == Boolean.class) return ((Boolean) value).booleanValue() ? 1 : 0; - if (c == Character.class) return ((Character) value).charValue(); + if (c == Boolean.class) return (Boolean) value ? 1 : 0; + if (c == Character.class) return (Character) value; String s = stringValue(value, true); return (s.length() == 0) ? 0.0 : Double.parseDouble(s); @@ -255,59 +224,50 @@ public static double doubleValue(Object value) /** * Evaluates the given object as a BigInteger. - * - * @param value - * an object to interpret as a BigInteger + * + * @param value an object to interpret as a BigInteger * @return the BigInteger value implied by the given object - * @throws NumberFormatException - * if the given object can't be understood as a BigInteger + * @throws NumberFormatException if the given object can't be understood as a BigInteger */ public static BigInteger bigIntValue(Object value) - throws NumberFormatException - { + throws NumberFormatException { if (value == null) return BigInteger.valueOf(0L); - Class c = value.getClass(); + Class c = value.getClass(); if (c == BigInteger.class) return (BigInteger) value; if (c == BigDecimal.class) return ((BigDecimal) value).toBigInteger(); if (c.getSuperclass() == Number.class) return BigInteger.valueOf(((Number) value).longValue()); - if (c == Boolean.class) return BigInteger.valueOf(((Boolean) value).booleanValue() ? 1 : 0); - if (c == Character.class) return BigInteger.valueOf(((Character) value).charValue()); + if (c == Boolean.class) return BigInteger.valueOf((Boolean) value ? 1 : 0); + if (c == Character.class) return BigInteger.valueOf((Character) value); return new BigInteger(stringValue(value, true)); } /** * Evaluates the given object as a BigDecimal. - * - * @param value - * an object to interpret as a BigDecimal + * + * @param value an object to interpret as a BigDecimal * @return the BigDecimal value implied by the given object - * @throws NumberFormatException - * if the given object can't be understood as a BigDecimal + * @throws NumberFormatException if the given object can't be understood as a BigDecimal */ public static BigDecimal bigDecValue(Object value) - throws NumberFormatException - { + throws NumberFormatException { if (value == null) return BigDecimal.valueOf(0L); - Class c = value.getClass(); + Class c = value.getClass(); if (c == BigDecimal.class) return (BigDecimal) value; if (c == BigInteger.class) return new BigDecimal((BigInteger) value); - if (c == Boolean.class) return BigDecimal.valueOf(((Boolean) value).booleanValue() ? 1 : 0); - if (c == Character.class) return BigDecimal.valueOf(((Character) value).charValue()); + if (c == Boolean.class) return BigDecimal.valueOf((Boolean) value ? 1 : 0); + if (c == Character.class) return BigDecimal.valueOf((Character) value); return new BigDecimal(stringValue(value, true)); } /** * Evaluates the given object as a String and trims it if the trim flag is true. - * - * @param value - * an object to interpret as a String - * @param trim - * true if result should be whitespace-trimmed, false otherwise. + * + * @param value an object to interpret as a String + * @param trim true if result should be whitespace-trimmed, false otherwise. * @return the String value implied by the given object as returned by the toString() method, or - * "null" if the object is null. + * "null" if the object is null. */ - public static String stringValue(Object value, boolean trim) - { + public static String stringValue(Object value, boolean trim) { String result; if (value == null) { @@ -323,29 +283,25 @@ public static String stringValue(Object value, boolean trim) /** * Evaluates the given object as a String. - * - * @param value - * an object to interpret as a String + * + * @param value an object to interpret as a String * @return the String value implied by the given object as returned by the toString() method, or - * "null" if the object is null. + * "null" if the object is null. */ - public static String stringValue(Object value) - { + public static String stringValue(Object value) { return stringValue(value, false); } /** * Returns a constant from the NumericTypes interface that represents the numeric type of the * given object. - * - * @param value - * an object that needs to be interpreted as a number + * + * @param value an object that needs to be interpreted as a number * @return the appropriate constant from the NumericTypes interface */ - public static int getNumericType(Object value) - { + public static int getNumericType(Object value) { if (value != null) { - Class c = value.getClass(); + Class c = value.getClass(); if (c == Integer.class) return INT; if (c == Double.class) return DOUBLE; if (c == Boolean.class) return BOOL; @@ -360,252 +316,209 @@ public static int getNumericType(Object value) return NONNUMERIC; } - public static Object toArray(char value, Class toType) - { + public static Object toArray(char value, Class toType) { return toArray(new Character(value), toType); } - public static Object toArray(byte value, Class toType) - { + public static Object toArray(byte value, Class toType) { return toArray(new Byte(value), toType); } - public static Object toArray(int value, Class toType) - { + public static Object toArray(int value, Class toType) { return toArray(new Integer(value), toType); } - public static Object toArray(long value, Class toType) - { + public static Object toArray(long value, Class toType) { return toArray(new Long(value), toType); } - public static Object toArray(float value, Class toType) - { + public static Object toArray(float value, Class toType) { return toArray(new Float(value), toType); } - public static Object toArray(double value, Class toType) - { + public static Object toArray(double value, Class toType) { return toArray(new Double(value), toType); } - public static Object toArray(boolean value, Class toType) - { - return toArray(new Boolean(value), toType); + public static Object toArray(boolean value, Class toType) { + return toArray(Boolean.valueOf(value), toType); } - public static Object convertValue(char value, Class toType) - { + public static Object convertValue(char value, Class toType) { return convertValue(new Character(value), toType); } - - public static Object convertValue(byte value, Class toType) - { + + public static Object convertValue(byte value, Class toType) { return convertValue(new Byte(value), toType); } - - public static Object convertValue(int value, Class toType) - { + + public static Object convertValue(int value, Class toType) { return convertValue(new Integer(value), toType); } - - public static Object convertValue(long value, Class toType) - { + + public static Object convertValue(long value, Class toType) { return convertValue(new Long(value), toType); } - - public static Object convertValue(float value, Class toType) - { + + public static Object convertValue(float value, Class toType) { return convertValue(new Float(value), toType); } - - public static Object convertValue(double value, Class toType) - { + + public static Object convertValue(double value, Class toType) { return convertValue(new Double(value), toType); } - - public static Object convertValue(boolean value, Class toType) - { - return convertValue(new Boolean(value), toType); + + public static Object convertValue(boolean value, Class toType) { + return convertValue(Boolean.valueOf(value), toType); } - - //////////////////////////////////////////////////////////////// - - public static Object convertValue(char value, Class toType, boolean preventNull) - { + + public static Object convertValue(char value, Class toType, boolean preventNull) { return convertValue(new Character(value), toType, preventNull); } - - public static Object convertValue(byte value, Class toType, boolean preventNull) - { + + public static Object convertValue(byte value, Class toType, boolean preventNull) { return convertValue(new Byte(value), toType, preventNull); } - - public static Object convertValue(int value, Class toType, boolean preventNull) - { + + public static Object convertValue(int value, Class toType, boolean preventNull) { return convertValue(new Integer(value), toType, preventNull); } - - public static Object convertValue(long value, Class toType, boolean preventNull) - { + + public static Object convertValue(long value, Class toType, boolean preventNull) { return convertValue(new Long(value), toType, preventNull); } - - public static Object convertValue(float value, Class toType, boolean preventNull) - { + + public static Object convertValue(float value, Class toType, boolean preventNull) { return convertValue(new Float(value), toType, preventNull); } - - public static Object convertValue(double value, Class toType, boolean preventNull) - { + + public static Object convertValue(double value, Class toType, boolean preventNull) { return convertValue(new Double(value), toType, preventNull); } - - public static Object convertValue(boolean value, Class toType, boolean preventNull) - { - return convertValue(new Boolean(value), toType, preventNull); - } - - ///////////////////////////////////////////////////////////////// + public static Object convertValue(boolean value, Class toType, boolean preventNull) { + return convertValue(Boolean.valueOf(value), toType, preventNull); + } - public static Object toArray(char value, Class toType, boolean preventNull) - { + public static Object toArray(char value, Class toType, boolean preventNull) { return toArray(new Character(value), toType, preventNull); } - public static Object toArray(byte value, Class toType, boolean preventNull) - { + public static Object toArray(byte value, Class toType, boolean preventNull) { return toArray(new Byte(value), toType, preventNull); } - public static Object toArray(int value, Class toType, boolean preventNull) - { + public static Object toArray(int value, Class toType, boolean preventNull) { return toArray(new Integer(value), toType, preventNull); } - public static Object toArray(long value, Class toType, boolean preventNull) - { + public static Object toArray(long value, Class toType, boolean preventNull) { return toArray(new Long(value), toType, preventNull); } - public static Object toArray(float value, Class toType, boolean preventNull) - { + public static Object toArray(float value, Class toType, boolean preventNull) { return toArray(new Float(value), toType, preventNull); } - public static Object toArray(double value, Class toType, boolean preventNull) - { + public static Object toArray(double value, Class toType, boolean preventNull) { return toArray(new Double(value), toType, preventNull); } - public static Object toArray(boolean value, Class toType, boolean preventNull) - { - return toArray(new Boolean(value), toType, preventNull); + public static Object toArray(boolean value, Class toType, boolean preventNull) { + return toArray(Boolean.valueOf(value), toType, preventNull); } - /** * Returns the value converted numerically to the given class type This method also detects when * arrays are being converted and converts the components of one array to the type of the other. - * - * @param value - * an object to be converted to the given type - * @param toType - * class type to be converted to + * + * @param value an object to be converted to the given type + * @param toType class type to be converted to * @return converted value of the type given, or value if the value cannot be converted to the - * given type. + * given type. */ - public static Object convertValue(Object value, Class toType) - { + public static Object convertValue(Object value, Class toType) { return convertValue(value, toType, false); } - public static Object toArray(Object value, Class toType) - { + public static Object toArray(Object value, Class toType) { return toArray(value, toType, false); } - - public static Object toArray(Object value, Class toType, boolean preventNulls) - { + + public static Object toArray(Object value, Class toType, boolean preventNulls) { if (value == null) return null; - - Object result = null; - + + Object result; + if (value.getClass().isArray() && toType.isAssignableFrom(value.getClass().getComponentType())) return value; if (!value.getClass().isArray()) { - + if (toType == Character.TYPE) return stringValue(value).toCharArray(); - + if (value instanceof Collection) - return ((Collection)value).toArray((Object[])Array.newInstance(toType, 0)); + return ((Collection) value).toArray((Object[]) Array.newInstance(toType, 0)); - Object arr = Array.newInstance(toType, 1); + Object arr = Array.newInstance(toType, 1); Array.set(arr, 0, convertValue(value, toType, preventNulls)); return arr; } - + result = Array.newInstance(toType, Array.getLength(value)); - for(int i = 0, icount = Array.getLength(value); i < icount; i++) { + for (int i = 0, icount = Array.getLength(value); i < icount; i++) { Array.set(result, i, convertValue(Array.get(value, i), toType)); } - - if (result == null && preventNulls) - return value; return result; } - public static Object convertValue(Object value, Class toType, boolean preventNulls) - { + public static Object convertValue(Object value, Class toType, boolean preventNulls) { Object result = null; - + if (value != null && toType.isAssignableFrom(value.getClass())) return value; - + if (value != null) { /* If array -> array then convert components of array individually */ if (value.getClass().isArray() && toType.isArray()) { - Class componentType = toType.getComponentType(); + Class componentType = toType.getComponentType(); result = Array.newInstance(componentType, Array.getLength(value)); - for(int i = 0, icount = Array.getLength(value); i < icount; i++) { + for (int i = 0, icount = Array.getLength(value); i < icount; i++) { Array.set(result, i, convertValue(Array.get(value, i), componentType)); } - } else if (value.getClass().isArray() && !toType.isArray()) { - + } else if (value.getClass().isArray()) { + return convertValue(Array.get(value, 0), toType); - } else if (!value.getClass().isArray() && toType.isArray()){ - + } else if (toType.isArray()) { + if (toType.getComponentType() == Character.TYPE) { result = stringValue(value).toCharArray(); } else if (toType.getComponentType() == Object.class) { if (value instanceof Collection) { - Collection vc = (Collection) value; + Collection vc = (Collection) value; return vc.toArray(new Object[0]); } else - return new Object[] { value }; + return new Object[]{value}; } } else { if ((toType == Integer.class) || (toType == Integer.TYPE)) { - result = new Integer((int) longValue(value)); + result = (int) longValue(value); } - if ((toType == Double.class) || (toType == Double.TYPE)) result = new Double(doubleValue(value)); + if ((toType == Double.class) || (toType == Double.TYPE)) result = doubleValue(value); if ((toType == Boolean.class) || (toType == Boolean.TYPE)) result = booleanValue(value) ? Boolean.TRUE : Boolean.FALSE; - if ((toType == Byte.class) || (toType == Byte.TYPE)) result = new Byte((byte) longValue(value)); + if ((toType == Byte.class) || (toType == Byte.TYPE)) result = (byte) longValue(value); if ((toType == Character.class) || (toType == Character.TYPE)) - result = new Character((char) longValue(value)); - if ((toType == Short.class) || (toType == Short.TYPE)) result = new Short((short) longValue(value)); - if ((toType == Long.class) || (toType == Long.TYPE)) result = new Long(longValue(value)); - if ((toType == Float.class) || (toType == Float.TYPE)) result = new Float(doubleValue(value)); + result = (char) longValue(value); + if ((toType == Short.class) || (toType == Short.TYPE)) result = (short) longValue(value); + if ((toType == Long.class) || (toType == Long.TYPE)) result = longValue(value); + if ((toType == Float.class) || (toType == Float.TYPE)) result = (float) doubleValue(value); if (toType == BigInteger.class) result = bigIntValue(value); if (toType == BigDecimal.class) result = bigDecValue(value); if (toType == String.class) result = stringValue(value); @@ -615,16 +528,16 @@ public static Object convertValue(Object value, Class toType, boolean preventNul result = OgnlRuntime.getPrimitiveDefaultValue(toType); } else if (preventNulls && toType == Boolean.class) { result = Boolean.FALSE; - } else if (preventNulls && Number.class.isAssignableFrom(toType)){ + } else if (preventNulls && Number.class.isAssignableFrom(toType)) { result = OgnlRuntime.getNumericDefaultValue(toType); } } - + if (result == null && preventNulls) return value; if (value != null && result == null) { - + throw new IllegalArgumentException("Unable to convert type " + value.getClass().getName() + " of " + value + " to type of " + toType.getName()); } @@ -640,28 +553,23 @@ public static Object convertValue(Object value, Class toType, boolean preventNul *
  • All other types result in calling Integer.parseInt(value.toString());
  • * * - * @param value - * The object to get the value of. + * @param value The object to get the value of. * @return A valid integer. */ - public static int getIntValue(Object value) - { - try - { + public static int getIntValue(Object value) { + try { if (value == null) return -1; - if (Number.class.isInstance(value)) { + if (value instanceof Number) { - return ((Number)value).intValue(); + return ((Number) value).intValue(); } - String str = String.class.isInstance(value) ? (String)value : value.toString(); - + String str = value instanceof String ? (String) value : value.toString(); + return Integer.parseInt(str); - } - catch (Throwable t) - { + } catch (Throwable t) { throw new RuntimeException("Error converting " + value + " to integer:", t); } } @@ -669,32 +577,25 @@ public static int getIntValue(Object value) /** * Returns the constant from the NumericTypes interface that best expresses the type of a * numeric operation on the two given objects. - * - * @param v1 - * one argument to a numeric operator - * @param v2 - * the other argument + * + * @param v1 one argument to a numeric operator + * @param v2 the other argument * @return the appropriate constant from the NumericTypes interface */ - public static int getNumericType(Object v1, Object v2) - { + public static int getNumericType(Object v1, Object v2) { return getNumericType(v1, v2, false); } /** * Returns the constant from the NumericTypes interface that best expresses the type of an * operation, which can be either numeric or not, on the two given types. - * - * @param t1 - * type of one argument to an operator - * @param t2 - * type of the other argument - * @param canBeNonNumeric - * whether the operator can be interpreted as non-numeric + * + * @param t1 type of one argument to an operator + * @param t2 type of the other argument + * @param canBeNonNumeric whether the operator can be interpreted as non-numeric * @return the appropriate constant from the NumericTypes interface */ - public static int getNumericType(int t1, int t2, boolean canBeNonNumeric) - { + public static int getNumericType(int t1, int t2, boolean canBeNonNumeric) { if (t1 == t2) return t1; if (canBeNonNumeric && (t1 == NONNUMERIC || t2 == NONNUMERIC || t1 == CHAR || t2 == CHAR)) return NONNUMERIC; @@ -717,17 +618,13 @@ public static int getNumericType(int t1, int t2, boolean canBeNonNumeric) /** * Returns the constant from the NumericTypes interface that best expresses the type of an * operation, which can be either numeric or not, on the two given objects. - * - * @param v1 - * one argument to an operator - * @param v2 - * the other argument - * @param canBeNonNumeric - * whether the operator can be interpreted as non-numeric + * + * @param v1 one argument to an operator + * @param v2 the other argument + * @param canBeNonNumeric whether the operator can be interpreted as non-numeric * @return the appropriate constant from the NumericTypes interface */ - public static int getNumericType(Object v1, Object v2, boolean canBeNonNumeric) - { + public static int getNumericType(Object v1, Object v2, boolean canBeNonNumeric) { return getNumericType(getNumericType(v1), getNumericType(v2), canBeNonNumeric); } @@ -735,38 +632,37 @@ public static int getNumericType(Object v1, Object v2, boolean canBeNonNumeric) * Returns a new Number object of an appropriate type to hold the given integer value. The type * of the returned object is consistent with the given type argument, which is a constant from * the NumericTypes interface. - * - * @param type - * the nominal numeric type of the result, a constant from the NumericTypes interface - * @param value - * the integer value to convert to a Number object + * + * @param type the nominal numeric type of the result, a constant from the NumericTypes interface + * @param value the integer value to convert to a Number object * @return a Number object with the given value, of type implied by the type argument */ - public static Number newInteger(int type, long value) - { - switch(type) { - case BOOL: - case CHAR: - case INT: - return new Integer((int) value); - - case FLOAT: - if ((long) (float) value == value) { return new Float((float) value); } - // else fall through: - case DOUBLE: - if ((long) (double) value == value) { return new Double((double) value); } - // else fall through: - case LONG: - return new Long(value); - - case BYTE: - return new Byte((byte) value); - - case SHORT: - return new Short((short) value); - - default: - return BigInteger.valueOf(value); + public static Number newInteger(int type, long value) { + switch (type) { + case BOOL: + case CHAR: + case INT: + return (int) value; + case FLOAT: + if ((long) (float) value == value) { + return (float) value; + } + // else fall through: + case DOUBLE: + if ((long) (double) value == value) { + return (double) value; + } + // else fall through: + case LONG: + return value; + case BYTE: + return (byte) value; + + case SHORT: + return (short) value; + + default: + return BigInteger.valueOf(value); } } @@ -774,298 +670,272 @@ public static Number newInteger(int type, long value) * Returns a new Number object of an appropriate type to hold the given real value. The type of * the returned object is always either Float or Double, and is only Float if the given type tag * (a constant from the NumericTypes interface) is FLOAT. - * - * @param type - * the nominal numeric type of the result, a constant from the NumericTypes interface - * @param value - * the real value to convert to a Number object + * + * @param type the nominal numeric type of the result, a constant from the NumericTypes interface + * @param value the real value to convert to a Number object * @return a Number object with the given value, of type implied by the type argument */ - public static Number newReal(int type, double value) - { - if (type == FLOAT) return new Float((float) value); - return new Double(value); + public static Number newReal(int type, double value) { + if (type == FLOAT) return (float) value; + return value; } - public static Object binaryOr(Object v1, Object v2) - { + public static Object binaryOr(Object v1, Object v2) { int type = getNumericType(v1, v2); if (type == BIGINT || type == BIGDEC) return bigIntValue(v1).or(bigIntValue(v2)); return newInteger(type, longValue(v1) | longValue(v2)); } - public static Object binaryXor(Object v1, Object v2) - { + public static Object binaryXor(Object v1, Object v2) { int type = getNumericType(v1, v2); if (type == BIGINT || type == BIGDEC) return bigIntValue(v1).xor(bigIntValue(v2)); return newInteger(type, longValue(v1) ^ longValue(v2)); } - public static Object binaryAnd(Object v1, Object v2) - { + public static Object binaryAnd(Object v1, Object v2) { int type = getNumericType(v1, v2); if (type == BIGINT || type == BIGDEC) return bigIntValue(v1).and(bigIntValue(v2)); return newInteger(type, longValue(v1) & longValue(v2)); } - public static boolean equal(Object v1, Object v2) - { - if (v1 == null) return v2 == null; - if (v1 == v2 || isEqual(v1, v2)) return true; - return false; + public static boolean equal(Object v1, Object v2) { + if (v1 == null) return v2 == null; + return v1 == v2 || isEqual(v1, v2); } - public static boolean less(Object v1, Object v2) - { + public static boolean less(Object v1, Object v2) { return compareWithConversion(v1, v2) < 0; } - public static boolean greater(Object v1, Object v2) - { + public static boolean greater(Object v1, Object v2) { return compareWithConversion(v1, v2) > 0; } public static boolean in(Object v1, Object v2) - throws OgnlException - { + throws OgnlException { if (v2 == null) // A null collection is always treated as empty return false; ElementsAccessor elementsAccessor = OgnlRuntime.getElementsAccessor(OgnlRuntime.getTargetClass(v2)); - - for(Enumeration e = elementsAccessor.getElements(v2); e.hasMoreElements();) { + + for (Enumeration e = elementsAccessor.getElements(v2); e.hasMoreElements(); ) { Object o = e.nextElement(); - if (equal(v1, o)) + if (equal(v1, o)) return true; } - + return false; } - public static Object shiftLeft(Object v1, Object v2) - { + public static Object shiftLeft(Object v1, Object v2) { int type = getNumericType(v1); if (type == BIGINT || type == BIGDEC) return bigIntValue(v1).shiftLeft((int) longValue(v2)); return newInteger(type, longValue(v1) << (int) longValue(v2)); } - public static Object shiftRight(Object v1, Object v2) - { + public static Object shiftRight(Object v1, Object v2) { int type = getNumericType(v1); if (type == BIGINT || type == BIGDEC) return bigIntValue(v1).shiftRight((int) longValue(v2)); return newInteger(type, longValue(v1) >> (int) longValue(v2)); } - public static Object unsignedShiftRight(Object v1, Object v2) - { + public static Object unsignedShiftRight(Object v1, Object v2) { int type = getNumericType(v1); if (type == BIGINT || type == BIGDEC) return bigIntValue(v1).shiftRight((int) longValue(v2)); if (type <= INT) return newInteger(INT, ((int) longValue(v1)) >>> (int) longValue(v2)); return newInteger(type, longValue(v1) >>> (int) longValue(v2)); } - public static Object add(Object v1, Object v2) - { + public static Object add(Object v1, Object v2) { int type = getNumericType(v1, v2, true); - switch(type) { - case BIGINT: - return bigIntValue(v1).add(bigIntValue(v2)); - case BIGDEC: - return bigDecValue(v1).add(bigDecValue(v2)); - case FLOAT: - case DOUBLE: - return newReal(type, doubleValue(v1) + doubleValue(v2)); - case NONNUMERIC: - int t1 = getNumericType(v1), - t2 = getNumericType(v2); - - if (((t1 != NONNUMERIC) && (v2 == null)) || ((t2 != NONNUMERIC) && (v1 == null))) { - throw new NullPointerException("Can't add values " + v1 + " , " + v2); - } + switch (type) { + case BIGINT: + return bigIntValue(v1).add(bigIntValue(v2)); + case BIGDEC: + return bigDecValue(v1).add(bigDecValue(v2)); + case FLOAT: + case DOUBLE: + return newReal(type, doubleValue(v1) + doubleValue(v2)); + case NONNUMERIC: + int t1 = getNumericType(v1), + t2 = getNumericType(v2); + + if (((t1 != NONNUMERIC) && (v2 == null)) || ((t2 != NONNUMERIC) && (v1 == null))) { + throw new NullPointerException("Can't add values " + v1 + " , " + v2); + } - return stringValue(v1) + stringValue(v2); - default: - return newInteger(type, longValue(v1) + longValue(v2)); + return stringValue(v1) + stringValue(v2); + default: + return newInteger(type, longValue(v1) + longValue(v2)); } } - public static Object subtract(Object v1, Object v2) - { + public static Object subtract(Object v1, Object v2) { int type = getNumericType(v1, v2); - switch(type) { - case BIGINT: - return bigIntValue(v1).subtract(bigIntValue(v2)); - case BIGDEC: - return bigDecValue(v1).subtract(bigDecValue(v2)); - case FLOAT: - case DOUBLE: - return newReal(type, doubleValue(v1) - doubleValue(v2)); - default: - return newInteger(type, longValue(v1) - longValue(v2)); + switch (type) { + case BIGINT: + return bigIntValue(v1).subtract(bigIntValue(v2)); + case BIGDEC: + return bigDecValue(v1).subtract(bigDecValue(v2)); + case FLOAT: + case DOUBLE: + return newReal(type, doubleValue(v1) - doubleValue(v2)); + default: + return newInteger(type, longValue(v1) - longValue(v2)); } } - public static Object multiply(Object v1, Object v2) - { + public static Object multiply(Object v1, Object v2) { int type = getNumericType(v1, v2); - switch(type) { - case BIGINT: - return bigIntValue(v1).multiply(bigIntValue(v2)); - case BIGDEC: - return bigDecValue(v1).multiply(bigDecValue(v2)); - case FLOAT: - case DOUBLE: - return newReal(type, doubleValue(v1) * doubleValue(v2)); - default: - return newInteger(type, longValue(v1) * longValue(v2)); + switch (type) { + case BIGINT: + return bigIntValue(v1).multiply(bigIntValue(v2)); + case BIGDEC: + return bigDecValue(v1).multiply(bigDecValue(v2)); + case FLOAT: + case DOUBLE: + return newReal(type, doubleValue(v1) * doubleValue(v2)); + default: + return newInteger(type, longValue(v1) * longValue(v2)); } } - public static Object divide(Object v1, Object v2) - { + public static Object divide(Object v1, Object v2) { int type = getNumericType(v1, v2); - switch(type) { - case BIGINT: - return bigIntValue(v1).divide(bigIntValue(v2)); - case BIGDEC: - return bigDecValue(v1).divide(bigDecValue(v2), BigDecimal.ROUND_HALF_EVEN); - case FLOAT: - case DOUBLE: - return newReal(type, doubleValue(v1) / doubleValue(v2)); - default: - return newInteger(type, longValue(v1) / longValue(v2)); + switch (type) { + case BIGINT: + return bigIntValue(v1).divide(bigIntValue(v2)); + case BIGDEC: + return bigDecValue(v1).divide(bigDecValue(v2), RoundingMode.HALF_EVEN); + case FLOAT: + case DOUBLE: + return newReal(type, doubleValue(v1) / doubleValue(v2)); + default: + return newInteger(type, longValue(v1) / longValue(v2)); } } - public static Object remainder(Object v1, Object v2) - { + public static Object remainder(Object v1, Object v2) { int type = getNumericType(v1, v2); - switch(type) { - case BIGDEC: - case BIGINT: - return bigIntValue(v1).remainder(bigIntValue(v2)); - default: - return newInteger(type, longValue(v1) % longValue(v2)); + switch (type) { + case BIGDEC: + case BIGINT: + return bigIntValue(v1).remainder(bigIntValue(v2)); + default: + return newInteger(type, longValue(v1) % longValue(v2)); } } - public static Object negate(Object value) - { + public static Object negate(Object value) { int type = getNumericType(value); - switch(type) { - case BIGINT: - return bigIntValue(value).negate(); - case BIGDEC: - return bigDecValue(value).negate(); - case FLOAT: - case DOUBLE: - return newReal(type, -doubleValue(value)); - default: - return newInteger(type, -longValue(value)); + switch (type) { + case BIGINT: + return bigIntValue(value).negate(); + case BIGDEC: + return bigDecValue(value).negate(); + case FLOAT: + case DOUBLE: + return newReal(type, -doubleValue(value)); + default: + return newInteger(type, -longValue(value)); } } - public static Object bitNegate(Object value) - { + public static Object bitNegate(Object value) { int type = getNumericType(value); - switch(type) { - case BIGDEC: - case BIGINT: - return bigIntValue(value).not(); - default: - return newInteger(type, ~longValue(value)); + switch (type) { + case BIGDEC: + case BIGINT: + return bigIntValue(value).not(); + default: + return newInteger(type, ~longValue(value)); } } - public static String getEscapeString(String value) - { - StringBuffer result = new StringBuffer(); + public static String getEscapeString(String value) { + StringBuilder result = new StringBuilder(); - for(int i = 0, icount = value.length(); i < icount; i++) { + for (int i = 0, icount = value.length(); i < icount; i++) { result.append(getEscapedChar(value.charAt(i))); } return new String(result); } - public static String getEscapedChar(char ch) - { + public static String getEscapedChar(char ch) { String result; - switch(ch) { - case '\b': - result = "\b"; - break; - case '\t': - result = "\\t"; - break; - case '\n': - result = "\\n"; - break; - case '\f': - result = "\\f"; - break; - case '\r': - result = "\\r"; - break; - case '\"': - result = "\\\""; - break; - case '\'': - result = "\\\'"; - break; - case '\\': - result = "\\\\"; - break; - default: - if (Character.isISOControl(ch)) { - - String hc = Integer.toString((int) ch, 16); - int hcl = hc.length(); - - result = "\\u"; - if (hcl < 4) { - if (hcl == 3) { - result = result + "0"; - } else { - if (hcl == 2) { - result = result + "00"; + switch (ch) { + case '\b': + result = "\b"; + break; + case '\t': + result = "\\t"; + break; + case '\n': + result = "\\n"; + break; + case '\f': + result = "\\f"; + break; + case '\r': + result = "\\r"; + break; + case '\"': + result = "\\\""; + break; + case '\'': + result = "\\\'"; + break; + case '\\': + result = "\\\\"; + break; + default: + if (Character.isISOControl(ch)) { + + String hc = Integer.toString(ch, 16); + int hcl = hc.length(); + + result = "\\u"; + if (hcl < 4) { + if (hcl == 3) { + result = result + "0"; } else { - result = result + "000"; + if (hcl == 2) { + result = result + "00"; + } else { + result = result + "000"; + } } } + + result = result + hc; + } else { + result = ch + ""; } - - result = result + hc; - } else { - result = new String(ch + ""); - } - break; + break; } return result; } - public static Object returnValue(Object ignore, Object returnValue) - { + public static Object returnValue(Object ignore, Object returnValue) { return returnValue; } /** - * Utility method that converts incoming exceptions to {@link RuntimeException} + * Utility method that converts incoming exceptions to {@link RuntimeException} * instances - or casts them if they already are. * - * @param t - * The exception to cast. + * @param t The exception to cast. * @return The exception cast to a {@link RuntimeException}. */ - public static RuntimeException castToRuntime(Throwable t) - { - if (RuntimeException.class.isInstance(t)) - return (RuntimeException)t; + public static RuntimeException castToRuntime(Throwable t) { + if (t instanceof RuntimeException) + return (RuntimeException) t; - if (OgnlException.class.isInstance(t)) + if (t instanceof OgnlException) throw new UnsupportedCompilationException("Error evluating expression: " + t.getMessage(), t); - + return new RuntimeException(t); } } diff --git a/src/main/java/ognl/OgnlParser.java b/src/main/java/ognl/OgnlParser.java deleted file mode 100644 index be165369..00000000 --- a/src/main/java/ognl/OgnlParser.java +++ /dev/null @@ -1,3293 +0,0 @@ -/* Generated By:JJTree&JavaCC: Do not edit this line. OgnlParser.java */ -package ognl; - -/** - * OgnlParser is a JavaCC parser class; it translates OGNL expressions into abstract - * syntax trees (ASTs) that can then be interpreted by the getValue and setValue methods. - */ -public class OgnlParser/*@bgen(jjtree)*/implements OgnlParserTreeConstants, OgnlParserConstants {/*@bgen(jjtree)*/ - protected JJTOgnlParserState jjtree = new JJTOgnlParserState(); - - /** - * This is the top-level construct of OGNL. - * - * @return the Node representing the top-level expression. - * @throws ParseException if the expression parsing fails. - */ - final public Node topLevelExpression() throws ParseException { - expression(); - jj_consume_token(0); - {if (true) return jjtree.rootNode();} - throw new Error("Missing return statement in function"); - } - -// sequence (level 14) - final public void expression() throws ParseException { - assignmentExpression(); - label_1: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 1: - ; - break; - default: - jj_la1[0] = jj_gen; - break label_1; - } - jj_consume_token(1); - ASTSequence jjtn001 = new ASTSequence(JJTSEQUENCE); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - assignmentExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - } - } - -// assignment expression (level 13) - final public void assignmentExpression() throws ParseException { - conditionalTestExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 2: - jj_consume_token(2); - ASTAssign jjtn001 = new ASTAssign(JJTASSIGN); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - assignmentExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - break; - default: - jj_la1[1] = jj_gen; - ; - } - } - -// conditional test (level 12) - final public void conditionalTestExpression() throws ParseException { - logicalOrExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 3: - jj_consume_token(3); - conditionalTestExpression(); - jj_consume_token(4); - ASTTest jjtn001 = new ASTTest(JJTTEST); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - conditionalTestExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 3); - } - } - break; - default: - jj_la1[2] = jj_gen; - ; - } - } - -// logical or (||) (level 11) - final public void logicalOrExpression() throws ParseException { - logicalAndExpression(); - label_2: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 5: - case 6: - ; - break; - default: - jj_la1[3] = jj_gen; - break label_2; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 5: - jj_consume_token(5); - break; - case 6: - jj_consume_token(6); - break; - default: - jj_la1[4] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTOr jjtn001 = new ASTOr(JJTOR); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - logicalAndExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - } - } - -// logical and (&&) (level 10) - final public void logicalAndExpression() throws ParseException { - inclusiveOrExpression(); - label_3: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 7: - case 8: - ; - break; - default: - jj_la1[5] = jj_gen; - break label_3; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 7: - jj_consume_token(7); - break; - case 8: - jj_consume_token(8); - break; - default: - jj_la1[6] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTAnd jjtn001 = new ASTAnd(JJTAND); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - inclusiveOrExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - } - } - -// bitwise or non-short-circuiting or (|) (level 9) - final public void inclusiveOrExpression() throws ParseException { - exclusiveOrExpression(); - label_4: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 9: - case 10: - ; - break; - default: - jj_la1[7] = jj_gen; - break label_4; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 9: - jj_consume_token(9); - break; - case 10: - jj_consume_token(10); - break; - default: - jj_la1[8] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTBitOr jjtn001 = new ASTBitOr(JJTBITOR); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - exclusiveOrExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - } - } - -// exclusive or (^) (level 8) - final public void exclusiveOrExpression() throws ParseException { - andExpression(); - label_5: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 11: - case 12: - ; - break; - default: - jj_la1[9] = jj_gen; - break label_5; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 11: - jj_consume_token(11); - break; - case 12: - jj_consume_token(12); - break; - default: - jj_la1[10] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTXor jjtn001 = new ASTXor(JJTXOR); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - andExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - } - } - -// bitwise or non-short-circuiting and (&) (level 7) - final public void andExpression() throws ParseException { - equalityExpression(); - label_6: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 13: - case 14: - ; - break; - default: - jj_la1[11] = jj_gen; - break label_6; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 13: - jj_consume_token(13); - break; - case 14: - jj_consume_token(14); - break; - default: - jj_la1[12] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTBitAnd jjtn001 = new ASTBitAnd(JJTBITAND); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - equalityExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - } - } - -// equality/inequality (==/!=) (level 6) - final public void equalityExpression() throws ParseException { - relationalExpression(); - label_7: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 15: - case 16: - case 17: - case 18: - ; - break; - default: - jj_la1[13] = jj_gen; - break label_7; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 15: - case 16: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 15: - jj_consume_token(15); - break; - case 16: - jj_consume_token(16); - break; - default: - jj_la1[14] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTEq jjtn001 = new ASTEq(JJTEQ); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - relationalExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - break; - case 17: - case 18: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 17: - jj_consume_token(17); - break; - case 18: - jj_consume_token(18); - break; - default: - jj_la1[15] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTNotEq jjtn002 = new ASTNotEq(JJTNOTEQ); - boolean jjtc002 = true; - jjtree.openNodeScope(jjtn002); - try { - relationalExpression(); - } catch (Throwable jjte002) { - if (jjtc002) { - jjtree.clearNodeScope(jjtn002); - jjtc002 = false; - } else { - jjtree.popNode(); - } - if (jjte002 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte002;} - } - if (jjte002 instanceof ParseException) { - {if (true) throw (ParseException)jjte002;} - } - {if (true) throw (Error)jjte002;} - } finally { - if (jjtc002) { - jjtree.closeNodeScope(jjtn002, 2); - } - } - break; - default: - jj_la1[16] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - } - -// boolean relational expressions (level 5) - final public void relationalExpression() throws ParseException { - shiftExpression(); - label_8: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 19: - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - case 27: - case 28: - ; - break; - default: - jj_la1[17] = jj_gen; - break label_8; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 19: - case 20: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 19: - jj_consume_token(19); - break; - case 20: - jj_consume_token(20); - break; - default: - jj_la1[18] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTLess jjtn001 = new ASTLess(JJTLESS); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - shiftExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - break; - case 21: - case 22: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 21: - jj_consume_token(21); - break; - case 22: - jj_consume_token(22); - break; - default: - jj_la1[19] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTGreater jjtn002 = new ASTGreater(JJTGREATER); - boolean jjtc002 = true; - jjtree.openNodeScope(jjtn002); - try { - shiftExpression(); - } catch (Throwable jjte002) { - if (jjtc002) { - jjtree.clearNodeScope(jjtn002); - jjtc002 = false; - } else { - jjtree.popNode(); - } - if (jjte002 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte002;} - } - if (jjte002 instanceof ParseException) { - {if (true) throw (ParseException)jjte002;} - } - {if (true) throw (Error)jjte002;} - } finally { - if (jjtc002) { - jjtree.closeNodeScope(jjtn002, 2); - } - } - break; - case 23: - case 24: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 23: - jj_consume_token(23); - break; - case 24: - jj_consume_token(24); - break; - default: - jj_la1[20] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTLessEq jjtn003 = new ASTLessEq(JJTLESSEQ); - boolean jjtc003 = true; - jjtree.openNodeScope(jjtn003); - try { - shiftExpression(); - } catch (Throwable jjte003) { - if (jjtc003) { - jjtree.clearNodeScope(jjtn003); - jjtc003 = false; - } else { - jjtree.popNode(); - } - if (jjte003 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte003;} - } - if (jjte003 instanceof ParseException) { - {if (true) throw (ParseException)jjte003;} - } - {if (true) throw (Error)jjte003;} - } finally { - if (jjtc003) { - jjtree.closeNodeScope(jjtn003, 2); - } - } - break; - case 25: - case 26: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 25: - jj_consume_token(25); - break; - case 26: - jj_consume_token(26); - break; - default: - jj_la1[21] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTGreaterEq jjtn004 = new ASTGreaterEq(JJTGREATEREQ); - boolean jjtc004 = true; - jjtree.openNodeScope(jjtn004); - try { - shiftExpression(); - } catch (Throwable jjte004) { - if (jjtc004) { - jjtree.clearNodeScope(jjtn004); - jjtc004 = false; - } else { - jjtree.popNode(); - } - if (jjte004 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte004;} - } - if (jjte004 instanceof ParseException) { - {if (true) throw (ParseException)jjte004;} - } - {if (true) throw (Error)jjte004;} - } finally { - if (jjtc004) { - jjtree.closeNodeScope(jjtn004, 2); - } - } - break; - case 27: - jj_consume_token(27); - ASTIn jjtn005 = new ASTIn(JJTIN); - boolean jjtc005 = true; - jjtree.openNodeScope(jjtn005); - try { - shiftExpression(); - } catch (Throwable jjte005) { - if (jjtc005) { - jjtree.clearNodeScope(jjtn005); - jjtc005 = false; - } else { - jjtree.popNode(); - } - if (jjte005 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte005;} - } - if (jjte005 instanceof ParseException) { - {if (true) throw (ParseException)jjte005;} - } - {if (true) throw (Error)jjte005;} - } finally { - if (jjtc005) { - jjtree.closeNodeScope(jjtn005, 2); - } - } - break; - case 28: - jj_consume_token(28); - jj_consume_token(27); - ASTNotIn jjtn006 = new ASTNotIn(JJTNOTIN); - boolean jjtc006 = true; - jjtree.openNodeScope(jjtn006); - try { - shiftExpression(); - } catch (Throwable jjte006) { - if (jjtc006) { - jjtree.clearNodeScope(jjtn006); - jjtc006 = false; - } else { - jjtree.popNode(); - } - if (jjte006 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte006;} - } - if (jjte006 instanceof ParseException) { - {if (true) throw (ParseException)jjte006;} - } - {if (true) throw (Error)jjte006;} - } finally { - if (jjtc006) { - jjtree.closeNodeScope(jjtn006, 2); - } - } - break; - default: - jj_la1[22] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - } - -// bit shift expressions (level 4) - final public void shiftExpression() throws ParseException { - additiveExpression(); - label_9: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 29: - case 30: - case 31: - case 32: - case 33: - case 34: - ; - break; - default: - jj_la1[23] = jj_gen; - break label_9; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 29: - case 30: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 29: - jj_consume_token(29); - break; - case 30: - jj_consume_token(30); - break; - default: - jj_la1[24] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTShiftLeft jjtn001 = new ASTShiftLeft(JJTSHIFTLEFT); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - additiveExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - break; - case 31: - case 32: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 31: - jj_consume_token(31); - break; - case 32: - jj_consume_token(32); - break; - default: - jj_la1[25] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTShiftRight jjtn002 = new ASTShiftRight(JJTSHIFTRIGHT); - boolean jjtc002 = true; - jjtree.openNodeScope(jjtn002); - try { - additiveExpression(); - } catch (Throwable jjte002) { - if (jjtc002) { - jjtree.clearNodeScope(jjtn002); - jjtc002 = false; - } else { - jjtree.popNode(); - } - if (jjte002 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte002;} - } - if (jjte002 instanceof ParseException) { - {if (true) throw (ParseException)jjte002;} - } - {if (true) throw (Error)jjte002;} - } finally { - if (jjtc002) { - jjtree.closeNodeScope(jjtn002, 2); - } - } - break; - case 33: - case 34: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 33: - jj_consume_token(33); - break; - case 34: - jj_consume_token(34); - break; - default: - jj_la1[26] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTUnsignedShiftRight jjtn003 = new ASTUnsignedShiftRight(JJTUNSIGNEDSHIFTRIGHT); - boolean jjtc003 = true; - jjtree.openNodeScope(jjtn003); - try { - additiveExpression(); - } catch (Throwable jjte003) { - if (jjtc003) { - jjtree.clearNodeScope(jjtn003); - jjtc003 = false; - } else { - jjtree.popNode(); - } - if (jjte003 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte003;} - } - if (jjte003 instanceof ParseException) { - {if (true) throw (ParseException)jjte003;} - } - {if (true) throw (Error)jjte003;} - } finally { - if (jjtc003) { - jjtree.closeNodeScope(jjtn003, 2); - } - } - break; - default: - jj_la1[27] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - } - -// binary addition/subtraction (level 3) - final public void additiveExpression() throws ParseException { - multiplicativeExpression(); - label_10: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 35: - case 36: - ; - break; - default: - jj_la1[28] = jj_gen; - break label_10; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 35: - jj_consume_token(35); - ASTAdd jjtn001 = new ASTAdd(JJTADD); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - multiplicativeExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - break; - case 36: - jj_consume_token(36); - ASTSubtract jjtn002 = new ASTSubtract(JJTSUBTRACT); - boolean jjtc002 = true; - jjtree.openNodeScope(jjtn002); - try { - multiplicativeExpression(); - } catch (Throwable jjte002) { - if (jjtc002) { - jjtree.clearNodeScope(jjtn002); - jjtc002 = false; - } else { - jjtree.popNode(); - } - if (jjte002 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte002;} - } - if (jjte002 instanceof ParseException) { - {if (true) throw (ParseException)jjte002;} - } - {if (true) throw (Error)jjte002;} - } finally { - if (jjtc002) { - jjtree.closeNodeScope(jjtn002, 2); - } - } - break; - default: - jj_la1[29] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - } - -// multiplication/division/remainder (level 2) - final public void multiplicativeExpression() throws ParseException { - unaryExpression(); - label_11: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 37: - case 38: - case 39: - ; - break; - default: - jj_la1[30] = jj_gen; - break label_11; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 37: - jj_consume_token(37); - ASTMultiply jjtn001 = new ASTMultiply(JJTMULTIPLY); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - unaryExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - break; - case 38: - jj_consume_token(38); - ASTDivide jjtn002 = new ASTDivide(JJTDIVIDE); - boolean jjtc002 = true; - jjtree.openNodeScope(jjtn002); - try { - unaryExpression(); - } catch (Throwable jjte002) { - if (jjtc002) { - jjtree.clearNodeScope(jjtn002); - jjtc002 = false; - } else { - jjtree.popNode(); - } - if (jjte002 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte002;} - } - if (jjte002 instanceof ParseException) { - {if (true) throw (ParseException)jjte002;} - } - {if (true) throw (Error)jjte002;} - } finally { - if (jjtc002) { - jjtree.closeNodeScope(jjtn002, 2); - } - } - break; - case 39: - jj_consume_token(39); - ASTRemainder jjtn003 = new ASTRemainder(JJTREMAINDER); - boolean jjtc003 = true; - jjtree.openNodeScope(jjtn003); - try { - unaryExpression(); - } catch (Throwable jjte003) { - if (jjtc003) { - jjtree.clearNodeScope(jjtn003); - jjtc003 = false; - } else { - jjtree.popNode(); - } - if (jjte003 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte003;} - } - if (jjte003 instanceof ParseException) { - {if (true) throw (ParseException)jjte003;} - } - {if (true) throw (Error)jjte003;} - } finally { - if (jjtc003) { - jjtree.closeNodeScope(jjtn003, 2); - } - } - break; - default: - jj_la1[31] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - } - -// unary (level 1) - final public void unaryExpression() throws ParseException { - StringBuffer sb; - Token t; - ASTInstanceof ionode; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 36: - jj_consume_token(36); - ASTNegate jjtn001 = new ASTNegate(JJTNEGATE); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - unaryExpression(); - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 1); - } - } - break; - case 35: - jj_consume_token(35); - unaryExpression(); - break; - case 40: - jj_consume_token(40); - ASTBitNegate jjtn002 = new ASTBitNegate(JJTBITNEGATE); - boolean jjtc002 = true; - jjtree.openNodeScope(jjtn002); - try { - unaryExpression(); - } catch (Throwable jjte002) { - if (jjtc002) { - jjtree.clearNodeScope(jjtn002); - jjtc002 = false; - } else { - jjtree.popNode(); - } - if (jjte002 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte002;} - } - if (jjte002 instanceof ParseException) { - {if (true) throw (ParseException)jjte002;} - } - {if (true) throw (Error)jjte002;} - } finally { - if (jjtc002) { - jjtree.closeNodeScope(jjtn002, 1); - } - } - break; - case 28: - case 41: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 41: - jj_consume_token(41); - break; - case 28: - jj_consume_token(28); - break; - default: - jj_la1[32] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTNot jjtn003 = new ASTNot(JJTNOT); - boolean jjtc003 = true; - jjtree.openNodeScope(jjtn003); - try { - unaryExpression(); - } catch (Throwable jjte003) { - if (jjtc003) { - jjtree.clearNodeScope(jjtn003); - jjtc003 = false; - } else { - jjtree.popNode(); - } - if (jjte003 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte003;} - } - if (jjte003 instanceof ParseException) { - {if (true) throw (ParseException)jjte003;} - } - {if (true) throw (Error)jjte003;} - } finally { - if (jjtc003) { - jjtree.closeNodeScope(jjtn003, 1); - } - } - break; - case 4: - case 44: - case 46: - case 47: - case 48: - case 49: - case 50: - case 51: - case 52: - case 54: - case 56: - case 57: - case IDENT: - case DYNAMIC_SUBSCRIPT: - case CHAR_LITERAL: - case BACK_CHAR_LITERAL: - case STRING_LITERAL: - case INT_LITERAL: - case FLT_LITERAL: - navigationChain(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 42: - jj_consume_token(42); - t = jj_consume_token(IDENT); - ASTInstanceof jjtn004 = new ASTInstanceof(JJTINSTANCEOF); - boolean jjtc004 = true; - jjtree.openNodeScope(jjtn004); - try { - jjtree.closeNodeScope(jjtn004, 1); - jjtc004 = false; - sb = new StringBuffer(t.image); ionode = jjtn004; - } finally { - if (jjtc004) { - jjtree.closeNodeScope(jjtn004, 1); - } - } - label_12: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 43: - ; - break; - default: - jj_la1[33] = jj_gen; - break label_12; - } - jj_consume_token(43); - t = jj_consume_token(IDENT); - sb.append('.').append( t.image ); - } - ionode.setTargetType( new String(sb) ); - break; - default: - jj_la1[34] = jj_gen; - ; - } - break; - default: - jj_la1[35] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - -// navigation chain: property references, method calls, projections, selections, etc. - final public void navigationChain() throws ParseException { - primaryExpression(); - label_13: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 43: - case 44: - case 52: - case DYNAMIC_SUBSCRIPT: - ; - break; - default: - jj_la1[36] = jj_gen; - break label_13; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 43: - jj_consume_token(43); - ASTChain jjtn001 = new ASTChain(JJTCHAIN); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case IDENT: - if (jj_2_1(2)) { - methodCall(); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case IDENT: - propertyName(); - break; - default: - jj_la1[37] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - break; - case 54: - if (jj_2_2(2)) { - projection(); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 54: - selection(); - break; - default: - jj_la1[38] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - break; - case 44: - jj_consume_token(44); - expression(); - jj_consume_token(45); - break; - default: - jj_la1[39] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 2); - } - } - break; - case 52: - case DYNAMIC_SUBSCRIPT: - ASTChain jjtn002 = new ASTChain(JJTCHAIN); - boolean jjtc002 = true; - jjtree.openNodeScope(jjtn002); - try { - index(); - } catch (Throwable jjte002) { - if (jjtc002) { - jjtree.clearNodeScope(jjtn002); - jjtc002 = false; - } else { - jjtree.popNode(); - } - if (jjte002 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte002;} - } - if (jjte002 instanceof ParseException) { - {if (true) throw (ParseException)jjte002;} - } - {if (true) throw (Error)jjte002;} - } finally { - if (jjtc002) { - jjtree.closeNodeScope(jjtn002, 2); - } - } - break; - case 44: - jj_consume_token(44); - expression(); - ASTEval jjtn003 = new ASTEval(JJTEVAL); - boolean jjtc003 = true; - jjtree.openNodeScope(jjtn003); - try { - jj_consume_token(45); - } finally { - if (jjtc003) { - jjtree.closeNodeScope(jjtn003, 2); - } - } - break; - default: - jj_la1[40] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - } - - final public void primaryExpression() throws ParseException { - Token t; - String className = null; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case CHAR_LITERAL: - case BACK_CHAR_LITERAL: - case STRING_LITERAL: - case INT_LITERAL: - case FLT_LITERAL: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case CHAR_LITERAL: - jj_consume_token(CHAR_LITERAL); - break; - case BACK_CHAR_LITERAL: - jj_consume_token(BACK_CHAR_LITERAL); - break; - case STRING_LITERAL: - jj_consume_token(STRING_LITERAL); - break; - case INT_LITERAL: - jj_consume_token(INT_LITERAL); - break; - case FLT_LITERAL: - jj_consume_token(FLT_LITERAL); - break; - default: - jj_la1[41] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - ASTConst jjtn001 = new ASTConst(JJTCONST); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - jjtree.closeNodeScope(jjtn001, 0); - jjtc001 = false; - jjtn001.setValue( token_source.literalValue ); - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 0); - } - } - break; - case 46: - jj_consume_token(46); - ASTConst jjtn002 = new ASTConst(JJTCONST); - boolean jjtc002 = true; - jjtree.openNodeScope(jjtn002); - try { - jjtree.closeNodeScope(jjtn002, 0); - jjtc002 = false; - jjtn002.setValue( Boolean.TRUE ); - } finally { - if (jjtc002) { - jjtree.closeNodeScope(jjtn002, 0); - } - } - break; - case 47: - jj_consume_token(47); - ASTConst jjtn003 = new ASTConst(JJTCONST); - boolean jjtc003 = true; - jjtree.openNodeScope(jjtn003); - try { - jjtree.closeNodeScope(jjtn003, 0); - jjtc003 = false; - jjtn003.setValue( Boolean.FALSE ); - } finally { - if (jjtc003) { - jjtree.closeNodeScope(jjtn003, 0); - } - } - break; - case 48: - ASTConst jjtn004 = new ASTConst(JJTCONST); - boolean jjtc004 = true; - jjtree.openNodeScope(jjtn004); - try { - jj_consume_token(48); - } finally { - if (jjtc004) { - jjtree.closeNodeScope(jjtn004, 0); - } - } - break; - default: - jj_la1[48] = jj_gen; - if (jj_2_4(2)) { - jj_consume_token(49); - ASTThisVarRef jjtn005 = new ASTThisVarRef(JJTTHISVARREF); - boolean jjtc005 = true; - jjtree.openNodeScope(jjtn005); - try { - jjtree.closeNodeScope(jjtn005, 0); - jjtc005 = false; - jjtn005.setName( "this" ); - } finally { - if (jjtc005) { - jjtree.closeNodeScope(jjtn005, 0); - } - } - } else if (jj_2_5(2)) { - jj_consume_token(50); - ASTRootVarRef jjtn006 = new ASTRootVarRef(JJTROOTVARREF); - boolean jjtc006 = true; - jjtree.openNodeScope(jjtn006); - try { - jjtree.closeNodeScope(jjtn006, 0); - jjtc006 = false; - jjtn006.setName( "root" ); - } finally { - if (jjtc006) { - jjtree.closeNodeScope(jjtn006, 0); - } - } - } else if (jj_2_6(2)) { - jj_consume_token(51); - t = jj_consume_token(IDENT); - ASTVarRef jjtn007 = new ASTVarRef(JJTVARREF); - boolean jjtc007 = true; - jjtree.openNodeScope(jjtn007); - try { - jjtree.closeNodeScope(jjtn007, 0); - jjtc007 = false; - jjtn007.setName( t.image ); - } finally { - if (jjtc007) { - jjtree.closeNodeScope(jjtn007, 0); - } - } - } else if (jj_2_7(2)) { - jj_consume_token(4); - jj_consume_token(52); - expression(); - jj_consume_token(53); - ASTConst jjtn008 = new ASTConst(JJTCONST); - boolean jjtc008 = true; - jjtree.openNodeScope(jjtn008); - try { - jjtree.closeNodeScope(jjtn008, 1); - jjtc008 = false; - jjtn008.setValue( jjtn008.jjtGetChild(0) ); - } finally { - if (jjtc008) { - jjtree.closeNodeScope(jjtn008, 1); - } - } - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 56: - staticReference(); - break; - default: - jj_la1[49] = jj_gen; - if (jj_2_8(2)) { - constructorCall(); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case IDENT: - if (jj_2_3(2)) { - methodCall(); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case IDENT: - propertyName(); - break; - default: - jj_la1[42] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - break; - case 52: - case DYNAMIC_SUBSCRIPT: - index(); - break; - case 44: - jj_consume_token(44); - expression(); - jj_consume_token(45); - break; - case 54: - jj_consume_token(54); - ASTList jjtn009 = new ASTList(JJTLIST); - boolean jjtc009 = true; - jjtree.openNodeScope(jjtn009); - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 4: - case 28: - case 35: - case 36: - case 40: - case 41: - case 44: - case 46: - case 47: - case 48: - case 49: - case 50: - case 51: - case 52: - case 54: - case 56: - case 57: - case IDENT: - case DYNAMIC_SUBSCRIPT: - case CHAR_LITERAL: - case BACK_CHAR_LITERAL: - case STRING_LITERAL: - case INT_LITERAL: - case FLT_LITERAL: - assignmentExpression(); - label_14: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 1: - ; - break; - default: - jj_la1[43] = jj_gen; - break label_14; - } - jj_consume_token(1); - assignmentExpression(); - } - break; - default: - jj_la1[44] = jj_gen; - ; - } - } catch (Throwable jjte009) { - if (jjtc009) { - jjtree.clearNodeScope(jjtn009); - jjtc009 = false; - } else { - jjtree.popNode(); - } - if (jjte009 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte009;} - } - if (jjte009 instanceof ParseException) { - {if (true) throw (ParseException)jjte009;} - } - {if (true) throw (Error)jjte009;} - } finally { - if (jjtc009) { - jjtree.closeNodeScope(jjtn009, true); - } - } - jj_consume_token(55); - break; - default: - jj_la1[50] = jj_gen; - if (jj_2_9(2)) { - ASTMap jjtn010 = new ASTMap(JJTMAP); - boolean jjtc010 = true; - jjtree.openNodeScope(jjtn010); - try { - jj_consume_token(51); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 56: - className = classReference(); - break; - default: - jj_la1[45] = jj_gen; - ; - } - jj_consume_token(54); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 4: - case 28: - case 35: - case 36: - case 40: - case 41: - case 44: - case 46: - case 47: - case 48: - case 49: - case 50: - case 51: - case 52: - case 54: - case 56: - case 57: - case IDENT: - case DYNAMIC_SUBSCRIPT: - case CHAR_LITERAL: - case BACK_CHAR_LITERAL: - case STRING_LITERAL: - case INT_LITERAL: - case FLT_LITERAL: - keyValueExpression(); - label_15: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 1: - ; - break; - default: - jj_la1[46] = jj_gen; - break label_15; - } - jj_consume_token(1); - keyValueExpression(); - } - break; - default: - jj_la1[47] = jj_gen; - ; - } - jjtn010.setClassName(className); - jj_consume_token(55); - } catch (Throwable jjte010) { - if (jjtc010) { - jjtree.clearNodeScope(jjtn010); - jjtc010 = false; - } else { - jjtree.popNode(); - } - if (jjte010 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte010;} - } - if (jjte010 instanceof ParseException) { - {if (true) throw (ParseException)jjte010;} - } - {if (true) throw (Error)jjte010;} - } finally { - if (jjtc010) { - jjtree.closeNodeScope(jjtn010, true); - } - } - } else { - jj_consume_token(-1); - throw new ParseException(); - } - } - } - } - } - } - } - - final public void keyValueExpression() throws ParseException { - ASTKeyValue jjtn001 = new ASTKeyValue(JJTKEYVALUE); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - assignmentExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 4: - jj_consume_token(4); - assignmentExpression(); - break; - default: - jj_la1[51] = jj_gen; - ; - } - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, true); - } - } - } - - final public void staticReference() throws ParseException { - String className = "java.lang.Math"; - Token t; - className = classReference(); - if (jj_2_10(2)) { - staticMethodCall(className); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case IDENT: - t = jj_consume_token(IDENT); - ASTStaticField jjtn001 = new ASTStaticField(JJTSTATICFIELD); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - jjtree.closeNodeScope(jjtn001, 0); - jjtc001 = false; - jjtn001.init( className, t.image ); - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, 0); - } - } - break; - default: - jj_la1[52] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - } - - final public String classReference() throws ParseException { - String result = "java.lang.Math"; - jj_consume_token(56); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case IDENT: - result = className(); - break; - default: - jj_la1[53] = jj_gen; - ; - } - jj_consume_token(56); - {if (true) return result;} - throw new Error("Missing return statement in function"); - } - - final public String className() throws ParseException { - Token t; - StringBuffer result; - t = jj_consume_token(IDENT); - result = new StringBuffer( t.image ); - label_16: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 43: - ; - break; - default: - jj_la1[54] = jj_gen; - break label_16; - } - jj_consume_token(43); - t = jj_consume_token(IDENT); - result.append('.').append( t.image ); - } - {if (true) return new String(result);} - throw new Error("Missing return statement in function"); - } - - final public void constructorCall() throws ParseException { - /*@bgen(jjtree) Ctor */ - ASTCtor jjtn000 = new ASTCtor(JJTCTOR); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);String className; - Token t; - StringBuffer sb; - try { - jj_consume_token(57); - className = className(); - if (jj_2_11(2)) { - jj_consume_token(44); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 4: - case 28: - case 35: - case 36: - case 40: - case 41: - case 44: - case 46: - case 47: - case 48: - case 49: - case 50: - case 51: - case 52: - case 54: - case 56: - case 57: - case IDENT: - case DYNAMIC_SUBSCRIPT: - case CHAR_LITERAL: - case BACK_CHAR_LITERAL: - case STRING_LITERAL: - case INT_LITERAL: - case FLT_LITERAL: - assignmentExpression(); - label_17: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 1: - ; - break; - default: - jj_la1[55] = jj_gen; - break label_17; - } - jj_consume_token(1); - assignmentExpression(); - } - break; - default: - jj_la1[56] = jj_gen; - ; - } - jj_consume_token(45); - jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; - jjtn000.setClassName(className); - } else if (jj_2_12(2)) { - jj_consume_token(52); - jj_consume_token(53); - jj_consume_token(54); - ASTList jjtn001 = new ASTList(JJTLIST); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 4: - case 28: - case 35: - case 36: - case 40: - case 41: - case 44: - case 46: - case 47: - case 48: - case 49: - case 50: - case 51: - case 52: - case 54: - case 56: - case 57: - case IDENT: - case DYNAMIC_SUBSCRIPT: - case CHAR_LITERAL: - case BACK_CHAR_LITERAL: - case STRING_LITERAL: - case INT_LITERAL: - case FLT_LITERAL: - assignmentExpression(); - label_18: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 1: - ; - break; - default: - jj_la1[57] = jj_gen; - break label_18; - } - jj_consume_token(1); - assignmentExpression(); - } - break; - default: - jj_la1[58] = jj_gen; - ; - } - } catch (Throwable jjte001) { - if (jjtc001) { - jjtree.clearNodeScope(jjtn001); - jjtc001 = false; - } else { - jjtree.popNode(); - } - if (jjte001 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte001;} - } - if (jjte001 instanceof ParseException) { - {if (true) throw (ParseException)jjte001;} - } - {if (true) throw (Error)jjte001;} - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, true); - } - } - jj_consume_token(55); - jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; - jjtn000.setClassName(className); - jjtn000.setArray(true); - } else if (jj_2_13(2)) { - jj_consume_token(52); - assignmentExpression(); - jj_consume_token(53); - jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; - jjtn000.setClassName(className); - jjtn000.setArray(true); - } else { - jj_consume_token(-1); - throw new ParseException(); - } - } catch (Throwable jjte000) { - if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte000;} - } - if (jjte000 instanceof ParseException) { - {if (true) throw (ParseException)jjte000;} - } - {if (true) throw (Error)jjte000;} - } finally { - if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - } - - final public void propertyName() throws ParseException { - /*@bgen(jjtree) Property */ - ASTProperty jjtn000 = new ASTProperty(JJTPROPERTY); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);Token t; - try { - t = jj_consume_token(IDENT); - ASTConst jjtn001 = new ASTConst(JJTCONST); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - jjtree.closeNodeScope(jjtn001, true); - jjtc001 = false; - jjtn001.setValue( t.image ); - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, true); - } - } - } finally { - if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - } - - final public void staticMethodCall(String className) throws ParseException { - /*@bgen(jjtree) StaticMethod */ - ASTStaticMethod jjtn000 = new ASTStaticMethod(JJTSTATICMETHOD); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);Token t; - try { - t = jj_consume_token(IDENT); - jj_consume_token(44); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 4: - case 28: - case 35: - case 36: - case 40: - case 41: - case 44: - case 46: - case 47: - case 48: - case 49: - case 50: - case 51: - case 52: - case 54: - case 56: - case 57: - case IDENT: - case DYNAMIC_SUBSCRIPT: - case CHAR_LITERAL: - case BACK_CHAR_LITERAL: - case STRING_LITERAL: - case INT_LITERAL: - case FLT_LITERAL: - assignmentExpression(); - label_19: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 1: - ; - break; - default: - jj_la1[59] = jj_gen; - break label_19; - } - jj_consume_token(1); - assignmentExpression(); - } - break; - default: - jj_la1[60] = jj_gen; - ; - } - jj_consume_token(45); - jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; - jjtn000.init( className, t.image ); - } catch (Throwable jjte000) { - if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte000;} - } - if (jjte000 instanceof ParseException) { - {if (true) throw (ParseException)jjte000;} - } - {if (true) throw (Error)jjte000;} - } finally { - if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - } - - final public void methodCall() throws ParseException { - /*@bgen(jjtree) Method */ - ASTMethod jjtn000 = new ASTMethod(JJTMETHOD); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000);Token t; - try { - t = jj_consume_token(IDENT); - jj_consume_token(44); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 4: - case 28: - case 35: - case 36: - case 40: - case 41: - case 44: - case 46: - case 47: - case 48: - case 49: - case 50: - case 51: - case 52: - case 54: - case 56: - case 57: - case IDENT: - case DYNAMIC_SUBSCRIPT: - case CHAR_LITERAL: - case BACK_CHAR_LITERAL: - case STRING_LITERAL: - case INT_LITERAL: - case FLT_LITERAL: - assignmentExpression(); - label_20: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 1: - ; - break; - default: - jj_la1[61] = jj_gen; - break label_20; - } - jj_consume_token(1); - assignmentExpression(); - } - break; - default: - jj_la1[62] = jj_gen; - ; - } - jj_consume_token(45); - jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; - jjtn000.setMethodName( t.image ); - } catch (Throwable jjte000) { - if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte000;} - } - if (jjte000 instanceof ParseException) { - {if (true) throw (ParseException)jjte000;} - } - {if (true) throw (Error)jjte000;} - } finally { - if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - } - - /** - * Apply an expression to all elements of a collection, creating a new collection - * as the result. - * - * @throws ParseException if the application of the projection expression fails. - */ - final public void projection() throws ParseException { - /*@bgen(jjtree) Project */ - ASTProject jjtn000 = new ASTProject(JJTPROJECT); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000); - try { - jj_consume_token(54); - expression(); - jj_consume_token(55); - } catch (Throwable jjte000) { - if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte000;} - } - if (jjte000 instanceof ParseException) { - {if (true) throw (ParseException)jjte000;} - } - {if (true) throw (Error)jjte000;} - } finally { - if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - } - - final public void selection() throws ParseException { - if (jj_2_14(2)) { - selectAll(); - } else if (jj_2_15(2)) { - selectFirst(); - } else if (jj_2_16(2)) { - selectLast(); - } else { - jj_consume_token(-1); - throw new ParseException(); - } - } - - /** - * Apply a boolean expression to all elements of a collection, creating a new collection - * containing those elements for which the expression returned true. - * - * @throws ParseException if the application of the select all expression fails. - */ - final public void selectAll() throws ParseException { - /*@bgen(jjtree) Select */ - ASTSelect jjtn000 = new ASTSelect(JJTSELECT); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000); - try { - jj_consume_token(54); - jj_consume_token(3); - expression(); - jj_consume_token(55); - } catch (Throwable jjte000) { - if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte000;} - } - if (jjte000 instanceof ParseException) { - {if (true) throw (ParseException)jjte000;} - } - {if (true) throw (Error)jjte000;} - } finally { - if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - } - - /** - * Apply a boolean expression to all elements of a collection, creating a new collection - * containing those elements for the first element for which the expression returned true. - * - * @throws ParseException if the application of the select first expression fails. - */ - final public void selectFirst() throws ParseException { - /*@bgen(jjtree) SelectFirst */ - ASTSelectFirst jjtn000 = new ASTSelectFirst(JJTSELECTFIRST); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000); - try { - jj_consume_token(54); - jj_consume_token(11); - expression(); - jj_consume_token(55); - } catch (Throwable jjte000) { - if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte000;} - } - if (jjte000 instanceof ParseException) { - {if (true) throw (ParseException)jjte000;} - } - {if (true) throw (Error)jjte000;} - } finally { - if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - } - - /** - * Apply a boolean expression to all elements of a collection, creating a new collection - * containing those elements for the last element for which the expression returned true. - * - * @throws ParseException if the application of the select last expression fails. - */ - final public void selectLast() throws ParseException { - /*@bgen(jjtree) SelectLast */ - ASTSelectLast jjtn000 = new ASTSelectLast(JJTSELECTLAST); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000); - try { - jj_consume_token(54); - jj_consume_token(58); - expression(); - jj_consume_token(55); - } catch (Throwable jjte000) { - if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte000;} - } - if (jjte000 instanceof ParseException) { - {if (true) throw (ParseException)jjte000;} - } - {if (true) throw (Error)jjte000;} - } finally { - if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - } - - final public void index() throws ParseException { - /*@bgen(jjtree) Property */ - ASTProperty jjtn000 = new ASTProperty(JJTPROPERTY); - boolean jjtc000 = true; - jjtree.openNodeScope(jjtn000); - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 52: - jj_consume_token(52); - expression(); - jj_consume_token(53); - jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; - jjtn000.setIndexedAccess(true); - break; - case DYNAMIC_SUBSCRIPT: - jj_consume_token(DYNAMIC_SUBSCRIPT); - ASTConst jjtn001 = new ASTConst(JJTCONST); - boolean jjtc001 = true; - jjtree.openNodeScope(jjtn001); - try { - jjtree.closeNodeScope(jjtn001, true); - jjtc001 = false; - jjtn001.setValue( token_source.literalValue ); - } finally { - if (jjtc001) { - jjtree.closeNodeScope(jjtn001, true); - } - } - jjtree.closeNodeScope(jjtn000, true); - jjtc000 = false; - jjtn000.setIndexedAccess(true); - break; - default: - jj_la1[63] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } catch (Throwable jjte000) { - if (jjtc000) { - jjtree.clearNodeScope(jjtn000); - jjtc000 = false; - } else { - jjtree.popNode(); - } - if (jjte000 instanceof RuntimeException) { - {if (true) throw (RuntimeException)jjte000;} - } - if (jjte000 instanceof ParseException) { - {if (true) throw (ParseException)jjte000;} - } - {if (true) throw (Error)jjte000;} - } finally { - if (jjtc000) { - jjtree.closeNodeScope(jjtn000, true); - } - } - } - - private boolean jj_2_1(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_1(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(0, xla); } - } - - private boolean jj_2_2(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_2(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(1, xla); } - } - - private boolean jj_2_3(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_3(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(2, xla); } - } - - private boolean jj_2_4(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_4(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(3, xla); } - } - - private boolean jj_2_5(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_5(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(4, xla); } - } - - private boolean jj_2_6(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_6(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(5, xla); } - } - - private boolean jj_2_7(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_7(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(6, xla); } - } - - private boolean jj_2_8(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_8(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(7, xla); } - } - - private boolean jj_2_9(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_9(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(8, xla); } - } - - private boolean jj_2_10(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_10(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(9, xla); } - } - - private boolean jj_2_11(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_11(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(10, xla); } - } - - private boolean jj_2_12(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_12(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(11, xla); } - } - - private boolean jj_2_13(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_13(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(12, xla); } - } - - private boolean jj_2_14(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_14(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(13, xla); } - } - - private boolean jj_2_15(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_15(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(14, xla); } - } - - private boolean jj_2_16(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_16(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(15, xla); } - } - - private boolean jj_3R_56() { - if (jj_scan_token(48)) return true; - return false; - } - - private boolean jj_3R_55() { - if (jj_scan_token(47)) return true; - return false; - } - - private boolean jj_3R_54() { - if (jj_scan_token(46)) return true; - return false; - } - - private boolean jj_3R_31() { - if (jj_3R_27()) return true; - return false; - } - - private boolean jj_3_13() { - if (jj_scan_token(52)) return true; - if (jj_3R_27()) return true; - return false; - } - - private boolean jj_3R_53() { - Token xsp; - xsp = jj_scanpos; - if (jj_scan_token(73)) { - jj_scanpos = xsp; - if (jj_scan_token(76)) { - jj_scanpos = xsp; - if (jj_scan_token(79)) { - jj_scanpos = xsp; - if (jj_scan_token(80)) { - jj_scanpos = xsp; - if (jj_scan_token(81)) return true; - } - } - } - } - return false; - } - - private boolean jj_3R_26() { - if (jj_3R_27()) return true; - return false; - } - - private boolean jj_3R_52() { - Token xsp; - xsp = jj_scanpos; - if (jj_3R_53()) { - jj_scanpos = xsp; - if (jj_3R_54()) { - jj_scanpos = xsp; - if (jj_3R_55()) { - jj_scanpos = xsp; - if (jj_3R_56()) { - jj_scanpos = xsp; - if (jj_3_4()) { - jj_scanpos = xsp; - if (jj_3_5()) { - jj_scanpos = xsp; - if (jj_3_6()) { - jj_scanpos = xsp; - if (jj_3_7()) { - jj_scanpos = xsp; - if (jj_3R_57()) { - jj_scanpos = xsp; - if (jj_3_8()) { - jj_scanpos = xsp; - if (jj_3R_58()) { - jj_scanpos = xsp; - if (jj_3R_59()) { - jj_scanpos = xsp; - if (jj_3R_60()) { - jj_scanpos = xsp; - if (jj_3R_61()) { - jj_scanpos = xsp; - if (jj_3_9()) return true; - } - } - } - } - } - } - } - } - } - } - } - } - } - } - return false; - } - - private boolean jj_3R_42() { - if (jj_3R_43()) return true; - return false; - } - - private boolean jj_3_12() { - if (jj_scan_token(52)) return true; - if (jj_scan_token(53)) return true; - return false; - } - - private boolean jj_3_11() { - if (jj_scan_token(44)) return true; - Token xsp; - xsp = jj_scanpos; - if (jj_3R_26()) jj_scanpos = xsp; - if (jj_scan_token(45)) return true; - return false; - } - - private boolean jj_3R_67() { - if (jj_scan_token(DYNAMIC_SUBSCRIPT)) return true; - return false; - } - - private boolean jj_3_2() { - if (jj_3R_22()) return true; - return false; - } - - private boolean jj_3R_66() { - if (jj_scan_token(52)) return true; - return false; - } - - private boolean jj_3R_64() { - Token xsp; - xsp = jj_scanpos; - if (jj_3R_66()) { - jj_scanpos = xsp; - if (jj_3R_67()) return true; - } - return false; - } - - private boolean jj_3_1() { - if (jj_3R_21()) return true; - return false; - } - - private boolean jj_3R_23() { - if (jj_scan_token(57)) return true; - if (jj_3R_32()) return true; - return false; - } - - private boolean jj_3R_41() { - if (jj_3R_42()) return true; - return false; - } - - private boolean jj_3R_30() { - if (jj_scan_token(54)) return true; - if (jj_scan_token(58)) return true; - return false; - } - - private boolean jj_3R_32() { - if (jj_scan_token(IDENT)) return true; - return false; - } - - private boolean jj_3R_51() { - if (jj_3R_52()) return true; - return false; - } - - private boolean jj_3R_29() { - if (jj_scan_token(54)) return true; - if (jj_scan_token(11)) return true; - return false; - } - - private boolean jj_3R_40() { - if (jj_3R_41()) return true; - return false; - } - - private boolean jj_3R_33() { - if (jj_scan_token(56)) return true; - return false; - } - - private boolean jj_3R_63() { - if (jj_3R_65()) return true; - return false; - } - - private boolean jj_3R_28() { - if (jj_scan_token(54)) return true; - if (jj_scan_token(3)) return true; - return false; - } - - private boolean jj_3R_50() { - if (jj_3R_51()) return true; - return false; - } - - private boolean jj_3R_39() { - if (jj_3R_40()) return true; - return false; - } - - private boolean jj_3_10() { - if (jj_3R_25()) return true; - return false; - } - - private boolean jj_3R_24() { - if (jj_3R_33()) return true; - return false; - } - - private boolean jj_3R_49() { - Token xsp; - xsp = jj_scanpos; - if (jj_scan_token(41)) { - jj_scanpos = xsp; - if (jj_scan_token(28)) return true; - } - return false; - } - - private boolean jj_3R_48() { - if (jj_scan_token(40)) return true; - return false; - } - - private boolean jj_3_16() { - if (jj_3R_30()) return true; - return false; - } - - private boolean jj_3R_47() { - if (jj_scan_token(35)) return true; - return false; - } - - private boolean jj_3_15() { - if (jj_3R_29()) return true; - return false; - } - - private boolean jj_3R_38() { - if (jj_3R_39()) return true; - return false; - } - - private boolean jj_3R_46() { - if (jj_scan_token(36)) return true; - return false; - } - - private boolean jj_3_14() { - if (jj_3R_28()) return true; - return false; - } - - private boolean jj_3R_62() { - if (jj_3R_33()) return true; - return false; - } - - private boolean jj_3R_45() { - Token xsp; - xsp = jj_scanpos; - if (jj_3R_46()) { - jj_scanpos = xsp; - if (jj_3R_47()) { - jj_scanpos = xsp; - if (jj_3R_48()) { - jj_scanpos = xsp; - if (jj_3R_49()) { - jj_scanpos = xsp; - if (jj_3R_50()) return true; - } - } - } - } - return false; - } - - private boolean jj_3R_37() { - if (jj_3R_38()) return true; - return false; - } - - private boolean jj_3R_22() { - if (jj_scan_token(54)) return true; - if (jj_3R_31()) return true; - return false; - } - - private boolean jj_3_9() { - if (jj_scan_token(51)) return true; - Token xsp; - xsp = jj_scanpos; - if (jj_3R_24()) jj_scanpos = xsp; - if (jj_scan_token(54)) return true; - return false; - } - - private boolean jj_3R_36() { - if (jj_3R_37()) return true; - return false; - } - - private boolean jj_3R_61() { - if (jj_scan_token(54)) return true; - return false; - } - - private boolean jj_3R_60() { - if (jj_scan_token(44)) return true; - return false; - } - - private boolean jj_3R_59() { - if (jj_3R_64()) return true; - return false; - } - - private boolean jj_3_3() { - if (jj_3R_21()) return true; - return false; - } - - private boolean jj_3R_21() { - if (jj_scan_token(IDENT)) return true; - if (jj_scan_token(44)) return true; - return false; - } - - private boolean jj_3R_58() { - Token xsp; - xsp = jj_scanpos; - if (jj_3_3()) { - jj_scanpos = xsp; - if (jj_3R_63()) return true; - } - return false; - } - - private boolean jj_3R_35() { - if (jj_3R_36()) return true; - return false; - } - - private boolean jj_3R_44() { - if (jj_3R_45()) return true; - return false; - } - - private boolean jj_3_8() { - if (jj_3R_23()) return true; - return false; - } - - private boolean jj_3R_57() { - if (jj_3R_62()) return true; - return false; - } - - private boolean jj_3R_34() { - if (jj_3R_35()) return true; - return false; - } - - private boolean jj_3_7() { - if (jj_scan_token(4)) return true; - if (jj_scan_token(52)) return true; - return false; - } - - private boolean jj_3R_25() { - if (jj_scan_token(IDENT)) return true; - if (jj_scan_token(44)) return true; - return false; - } - - private boolean jj_3_6() { - if (jj_scan_token(51)) return true; - if (jj_scan_token(IDENT)) return true; - return false; - } - - private boolean jj_3_5() { - if (jj_scan_token(50)) return true; - return false; - } - - private boolean jj_3R_27() { - if (jj_3R_34()) return true; - return false; - } - - private boolean jj_3_4() { - if (jj_scan_token(49)) return true; - return false; - } - - private boolean jj_3R_65() { - if (jj_scan_token(IDENT)) return true; - return false; - } - - private boolean jj_3R_43() { - if (jj_3R_44()) return true; - return false; - } - - /** Generated Token Manager. */ - public OgnlParserTokenManager token_source; - JavaCharStream jj_input_stream; - /** Current token. */ - public Token token; - /** Next token. */ - public Token jj_nt; - private int jj_ntk; - private Token jj_scanpos, jj_lastpos; - private int jj_la; - /** Whether we are looking ahead. */ - private boolean jj_lookingAhead = false; - private boolean jj_semLA; - private int jj_gen; - final private int[] jj_la1 = new int[64]; - static private int[] jj_la1_0; - static private int[] jj_la1_1; - static private int[] jj_la1_2; - static { - jj_la1_init_0(); - jj_la1_init_1(); - jj_la1_init_2(); - } - private static void jj_la1_init_0() { - jj_la1_0 = new int[] {0x2,0x4,0x8,0x60,0x60,0x180,0x180,0x600,0x600,0x1800,0x1800,0x6000,0x6000,0x78000,0x18000,0x60000,0x78000,0x1ff80000,0x180000,0x600000,0x1800000,0x6000000,0x1ff80000,0xe0000000,0x60000000,0x80000000,0x0,0xe0000000,0x0,0x0,0x0,0x0,0x10000000,0x0,0x0,0x10000010,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x2,0x10000010,0x0,0x2,0x10000010,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x2,0x10000010,0x2,0x10000010,0x2,0x10000010,0x2,0x10000010,0x0,}; - } - private static void jj_la1_init_1() { - jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0x0,0x1,0x6,0x7,0x18,0x18,0xe0,0xe0,0x200,0x800,0x400,0x35fd318,0x101800,0x0,0x400000,0x401000,0x101800,0x0,0x0,0x0,0x35fd318,0x1000000,0x0,0x35fd318,0x1c000,0x1000000,0x501000,0x0,0x0,0x0,0x800,0x0,0x35fd318,0x0,0x35fd318,0x0,0x35fd318,0x0,0x35fd318,0x100000,}; - } - private static void jj_la1_init_2() { - jj_la1_2 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x39209,0x8,0x1,0x0,0x1,0x8,0x39200,0x1,0x0,0x39209,0x0,0x0,0x39209,0x39200,0x0,0x9,0x0,0x1,0x1,0x0,0x0,0x39209,0x0,0x39209,0x0,0x39209,0x0,0x39209,0x8,}; - } - final private JJCalls[] jj_2_rtns = new JJCalls[16]; - private boolean jj_rescan = false; - private int jj_gc = 0; - - /** - * Constructor with InputStream. - * - * @param stream the InputStream to parse. - */ - public OgnlParser(java.io.InputStream stream) { - this(stream, null); - } - - /** - * Constructor with InputStream and supplied encoding - * - * @param stream the InputStream to parse. - * @param encoding the encoding to use for the stream. - */ - public OgnlParser(java.io.InputStream stream, String encoding) { - try { jj_input_stream = new JavaCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } - token_source = new OgnlParserTokenManager(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 64; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - /** - * Reinitialise. - * - * @param stream the InputStream to parse. - */ - public void ReInit(java.io.InputStream stream) { - ReInit(stream, null); - } - - /** - * Reinitialise. - * - * @param stream the InputStream to parse. - * @param encoding the encoding to use for the stream. - */ - public void ReInit(java.io.InputStream stream, String encoding) { - try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } - token_source.ReInit(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jjtree.reset(); - jj_gen = 0; - for (int i = 0; i < 64; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - /** - * Constructor. - * - * @param stream the Reader to parse. - */ - public OgnlParser(java.io.Reader stream) { - jj_input_stream = new JavaCharStream(stream, 1, 1); - token_source = new OgnlParserTokenManager(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 64; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - /** - * Reinitialise. - * - * @param stream the Reader to parse. - */ - public void ReInit(java.io.Reader stream) { - jj_input_stream.ReInit(stream, 1, 1); - token_source.ReInit(jj_input_stream); - token = new Token(); - jj_ntk = -1; - jjtree.reset(); - jj_gen = 0; - for (int i = 0; i < 64; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - /** - * Constructor with generated Token Manager. - * - * @param tm the OgnParserTokenManager to use during parsing. - */ - public OgnlParser(OgnlParserTokenManager tm) { - token_source = tm; - token = new Token(); - jj_ntk = -1; - jj_gen = 0; - for (int i = 0; i < 64; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - /** - * Reinitialise. - * - * @param tm the OgnParserTokenManager to use during parsing. - */ - public void ReInit(OgnlParserTokenManager tm) { - token_source = tm; - token = new Token(); - jj_ntk = -1; - jjtree.reset(); - jj_gen = 0; - for (int i = 0; i < 64; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); - } - - private Token jj_consume_token(int kind) throws ParseException { - Token oldToken; - if ((oldToken = token).next != null) token = token.next; - else token = token.next = token_source.getNextToken(); - jj_ntk = -1; - if (token.kind == kind) { - jj_gen++; - if (++jj_gc > 100) { - jj_gc = 0; - for (int i = 0; i < jj_2_rtns.length; i++) { - JJCalls c = jj_2_rtns[i]; - while (c != null) { - if (c.gen < jj_gen) c.first = null; - c = c.next; - } - } - } - return token; - } - token = oldToken; - jj_kind = kind; - throw generateParseException(); - } - - static private final class LookaheadSuccess extends java.lang.Error { } - final private LookaheadSuccess jj_ls = new LookaheadSuccess(); - private boolean jj_scan_token(int kind) { - if (jj_scanpos == jj_lastpos) { - jj_la--; - if (jj_scanpos.next == null) { - jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); - } else { - jj_lastpos = jj_scanpos = jj_scanpos.next; - } - } else { - jj_scanpos = jj_scanpos.next; - } - if (jj_rescan) { - int i = 0; Token tok = token; - while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } - if (tok != null) jj_add_error_token(kind, i); - } - if (jj_scanpos.kind != kind) return true; - if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; - return false; - } - - - /** - * Get the next Token. - * - * @return the next Token result from parsing. - */ - final public Token getNextToken() { - if (token.next != null) token = token.next; - else token = token.next = token_source.getNextToken(); - jj_ntk = -1; - jj_gen++; - return token; - } - - /** - * Get the specific Token. - * - * @param index specifies how far to scan ahead for the Token. - * @return the Token at the given index. - */ - final public Token getToken(int index) { - Token t = jj_lookingAhead ? jj_scanpos : token; - for (int i = 0; i < index; i++) { - if (t.next != null) t = t.next; - else t = t.next = token_source.getNextToken(); - } - return t; - } - - private int jj_ntk() { - if ((jj_nt=token.next) == null) - return (jj_ntk = (token.next=token_source.getNextToken()).kind); - else - return (jj_ntk = jj_nt.kind); - } - - private java.util.List jj_expentries = new java.util.ArrayList(); - private int[] jj_expentry; - private int jj_kind = -1; - private int[] jj_lasttokens = new int[100]; - private int jj_endpos; - - private void jj_add_error_token(int kind, int pos) { - if (pos >= 100) return; - if (pos == jj_endpos + 1) { - jj_lasttokens[jj_endpos++] = kind; - } else if (jj_endpos != 0) { - jj_expentry = new int[jj_endpos]; - for (int i = 0; i < jj_endpos; i++) { - jj_expentry[i] = jj_lasttokens[i]; - } - jj_entries_loop: for (java.util.Iterator it = jj_expentries.iterator(); it.hasNext();) { - int[] oldentry = (int[])(it.next()); - if (oldentry.length == jj_expentry.length) { - for (int i = 0; i < jj_expentry.length; i++) { - if (oldentry[i] != jj_expentry[i]) { - continue jj_entries_loop; - } - } - jj_expentries.add(jj_expentry); - break jj_entries_loop; - } - } - if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; - } - } - - /** - * Generate ParseException. - * - * @return a ParseException with information about current token parsing state. - */ - public ParseException generateParseException() { - jj_expentries.clear(); - boolean[] la1tokens = new boolean[86]; - if (jj_kind >= 0) { - la1tokens[jj_kind] = true; - jj_kind = -1; - } - for (int i = 0; i < 64; i++) { - if (jj_la1[i] == jj_gen) { - for (int j = 0; j < 32; j++) { - if ((jj_la1_0[i] & (1< jj_gen) { - jj_la = p.arg; jj_lastpos = jj_scanpos = p.first; - switch (i) { - case 0: jj_3_1(); break; - case 1: jj_3_2(); break; - case 2: jj_3_3(); break; - case 3: jj_3_4(); break; - case 4: jj_3_5(); break; - case 5: jj_3_6(); break; - case 6: jj_3_7(); break; - case 7: jj_3_8(); break; - case 8: jj_3_9(); break; - case 9: jj_3_10(); break; - case 10: jj_3_11(); break; - case 11: jj_3_12(); break; - case 12: jj_3_13(); break; - case 13: jj_3_14(); break; - case 14: jj_3_15(); break; - case 15: jj_3_16(); break; - } - } - p = p.next; - } while (p != null); - } catch(LookaheadSuccess ls) { } - } - jj_rescan = false; - } - - private void jj_save(int index, int xla) { - JJCalls p = jj_2_rtns[index]; - while (p.gen > jj_gen) { - if (p.next == null) { p = p.next = new JJCalls(); break; } - p = p.next; - } - p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; - } - - static final class JJCalls { - int gen; - Token first; - int arg; - JJCalls next; - } - -} diff --git a/src/main/java/ognl/OgnlParserConstants.java b/src/main/java/ognl/OgnlParserConstants.java deleted file mode 100644 index 992f9fa6..00000000 --- a/src/main/java/ognl/OgnlParserConstants.java +++ /dev/null @@ -1,145 +0,0 @@ -/* Generated By:JJTree&JavaCC: Do not edit this line. OgnlParserConstants.java */ -package ognl; - - -/** - * Token literal values and constants. - * Generated by org.javacc.parser.OtherFilesGen#start() - */ -public interface OgnlParserConstants { - - /** End of File. */ - int EOF = 0; - /** RegularExpression Id. */ - int IDENT = 64; - /** RegularExpression Id. */ - int LETTER = 65; - /** RegularExpression Id. */ - int DIGIT = 66; - /** RegularExpression Id. */ - int DYNAMIC_SUBSCRIPT = 67; - /** RegularExpression Id. */ - int ESC = 71; - /** RegularExpression Id. */ - int CHAR_LITERAL = 73; - /** RegularExpression Id. */ - int BACK_CHAR_ESC = 74; - /** RegularExpression Id. */ - int BACK_CHAR_LITERAL = 76; - /** RegularExpression Id. */ - int STRING_ESC = 77; - /** RegularExpression Id. */ - int STRING_LITERAL = 79; - /** RegularExpression Id. */ - int INT_LITERAL = 80; - /** RegularExpression Id. */ - int FLT_LITERAL = 81; - /** RegularExpression Id. */ - int DEC_FLT = 82; - /** RegularExpression Id. */ - int DEC_DIGITS = 83; - /** RegularExpression Id. */ - int EXPONENT = 84; - /** RegularExpression Id. */ - int FLT_SUFF = 85; - - /** Lexical state. */ - int DEFAULT = 0; - /** Lexical state. */ - int WithinCharLiteral = 1; - /** Lexical state. */ - int WithinBackCharLiteral = 2; - /** Lexical state. */ - int WithinStringLiteral = 3; - - /** Literal token values. */ - String[] tokenImage = { - "", - "\",\"", - "\"=\"", - "\"?\"", - "\":\"", - "\"||\"", - "\"or\"", - "\"&&\"", - "\"and\"", - "\"|\"", - "\"bor\"", - "\"^\"", - "\"xor\"", - "\"&\"", - "\"band\"", - "\"==\"", - "\"eq\"", - "\"!=\"", - "\"neq\"", - "\"<\"", - "\"lt\"", - "\">\"", - "\"gt\"", - "\"<=\"", - "\"lte\"", - "\">=\"", - "\"gte\"", - "\"in\"", - "\"not\"", - "\"<<\"", - "\"shl\"", - "\">>\"", - "\"shr\"", - "\">>>\"", - "\"ushr\"", - "\"+\"", - "\"-\"", - "\"*\"", - "\"/\"", - "\"%\"", - "\"~\"", - "\"!\"", - "\"instanceof\"", - "\".\"", - "\"(\"", - "\")\"", - "\"true\"", - "\"false\"", - "\"null\"", - "\"#this\"", - "\"#root\"", - "\"#\"", - "\"[\"", - "\"]\"", - "\"{\"", - "\"}\"", - "\"@\"", - "\"new\"", - "\"$\"", - "\" \"", - "\"\\t\"", - "\"\\f\"", - "\"\\r\"", - "\"\\n\"", - "", - "", - "", - "", - "\"`\"", - "\"\\\'\"", - "\"\\\"\"", - "", - "", - "\"\\\'\"", - "", - "", - "\"`\"", - "", - "", - "\"\\\"\"", - "", - "", - "", - "", - "", - "", - }; - -} diff --git a/src/main/java/ognl/OgnlParserTokenManager.java b/src/main/java/ognl/OgnlParserTokenManager.java deleted file mode 100644 index 96ae161f..00000000 --- a/src/main/java/ognl/OgnlParserTokenManager.java +++ /dev/null @@ -1,1696 +0,0 @@ -/* Generated By:JJTree&JavaCC: Do not edit this line. OgnlParserTokenManager.java */ -package ognl; - -import java.math.BigDecimal; -import java.math.BigInteger; - -/** Token Manager. */ -public class OgnlParserTokenManager implements OgnlParserConstants -{ - /** Holds the last value computed by a constant token. */ - Object literalValue; - /** Holds the last character escaped or in a character literal. */ - private char charValue; - /** Holds char literal start token. */ - private char charLiteralStartQuote; - /** Holds the last string literal parsed. */ - private StringBuffer stringBuffer; - - /** Converts an escape sequence into a character value. */ - private char escapeChar() - { - int ofs = image.length() - 1; - switch ( image.charAt(ofs) ) { - case 'n': return '\n'; - case 'r': return '\r'; - case 't': return '\t'; - case 'b': return '\b'; - case 'f': return '\f'; - case '\\': return '\\'; - case '\'': return '\''; - case '\"': return '\"'; - } - - // Otherwise, it's an octal number. Find the backslash and convert. - while ( image.charAt(--ofs) != '\\' ) - {} - int value = 0; - while ( ++ofs < image.length() ) - value = (value << 3) | (image.charAt(ofs) - '0'); - return (char) value; - } - - private Object makeInt() - { - Object result; - String s = image.toString(); - int base = 10; - - if ( s.charAt(0) == '0' ) - base = (s.length() > 1 && (s.charAt(1) == 'x' || s.charAt(1) == 'X'))? 16 : 8; - if ( base == 16 ) - s = s.substring(2); // Trim the 0x off the front - switch ( s.charAt(s.length()-1) ) { - case 'l': case 'L': - result = Long.valueOf( s.substring(0,s.length()-1), base ); - break; - - case 'h': case 'H': - result = new BigInteger( s.substring(0,s.length()-1), base ); - break; - - default: - result = Integer.valueOf( s, base ); - break; - } - return result; - } - - private Object makeFloat() - { - String s = image.toString(); - switch ( s.charAt(s.length()-1) ) { - case 'f': case 'F': - return Float.valueOf( s ); - - case 'b': case 'B': - return new BigDecimal( s.substring(0,s.length()-1) ); - - case 'd': case 'D': - default: - return Double.valueOf( s ); - } - } - - /** Debug output. */ - public java.io.PrintStream debugStream = System.out; - - /** - * Set debug output. - * - * @param ds the PrintStream to use for debugging output capture. - */ - public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } - -private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1) -{ - switch (pos) - { - case 0: - if ((active0 & 0x201c4055d555540L) != 0L) - { - jjmatchedKind = 64; - return 1; - } - if ((active0 & 0x400000000000000L) != 0L) - return 1; - if ((active0 & 0x10000000000000L) != 0L) - return 3; - if ((active0 & 0x80000000000L) != 0L) - return 9; - return -1; - case 1: - if ((active0 & 0x201c00550045500L) != 0L) - { - if (jjmatchedPos != 1) - { - jjmatchedKind = 64; - jjmatchedPos = 1; - } - return 1; - } - if ((active0 & 0x4000d510040L) != 0L) - return 1; - return -1; - case 2: - if ((active0 & 0x1c40400004000L) != 0L) - { - jjmatchedKind = 64; - jjmatchedPos = 2; - return 1; - } - if ((active0 & 0x200000155041500L) != 0L) - return 1; - return -1; - case 3: - if ((active0 & 0x1400400004000L) != 0L) - return 1; - if ((active0 & 0x840000000000L) != 0L) - { - jjmatchedKind = 64; - jjmatchedPos = 3; - return 1; - } - return -1; - case 4: - if ((active0 & 0x800000000000L) != 0L) - return 1; - if ((active0 & 0x40000000000L) != 0L) - { - jjmatchedKind = 64; - jjmatchedPos = 4; - return 1; - } - return -1; - case 5: - if ((active0 & 0x40000000000L) != 0L) - { - jjmatchedKind = 64; - jjmatchedPos = 5; - return 1; - } - return -1; - case 6: - if ((active0 & 0x40000000000L) != 0L) - { - jjmatchedKind = 64; - jjmatchedPos = 6; - return 1; - } - return -1; - case 7: - if ((active0 & 0x40000000000L) != 0L) - { - jjmatchedKind = 64; - jjmatchedPos = 7; - return 1; - } - return -1; - case 8: - if ((active0 & 0x40000000000L) != 0L) - { - jjmatchedKind = 64; - jjmatchedPos = 8; - return 1; - } - return -1; - default : - return -1; - } -} -private final int jjStartNfa_0(int pos, long active0, long active1) -{ - return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1); -} -private int jjStopAtPos(int pos, int kind) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - return pos + 1; -} -private int jjMoveStringLiteralDfa0_0() -{ - switch(curChar) - { - case 33: - jjmatchedKind = 41; - return jjMoveStringLiteralDfa1_0(0x20000L); - case 34: - return jjStopAtPos(0, 70); - case 35: - jjmatchedKind = 51; - return jjMoveStringLiteralDfa1_0(0x6000000000000L); - case 36: - return jjStartNfaWithStates_0(0, 58, 1); - case 37: - return jjStopAtPos(0, 39); - case 38: - jjmatchedKind = 13; - return jjMoveStringLiteralDfa1_0(0x80L); - case 39: - return jjStopAtPos(0, 69); - case 40: - return jjStopAtPos(0, 44); - case 41: - return jjStopAtPos(0, 45); - case 42: - return jjStopAtPos(0, 37); - case 43: - return jjStopAtPos(0, 35); - case 44: - return jjStopAtPos(0, 1); - case 45: - return jjStopAtPos(0, 36); - case 46: - return jjStartNfaWithStates_0(0, 43, 9); - case 47: - return jjStopAtPos(0, 38); - case 58: - return jjStopAtPos(0, 4); - case 60: - jjmatchedKind = 19; - return jjMoveStringLiteralDfa1_0(0x20800000L); - case 61: - jjmatchedKind = 2; - return jjMoveStringLiteralDfa1_0(0x8000L); - case 62: - jjmatchedKind = 21; - return jjMoveStringLiteralDfa1_0(0x282000000L); - case 63: - return jjStopAtPos(0, 3); - case 64: - return jjStopAtPos(0, 56); - case 91: - return jjStartNfaWithStates_0(0, 52, 3); - case 93: - return jjStopAtPos(0, 53); - case 94: - return jjStopAtPos(0, 11); - case 96: - return jjStopAtPos(0, 68); - case 97: - return jjMoveStringLiteralDfa1_0(0x100L); - case 98: - return jjMoveStringLiteralDfa1_0(0x4400L); - case 101: - return jjMoveStringLiteralDfa1_0(0x10000L); - case 102: - return jjMoveStringLiteralDfa1_0(0x800000000000L); - case 103: - return jjMoveStringLiteralDfa1_0(0x4400000L); - case 105: - return jjMoveStringLiteralDfa1_0(0x40008000000L); - case 108: - return jjMoveStringLiteralDfa1_0(0x1100000L); - case 110: - return jjMoveStringLiteralDfa1_0(0x201000010040000L); - case 111: - return jjMoveStringLiteralDfa1_0(0x40L); - case 115: - return jjMoveStringLiteralDfa1_0(0x140000000L); - case 116: - return jjMoveStringLiteralDfa1_0(0x400000000000L); - case 117: - return jjMoveStringLiteralDfa1_0(0x400000000L); - case 120: - return jjMoveStringLiteralDfa1_0(0x1000L); - case 123: - return jjStopAtPos(0, 54); - case 124: - jjmatchedKind = 9; - return jjMoveStringLiteralDfa1_0(0x20L); - case 125: - return jjStopAtPos(0, 55); - case 126: - return jjStopAtPos(0, 40); - default : - return jjMoveNfa_0(0, 0); - } -} -private int jjMoveStringLiteralDfa1_0(long active0) -{ - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(0, active0, 0L); - return 1; - } - switch(curChar) - { - case 38: - if ((active0 & 0x80L) != 0L) - return jjStopAtPos(1, 7); - break; - case 60: - if ((active0 & 0x20000000L) != 0L) - return jjStopAtPos(1, 29); - break; - case 61: - if ((active0 & 0x8000L) != 0L) - return jjStopAtPos(1, 15); - else if ((active0 & 0x20000L) != 0L) - return jjStopAtPos(1, 17); - else if ((active0 & 0x800000L) != 0L) - return jjStopAtPos(1, 23); - else if ((active0 & 0x2000000L) != 0L) - return jjStopAtPos(1, 25); - break; - case 62: - if ((active0 & 0x80000000L) != 0L) - { - jjmatchedKind = 31; - jjmatchedPos = 1; - } - return jjMoveStringLiteralDfa2_0(active0, 0x200000000L); - case 97: - return jjMoveStringLiteralDfa2_0(active0, 0x800000004000L); - case 101: - return jjMoveStringLiteralDfa2_0(active0, 0x200000000040000L); - case 104: - return jjMoveStringLiteralDfa2_0(active0, 0x140000000L); - case 110: - if ((active0 & 0x8000000L) != 0L) - { - jjmatchedKind = 27; - jjmatchedPos = 1; - } - return jjMoveStringLiteralDfa2_0(active0, 0x40000000100L); - case 111: - return jjMoveStringLiteralDfa2_0(active0, 0x10001400L); - case 113: - if ((active0 & 0x10000L) != 0L) - return jjStartNfaWithStates_0(1, 16, 1); - break; - case 114: - if ((active0 & 0x40L) != 0L) - return jjStartNfaWithStates_0(1, 6, 1); - return jjMoveStringLiteralDfa2_0(active0, 0x4400000000000L); - case 115: - return jjMoveStringLiteralDfa2_0(active0, 0x400000000L); - case 116: - if ((active0 & 0x100000L) != 0L) - { - jjmatchedKind = 20; - jjmatchedPos = 1; - } - else if ((active0 & 0x400000L) != 0L) - { - jjmatchedKind = 22; - jjmatchedPos = 1; - } - return jjMoveStringLiteralDfa2_0(active0, 0x2000005000000L); - case 117: - return jjMoveStringLiteralDfa2_0(active0, 0x1000000000000L); - case 124: - if ((active0 & 0x20L) != 0L) - return jjStopAtPos(1, 5); - break; - default : - break; - } - return jjStartNfa_0(0, active0, 0L); -} -private int jjMoveStringLiteralDfa2_0(long old0, long active0) -{ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(0, old0, 0L); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(1, active0, 0L); - return 2; - } - switch(curChar) - { - case 62: - if ((active0 & 0x200000000L) != 0L) - return jjStopAtPos(2, 33); - break; - case 100: - if ((active0 & 0x100L) != 0L) - return jjStartNfaWithStates_0(2, 8, 1); - break; - case 101: - if ((active0 & 0x1000000L) != 0L) - return jjStartNfaWithStates_0(2, 24, 1); - else if ((active0 & 0x4000000L) != 0L) - return jjStartNfaWithStates_0(2, 26, 1); - break; - case 104: - return jjMoveStringLiteralDfa3_0(active0, 0x2000400000000L); - case 108: - if ((active0 & 0x40000000L) != 0L) - return jjStartNfaWithStates_0(2, 30, 1); - return jjMoveStringLiteralDfa3_0(active0, 0x1800000000000L); - case 110: - return jjMoveStringLiteralDfa3_0(active0, 0x4000L); - case 111: - return jjMoveStringLiteralDfa3_0(active0, 0x4000000000000L); - case 113: - if ((active0 & 0x40000L) != 0L) - return jjStartNfaWithStates_0(2, 18, 1); - break; - case 114: - if ((active0 & 0x400L) != 0L) - return jjStartNfaWithStates_0(2, 10, 1); - else if ((active0 & 0x1000L) != 0L) - return jjStartNfaWithStates_0(2, 12, 1); - else if ((active0 & 0x100000000L) != 0L) - return jjStartNfaWithStates_0(2, 32, 1); - break; - case 115: - return jjMoveStringLiteralDfa3_0(active0, 0x40000000000L); - case 116: - if ((active0 & 0x10000000L) != 0L) - return jjStartNfaWithStates_0(2, 28, 1); - break; - case 117: - return jjMoveStringLiteralDfa3_0(active0, 0x400000000000L); - case 119: - if ((active0 & 0x200000000000000L) != 0L) - return jjStartNfaWithStates_0(2, 57, 1); - break; - default : - break; - } - return jjStartNfa_0(1, active0, 0L); -} -private int jjMoveStringLiteralDfa3_0(long old0, long active0) -{ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(1, old0, 0L); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(2, active0, 0L); - return 3; - } - switch(curChar) - { - case 100: - if ((active0 & 0x4000L) != 0L) - return jjStartNfaWithStates_0(3, 14, 1); - break; - case 101: - if ((active0 & 0x400000000000L) != 0L) - return jjStartNfaWithStates_0(3, 46, 1); - break; - case 105: - return jjMoveStringLiteralDfa4_0(active0, 0x2000000000000L); - case 108: - if ((active0 & 0x1000000000000L) != 0L) - return jjStartNfaWithStates_0(3, 48, 1); - break; - case 111: - return jjMoveStringLiteralDfa4_0(active0, 0x4000000000000L); - case 114: - if ((active0 & 0x400000000L) != 0L) - return jjStartNfaWithStates_0(3, 34, 1); - break; - case 115: - return jjMoveStringLiteralDfa4_0(active0, 0x800000000000L); - case 116: - return jjMoveStringLiteralDfa4_0(active0, 0x40000000000L); - default : - break; - } - return jjStartNfa_0(2, active0, 0L); -} -private int jjMoveStringLiteralDfa4_0(long old0, long active0) -{ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(2, old0, 0L); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(3, active0, 0L); - return 4; - } - switch(curChar) - { - case 97: - return jjMoveStringLiteralDfa5_0(active0, 0x40000000000L); - case 101: - if ((active0 & 0x800000000000L) != 0L) - return jjStartNfaWithStates_0(4, 47, 1); - break; - case 115: - if ((active0 & 0x2000000000000L) != 0L) - return jjStopAtPos(4, 49); - break; - case 116: - if ((active0 & 0x4000000000000L) != 0L) - return jjStopAtPos(4, 50); - break; - default : - break; - } - return jjStartNfa_0(3, active0, 0L); -} -private int jjMoveStringLiteralDfa5_0(long old0, long active0) -{ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(3, old0, 0L); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(4, active0, 0L); - return 5; - } - switch(curChar) - { - case 110: - return jjMoveStringLiteralDfa6_0(active0, 0x40000000000L); - default : - break; - } - return jjStartNfa_0(4, active0, 0L); -} -private int jjMoveStringLiteralDfa6_0(long old0, long active0) -{ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(4, old0, 0L); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(5, active0, 0L); - return 6; - } - switch(curChar) - { - case 99: - return jjMoveStringLiteralDfa7_0(active0, 0x40000000000L); - default : - break; - } - return jjStartNfa_0(5, active0, 0L); -} -private int jjMoveStringLiteralDfa7_0(long old0, long active0) -{ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(5, old0, 0L); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(6, active0, 0L); - return 7; - } - switch(curChar) - { - case 101: - return jjMoveStringLiteralDfa8_0(active0, 0x40000000000L); - default : - break; - } - return jjStartNfa_0(6, active0, 0L); -} -private int jjMoveStringLiteralDfa8_0(long old0, long active0) -{ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(6, old0, 0L); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(7, active0, 0L); - return 8; - } - switch(curChar) - { - case 111: - return jjMoveStringLiteralDfa9_0(active0, 0x40000000000L); - default : - break; - } - return jjStartNfa_0(7, active0, 0L); -} -private int jjMoveStringLiteralDfa9_0(long old0, long active0) -{ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(7, old0, 0L); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(8, active0, 0L); - return 9; - } - switch(curChar) - { - case 102: - if ((active0 & 0x40000000000L) != 0L) - return jjStartNfaWithStates_0(9, 42, 1); - break; - default : - break; - } - return jjStartNfa_0(8, active0, 0L); -} -private int jjStartNfaWithStates_0(int pos, int kind, int state) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return pos + 1; } - return jjMoveNfa_0(state, pos + 1); -} -static final long[] jjbitVec0 = { - 0x1ff00000fffffffeL, 0xffffffffffffc000L, 0xffffffffL, 0x600000000000000L -}; -static final long[] jjbitVec2 = { - 0x0L, 0x0L, 0x0L, 0xff7fffffff7fffffL -}; -static final long[] jjbitVec3 = { - 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL -}; -static final long[] jjbitVec4 = { - 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffL, 0x0L -}; -static final long[] jjbitVec5 = { - 0xffffffffffffffffL, 0xffffffffffffffffL, 0x0L, 0x0L -}; -static final long[] jjbitVec6 = { - 0x3fffffffffffL, 0x0L, 0x0L, 0x0L -}; -private int jjMoveNfa_0(int startState, int curPos) -{ - //int[] nextStates; // not used - int startsAt = 0; - jjnewStateCnt = 27; - int i = 1; - jjstateSet[0] = startState; - //int j; // not used - int kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddStates(0, 5); - else if (curChar == 46) - jjCheckNAdd(9); - else if (curChar == 36) - { - if (kind > 64) - kind = 64; - jjCheckNAdd(1); - } - if ((0x3fe000000000000L & l) != 0L) - { - if (kind > 80) - kind = 80; - jjCheckNAddTwoStates(6, 7); - } - else if (curChar == 48) - { - if (kind > 80) - kind = 80; - jjCheckNAddStates(6, 8); - } - break; - case 1: - if ((0x3ff001000000000L & l) == 0L) - break; - if (kind > 64) - kind = 64; - jjCheckNAdd(1); - break; - case 3: - if ((0x41000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 4; - break; - case 5: - if ((0x3fe000000000000L & l) == 0L) - break; - if (kind > 80) - kind = 80; - jjCheckNAddTwoStates(6, 7); - break; - case 6: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 80) - kind = 80; - jjCheckNAddTwoStates(6, 7); - break; - case 8: - if (curChar == 46) - jjCheckNAdd(9); - break; - case 9: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 81) - kind = 81; - jjCheckNAddStates(9, 11); - break; - case 11: - if ((0x280000000000L & l) != 0L) - jjCheckNAdd(12); - break; - case 12: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 81) - kind = 81; - jjCheckNAddTwoStates(12, 13); - break; - case 14: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddStates(0, 5); - break; - case 15: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddTwoStates(15, 16); - break; - case 16: - if (curChar != 46) - break; - if (kind > 81) - kind = 81; - jjCheckNAddStates(12, 14); - break; - case 17: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 81) - kind = 81; - jjCheckNAddStates(12, 14); - break; - case 18: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddTwoStates(18, 19); - break; - case 20: - if ((0x280000000000L & l) != 0L) - jjCheckNAdd(21); - break; - case 21: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 81) - kind = 81; - jjCheckNAddTwoStates(21, 13); - break; - case 22: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddTwoStates(22, 13); - break; - case 23: - if (curChar != 48) - break; - if (kind > 80) - kind = 80; - jjCheckNAddStates(6, 8); - break; - case 24: - if ((0xff000000000000L & l) == 0L) - break; - if (kind > 80) - kind = 80; - jjCheckNAddTwoStates(24, 7); - break; - case 26: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 80) - kind = 80; - jjCheckNAddTwoStates(26, 7); - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 64) - kind = 64; - jjCheckNAdd(1); - } - else if (curChar == 91) - jjstateSet[jjnewStateCnt++] = 3; - break; - case 1: - if ((0x7fffffe87fffffeL & l) == 0L) - break; - if (kind > 64) - kind = 64; - jjCheckNAdd(1); - break; - case 2: - if (curChar == 91) - jjstateSet[jjnewStateCnt++] = 3; - break; - case 3: - if ((0x1000000040000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 4; - break; - case 4: - if (curChar == 93) - kind = 67; - break; - case 7: - if ((0x110000001100L & l) != 0L && kind > 80) - kind = 80; - break; - case 10: - if ((0x2000000020L & l) != 0L) - jjAddStates(15, 16); - break; - case 13: - if ((0x5400000054L & l) != 0L && kind > 81) - kind = 81; - break; - case 19: - if ((0x2000000020L & l) != 0L) - jjAddStates(17, 18); - break; - case 25: - if ((0x100000001000000L & l) != 0L) - jjCheckNAdd(26); - break; - case 26: - if ((0x7e0000007eL & l) == 0L) - break; - if (kind > 80) - kind = 80; - jjCheckNAddTwoStates(26, 7); - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - case 1: - if (!jjCanMove_0(hiByte, i1, i2, l1, l2)) - break; - if (kind > 64) - kind = 64; - jjCheckNAdd(1); - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 27 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjStopStringLiteralDfa_2(int pos, long active0, long active1) -{ - switch (pos) - { - default : - return -1; - } -} -private final int jjStartNfa_2(int pos, long active0, long active1) -{ - return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0, active1), pos + 1); -} -private int jjMoveStringLiteralDfa0_2() -{ - switch(curChar) - { - case 96: - return jjStopAtPos(0, 76); - default : - return jjMoveNfa_2(0, 0); - } -} -static final long[] jjbitVec7 = { - 0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL -}; -static final long[] jjbitVec8 = { - 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL -}; -private int jjMoveNfa_2(int startState, int curPos) -{ - //int[] nextStates; // not used - int startsAt = 0; - jjnewStateCnt = 6; - int i = 1; - jjstateSet[0] = startState; - //int j; // not used - int kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - do - { - switch(jjstateSet[--i]) - { - case 0: - if (kind > 75) - kind = 75; - break; - case 1: - if ((0x8400000000L & l) != 0L && kind > 74) - kind = 74; - break; - case 2: - if ((0xf000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 3; - break; - case 3: - if ((0xff000000000000L & l) == 0L) - break; - if (kind > 74) - kind = 74; - jjstateSet[jjnewStateCnt++] = 4; - break; - case 4: - if ((0xff000000000000L & l) != 0L && kind > 74) - kind = 74; - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xfffffffeefffffffL & l) != 0L) - { - if (kind > 75) - kind = 75; - } - else if (curChar == 92) - jjAddStates(19, 21); - break; - case 1: - if ((0x14404510000000L & l) != 0L && kind > 74) - kind = 74; - break; - case 5: - if ((0xfffffffeefffffffL & l) != 0L && kind > 75) - kind = 75; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if (jjCanMove_1(hiByte, i1, i2, l1, l2) && kind > 75) - kind = 75; - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 6 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjStopStringLiteralDfa_1(int pos, long active0, long active1) -{ - switch (pos) - { - default : - return -1; - } -} -private final int jjStartNfa_1(int pos, long active0, long active1) -{ - return jjMoveNfa_1(jjStopStringLiteralDfa_1(pos, active0, active1), pos + 1); -} -private int jjMoveStringLiteralDfa0_1() -{ - switch(curChar) - { - case 39: - return jjStopAtPos(0, 73); - default : - return jjMoveNfa_1(0, 0); - } -} -private int jjMoveNfa_1(int startState, int curPos) -{ - //int[] nextStates; // not used - int startsAt = 0; - jjnewStateCnt = 6; - int i = 1; - jjstateSet[0] = startState; - //int j; // not used - int kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xffffff7fffffffffL & l) != 0L && kind > 72) - kind = 72; - break; - case 1: - if ((0x8400000000L & l) != 0L && kind > 71) - kind = 71; - break; - case 2: - if ((0xf000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 3; - break; - case 3: - if ((0xff000000000000L & l) == 0L) - break; - if (kind > 71) - kind = 71; - jjstateSet[jjnewStateCnt++] = 4; - break; - case 4: - if ((0xff000000000000L & l) != 0L && kind > 71) - kind = 71; - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xffffffffefffffffL & l) != 0L) - { - if (kind > 72) - kind = 72; - } - else if (curChar == 92) - jjAddStates(19, 21); - break; - case 1: - if ((0x14404510000000L & l) != 0L && kind > 71) - kind = 71; - break; - case 5: - if ((0xffffffffefffffffL & l) != 0L && kind > 72) - kind = 72; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if (jjCanMove_1(hiByte, i1, i2, l1, l2) && kind > 72) - kind = 72; - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 6 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjStopStringLiteralDfa_3(int pos, long active0, long active1) -{ - switch (pos) - { - default : - return -1; - } -} -private final int jjStartNfa_3(int pos, long active0, long active1) -{ - return jjMoveNfa_3(jjStopStringLiteralDfa_3(pos, active0, active1), pos + 1); -} -private int jjMoveStringLiteralDfa0_3() -{ - switch(curChar) - { - case 34: - return jjStopAtPos(0, 79); - default : - return jjMoveNfa_3(0, 0); - } -} -private int jjMoveNfa_3(int startState, int curPos) -{ - //int[] nextStates; // not used - int startsAt = 0; - jjnewStateCnt = 6; - int i = 1; - jjstateSet[0] = startState; - //int j; // not used - int kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xfffffffbffffffffL & l) != 0L && kind > 78) - kind = 78; - break; - case 1: - if ((0x8400000000L & l) != 0L && kind > 77) - kind = 77; - break; - case 2: - if ((0xf000000000000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 3; - break; - case 3: - if ((0xff000000000000L & l) == 0L) - break; - if (kind > 77) - kind = 77; - jjstateSet[jjnewStateCnt++] = 4; - break; - case 4: - if ((0xff000000000000L & l) != 0L && kind > 77) - kind = 77; - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xffffffffefffffffL & l) != 0L) - { - if (kind > 78) - kind = 78; - } - else if (curChar == 92) - jjAddStates(19, 21); - break; - case 1: - if ((0x14404510000000L & l) != 0L && kind > 77) - kind = 77; - break; - case 5: - if ((0xffffffffefffffffL & l) != 0L && kind > 78) - kind = 78; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int hiByte = (int)(curChar >> 8); - int i1 = hiByte >> 6; - long l1 = 1L << (hiByte & 077); - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if (jjCanMove_1(hiByte, i1, i2, l1, l2) && kind > 78) - kind = 78; - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 6 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -static final int[] jjnextStates = { - 15, 16, 18, 19, 22, 13, 24, 25, 7, 9, 10, 13, 17, 10, 13, 11, - 12, 20, 21, 1, 2, 3, -}; -private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) -{ - switch(hiByte) - { - case 0: - return ((jjbitVec2[i2] & l2) != 0L); - case 48: - return ((jjbitVec3[i2] & l2) != 0L); - case 49: - return ((jjbitVec4[i2] & l2) != 0L); - case 51: - return ((jjbitVec5[i2] & l2) != 0L); - case 61: - return ((jjbitVec6[i2] & l2) != 0L); - default : - if ((jjbitVec0[i1] & l1) != 0L) - return true; - return false; - } -} -private static final boolean jjCanMove_1(int hiByte, int i1, int i2, long l1, long l2) -{ - switch(hiByte) - { - case 0: - return ((jjbitVec8[i2] & l2) != 0L); - default : - if ((jjbitVec7[i1] & l1) != 0L) - return true; - return false; - } -} - -/** Token literal values. */ -public static final String[] jjstrLiteralImages = { -"", "\54", "\75", "\77", "\72", "\174\174", "\157\162", "\46\46", -"\141\156\144", "\174", "\142\157\162", "\136", "\170\157\162", "\46", "\142\141\156\144", -"\75\75", "\145\161", "\41\75", "\156\145\161", "\74", "\154\164", "\76", "\147\164", -"\74\75", "\154\164\145", "\76\75", "\147\164\145", "\151\156", "\156\157\164", -"\74\74", "\163\150\154", "\76\76", "\163\150\162", "\76\76\76", "\165\163\150\162", -"\53", "\55", "\52", "\57", "\45", "\176", "\41", -"\151\156\163\164\141\156\143\145\157\146", "\56", "\50", "\51", "\164\162\165\145", "\146\141\154\163\145", -"\156\165\154\154", "\43\164\150\151\163", "\43\162\157\157\164", "\43", "\133", "\135", "\173", -"\175", "\100", "\156\145\167", "\44", null, null, null, null, null, null, null, null, -null, null, null, null, null, null, null, null, null, null, null, null, null, null, -null, null, null, null, null, }; - -/** Lexer state names. */ -public static final String[] lexStateNames = { - "DEFAULT", - "WithinCharLiteral", - "WithinBackCharLiteral", - "WithinStringLiteral", -}; - -/** Lex State array. */ -public static final int[] jjnewLexState = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 1, 3, -1, -1, 0, -1, - -1, 0, -1, -1, 0, -1, -1, -1, -1, -1, -1, -}; -static final long[] jjtoToken = { - 0x7ffffffffffffffL, 0x39209L, -}; -static final long[] jjtoSkip = { - 0xf800000000000000L, 0x0L, -}; -static final long[] jjtoMore = { - 0x0L, 0x6df0L, -}; -protected JavaCharStream input_stream; -private final int[] jjrounds = new int[27]; -private final int[] jjstateSet = new int[54]; -private final StringBuffer image = new StringBuffer(); -private int jjimageLen; -private int lengthOfMatch; -protected char curChar; - -/** - * Constructor. - * - * @param stream the JavaCharStream to parse. - */ -public OgnlParserTokenManager(JavaCharStream stream){ - if (JavaCharStream.staticFlag) - throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); - input_stream = stream; -} - -/** - * Constructor. - * - * @param stream the JavaCharStream to parse. - * @param lexState the lexical state to use for the OgnlParserTokenManager instance. - */ -public OgnlParserTokenManager(JavaCharStream stream, int lexState){ - this(stream); - SwitchTo(lexState); -} - -/** - * Reinitialise parser. - * - * @param stream the JavaCharStream to parse. - */ -public void ReInit(JavaCharStream stream) -{ - jjmatchedPos = jjnewStateCnt = 0; - curLexState = defaultLexState; - input_stream = stream; - ReInitRounds(); -} -private void ReInitRounds() -{ - int i; - jjround = 0x80000001; - for (i = 27; i-- > 0;) - jjrounds[i] = 0x80000000; -} - -/** - * Reinitialise parser. - * - * @param stream the JavaCharStream to parse. - * @param lexState the lexical state to use for the OgnlParserTokenManager instance. - */ -public void ReInit(JavaCharStream stream, int lexState) -{ - ReInit(stream); - SwitchTo(lexState); -} - -/** - * Switch to specified lex state. - * - * @param lexState the lexical state (0 to 3) to use for the OgnlParserTokenManager instance. - * @throws TokenMgrError (an unchecked Error exception) if the lexical state is invalid. - */ -public void SwitchTo(int lexState) -{ - if (lexState >= 4 || lexState < 0) - throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); - else - curLexState = lexState; -} - -protected Token jjFillToken() -{ - final Token t; - final String tokenImage; - final int beginLine; - final int endLine; - final int beginColumn; - final int endColumn; - String im = jjstrLiteralImages[jjmatchedKind]; - tokenImage = (im == null) ? input_stream.GetImage() : im; - beginLine = input_stream.getBeginLine(); - beginColumn = input_stream.getBeginColumn(); - endLine = input_stream.getEndLine(); - endColumn = input_stream.getEndColumn(); - t = Token.newToken(jjmatchedKind, tokenImage); - - t.beginLine = beginLine; - t.endLine = endLine; - t.beginColumn = beginColumn; - t.endColumn = endColumn; - - return t; -} - -int curLexState = 0; -int defaultLexState = 0; -int jjnewStateCnt; -int jjround; -int jjmatchedPos; -int jjmatchedKind; - -/** - * Get the next Token. - * - * @return the next Token parsed from the stream. - */ -public Token getNextToken() -{ - Token matchedToken; - int curPos = 0; - - EOFLoop : - for (;;) - { - try - { - curChar = input_stream.BeginToken(); - } - catch(java.io.IOException e) - { - jjmatchedKind = 0; - matchedToken = jjFillToken(); - return matchedToken; - } - image.setLength(0); - jjimageLen = 0; - - for (;;) - { - switch(curLexState) - { - case 0: - try { input_stream.backup(0); - while (curChar <= 32 && (0x100003600L & (1L << curChar)) != 0L) - curChar = input_stream.BeginToken(); - } - catch (java.io.IOException e1) { continue EOFLoop; } - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_0(); - break; - case 1: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_1(); - break; - case 2: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_2(); - break; - case 3: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_3(); - break; - } - if (jjmatchedKind != 0x7fffffff) - { - if (jjmatchedPos + 1 < curPos) - input_stream.backup(curPos - jjmatchedPos - 1); - if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) - { - matchedToken = jjFillToken(); - TokenLexicalActions(matchedToken); - if (jjnewLexState[jjmatchedKind] != -1) - curLexState = jjnewLexState[jjmatchedKind]; - return matchedToken; - } - else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) - { - if (jjnewLexState[jjmatchedKind] != -1) - curLexState = jjnewLexState[jjmatchedKind]; - continue EOFLoop; - } - MoreLexicalActions(); - if (jjnewLexState[jjmatchedKind] != -1) - curLexState = jjnewLexState[jjmatchedKind]; - curPos = 0; - jjmatchedKind = 0x7fffffff; - try { - curChar = input_stream.readChar(); - continue; - } - catch (java.io.IOException e1) { } - } - int error_line = input_stream.getEndLine(); - int error_column = input_stream.getEndColumn(); - String error_after = null; - boolean EOFSeen = false; - try { input_stream.readChar(); input_stream.backup(1); } - catch (java.io.IOException e1) { - EOFSeen = true; - error_after = curPos <= 1 ? "" : input_stream.GetImage(); - if (curChar == '\n' || curChar == '\r') { - error_line++; - error_column = 0; - } - else - error_column++; - } - if (!EOFSeen) { - input_stream.backup(1); - error_after = curPos <= 1 ? "" : input_stream.GetImage(); - } - throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); - } - } -} - -void MoreLexicalActions() -{ - jjimageLen += (lengthOfMatch = jjmatchedPos + 1); - switch(jjmatchedKind) - { - case 69 : - image.append(input_stream.GetSuffix(jjimageLen)); - jjimageLen = 0; - stringBuffer = new StringBuffer(); - break; - case 70 : - image.append(input_stream.GetSuffix(jjimageLen)); - jjimageLen = 0; - stringBuffer = new StringBuffer(); - break; - case 71 : - image.append(input_stream.GetSuffix(jjimageLen)); - jjimageLen = 0; - charValue = escapeChar(); stringBuffer.append(charValue); - break; - case 72 : - image.append(input_stream.GetSuffix(jjimageLen)); - jjimageLen = 0; - charValue = image.charAt( image.length()-1 ); stringBuffer.append(charValue); - break; - case 74 : - image.append(input_stream.GetSuffix(jjimageLen)); - jjimageLen = 0; - charValue = escapeChar(); - break; - case 75 : - image.append(input_stream.GetSuffix(jjimageLen)); - jjimageLen = 0; - charValue = image.charAt( image.length()-1 ); - break; - case 77 : - image.append(input_stream.GetSuffix(jjimageLen)); - jjimageLen = 0; - stringBuffer.append( escapeChar() ); - break; - case 78 : - image.append(input_stream.GetSuffix(jjimageLen)); - jjimageLen = 0; - stringBuffer.append( image.charAt(image.length()-1) ); - break; - default : - break; - } -} -void TokenLexicalActions(Token matchedToken) -{ - switch(jjmatchedKind) - { - case 67 : - image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); - switch (image.charAt(1)) { - case '^': literalValue = DynamicSubscript.first; break; - case '|': literalValue = DynamicSubscript.mid; break; - case '$': literalValue = DynamicSubscript.last; break; - case '*': literalValue = DynamicSubscript.all; break; - } - break; - case 73 : - image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); - if (stringBuffer.length() == 1) { - literalValue = new Character( charValue ); - } else { - literalValue = new String( stringBuffer ); - } - break; - case 76 : - image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); - literalValue = new Character( charValue ); - break; - case 79 : - image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); - literalValue = new String( stringBuffer ); - break; - case 80 : - image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); - literalValue = - makeInt(); - break; - case 81 : - image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); - literalValue = makeFloat(); - break; - default : - break; - } -} -private void jjCheckNAdd(int state) -{ - if (jjrounds[state] != jjround) - { - jjstateSet[jjnewStateCnt++] = state; - jjrounds[state] = jjround; - } -} -private void jjAddStates(int start, int end) -{ - do { - jjstateSet[jjnewStateCnt++] = jjnextStates[start]; - } while (start++ != end); -} -private void jjCheckNAddTwoStates(int state1, int state2) -{ - jjCheckNAdd(state1); - jjCheckNAdd(state2); -} - -private void jjCheckNAddStates(int start, int end) -{ - do { - jjCheckNAdd(jjnextStates[start]); - } while (start++ != end); -} - -} diff --git a/src/main/java/ognl/OgnlParserTreeConstants.java b/src/main/java/ognl/OgnlParserTreeConstants.java index f01affce..db194724 100644 --- a/src/main/java/ognl/OgnlParserTreeConstants.java +++ b/src/main/java/ognl/OgnlParserTreeConstants.java @@ -1,105 +1,104 @@ /* Generated By:JavaCC: Do not edit this line. OgnlParserTreeConstants.java Version 4.1d1 */ package ognl; -public interface OgnlParserTreeConstants -{ - public int JJTVOID = 0; - public int JJTSEQUENCE = 1; - public int JJTASSIGN = 2; - public int JJTTEST = 3; - public int JJTOR = 4; - public int JJTAND = 5; - public int JJTBITOR = 6; - public int JJTXOR = 7; - public int JJTBITAND = 8; - public int JJTEQ = 9; - public int JJTNOTEQ = 10; - public int JJTLESS = 11; - public int JJTGREATER = 12; - public int JJTLESSEQ = 13; - public int JJTGREATEREQ = 14; - public int JJTIN = 15; - public int JJTNOTIN = 16; - public int JJTSHIFTLEFT = 17; - public int JJTSHIFTRIGHT = 18; - public int JJTUNSIGNEDSHIFTRIGHT = 19; - public int JJTADD = 20; - public int JJTSUBTRACT = 21; - public int JJTMULTIPLY = 22; - public int JJTDIVIDE = 23; - public int JJTREMAINDER = 24; - public int JJTNEGATE = 25; - public int JJTBITNEGATE = 26; - public int JJTNOT = 27; - public int JJTINSTANCEOF = 28; - public int JJTCHAIN = 29; - public int JJTEVAL = 30; - public int JJTCONST = 31; - public int JJTTHISVARREF = 32; - public int JJTROOTVARREF = 33; - public int JJTVARREF = 34; - public int JJTLIST = 35; - public int JJTMAP = 36; - public int JJTKEYVALUE = 37; - public int JJTSTATICFIELD = 38; - public int JJTCTOR = 39; - public int JJTPROPERTY = 40; - public int JJTSTATICMETHOD = 41; - public int JJTMETHOD = 42; - public int JJTPROJECT = 43; - public int JJTSELECT = 44; - public int JJTSELECTFIRST = 45; - public int JJTSELECTLAST = 46; +public interface OgnlParserTreeConstants { + public int JJTVOID = 0; + public int JJTSEQUENCE = 1; + public int JJTASSIGN = 2; + public int JJTTEST = 3; + public int JJTOR = 4; + public int JJTAND = 5; + public int JJTBITOR = 6; + public int JJTXOR = 7; + public int JJTBITAND = 8; + public int JJTEQ = 9; + public int JJTNOTEQ = 10; + public int JJTLESS = 11; + public int JJTGREATER = 12; + public int JJTLESSEQ = 13; + public int JJTGREATEREQ = 14; + public int JJTIN = 15; + public int JJTNOTIN = 16; + public int JJTSHIFTLEFT = 17; + public int JJTSHIFTRIGHT = 18; + public int JJTUNSIGNEDSHIFTRIGHT = 19; + public int JJTADD = 20; + public int JJTSUBTRACT = 21; + public int JJTMULTIPLY = 22; + public int JJTDIVIDE = 23; + public int JJTREMAINDER = 24; + public int JJTNEGATE = 25; + public int JJTBITNEGATE = 26; + public int JJTNOT = 27; + public int JJTINSTANCEOF = 28; + public int JJTCHAIN = 29; + public int JJTEVAL = 30; + public int JJTCONST = 31; + public int JJTTHISVARREF = 32; + public int JJTROOTVARREF = 33; + public int JJTVARREF = 34; + public int JJTLIST = 35; + public int JJTMAP = 36; + public int JJTKEYVALUE = 37; + public int JJTSTATICFIELD = 38; + public int JJTCTOR = 39; + public int JJTPROPERTY = 40; + public int JJTSTATICMETHOD = 41; + public int JJTMETHOD = 42; + public int JJTPROJECT = 43; + public int JJTSELECT = 44; + public int JJTSELECTFIRST = 45; + public int JJTSELECTLAST = 46; - public String[] jjtNodeName = { - "void", - "Sequence", - "Assign", - "Test", - "Or", - "And", - "BitOr", - "Xor", - "BitAnd", - "Eq", - "NotEq", - "Less", - "Greater", - "LessEq", - "GreaterEq", - "In", - "NotIn", - "ShiftLeft", - "ShiftRight", - "UnsignedShiftRight", - "Add", - "Subtract", - "Multiply", - "Divide", - "Remainder", - "Negate", - "BitNegate", - "Not", - "Instanceof", - "Chain", - "Eval", - "Const", - "ThisVarRef", - "RootVarRef", - "VarRef", - "List", - "Map", - "KeyValue", - "StaticField", - "Ctor", - "Property", - "StaticMethod", - "Method", - "Project", - "Select", - "SelectFirst", - "SelectLast", - }; + public String[] jjtNodeName = { + "void", + "Sequence", + "Assign", + "Test", + "Or", + "And", + "BitOr", + "Xor", + "BitAnd", + "Eq", + "NotEq", + "Less", + "Greater", + "LessEq", + "GreaterEq", + "In", + "NotIn", + "ShiftLeft", + "ShiftRight", + "UnsignedShiftRight", + "Add", + "Subtract", + "Multiply", + "Divide", + "Remainder", + "Negate", + "BitNegate", + "Not", + "Instanceof", + "Chain", + "Eval", + "Const", + "ThisVarRef", + "RootVarRef", + "VarRef", + "List", + "Map", + "KeyValue", + "StaticField", + "Ctor", + "Property", + "StaticMethod", + "Method", + "Project", + "Select", + "SelectFirst", + "SelectLast", + }; } /* JavaCC - OriginalChecksum=effe3edc2df093c4b217c61a43612af5 (do not edit this line) */ diff --git a/src/main/java/ognl/OgnlRuntime.java b/src/main/java/ognl/OgnlRuntime.java index f349f237..4d1f3cb6 100644 --- a/src/main/java/ognl/OgnlRuntime.java +++ b/src/main/java/ognl/OgnlRuntime.java @@ -1,48 +1,64 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionCompiler; import ognl.enhance.OgnlExpressionCompiler; -import ognl.internal.ClassCache; -import ognl.internal.ClassCacheImpl; +import ognl.internal.CacheException; +import ognl.internal.entry.DeclaredMethodCacheEntry; +import ognl.internal.entry.GenericMethodParameterTypeCacheEntry; +import ognl.internal.entry.PermissionCacheEntry; import ognl.security.OgnlSecurityManagerFactory; import ognl.security.UserMethod; -import java.beans.*; -import java.lang.reflect.*; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.security.*; -import java.util.*; +import java.beans.BeanInfo; +import java.beans.IndexedPropertyDescriptor; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.MethodDescriptor; +import java.beans.PropertyDescriptor; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Proxy; +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.Permission; +import java.security.Permissions; +import java.security.PrivilegedActionException; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** @@ -54,9 +70,6 @@ *
  • Core runtime configuration point for setting/using global {@link TypeConverter} / {@link OgnlExpressionCompiler} / * {@link NullHandler} instances / etc..
  • * - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ public class OgnlRuntime { @@ -65,10 +78,7 @@ public class OgnlRuntime { * during reflection operations. */ public static final Object NotFound = new Object(); - public static final List NotFoundList = new ArrayList(); - public static final Map NotFoundMap = new HashMap(); public static final Object[] NoArguments = new Object[]{}; - public static final Class[] NoArgumentTypes = new Class[]{}; /** * Token returned by TypeConverter for no conversion possible @@ -96,20 +106,22 @@ public class OgnlRuntime { /** * Java beans standard set method prefix. */ - private static final String SET_PREFIX = "set"; + public static final String SET_PREFIX = "set"; + /** * Java beans standard get method prefix. */ - private static final String GET_PREFIX = "get"; + public static final String GET_PREFIX = "get"; + /** - * Java beans standard is boolean getter prefix. + * Java beans standard {@code is} boolean getter prefix. */ - private static final String IS_PREFIX = "is"; + public static final String IS_PREFIX = "is"; /** * Prefix padding for hexadecimal numbers to HEX_LENGTH. */ - private static final Map HEX_PADDING = new HashMap(); + private static final Map HEX_PADDING = new HashMap<>(); private static final int HEX_LENGTH = 8; @@ -118,53 +130,48 @@ public class OgnlRuntime { */ private static final String NULL_OBJECT_STRING = ""; - /** - * Used to store the result of determining if current jvm is 1.5 language compatible. - */ - private static boolean _jdk15 = false; - private static boolean _jdkChecked = false; - /** * Control usage of JDK9+ access handler using the JVM option: - * -Dognl.UseJDK9PlusAccessHandler=true - * -Dognl.UseJDK9PlusAccessHandler=false - * + * -Dognl.UseJDK9PlusAccessHandler=true + * -Dognl.UseJDK9PlusAccessHandler=false + *

    * Note: Set to "true" to allow the new JDK9 and later behaviour, provided a newer JDK9+ - * is detected. By default the standard pre-JDK9 AccessHandler will be used even when - * running on JDK9+, so users must "opt-in" in order to enable the alternate JDK9+ AccessHandler. - * Using the JDK9PlusAccessHandler may avoid / mask JDK9+ warnings of the form: - * "WARNING: Illegal reflective access by ognl.OgnlRuntime" - * or provide an alternative when running in environments set with "--illegal-access=deny". - * + * is detected. By default the standard pre-JDK9 AccessHandler will be used even when + * running on JDK9+, so users must "opt-in" in order to enable the alternate JDK9+ AccessHandler. + * Using the JDK9PlusAccessHandler may avoid / mask JDK9+ warnings of the form: + * "WARNING: Illegal reflective access by ognl.OgnlRuntime" + * or provide an alternative when running in environments set with "--illegal-access=deny". + *

    * Note: The default behaviour is to use the standard pre-JDK9 access handler. - * Using the "false" value has the same effect as omitting the option completely. - * + * Using the "false" value has the same effect as omitting the option completely. + *

    * Warning: Users are strongly advised to review their code and confirm they really - * need the AccessHandler modifying access levels, looking at alternatives to avoid that need. + * need the AccessHandler modifying access levels, looking at alternatives to avoid that need. */ - static final String USE_JDK9PLUS_ACESS_HANDLER = "ognl.UseJDK9PlusAccessHandler"; + static final String USE_JDK9PLUS_ACCESS_HANDLER = "ognl.UseJDK9PlusAccessHandler"; /** * Control usage of "stricter" invocation processing by invokeMethod() using the JVM options: - * -Dognl.UseStricterInvocation=true - * -Dognl.UseStricterInvocation=false - * + * -Dognl.UseStricterInvocation=true + * -Dognl.UseStricterInvocation=false + *

    * Note: Using the "true" value has the same effect as omitting the option completely. - * The default behaviour is to use the "stricter" invocation processing. - * Using the "false" value reverts to the older "less strict" invocation processing - * (in the event the "stricter" processing causes issues for existing applications). + * The default behaviour is to use the "stricter" invocation processing. + * Using the "false" value reverts to the older "less strict" invocation processing + * (in the event the "stricter" processing causes issues for existing applications). */ static final String USE_STRICTER_INVOCATION = "ognl.UseStricterInvocation"; /** * Hold environment flag state associated with USE_JDK9PLUS_ACESS_HANDLER. - * Default: false (if not set) + * Default: false (if not set) */ private static final boolean _useJDK9PlusAccessHandler; + static { boolean initialFlagState = false; try { - final String propertyString = System.getProperty(USE_JDK9PLUS_ACESS_HANDLER); + final String propertyString = System.getProperty(USE_JDK9PLUS_ACCESS_HANDLER); if (propertyString != null && propertyString.length() > 0) { initialFlagState = Boolean.parseBoolean(propertyString); } @@ -176,9 +183,10 @@ public class OgnlRuntime { /** * Hold environment flag state associated with USE_STRICTER_INVOCATION. - * Default: true (if not set) + * Default: true (if not set) */ private static final boolean _useStricterInvocation; + static { boolean initialFlagState = true; try { @@ -200,15 +208,16 @@ public class OgnlRuntime { /* * Assign an accessibility modification mechanism, based on Major Java Version and Java option flag - * flag {@link OgnlRuntime#USE_JDK9PLUS_ACESS_HANDLER}. + * flag {@link OgnlRuntime#USE_JDK9PLUS_ACCESS_HANDLER}. * * Note: Will use the standard Pre-JDK9 accessibility modification mechanism unless OGNL is running * on JDK9+ and the Java option flag has also been set true. */ private static final AccessibleObjectHandler _accessibleObjectHandler; + static { _accessibleObjectHandler = usingJDK9PlusAccessHandler() ? AccessibleObjectHandlerJDK9Plus.createHandler() : - AccessibleObjectHandlerPreJDK9.createHandler(); + AccessibleObjectHandlerPreJDK9.createHandler(); } /** @@ -219,7 +228,7 @@ public class OgnlRuntime { private static final Method AO_SETACCESSIBLE_REF; private static final Method AO_SETACCESSIBLE_ARR_REF; - /** + /* * Initialize the Method references used for blocking usage within invokeMethod(). */ static { @@ -228,7 +237,7 @@ public class OgnlRuntime { Method systemExitMethod = null; Method systemConsoleMethod = null; try { - setAccessibleMethod = AccessibleObject.class.getMethod("setAccessible", new Class[]{boolean.class}); + setAccessibleMethod = AccessibleObject.class.getMethod("setAccessible", boolean.class); } catch (NoSuchMethodException nsme) { // Should not happen. To debug, uncomment the next line. //throw new IllegalStateException("OgnlRuntime initialization missing setAccessible method", nsme); @@ -240,7 +249,7 @@ public class OgnlRuntime { } try { - setAccessibleMethodArray = AccessibleObject.class.getMethod("setAccessible", new Class[]{AccessibleObject[].class, boolean.class}); + setAccessibleMethodArray = AccessibleObject.class.getMethod("setAccessible", AccessibleObject[].class, boolean.class); } catch (NoSuchMethodException nsme) { // Should not happen. To debug, uncomment the next line. //throw new IllegalStateException("OgnlRuntime initialization missing setAccessible method", nsme); @@ -252,7 +261,7 @@ public class OgnlRuntime { } try { - systemExitMethod = System.class.getMethod("exit", new Class[]{int.class}); + systemExitMethod = System.class.getMethod("exit", int.class); } catch (NoSuchMethodException nsme) { // Should not happen. To debug, uncomment the next line. //throw new IllegalStateException("OgnlRuntime initialization missing exit method", nsme); @@ -264,7 +273,7 @@ public class OgnlRuntime { } try { - systemConsoleMethod = System.class.getMethod("console", new Class[]{}); // Not available in JDK 1.5 or earlier + systemConsoleMethod = System.class.getMethod("console"); // Not available in JDK 1.5 or earlier } catch (NoSuchMethodException nsme) { // May happen for JDK 1.5 and earlier. To debug, uncomment the next line. //throw new IllegalStateException("OgnlRuntime initialization missing console method", nsme); @@ -278,16 +287,16 @@ public class OgnlRuntime { /** * Control usage of the OGNL Security Manager using the JVM option: - * -Dognl.security.manager=true (or any non-null value other than 'disable') - * + * -Dognl.security.manager=true (or any non-null value other than 'disable') + *

    * Omit '-Dognl.security.manager=' or nullify the property to disable the feature. - * + *

    * To forcibly disable the feature (only possible at OGNL Library initialization, use the option: - * -Dognl.security.manager=forceDisableOnInit - * + * -Dognl.security.manager=forceDisableOnInit + *

    * Users that have their own Security Manager implementations and no intention to use the OGNL SecurityManager - * sandbox may choose to use the 'forceDisableOnInit' flag option for performance reasons (avoiding overhead - * involving the system property security checks - when that feature will not be used). + * sandbox may choose to use the 'forceDisableOnInit' flag option for performance reasons (avoiding overhead + * involving the system property security checks - when that feature will not be used). */ static final String OGNL_SECURITY_MANAGER = "ognl.security.manager"; static final String OGNL_SM_FORCE_DISABLE_ON_INIT = "forceDisableOnInit"; @@ -295,9 +304,10 @@ public class OgnlRuntime { /** * Hold environment flag state associated with OGNL_SECURITY_MANAGER. See * {@link OgnlRuntime#OGNL_SECURITY_MANAGER} for more details. - * Default: false (if not set). + * Default: false (if not set). */ private static final boolean _disableOgnlSecurityManagerOnInit; + static { boolean initialFlagState = false; try { @@ -313,21 +323,22 @@ public class OgnlRuntime { /** * Allow users to revert to the old "first match" lookup for getters/setters by OGNL using the JVM options: - * -Dognl.UseFirstMatchGetSetLookup=true - * -Dognl.UseFirstMatchGetSetLookup=false - * + * -Dognl.UseFirstMatchGetSetLookup=true + * -Dognl.UseFirstMatchGetSetLookup=false + *

    * Note: Using the "false" value has the same effect as omitting the option completely. - * The default behaviour is to use the "best match" lookup for getters/setters. - * Using the "true" value reverts to the older "first match" lookup for getters/setters - * (in the event the "best match" processing causes issues for existing applications). + * The default behaviour is to use the "best match" lookup for getters/setters. + * Using the "true" value reverts to the older "first match" lookup for getters/setters + * (in the event the "best match" processing causes issues for existing applications). */ static final String USE_FIRSTMATCH_GETSET_LOOKUP = "ognl.UseFirstMatchGetSetLookup"; /** * Hold environment flag state associated with USE_FIRSTMATCH_GETSET_LOOKUP. - * Default: false (if not set) + * Default: false (if not set) */ private static final boolean _useFirstMatchGetSetLookup; + static { boolean initialFlagState = false; try { @@ -341,151 +352,64 @@ public class OgnlRuntime { _useFirstMatchGetSetLookup = initialFlagState; } - static final ClassCache _methodAccessors = new ClassCacheImpl(); - static final ClassCache _propertyAccessors = new ClassCacheImpl(); - static final ClassCache _elementsAccessors = new ClassCacheImpl(); - static final ClassCache _nullHandlers = new ClassCacheImpl(); - - static final ClassCache _propertyDescriptorCache = new ClassCacheImpl(); - static final ClassCache _constructorCache = new ClassCacheImpl(); - static final ClassCache _staticMethodCache = new ClassCacheImpl(); - static final ClassCache _instanceMethodCache = new ClassCacheImpl(); - static final ClassCache _invokePermissionCache = new ClassCacheImpl(); - static final ClassCache _fieldCache = new ClassCacheImpl(); - static final List _superclasses = new ArrayList(); /* Used by fieldCache lookup */ - static final ClassCache[] _declaredMethods = new ClassCache[]{new ClassCacheImpl(), new ClassCacheImpl()}; - - static final Map _primitiveTypes = new HashMap(101); - static final ClassCache _primitiveDefaults = new ClassCacheImpl(); - static final Map _methodParameterTypesCache = new HashMap(101); - static final Map _genericMethodParameterTypesCache = new HashMap(101); - static final Map _ctorParameterTypesCache = new HashMap(101); - static SecurityManager _securityManager = System.getSecurityManager(); + static final OgnlCache cache = new OgnlCache(); + + private static final PrimitiveTypes primitiveTypes = new PrimitiveTypes(); + private static final PrimitiveDefaults primitiveDefaults = new PrimitiveDefaults(); + + static SecurityManager securityManager = System.getSecurityManager(); static final EvaluationPool _evaluationPool = new EvaluationPool(); - static final ObjectArrayPool _objectArrayPool = new ObjectArrayPool(); - static final Map _methodAccessCache = new ConcurrentHashMap(); - static final Map _methodPermCache = new ConcurrentHashMap(); + static final Map _methodAccessCache = new ConcurrentHashMap<>(); + static final Map _methodPermCache = new ConcurrentHashMap<>(); static final ClassPropertyMethodCache cacheSetMethod = new ClassPropertyMethodCache(); static final ClassPropertyMethodCache cacheGetMethod = new ClassPropertyMethodCache(); - static ClassCacheInspector _cacheInspector; - /** * Expression compiler used by {@link Ognl#compileExpression(OgnlContext, Object, String)} calls. */ private static OgnlExpressionCompiler _compiler; /** - * Lazy loading of Javassist library - */ - static { - try { - Class.forName("javassist.ClassPool"); - _compiler = new ExpressionCompiler(); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("Javassist library is missing in classpath! Please add missed dependency!",e); - } catch (RuntimeException rt) { - throw new IllegalStateException("Javassist library cannot be loaded, is it restricted by runtime environment?"); - } - } - - private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; - - private static IdentityHashMap PRIMITIVE_WRAPPER_CLASSES = new IdentityHashMap(); - - /** - * Used to provide primitive type equivalent conversions into and out of - * native / object types. + * Used to provide primitive type equivalent conversions into and out of native / object types. */ - static { - PRIMITIVE_WRAPPER_CLASSES.put(Boolean.TYPE, Boolean.class); - PRIMITIVE_WRAPPER_CLASSES.put(Boolean.class, Boolean.TYPE); - PRIMITIVE_WRAPPER_CLASSES.put(Byte.TYPE, Byte.class); - PRIMITIVE_WRAPPER_CLASSES.put(Byte.class, Byte.TYPE); - PRIMITIVE_WRAPPER_CLASSES.put(Character.TYPE, Character.class); - PRIMITIVE_WRAPPER_CLASSES.put(Character.class, Character.TYPE); - PRIMITIVE_WRAPPER_CLASSES.put(Short.TYPE, Short.class); - PRIMITIVE_WRAPPER_CLASSES.put(Short.class, Short.TYPE); - PRIMITIVE_WRAPPER_CLASSES.put(Integer.TYPE, Integer.class); - PRIMITIVE_WRAPPER_CLASSES.put(Integer.class, Integer.TYPE); - PRIMITIVE_WRAPPER_CLASSES.put(Long.TYPE, Long.class); - PRIMITIVE_WRAPPER_CLASSES.put(Long.class, Long.TYPE); - PRIMITIVE_WRAPPER_CLASSES.put(Float.TYPE, Float.class); - PRIMITIVE_WRAPPER_CLASSES.put(Float.class, Float.TYPE); - PRIMITIVE_WRAPPER_CLASSES.put(Double.TYPE, Double.class); - PRIMITIVE_WRAPPER_CLASSES.put(Double.class, Double.TYPE); - } - - private static final Map NUMERIC_CASTS = new HashMap(); + private static final PrimitiveWrapperClasses primitiveWrapperClasses = new PrimitiveWrapperClasses(); /** * Constant strings for casting different primitive types. */ - static { - NUMERIC_CASTS.put(Double.class, "(double)"); - NUMERIC_CASTS.put(Float.class, "(float)"); - NUMERIC_CASTS.put(Integer.class, "(int)"); - NUMERIC_CASTS.put(Long.class, "(long)"); - NUMERIC_CASTS.put(BigDecimal.class, "(double)"); - NUMERIC_CASTS.put(BigInteger.class, ""); - } - - private static final Map NUMERIC_VALUES = new HashMap(); + private static final NumericCasts numericCasts = new NumericCasts(); /** - * Constant strings for getting the primitive value of different - * native types on the generic {@link Number} object interface. (or the less - * generic BigDecimal/BigInteger types) + * Constant strings for getting the primitive value of different native types on the generic {@link Number} object + * interface. (or the less generic BigDecimal/BigInteger types) */ - static { - NUMERIC_VALUES.put(Double.class, "doubleValue()"); - NUMERIC_VALUES.put(Float.class, "floatValue()"); - NUMERIC_VALUES.put(Integer.class, "intValue()"); - NUMERIC_VALUES.put(Long.class, "longValue()"); - NUMERIC_VALUES.put(Short.class, "shortValue()"); - NUMERIC_VALUES.put(Byte.class, "byteValue()"); - NUMERIC_VALUES.put(BigDecimal.class, "doubleValue()"); - NUMERIC_VALUES.put(BigInteger.class, "doubleValue()"); - NUMERIC_VALUES.put(Boolean.class, "booleanValue()"); - } - - private static final Map NUMERIC_LITERALS = new HashMap(); + private static final NumericValues numericValues = new NumericValues(); /** * Numeric primitive literal string expressions. */ - static { - NUMERIC_LITERALS.put(Integer.class, ""); - NUMERIC_LITERALS.put(Integer.TYPE, ""); - NUMERIC_LITERALS.put(Long.class, "l"); - NUMERIC_LITERALS.put(Long.TYPE, "l"); - NUMERIC_LITERALS.put(BigInteger.class, "d"); - NUMERIC_LITERALS.put(Float.class, "f"); - NUMERIC_LITERALS.put(Float.TYPE, "f"); - NUMERIC_LITERALS.put(Double.class, "d"); - NUMERIC_LITERALS.put(Double.TYPE, "d"); - NUMERIC_LITERALS.put(BigInteger.class, "d"); - NUMERIC_LITERALS.put(BigDecimal.class, "d"); - } + private static final NumericLiterals numericLiterals = new NumericLiterals(); - private static final Map NUMERIC_DEFAULTS = new HashMap(); + private static final NumericDefaults numericDefaults = new NumericDefaults(); + /* + * Lazy loading of Javassist library + */ static { - NUMERIC_DEFAULTS.put(Boolean.class, Boolean.FALSE); - NUMERIC_DEFAULTS.put(Byte.class, new Byte((byte) 0)); - NUMERIC_DEFAULTS.put(Short.class, new Short((short) 0)); - NUMERIC_DEFAULTS.put(Character.class, new Character((char) 0)); - NUMERIC_DEFAULTS.put(Integer.class, new Integer(0)); - NUMERIC_DEFAULTS.put(Long.class, new Long(0L)); - NUMERIC_DEFAULTS.put(Float.class, new Float(0.0f)); - NUMERIC_DEFAULTS.put(Double.class, new Double(0.0)); - - NUMERIC_DEFAULTS.put(BigInteger.class, new BigInteger("0")); - NUMERIC_DEFAULTS.put(BigDecimal.class, new BigDecimal(0.0)); + try { + Class.forName("javassist.ClassPool"); + _compiler = new ExpressionCompiler(); + } catch (ClassNotFoundException e) { + throw new IllegalArgumentException("Javassist library is missing in classpath! Please add missed dependency!", e); + } catch (RuntimeException rt) { + throw new IllegalStateException("Javassist library cannot be loaded, is it restricted by runtime environment?"); + } } + private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; + static { PropertyAccessor p = new ArrayPropertyAccessor(); @@ -544,30 +468,6 @@ public class OgnlRuntime { setMethodAccessor(float[].class, ma); setMethodAccessor(double[].class, ma); setMethodAccessor(Object[].class, ma); - - _primitiveTypes.put("boolean", Boolean.TYPE); - _primitiveTypes.put("byte", Byte.TYPE); - _primitiveTypes.put("short", Short.TYPE); - _primitiveTypes.put("char", Character.TYPE); - _primitiveTypes.put("int", Integer.TYPE); - _primitiveTypes.put("long", Long.TYPE); - _primitiveTypes.put("float", Float.TYPE); - _primitiveTypes.put("double", Double.TYPE); - - _primitiveDefaults.put(Boolean.TYPE, Boolean.FALSE); - _primitiveDefaults.put(Boolean.class, Boolean.FALSE); - _primitiveDefaults.put(Byte.TYPE, new Byte((byte) 0)); - _primitiveDefaults.put(Byte.class, new Byte((byte) 0)); - _primitiveDefaults.put(Short.TYPE, new Short((short) 0)); - _primitiveDefaults.put(Short.class, new Short((short) 0)); - _primitiveDefaults.put(Character.TYPE, new Character((char) 0)); - _primitiveDefaults.put(Integer.TYPE, new Integer(0)); - _primitiveDefaults.put(Long.TYPE, new Long(0L)); - _primitiveDefaults.put(Float.TYPE, new Float(0.0f)); - _primitiveDefaults.put(Double.TYPE, new Double(0.0)); - - _primitiveDefaults.put(BigInteger.class, new BigInteger("0")); - _primitiveDefaults.put(BigDecimal.class, new BigDecimal(0.0)); } /** @@ -580,48 +480,15 @@ public class OgnlRuntime { * drain on your expressions - use with care. *

    */ - public static void clearCache() - { - synchronized(_methodParameterTypesCache) { - _methodParameterTypesCache.clear(); - } - synchronized(_ctorParameterTypesCache) { - _ctorParameterTypesCache.clear(); - } - synchronized(_propertyDescriptorCache) { - _propertyDescriptorCache.clear(); - } - synchronized(_constructorCache) { - _constructorCache.clear(); - } - synchronized(_staticMethodCache) { - _staticMethodCache.clear(); - } - synchronized(_instanceMethodCache) { - _instanceMethodCache.clear(); - } - synchronized(_invokePermissionCache) { - _invokePermissionCache.clear(); - } - synchronized(_fieldCache) { - _fieldCache.clear(); - _superclasses.clear(); // Used by fieldCache lookup (synchronized on _fieldCache). - } - synchronized(_declaredMethods[0]) { - _declaredMethods[0].clear(); - } - synchronized(_declaredMethods[1]) { - _declaredMethods[1].clear(); - } - _methodAccessCache.clear(); - _methodPermCache.clear(); + public static void clearCache() { + cache.clear(); } /** * Clears some additional caches used by OgnlRuntime. The existing {@link OgnlRuntime#clearCache()} * clears the standard reflection-related caches, but some applications may have need to clear * the additional caches as well. - * + *

    * Clearing the additional caches may have greater impact than the {@link OgnlRuntime#clearCache()} * method so it should only be used when the normal cache clear is insufficient. * @@ -632,13 +499,10 @@ public static void clearCache() * * @since 3.1.25 */ - public static void clearAdditionalCache() - { + public static void clearAdditionalCache() { cacheSetMethod.clear(); cacheGetMethod.clear(); - synchronized(_genericMethodParameterTypesCache) { - _genericMethodParameterTypesCache.clear(); - } + cache.clear(); } /** @@ -659,39 +523,32 @@ public static boolean isJdk9Plus() { return _jdk9Plus; } - public static String getNumericValueGetter(Class type) - { - return (String) NUMERIC_VALUES.get(type); + public static String getNumericValueGetter(Class type) { + return numericValues.get(type); } - public static Class getPrimitiveWrapperClass(Class primitiveClass) - { - return (Class) PRIMITIVE_WRAPPER_CLASSES.get(primitiveClass); + public static Class getPrimitiveWrapperClass(Class primitiveClass) { + return primitiveWrapperClasses.get(primitiveClass); } - public static String getNumericCast(Class type) - { - return (String) NUMERIC_CASTS.get(type); + public static String getNumericCast(Class type) { + return numericCasts.get(type); } - public static String getNumericLiteral(Class type) - { - return (String) NUMERIC_LITERALS.get(type); + public static String getNumericLiteral(Class type) { + return numericLiterals.get(type); } - public static void setCompiler(OgnlExpressionCompiler compiler) - { + public static void setCompiler(OgnlExpressionCompiler compiler) { _compiler = compiler; } - public static OgnlExpressionCompiler getCompiler() - { + public static OgnlExpressionCompiler getCompiler() { return _compiler; } public static void compileExpression(OgnlContext context, Node expression, Object root) - throws Exception - { + throws Exception { _compiler.compileExpression(context, expression, root); } @@ -703,9 +560,8 @@ public static void compileExpression(OgnlContext context, Node expression, Objec * @param o the Object from which to retrieve its Class. * @return the Class of o. */ - public static Class getTargetClass(Object o) - { - return (o == null) ? null : ((o instanceof Class) ? (Class) o : o.getClass()); + public static Class getTargetClass(Object o) { + return (o == null) ? null : ((o instanceof Class) ? (Class) o : o.getClass()); } /** @@ -715,8 +571,7 @@ public static Class getTargetClass(Object o) * @param o the Object from which to retrieve its base classname. * @return the base classname of o's Class. */ - public static String getBaseName(Object o) - { + public static String getBaseName(Object o) { return (o == null) ? null : getClassBaseName(o.getClass()); } @@ -726,25 +581,21 @@ public static String getBaseName(Object o) * @param c the Class from which to retrieve its name. * @return the base classname of c. */ - public static String getClassBaseName(Class c) - { + public static String getClassBaseName(Class c) { String s = c.getName(); return s.substring(s.lastIndexOf('.') + 1); } - public static String getClassName(Object o, boolean fullyQualified) - { - if (!(o instanceof Class)) - { + public static String getClassName(Object o, boolean fullyQualified) { + if (!(o instanceof Class)) { o = o.getClass(); } - return getClassName((Class) o, fullyQualified); + return getClassName((Class) o, fullyQualified); } - public static String getClassName(Class c, boolean fullyQualified) - { + public static String getClassName(Class c, boolean fullyQualified) { return fullyQualified ? c.getName() : getClassBaseName(c); } @@ -754,8 +605,7 @@ public static String getClassName(Class c, boolean fullyQualified) * @param o the Object from which to retrieve its Class package name. * @return the package name of o's Class. */ - public static String getPackageName(Object o) - { + public static String getPackageName(Object o) { return (o == null) ? null : getClassPackageName(o.getClass()); } @@ -765,8 +615,7 @@ public static String getPackageName(Object o) * @param c the Class from which to retrieve its package name. * @return the package name of c. */ - public static String getClassPackageName(Class c) - { + public static String getClassPackageName(Class c) { String s = c.getName(); int i = s.lastIndexOf('.'); @@ -779,15 +628,14 @@ public static String getClassPackageName(Class c) * @param num the int to convert into a "pointer" string in hex format. * @return the String representing num as a "pointer" string in hex format. */ - public static String getPointerString(int num) - { - StringBuffer result = new StringBuffer(); + public static String getPointerString(int num) { + StringBuilder result = new StringBuilder(); String hex = Integer.toHexString(num), pad; - Integer l = new Integer(hex.length()); + Integer l = hex.length(); // result.append(HEX_PREFIX); - if ((pad = (String) HEX_PADDING.get(l)) == null) { - StringBuffer pb = new StringBuffer(); + if ((pad = HEX_PADDING.get(l)) == null) { + StringBuilder pb = new StringBuilder(); for (int i = hex.length(); i < HEX_LENGTH; i++) { pb.append('0'); @@ -807,8 +655,7 @@ public static String getPointerString(int num) * @param o the Object to convert into a "pointer" string in hex format. * @return the String representing o as a "pointer" string in hex format. */ - public static String getPointerString(Object o) - { + public static String getPointerString(Object o) { return getPointerString((o == null) ? 0 : System.identityHashCode(o)); } @@ -817,17 +664,16 @@ public static String getPointerString(Object o) * identifier. If fullyQualified is true then the class name will be fully qualified to include * the package name, else it will be just the class' base name. * - * @param object the Object for which a unique descriptor string is desired. + * @param object the Object for which a unique descriptor string is desired. * @param fullyQualified true if the descriptor string is fully-qualified (package name), false for just the Class' base name. * @return the unique descriptor String for the object, qualified as per fullyQualified parameter. */ - public static String getUniqueDescriptor(Object object, boolean fullyQualified) - { - StringBuffer result = new StringBuffer(); + public static String getUniqueDescriptor(Object object, boolean fullyQualified) { + StringBuilder result = new StringBuilder(); if (object != null) { if (object instanceof Proxy) { - Class interfaceClass = object.getClass().getInterfaces()[0]; + Class interfaceClass = object.getClass().getInterfaces()[0]; result.append(getClassName(interfaceClass, fullyQualified)); result.append('^'); @@ -849,53 +695,18 @@ public static String getUniqueDescriptor(Object object, boolean fullyQualified) * @param object the Object for which a unique descriptor string is desired. * @return the unique descriptor String for the object, NOT fully-qualified. */ - public static String getUniqueDescriptor(Object object) - { + public static String getUniqueDescriptor(Object object) { return getUniqueDescriptor(object, false); } - /** - * Utility to convert a List into an Object[] array. If the list is zero elements this will - * return a constant array; toArray() on List always returns a new object and this is wasteful - * for our purposes. - * - * @param list the List to convert into an Object array. - * @return the array of Objects from the list. - */ - public static Object[] toArray(List list) - { - Object[] result; - int size = list.size(); - - if (size == 0) { - result = NoArguments; - } else { - result = getObjectArrayPool().create(list.size()); - for (int i = 0; i < size; i++) { - result[i] = list.get(i); - } - } - return result; - } - /** * Returns the parameter types of the given method. * - * @param m the Method whose parameter types are being queried. + * @param method the Method whose parameter types are being queried. * @return the array of Class elements representing m's parameters. May be null if m does not utilize parameters. */ - public static Class[] getParameterTypes(Method m) - { - synchronized (_methodParameterTypesCache) - { - Class[] result; - - if ((result = (Class[]) _methodParameterTypesCache.get(m)) == null) - { - _methodParameterTypesCache.put(m, result = m.getParameterTypes()); - } - return result; - } + public static Class[] getParameterTypes(Method method) throws CacheException { + return cache.getMethodParameterTypes(method); } /** @@ -903,172 +714,27 @@ public static Class[] getParameterTypes(Method m) * {@link Class} instance of the type the method is associated with. Correctly * finds generic types if running in >= 1.5 jre as well. * - * @param type The class type the method is being executed against. - * @param m The method to find types for. + * @param type The class type the method is being executed against. + * @param method The method to find types for. * @return Array of parameter types for the given method. */ - public static Class[] findParameterTypes(Class type, Method m) - { - Type[] genTypes = m.getGenericParameterTypes(); - Class[] types = new Class[genTypes.length];; - boolean noGenericParameter = true; - for (int i=0; i < genTypes.length; i++) - { - if (Class.class.isInstance(genTypes[i])) - { - types[i] = (Class) genTypes[i]; - continue; - } - noGenericParameter = false; - break; - } - if (noGenericParameter) - { - return types; - } - - if (type == null) - { - return getParameterTypes(m); - } - - final Type typeGenericSuperclass = type.getGenericSuperclass(); - if (typeGenericSuperclass == null - || !ParameterizedType.class.isInstance(typeGenericSuperclass) - || m.getDeclaringClass().getTypeParameters() == null) - { - return getParameterTypes(m); - } - - if ((types = (Class[]) _genericMethodParameterTypesCache.get(m)) != null) - { - ParameterizedType genericSuperclass = (ParameterizedType) typeGenericSuperclass; - if (Arrays.equals(types, genericSuperclass.getActualTypeArguments())) { - return types; - } - } - - ParameterizedType param = (ParameterizedType)typeGenericSuperclass; - TypeVariable[] declaredTypes = m.getDeclaringClass().getTypeParameters(); - - types = new Class[genTypes.length]; - - for (int i=0; i < genTypes.length; i++) - { - TypeVariable paramType = null; - - if (TypeVariable.class.isInstance(genTypes[i])) - { - paramType = (TypeVariable)genTypes[i]; - } else if (GenericArrayType.class.isInstance(genTypes[i])) - { - paramType = (TypeVariable) ((GenericArrayType)genTypes[i]).getGenericComponentType(); - } - else if (ParameterizedType.class.isInstance(genTypes[i])) - { - types[i] = (Class) ((ParameterizedType) genTypes[i]).getRawType(); - continue; - } else if (Class.class.isInstance(genTypes[i])) - { - types[i] = (Class) genTypes[i]; - continue; - } - - Class resolved = resolveType(param, paramType, declaredTypes); - - if (resolved != null) - { - if (GenericArrayType.class.isInstance(genTypes[i])) - { - resolved = Array.newInstance(resolved, 0).getClass(); - } - - types[i] = resolved; - continue; - } - - types[i] = m.getParameterTypes()[i]; - } - - synchronized (_genericMethodParameterTypesCache) - { - _genericMethodParameterTypesCache.put(m, types); - } - - return types; - } - - static Class resolveType(ParameterizedType param, TypeVariable var, TypeVariable[] declaredTypes) - { - if (param.getActualTypeArguments().length < 1) - return null; - - for (int i=0; i < declaredTypes.length; i++) - { - if (!TypeVariable.class.isInstance( param.getActualTypeArguments()[i]) - && declaredTypes[i].getName().equals(var.getName())) - { - return (Class) param.getActualTypeArguments()[i]; - } - } - - /* - for (int i=0; i < var.getBounds().length; i++) - { - Type t = var.getBounds()[i]; - Class resolvedType = null; - - if (ParameterizedType.class.isInstance(t)) - { - ParameterizedType pparam = (ParameterizedType)t; - for (int e=0; e < pparam.getActualTypeArguments().length; e++) - { - if (!TypeVariable.class.isInstance(pparam.getActualTypeArguments()[e])) - continue; - - resolvedType = resolveType(pparam, (TypeVariable)pparam.getActualTypeArguments()[e], declaredTypes); - } - } else - { - resolvedType = findType(param.getActualTypeArguments(), (Class)t); - } - - if (resolvedType != null) - return resolvedType; - } - */ - - return null; - } - - static Class findType(Type[] types, Class type) - { - for (int i = 0; i < types.length; i++) - { - if (Class.class.isInstance(types[i]) && type.isAssignableFrom((Class)types[i])) - return (Class)types[i]; + public static Class[] findParameterTypes(Class type, Method method) { + if (type == null || type.getGenericSuperclass() == null || !(type.getGenericSuperclass() instanceof ParameterizedType)) { + return getParameterTypes(method); } - return null; + GenericMethodParameterTypeCacheEntry key = new GenericMethodParameterTypeCacheEntry(method, type); + return cache.getGenericMethodParameterTypes(key); } /** * Returns the parameter types of the given method. * - * @param c the Constructor whose parameter types are being queried. + * @param constructor the Constructor whose parameter types are being queried. * @return the array of Class elements representing c's parameters. May be null if c does not utilize parameters. */ - public static Class[] getParameterTypes(Constructor c) - { - Class[] result; - if ((result = (Class[]) _ctorParameterTypesCache.get(c)) == null) { - synchronized (_ctorParameterTypesCache) { - if ((result = (Class[]) _ctorParameterTypesCache.get(c)) == null) { - _ctorParameterTypesCache.put(c, result = c.getParameterTypes()); - } - } - } - return result; + public static Class[] getParameterTypes(Constructor constructor) throws CacheException { + return cache.getParameterTypes(constructor); } /** @@ -1076,9 +742,8 @@ public static Class[] getParameterTypes(Constructor c) * * @return SecurityManager for OGNL */ - public static SecurityManager getSecurityManager() - { - return _securityManager; + public static SecurityManager getSecurityManager() { + return securityManager; } /** @@ -1086,9 +751,8 @@ public static SecurityManager getSecurityManager() * * @param value SecurityManager to set */ - public static void setSecurityManager(SecurityManager value) - { - _securityManager = value; + public static void setSecurityManager(SecurityManager value) { + securityManager = value; } /** @@ -1097,48 +761,33 @@ public static void setSecurityManager(SecurityManager value) * @param method the Method whose Permission is being requested. * @return the Permission for method named "invoke.<declaring-class>.<method-name>". */ - public static Permission getPermission(Method method) - { - Permission result; - Class mc = method.getDeclaringClass(); - - synchronized (_invokePermissionCache) { - Map permissions = (Map) _invokePermissionCache.get(mc); - - if (permissions == null) { - _invokePermissionCache.put(mc, permissions = new HashMap(101)); - } - if ((result = (Permission) permissions.get(method.getName())) == null) { - result = new OgnlInvokePermission("invoke." + mc.getName() + "." + method.getName()); - permissions.put(method.getName(), result); - } - } - return result; + public static Permission getPermission(Method method) throws CacheException { + PermissionCacheEntry key = new PermissionCacheEntry(method); + return cache.getInvokePermission(key); } public static Object invokeMethod(Object target, Method method, Object[] argsArray) - throws InvocationTargetException, IllegalAccessException - { + throws InvocationTargetException, IllegalAccessException { boolean syncInvoke; boolean checkPermission; Boolean methodAccessCacheValue; Boolean methodPermCacheValue; if (_useStricterInvocation) { - final Class methodDeclaringClass = method.getDeclaringClass(); // Note: synchronized(method) call below will already NPE, so no null check. - if ( (AO_SETACCESSIBLE_REF != null && AO_SETACCESSIBLE_REF.equals(method)) || - (AO_SETACCESSIBLE_ARR_REF != null && AO_SETACCESSIBLE_ARR_REF.equals(method)) || - (SYS_EXIT_REF != null && SYS_EXIT_REF.equals(method)) || - (SYS_CONSOLE_REF != null && SYS_CONSOLE_REF.equals(method)) || - AccessibleObjectHandler.class.isAssignableFrom(methodDeclaringClass) || - ClassResolver.class.isAssignableFrom(methodDeclaringClass) || - MethodAccessor.class.isAssignableFrom(methodDeclaringClass) || - MemberAccess.class.isAssignableFrom(methodDeclaringClass) || - OgnlContext.class.isAssignableFrom(methodDeclaringClass) || - Runtime.class.isAssignableFrom(methodDeclaringClass) || - ClassLoader.class.isAssignableFrom(methodDeclaringClass) || - ProcessBuilder.class.isAssignableFrom(methodDeclaringClass) || - AccessibleObjectHandlerJDK9Plus.unsafeOrDescendant(methodDeclaringClass) ) { + final Class methodDeclaringClass = method.getDeclaringClass(); // Note: synchronized(method) call below will already NPE, so no null check. + if ((AO_SETACCESSIBLE_REF != null && AO_SETACCESSIBLE_REF.equals(method)) || + (AO_SETACCESSIBLE_ARR_REF != null && AO_SETACCESSIBLE_ARR_REF.equals(method)) || + (SYS_EXIT_REF != null && SYS_EXIT_REF.equals(method)) || + (SYS_CONSOLE_REF != null && SYS_CONSOLE_REF.equals(method)) || + AccessibleObjectHandler.class.isAssignableFrom(methodDeclaringClass) || + ClassResolver.class.isAssignableFrom(methodDeclaringClass) || + MethodAccessor.class.isAssignableFrom(methodDeclaringClass) || + MemberAccess.class.isAssignableFrom(methodDeclaringClass) || + OgnlContext.class.isAssignableFrom(methodDeclaringClass) || + Runtime.class.isAssignableFrom(methodDeclaringClass) || + ClassLoader.class.isAssignableFrom(methodDeclaringClass) || + ProcessBuilder.class.isAssignableFrom(methodDeclaringClass) || + AccessibleObjectHandlerJDK9Plus.unsafeOrDescendant(methodDeclaringClass)) { // Prevent calls to some specific methods, as well as all methods of certain classes/interfaces // for which no (apparent) legitimate use cases exist for their usage within OGNL invokeMethod(). throw new IllegalAccessException("Method [" + method + "] cannot be called from within OGNL invokeMethod() " + @@ -1148,22 +797,18 @@ public static Object invokeMethod(Object target, Method method, Object[] argsArr // only synchronize method invocation if it actually requires it - synchronized(method) { + synchronized (method) { methodAccessCacheValue = _methodAccessCache.get(method); if (methodAccessCacheValue == null) { - if (!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) - { - if (!(((AccessibleObject) method).isAccessible())) - { + if (!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) { + if (!(method.isAccessible())) { methodAccessCacheValue = Boolean.TRUE; _methodAccessCache.put(method, methodAccessCacheValue); - } else - { + } else { methodAccessCacheValue = Boolean.FALSE; _methodAccessCache.put(method, methodAccessCacheValue); } - } else - { + } else { methodAccessCacheValue = Boolean.FALSE; _methodAccessCache.put(method, methodAccessCacheValue); } @@ -1172,10 +817,9 @@ public static Object invokeMethod(Object target, Method method, Object[] argsArr methodPermCacheValue = _methodPermCache.get(method); if (methodPermCacheValue == null) { - if (_securityManager != null) { - try - { - _securityManager.checkPermission(getPermission(method)); + if (securityManager != null) { + try { + securityManager.checkPermission(getPermission(method)); methodPermCacheValue = Boolean.TRUE; _methodPermCache.put(method, methodPermCacheValue); } catch (SecurityException ex) { @@ -1183,8 +827,7 @@ public static Object invokeMethod(Object target, Method method, Object[] argsArr _methodPermCache.put(method, methodPermCacheValue); throw new IllegalAccessException("Method [" + method + "] cannot be accessed."); } - } - else { + } else { methodPermCacheValue = Boolean.TRUE; _methodPermCache.put(method, methodPermCacheValue); } @@ -1196,13 +839,10 @@ public static Object invokeMethod(Object target, Method method, Object[] argsArr if (syncInvoke) //if is not public and is not accessible { - synchronized(method) - { - if (checkPermission) - { - try - { - _securityManager.checkPermission(getPermission(method)); + synchronized (method) { + if (checkPermission) { + try { + securityManager.checkPermission(getPermission(method)); } catch (SecurityException ex) { throw new IllegalAccessException("Method [" + method + "] cannot be accessed."); } @@ -1215,13 +855,10 @@ public static Object invokeMethod(Object target, Method method, Object[] argsArr _accessibleObjectHandler.setAccessible(method, false); } } - } else - { - if (checkPermission) - { - try - { - _securityManager.checkPermission(getPermission(method)); + } else { + if (checkPermission) { + try { + securityManager.checkPermission(getPermission(method)); } catch (SecurityException ex) { throw new IllegalAccessException("Method [" + method + "] cannot be accessed."); } @@ -1297,11 +934,10 @@ private static Object invokeMethodInsideSandbox(Object target, Method method, Ob * @param arg an object that is being passed to a method * @return the class to use to look up the method */ - public static final Class getArgClass(Object arg) - { + public static Class getArgClass(Object arg) { if (arg == null) return null; - Class c = arg.getClass(); + Class c = arg.getClass(); if (c == Boolean.class) return Boolean.TYPE; else if (c.getSuperclass() == Number.class) { @@ -1322,12 +958,13 @@ else if (c.getSuperclass() == Number.class) { return c; } - public static Class[] getArgClasses(Object[] args) { - if (args == null) - return null; - Class[] argClasses = new Class[args.length]; - for (int i=0; i[] getArgClasses(Object[] args) { + if (args == null) return null; + + Class[] argClasses = new Class[args.length]; + for (int i = 0; i < args.length; i++) { argClasses[i] = getArgClass(args[i]); + } return argClasses; } @@ -1338,22 +975,21 @@ public static Class[] getArgClasses(Object[] args) { * type. * * @param object the Object to check for type-compatibility with Class c. - * @param c the Class for which object's type-compatibility is being checked. + * @param c the Class for which object's type-compatibility is being checked. * @return true if object is type-compatible with c. */ - public static final boolean isTypeCompatible(Object object, Class c) { + public static boolean isTypeCompatible(Object object, Class c) { if (object == null) return true; + ArgsCompatbilityReport report = new ArgsCompatbilityReport(0, new boolean[1]); if (!isTypeCompatible(getArgClass(object), c, 0, report)) return false; - if (report.conversionNeeded[0]) - return false; // we don't allow conversions during this path... - return true; + + return !report.conversionNeeded[0]; // we don't allow conversions during this path... } - public static final boolean isTypeCompatible(Class parameterClass, Class methodArgumentClass, int index, ArgsCompatbilityReport report) - { + public static boolean isTypeCompatible(Class parameterClass, Class methodArgumentClass, int index, ArgsCompatbilityReport report) { if (parameterClass == null) { // happens when we cannot determine parameter... report.score += 500; @@ -1365,8 +1001,8 @@ public static final boolean isTypeCompatible(Class parameterClass, Class methodA // return false; // really? int can be assigned to long... *hmm* if (methodArgumentClass.isArray()) { if (parameterClass.isArray()) { - Class pct = parameterClass.getComponentType(); - Class mct = methodArgumentClass.getComponentType(); + Class pct = parameterClass.getComponentType(); + Class mct = methodArgumentClass.getComponentType(); if (mct.isAssignableFrom(pct)) { // two arrays are better then a array and a list or other conversions... report.score += 25; @@ -1377,9 +1013,9 @@ public static final boolean isTypeCompatible(Class parameterClass, Class methodA if (Collection.class.isAssignableFrom(parameterClass)) { // we have to assume that all Collections carry objects - generics access is of no use during runtime because of // Type Erasure - http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Type%20Erasure - Class mct = methodArgumentClass.getComponentType(); + Class mct = methodArgumentClass.getComponentType(); if (mct == Object.class) { - report.conversionNeeded[index]=true; + report.conversionNeeded[index] = true; report.score += 30; return true; } else { @@ -1390,7 +1026,7 @@ public static final boolean isTypeCompatible(Class parameterClass, Class methodA } else if (Collection.class.isAssignableFrom(methodArgumentClass)) { if (parameterClass.isArray()) { // TODO get generics type here and do further evaluations... - report.conversionNeeded[index]=true; + report.conversionNeeded[index] = true; report.score += 50; return true; } @@ -1401,7 +1037,7 @@ public static final boolean isTypeCompatible(Class parameterClass, Class methodA return true; } // TODO get generics type here and do further evaluations... - report.conversionNeeded[index]=true; + report.conversionNeeded[index] = true; report.score += 50; return true; } @@ -1411,7 +1047,7 @@ public static final boolean isTypeCompatible(Class parameterClass, Class methodA return true; } if (parameterClass.isPrimitive()) { - Class ptc = (Class)PRIMITIVE_WRAPPER_CLASSES.get(parameterClass); + Class ptc = primitiveWrapperClasses.get(parameterClass); if (methodArgumentClass == ptc) { report.score += 2; // quite an good match return true; @@ -1446,16 +1082,16 @@ public static final boolean isTypeCompatible(Class parameterClass, Class methodA public static class ArgsCompatbilityReport { int score; boolean[] conversionNeeded; + public ArgsCompatbilityReport(int score, boolean[] conversionNeeded) { this.score = score; this.conversionNeeded = conversionNeeded; } } - public static final ArgsCompatbilityReport NoArgsReport = new ArgsCompatbilityReport(0, new boolean[0]); + public static final ArgsCompatbilityReport NoArgsReport = new ArgsCompatbilityReport(0, new boolean[0]); - public static boolean areArgsCompatible(Object[] args, Class[] classes) - { + public static boolean areArgsCompatible(Object[] args, Class[] classes) { ArgsCompatbilityReport report = areArgsCompatible(getArgClasses(args), classes, null); if (report == null) return false; @@ -1465,12 +1101,11 @@ public static boolean areArgsCompatible(Object[] args, Class[] classes) return true; } - public static ArgsCompatbilityReport areArgsCompatible(Class[] args, Class[] classes, Method m) - { + public static ArgsCompatbilityReport areArgsCompatible(Class[] args, Class[] classes, Method m) { boolean varArgs = m != null && m.isVarArgs(); - if ( args==null || args.length == 0 ) { // handle methods without arguments - if ( classes == null || classes.length == 0 ) { + if (args == null || args.length == 0) { // handle methods without arguments + if (classes == null || classes.length == 0) { return NoArgsReport; } else { if (varArgs) { @@ -1504,7 +1139,7 @@ public static ArgsCompatbilityReport areArgsCompatible(Class[] args, Class[] cla return null; // type check on varargs - Class varArgsType = classes[classes.length - 1].getComponentType(); + Class varArgsType = classes[classes.length - 1].getComponentType(); for (int index = classes.length - 1, count = args.length; index < count; ++index) if (!isTypeCompatible(args[index], varArgsType, index, report)) return null; @@ -1527,10 +1162,9 @@ public static ArgsCompatbilityReport areArgsCompatible(Class[] args, Class[] cla * @param classes2 the Class array that classes1 is being checked against to see if classes1 is "more specific" than classes2. * @return true if the classes1 Class contents are "more specific" than classes2 Class contents, false otherwise. */ - public static final boolean isMoreSpecific(Class[] classes1, Class[] classes2) - { + public static boolean isMoreSpecific(Class[] classes1, Class[] classes2) { for (int index = 0, count = classes1.length; index < count; ++index) { - Class c1 = classes1[index], c2 = classes2[index]; + Class c1 = classes1[index], c2 = classes2[index]; if (c1 == c2) continue; else if (c1.isPrimitive()) @@ -1545,8 +1179,7 @@ else if (c2.isAssignableFrom(c1)) return false; } - public static String getModifierString(int modifiers) - { + public static String getModifierString(int modifiers) { String result; if (Modifier.isPublic(modifiers)) @@ -1570,10 +1203,8 @@ else if (Modifier.isPrivate(modifiers)) return result; } - public static Class classForName(OgnlContext context, String className) - throws ClassNotFoundException - { - Class result = (Class) _primitiveTypes.get(className); + public static Class classForName(OgnlContext context, String className) throws ClassNotFoundException { + Class result = primitiveTypes.get(className); if (result == null) { ClassResolver resolver; @@ -1581,52 +1212,47 @@ public static Class classForName(OgnlContext context, String className) if ((context == null) || ((resolver = context.getClassResolver()) == null)) { resolver = new DefaultClassResolver(); } - result = resolver.classForName(className, context); + result = resolver.classForName(className, context); } if (result == null) throw new ClassNotFoundException("Unable to resolve class: " + className); - return result; + return (Class) result; } public static boolean isInstance(OgnlContext context, Object value, String className) - throws OgnlException - { + throws OgnlException { try { - Class c = classForName(context, className); + Class c = classForName(context, className); return c.isInstance(value); } catch (ClassNotFoundException e) { throw new OgnlException("No such class: " + className, e); } } - public static Object getPrimitiveDefaultValue(Class forClass) - { - return _primitiveDefaults.get(forClass); + public static Object getPrimitiveDefaultValue(Class forClass) { + return primitiveDefaults.get(forClass); } - public static Object getNumericDefaultValue(Class forClass) - { - return NUMERIC_DEFAULTS.get(forClass); + public static Object getNumericDefaultValue(Class forClass) { + return numericDefaults.get(forClass); } public static Object getConvertedType(OgnlContext context, Object target, Member member, String propertyName, - Object value, Class type) - { + Object value, Class type) { return context.getTypeConverter().convertValue(context, target, member, propertyName, value, type); } public static boolean getConvertedTypes(OgnlContext context, Object target, Member member, String propertyName, - Class[] parameterTypes, Object[] args, Object[] newArgs) - { + Class[] parameterTypes, Object[] args, Object[] newArgs) { boolean result = false; if (parameterTypes.length == args.length) { result = true; for (int i = 0, ilast = parameterTypes.length - 1; result && (i <= ilast); i++) { Object arg = args[i]; - Class type = parameterTypes[i]; + Class type = parameterTypes[i]; if (isTypeCompatible(arg, type)) { newArgs[i] = arg; @@ -1644,16 +1270,15 @@ public static boolean getConvertedTypes(OgnlContext context, Object target, Memb return result; } - public static Constructor getConvertedConstructorAndArgs(OgnlContext context, Object target, List constructors, - Object[] args, Object[] newArgs) - { - Constructor result = null; + public static Constructor getConvertedConstructorAndArgs(OgnlContext context, Object target, List> constructors, + Object[] args, Object[] newArgs) { + Constructor result = null; TypeConverter converter = context.getTypeConverter(); if ((converter != null) && (constructors != null)) { for (int i = 0, icount = constructors.size(); (result == null) && (i < icount); i++) { - Constructor ctor = (Constructor) constructors.get(i); - Class[] parameterTypes = getParameterTypes(ctor); + Constructor ctor = constructors.get(i); + Class[] parameterTypes = getParameterTypes(ctor); if (getConvertedTypes(context, target, ctor, null, parameterTypes, args, newArgs)) { result = ctor; @@ -1669,40 +1294,36 @@ public static Constructor getConvertedConstructorAndArgs(OgnlContext context, Ob * converted arguments in actualArgs. If unsuccessful this method will return null and the * actualArgs will be empty. * - * @param context The current execution context. - * @param source Target object to run against or method name. - * @param target Instance of object to be run against. + * @param context The current execution context. + * @param source Target object to run against or method name. + * @param target Instance of object to be run against. * @param propertyName Name of property to get method of. - * @param methodName Name of the method to get from known methods. - * @param methods List of current known methods. - * @param args Arguments originally passed in. - * @param actualArgs Converted arguments. - * + * @param methodName Name of the method to get from known methods. + * @param methods List of current known methods. + * @param args Arguments originally passed in. + * @param actualArgs Converted arguments. * @return Best method match or null if none could be found. */ public static Method getAppropriateMethod(OgnlContext context, Object source, Object target, String propertyName, - String methodName, List methods, Object[] args, Object[] actualArgs) - { + String methodName, List methods, Object[] args, Object[] actualArgs) { Method result = null; - if (methods != null) - { - Class typeClass = target != null ? target.getClass() : null; - if (typeClass == null && source != null && Class.class.isInstance(source)) - { - typeClass = (Class)source; + if (methods != null) { + Class typeClass = target != null ? target.getClass() : null; + if (typeClass == null && source instanceof Class) { + typeClass = (Class) source; } - Class[] argClasses = getArgClasses(args); + Class[] argClasses = getArgClasses(args); MatchingMethod mm = findBestMethod(methods, typeClass, methodName, argClasses); if (mm != null) { result = mm.mMethod; - Class[] mParameterTypes = mm.mParameterTypes; + Class[] mParameterTypes = mm.mParameterTypes; System.arraycopy(args, 0, actualArgs, 0, args.length); if (actualArgs.length > 0) { for (int j = 0; j < mParameterTypes.length; j++) { - Class type = mParameterTypes[j]; + Class type = mParameterTypes[j]; if (mm.report.conversionNeeded[j] || (type.isPrimitive() && (actualArgs[j] == null))) { actualArgs[j] = getConvertedType(context, source, result, propertyName, args[j], type); @@ -1712,8 +1333,7 @@ public static Method getAppropriateMethod(OgnlContext context, Object source, Ob } } - if (result == null) - { + if (result == null) { result = getConvertedMethodAndArgs(context, target, propertyName, methods, args, actualArgs); } @@ -1721,14 +1341,14 @@ public static Method getAppropriateMethod(OgnlContext context, Object source, Ob } public static Method getConvertedMethodAndArgs(OgnlContext context, Object target, String propertyName, - List methods, Object[] args, Object[] newArgs) { + List methods, Object[] args, Object[] newArgs) { Method result = null; TypeConverter converter = context.getTypeConverter(); if ((converter != null) && (methods != null)) { for (int i = 0, icount = methods.size(); (result == null) && (i < icount); i++) { - Method m = (Method) methods.get(i); - Class[] parameterTypes = findParameterTypes(target != null ? target.getClass() : null, m);//getParameterTypes(m); + Method m = methods.get(i); + Class[] parameterTypes = findParameterTypes(target != null ? target.getClass() : null, m);//getParameterTypes(m); if (getConvertedTypes(context, target, m, propertyName, parameterTypes, args, newArgs)) { result = m; @@ -1739,12 +1359,13 @@ public static Method getConvertedMethodAndArgs(OgnlContext context, Object targe } private static class MatchingMethod { - Method mMethod; - int score; - ArgsCompatbilityReport report; - Class[] mParameterTypes; - private MatchingMethod(Method method, int score, ArgsCompatbilityReport report, Class[] mParameterTypes) { + Method mMethod; + int score; + ArgsCompatbilityReport report; + Class[] mParameterTypes; + + private MatchingMethod(Method method, int score, ArgsCompatbilityReport report, Class[] mParameterTypes) { this.mMethod = method; this.score = score; this.report = report; @@ -1752,18 +1373,16 @@ private MatchingMethod(Method method, int score, ArgsCompatbilityReport report, } } - private static MatchingMethod findBestMethod(List methods, Class typeClass, String name, Class[] argClasses) { + private static MatchingMethod findBestMethod(List methods, Class typeClass, String name, Class[] argClasses) { MatchingMethod mm = null; IllegalArgumentException failure = null; - for (int i = 0, icount = methods.size(); i < icount; i++) { - Method m = (Method) methods.get(i); - - Class[] mParameterTypes = findParameterTypes(typeClass, m); - ArgsCompatbilityReport report = areArgsCompatible(argClasses, mParameterTypes, m); + for (Method method : methods) { + Class[] mParameterTypes = findParameterTypes(typeClass, method); + ArgsCompatbilityReport report = areArgsCompatible(argClasses, mParameterTypes, method); if (report == null) continue; - String methodName = m.getName(); + String methodName = method.getName(); int score = report.score; if (name.equals(methodName)) { // exact match - no additinal score... @@ -1778,84 +1397,84 @@ private static MatchingMethod findBestMethod(List methods, Class typeClass, Stri score += 5000; } if (mm == null || mm.score > score) { - mm = new MatchingMethod(m, score, report, mParameterTypes); + mm = new MatchingMethod(method, score, report, mParameterTypes); failure = null; } else if (mm.score == score) { // it happens that we see the same method signature multiple times - for the current class or interfaces ... // check for same signature - if (Arrays.equals(mm.mMethod.getParameterTypes(), m.getParameterTypes()) && mm.mMethod.getName().equals(m.getName())) { + if (Arrays.equals(mm.mMethod.getParameterTypes(), method.getParameterTypes()) && mm.mMethod.getName().equals(method.getName())) { // it is the same method. we use the public one... if (!Modifier.isPublic(mm.mMethod.getDeclaringClass().getModifiers()) - && Modifier.isPublic(m.getDeclaringClass().getModifiers())) { - mm = new MatchingMethod(m, score, report, mParameterTypes); + && Modifier.isPublic(method.getDeclaringClass().getModifiers())) { + mm = new MatchingMethod(method, score, report, mParameterTypes); failure = null; } } else { // two methods with same score - direct compare to find the better one... // legacy wins over varargs - if (m.isVarArgs() || mm.mMethod.isVarArgs()) { - if (m.isVarArgs() && !mm.mMethod.isVarArgs()) { + if (method.isVarArgs() || mm.mMethod.isVarArgs()) { + if (method.isVarArgs() && !mm.mMethod.isVarArgs()) { // keep with current - } else if (!m.isVarArgs() && mm.mMethod.isVarArgs()) { + } else if (!method.isVarArgs()) { // legacy wins... - mm = new MatchingMethod(m, score, report, mParameterTypes); + mm = new MatchingMethod(method, score, report, mParameterTypes); failure = null; } else { // both arguments are varargs... - System.err.println("Two vararg methods with same score("+score+"): \""+mm.mMethod+"\" and \""+m+"\" please report!"); + System.err.println("Two vararg methods with same score(" + score + "): \"" + mm.mMethod + "\" and \"" + method + "\" please report!"); } } else { int scoreCurr = 0; int scoreOther = 0; - for (int j=0; j argClass = argClasses[j]; + Class mcClass = mm.mParameterTypes[j]; + Class moClass = mParameterTypes[j]; + if (argClass == null) { // TODO can we avoid this case? // we don't know the class. use the most generic implementation... if (mcClass == moClass) { // equal args - no winner... } else if (mcClass.isAssignableFrom(moClass)) { - scoreOther += 1000; // current wins... + scoreOther += 1000; // current wins... } else if (moClass.isAssignableFrom(moClass)) { - scoreCurr += 1000; // other wins... + scoreCurr += 1000; // other wins... } else { // both items can't be assigned to each other.. - failure = new IllegalArgumentException("Can't decide wich method to use: \""+mm.mMethod+"\" or \""+m+"\""); + failure = new IllegalArgumentException("Can't decide wich method to use: \"" + mm.mMethod + "\" or \"" + method + "\""); } } else { // we try to find the more specific implementation if (mcClass == moClass) { // equal args - no winner... } else if (mcClass == argClass) { - scoreOther += 100; // current wins... + scoreOther += 100; // current wins... } else if (moClass == argClass) { - scoreCurr += 100; // other wins... + scoreCurr += 100; // other wins... } else if (mcClass.isAssignableFrom(moClass)) { - scoreOther += 50; // current wins... + scoreOther += 50; // current wins... } else if (moClass.isAssignableFrom(moClass)) { - scoreCurr += 50; // other wins... + scoreCurr += 50; // other wins... } else { // both items can't be assigned to each other.. // TODO: if this happens we have to put some weight on the inheritance... - failure = new IllegalArgumentException("Can't decide wich method to use: \""+mm.mMethod+"\" or \""+m+"\""); + failure = new IllegalArgumentException("Can't decide wich method to use: \"" + mm.mMethod + "\" or \"" + method + "\""); } } } if (scoreCurr == scoreOther) { if (failure == null) { boolean currentIsAbstract = Modifier.isAbstract(mm.mMethod.getModifiers()); - boolean otherIsAbstract = Modifier.isAbstract(m.getModifiers()); - if (! (currentIsAbstract ^ otherIsAbstract) ) { + boolean otherIsAbstract = Modifier.isAbstract(method.getModifiers()); + if (currentIsAbstract == otherIsAbstract) { // Only report as an error when the score is equal and BOTH methods are abstract or BOTH are concrete. // If one is abstract and the other concrete then either choice should work for OGNL, // so we just keep the current choice and continue (without error output). - System.err.println("Two methods with same score("+score+"): \""+mm.mMethod+"\" and \""+m+"\" please report!"); + System.err.println("Two methods with same score(" + score + "): \"" + mm.mMethod + "\" and \"" + method + "\" please report!"); } } } else if (scoreCurr > scoreOther) { // other wins... - mm = new MatchingMethod(m, score, report, mParameterTypes); + mm = new MatchingMethod(method, score, report, mParameterTypes); failure = null; } // else current one wins... } @@ -1868,32 +1487,27 @@ private static MatchingMethod findBestMethod(List methods, Class typeClass, Stri } public static Object callAppropriateMethod(OgnlContext context, Object source, Object target, String methodName, - String propertyName, List methods, Object[] args) - throws MethodFailedException - { - Throwable reason = null; - Object[] actualArgs = _objectArrayPool.create(args.length); + String propertyName, List methods, Object[] args) + throws MethodFailedException { + Throwable reason; + Object[] actualArgs = new Object[args.length]; try { Method method = getAppropriateMethod(context, source, target, propertyName, methodName, methods, args, actualArgs); - if ((method == null) || !isMethodAccessible(context, source, method, propertyName)) - { - StringBuffer buffer = new StringBuffer(); + if (!isMethodAccessible(context, source, method, propertyName)) { + StringBuilder buffer = new StringBuilder(); String className = ""; - if (target != null) - { + if (target != null) { className = target.getClass().getName() + "."; } - for (int i = 0, ilast = args.length - 1; i <= ilast; i++) - { + for (int i = 0, ilast = args.length - 1; i <= ilast; i++) { Object arg = args[i]; buffer.append((arg == null) ? NULL_STRING : arg.getClass().getName()); - if (i < ilast) - { + if (i < ilast) { buffer.append(", "); } } @@ -1903,18 +1517,15 @@ public static Object callAppropriateMethod(OgnlContext context, Object source, O Object[] convertedArgs = actualArgs; - if (method.isVarArgs()) - { - Class[] parmTypes = method.getParameterTypes(); + if (method.isVarArgs()) { + Class[] parmTypes = method.getParameterTypes(); // split arguments in to two dimensional array for varargs reflection invocation // where it is expected that the parameter passed in to invoke the method // will look like "new Object[] { arrayOfNonVarArgsArguments, arrayOfVarArgsArguments }" - for (int i=0; i < parmTypes.length; i++) - { - if (parmTypes[i].isArray()) - { + for (int i = 0; i < parmTypes.length; i++) { + if (parmTypes[i].isArray()) { convertedArgs = new Object[i + 1]; if (actualArgs.length > 0) { System.arraycopy(actualArgs, 0, convertedArgs, 0, convertedArgs.length); @@ -1924,13 +1535,10 @@ public static Object callAppropriateMethod(OgnlContext context, Object source, O // if they passed in varargs arguments grab them and dump in to new varargs array - if (actualArgs.length > i) - { - ArrayList varArgsList = new ArrayList(); - for (int j=i; j < actualArgs.length; j++) - { - if (actualArgs[j] != null) - { + if (actualArgs.length > i) { + List varArgsList = new ArrayList<>(); + for (int j = i; j < actualArgs.length; j++) { + if (actualArgs[j] != null) { varArgsList.add(actualArgs[j]); } } @@ -1957,26 +1565,19 @@ public static Object callAppropriateMethod(OgnlContext context, Object source, O return invokeMethod(target, method, convertedArgs); - } catch (NoSuchMethodException e) { - reason = e; - } catch (IllegalAccessException e) { + } catch (NoSuchMethodException | IllegalAccessException e) { reason = e; } catch (InvocationTargetException e) { reason = e.getTargetException(); - } finally { - _objectArrayPool.recycle(actualArgs); } throw new MethodFailedException(source, methodName, reason); } public static Object callStaticMethod(OgnlContext context, String className, String methodName, Object[] args) - throws OgnlException - { + throws OgnlException { try { - Class targetClass = classForName(context, className); - if (targetClass == null) - throw new ClassNotFoundException("Unable to resolve class with name " + className); + Class targetClass = classForName(context, className); MethodAccessor ma = getMethodAccessor(targetClass); @@ -1989,45 +1590,32 @@ public static Object callStaticMethod(OgnlContext context, String className, Str /** * Invokes the specified method against the target object. * - * @param context - * The current execution context. - * @param target - * The object to invoke the method on. - * @param methodName - * Name of the method - as in "getValue" or "add", etc.. - * @param propertyName - * Name of the property to call instead? - * @param args - * Optional arguments needed for method. + * @param context The current execution context. + * @param target The object to invoke the method on. + * @param methodName Name of the method - as in "getValue" or "add", etc.. + * @param propertyName Name of the property to call instead? + * @param args Optional arguments needed for method. * @return Result of invoking method. - * - * @deprecated Use {@link #callMethod(OgnlContext, Object, String, Object[])} instead. * @throws OgnlException For lots of different reasons. + * @deprecated Use {@link #callMethod(OgnlContext, Object, String, Object[])} instead. */ public static Object callMethod(OgnlContext context, Object target, String methodName, String propertyName, Object[] args) - throws OgnlException - { + throws OgnlException { return callMethod(context, target, methodName == null ? propertyName : methodName, args); } /** * Invokes the specified method against the target object. * - * @param context - * The current execution context. - * @param target - * The object to invoke the method on. - * @param methodName - * Name of the method - as in "getValue" or "add", etc.. - * @param args - * Optional arguments needed for method. + * @param context The current execution context. + * @param target The object to invoke the method on. + * @param methodName Name of the method - as in "getValue" or "add", etc.. + * @param args Optional arguments needed for method. * @return Result of invoking method. - * * @throws OgnlException For lots of different reasons. */ public static Object callMethod(OgnlContext context, Object target, String methodName, Object[] args) - throws OgnlException - { + throws OgnlException { if (target == null) throw new NullPointerException("target is null for method " + methodName); @@ -2035,29 +1623,27 @@ public static Object callMethod(OgnlContext context, Object target, String metho } public static Object callConstructor(OgnlContext context, String className, Object[] args) - throws OgnlException - { - Throwable reason = null; + throws OgnlException { + Throwable reason; Object[] actualArgs = args; try { - Constructor ctor = null; - Class[] ctorParameterTypes = null; - Class target = classForName(context, className); - List constructors = getConstructors(target); + Constructor ctor = null; + Class[] ctorParameterTypes = null; + Class target = classForName(context, className); + List> constructors = getConstructors(target); - for (int i = 0, icount = constructors.size(); i < icount; i++) { - Constructor c = (Constructor) constructors.get(i); - Class[] cParameterTypes = getParameterTypes(c); + for (Constructor constructor : constructors) { + Class[] cParameterTypes = getParameterTypes(constructor); if (areArgsCompatible(args, cParameterTypes) - && (ctor == null || isMoreSpecific(cParameterTypes, ctorParameterTypes))) { - ctor = c; + && (ctor == null || isMoreSpecific(cParameterTypes, ctorParameterTypes))) { + ctor = constructor; ctorParameterTypes = cParameterTypes; } } if (ctor == null) { - actualArgs = _objectArrayPool.create(args.length); + actualArgs = new Object[args.length]; if ((ctor = getConvertedConstructorAndArgs(context, target, constructors, args, actualArgs)) == null) { throw new NoSuchMethodException(); } @@ -2067,20 +1653,10 @@ public static Object callConstructor(OgnlContext context, String className, Obje "access denied to " + target.getName() + "()"); } return ctor.newInstance(actualArgs); - } catch (ClassNotFoundException e) { - reason = e; - } catch (NoSuchMethodException e) { - reason = e; - } catch (IllegalAccessException e) { + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException e) { reason = e; } catch (InvocationTargetException e) { reason = e.getTargetException(); - } catch (InstantiationException e) { - reason = e; - } finally { - if (actualArgs != args) { - _objectArrayPool.recycle(actualArgs); - } } throw new MethodFailedException(className, "new", reason); @@ -2089,19 +1665,18 @@ public static Object callConstructor(OgnlContext context, String className, Obje /** * Don't use this method as it doesn't check member access rights via {@link MemberAccess} interface * - * @param context the current execution context. - * @param target the object to invoke the property name get on. + * @param context the current execution context. + * @param target the object to invoke the property name get on. * @param propertyName the name of the property to be retrieved from target. * @return the result invoking property retrieval of propertyName for target. - * @throws OgnlException for lots of different reasons. + * @throws OgnlException for lots of different reasons. * @throws IllegalAccessException if access not permitted. - * @throws NoSuchMethodException if no property accessor exists. + * @throws NoSuchMethodException if no property accessor exists. * @throws IntrospectionException on errors using {@link Introspector}. */ @Deprecated - public static final Object getMethodValue(OgnlContext context, Object target, String propertyName) - throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException - { + public static Object getMethodValue(OgnlContext context, Object target, String propertyName) + throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException { return getMethodValue(context, target, propertyName, false); } @@ -2110,29 +1685,24 @@ public static final Object getMethodValue(OgnlContext context, Object target, St * exists and if it is accessible according to the context's MemberAccess. If neither test * passes this will return NotFound. * - * @param context the current execution context. - * @param target the object to invoke the property name get on. - * @param propertyName the name of the property to be retrieved from target. + * @param context the current execution context. + * @param target the object to invoke the property name get on. + * @param propertyName the name of the property to be retrieved from target. * @param checkAccessAndExistence true if this method should check access levels and existence for propertyName of target, false otherwise. * @return the result invoking property retrieval of propertyName for target. - * @throws OgnlException for lots of different reasons. + * @throws OgnlException for lots of different reasons. * @throws IllegalAccessException if access not permitted. - * @throws NoSuchMethodException if no property accessor exists. - * @throws IntrospectionException on errors using {@link Introspector}. + * @throws NoSuchMethodException if no property accessor exists. */ - public static final Object getMethodValue(OgnlContext context, Object target, String propertyName, - boolean checkAccessAndExistence) - throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException - { + public static Object getMethodValue(OgnlContext context, Object target, String propertyName, boolean checkAccessAndExistence) + throws OgnlException, IllegalAccessException, NoSuchMethodException { Object result = null; - Method m = getGetMethod(context, (target == null) ? null : target.getClass() , propertyName); + Method m = getGetMethod((target == null) ? null : target.getClass(), propertyName); if (m == null) m = getReadMethod((target == null) ? null : target.getClass(), propertyName, null); - if (checkAccessAndExistence) - { - if ((m == null) || !context.getMemberAccess().isAccessible(context, target, m, propertyName)) - { + if (checkAccessAndExistence) { + if ((m == null) || !context.getMemberAccess().isAccessible(context, target, m, propertyName)) { result = NotFound; } } @@ -2153,54 +1723,33 @@ public static final Object getMethodValue(OgnlContext context, Object target, St /** * Don't use this method as it doesn't check member access rights via {@link MemberAccess} interface * - * @param context the current execution context. - * @param target the object to invoke the property name get on. + * @param context the current execution context. + * @param target the object to invoke the property name get on. * @param propertyName the name of the property to be set for target. - * @param value the value to set for propertyName of target. + * @param value the value to set for propertyName of target. * @return true if the operation succeeded, false otherwise. * @throws OgnlException for lots of different reasons. - * @throws IllegalAccessException if access not permitted. - * @throws NoSuchMethodException if no property accessor exists. - * @throws IntrospectionException on errors using {@link Introspector}. */ @Deprecated - public static boolean setMethodValue(OgnlContext context, Object target, String propertyName, Object value) - throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException - { + public static boolean setMethodValue(OgnlContext context, Object target, String propertyName, Object value) throws OgnlException { return setMethodValue(context, target, propertyName, value, false); } - public static boolean setMethodValue(OgnlContext context, Object target, String propertyName, Object value, - boolean checkAccessAndExistence) - throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException - { + public static boolean setMethodValue(OgnlContext context, Object target, String propertyName, Object value, boolean checkAccessAndExistence) throws OgnlException { boolean result = true; Method m = getSetMethod(context, (target == null) ? null : target.getClass(), propertyName); - if (checkAccessAndExistence) - { - if ((m == null) || !context.getMemberAccess().isAccessible(context, target, m, propertyName)) - { + if (checkAccessAndExistence) { + if ((m == null) || !context.getMemberAccess().isAccessible(context, target, m, propertyName)) { result = false; } } - if (result) - { - if (m != null) - { - Object[] args = _objectArrayPool.create(value); - - try - { - callAppropriateMethod(context, target, target, m.getName(), propertyName, - Collections.nCopies(1, m), args); - } finally - { - _objectArrayPool.recycle(args); - } - } else - { + if (result) { + if (m != null) { + Object[] args = new Object[]{value}; + callAppropriateMethod(context, target, target, m.getName(), propertyName, Collections.nCopies(1, m), args); + } else { result = false; } } @@ -2208,82 +1757,28 @@ public static boolean setMethodValue(OgnlContext context, Object target, String return result; } - public static List getConstructors(Class targetClass) - { - List result; - if ((result = (List) _constructorCache.get(targetClass)) == null) { - synchronized (_constructorCache) { - if ((result = (List) _constructorCache.get(targetClass)) == null) { - _constructorCache.put(targetClass, result = Arrays.asList(targetClass.getConstructors())); - } - } - } - return result; - } - - public static Map getMethods(Class targetClass, boolean staticMethods) - { - ClassCache cache = (staticMethods ? _staticMethodCache : _instanceMethodCache); - Map result; - - if ((result = (Map) cache.get(targetClass)) == null) { - synchronized (cache) - { - if ((result = (Map) cache.get(targetClass)) == null) - { - result = new HashMap(23); - collectMethods(targetClass, result, staticMethods); - cache.put(targetClass, result); - } - } - } - return result; - } - - private static void collectMethods(Class c, Map result, boolean staticMethods) { - Method[] ma; - try { - ma = c.getDeclaredMethods(); - } catch (SecurityException ignored) { - ma = c.getMethods(); - } - for (int i = 0, icount = ma.length; i < icount; i++) - { - if (!isMethodCallable_BridgeOrNonSynthetic(ma[i])) - continue; - - if (Modifier.isStatic(ma[i].getModifiers()) == staticMethods) - addMethodToResult(result, ma[i]); - } - - final Class superclass = c.getSuperclass(); - if (superclass != null) - collectMethods(superclass, result, staticMethods); - - for (final Class iface : c.getInterfaces()) - collectMethods(iface, result, staticMethods); + public static List> getConstructors(Class targetClass) { + return cache.getConstructor(targetClass); } - private static void addMethodToResult(Map result, Method method) - { - List ml = (List) result.get(method.getName()); - if (ml == null) - result.put(method.getName(), ml = new ArrayList()); - ml.add(method); + public static Map> getMethods(Class targetClass, boolean staticMethods) { + DeclaredMethodCacheEntry.MethodType type = staticMethods ? + DeclaredMethodCacheEntry.MethodType.STATIC : + DeclaredMethodCacheEntry.MethodType.NON_STATIC; + DeclaredMethodCacheEntry key = new DeclaredMethodCacheEntry(targetClass, type); + return cache.getMethod(key); } /** * Backport of java.lang.reflect.Method#isDefault() - * + *

    * JDK8+ supports Default Methods for interfaces. Default Methods are defined as: - * public, non-abstract and declared within an interface (must also be non-static). + * public, non-abstract and declared within an interface (must also be non-static). * * @param method The Method to check against the requirements for a Default Method. - * * @return true If the Method qualifies as a Default Method, false otherwise. */ - private static boolean isDefaultMethod(Method method) - { + private static boolean isDefaultMethod(Method method) { return ((method.getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC) && method.getDeclaringClass().isInterface(); @@ -2291,14 +1786,12 @@ private static boolean isDefaultMethod(Method method) /** * Determine if the provided Method is a non-Default public Interface method. - * + *

    * Public non-Default Methods are defined as: - * public, abstract, non-static and declared within an interface. + * public, abstract, non-static and declared within an interface. * * @param method The Method to check against the requirements for a non-Default Method. - * * @return true If method qualifies as a non-Default public Interface method, false otherwise. - * * @since 3.1.25 */ private static boolean isNonDefaultPublicInterfaceMethod(Method method) { @@ -2307,150 +1800,65 @@ private static boolean isNonDefaultPublicInterfaceMethod(Method method) { && method.getDeclaringClass().isInterface(); } - public static Map getAllMethods(Class targetClass, boolean staticMethods) - { - ClassCache cache = (staticMethods ? _staticMethodCache : _instanceMethodCache); - Map result; + /* + * @deprecated use {@link #getMethods(Class, boolean)} directly + */ + @Deprecated + public static Map> getAllMethods(Class targetClass, boolean staticMethods) { + return getMethods(targetClass, staticMethods); + } - if ((result = (Map) cache.get(targetClass)) == null) { - synchronized (cache) - { - if ((result = (Map) cache.get(targetClass)) == null) - { - result = new HashMap(23); + public static List getMethods(Class targetClass, String name, boolean staticMethods) { + return getMethods(targetClass, staticMethods).get(name); + } - for (Class c = targetClass; c != null; c = c.getSuperclass()) - { - Method[] ma = c.getMethods(); - - for (int i = 0, icount = ma.length; i < icount; i++) - { - // skip over synthetic methods - - if (!isMethodCallable(ma[i])) - continue; - - if (Modifier.isStatic(ma[i].getModifiers()) == staticMethods) - { - List ml = (List) result.get(ma[i].getName()); - - if (ml == null) - result.put(ma[i].getName(), ml = new ArrayList()); - - ml.add(ma[i]); - } - } - } - cache.put(targetClass, result); - } - } - } - return result; - } - - public static List getMethods(Class targetClass, String name, boolean staticMethods) - { - return (List) getMethods(targetClass, staticMethods).get(name); + /* + * @deprecated use {@link #getMethods(Class, String, boolean)} directly + */ + @Deprecated + public static List getAllMethods(Class targetClass, String name, boolean staticMethods) { + return getAllMethods(targetClass, staticMethods).get(name); } - public static List getAllMethods(Class targetClass, String name, boolean staticMethods) - { - return (List) getAllMethods(targetClass, staticMethods).get(name); + public static Map getFields(Class targetClass) { + return cache.getField(targetClass); } - public static Map getFields(Class targetClass) - { - Map result; + public static Field getField(Class inClass, String name) { + Field field = getFields(inClass).get(name); - if ((result = (Map) _fieldCache.get(targetClass)) == null) { - synchronized (_fieldCache) { - if ((result = (Map) _fieldCache.get(targetClass)) == null) { - Field fa[]; - - result = new HashMap(23); - try { - fa = targetClass.getDeclaredFields(); - } catch (SecurityException ignored) { - fa = targetClass.getFields(); - } - for (int i = 0; i < fa.length; i++) { - result.put(fa[i].getName(), fa[i]); - } - _fieldCache.put(targetClass, result); - } - } - } - return result; - } - - public static Field getField(Class inClass, String name) - { - Field result = null; - - Object o = getFields(inClass).get(name); - if(o == null) { - synchronized (_fieldCache) { - o = getFields(inClass).get(name); - - if (o == null) { - _superclasses.clear(); - for (Class sc = inClass; (sc != null); sc = sc.getSuperclass()) { - if ((o = getFields(sc).get(name)) == NotFound) - break; - - _superclasses.add(sc); - - if ((result = (Field) o) != null) - break; - } - /* - * Bubble the found value (either cache miss or actual field) to all supeclasses - * that we saw for quicker access next time. - */ - for (int i = 0, icount = _superclasses.size(); i < icount; i++) { - getFields((Class) _superclasses.get(i)).put(name, (result == null) ? NotFound : result); - } - } else { - if (o instanceof Field) { - result = (Field) o; - } else { - if (result == NotFound) - result = null; - } + if (field == null) { + // if field is null, it should search along the superclasses + Class superClass = inClass.getSuperclass(); + while (superClass != null) { + field = getFields(superClass).get(name); + if (field != null) { + return field; } + superClass = superClass.getSuperclass(); } } - else { - if (o instanceof Field) { - result = (Field) o; - } else { - if (result == NotFound) - result = null; - } - } - return result; + return field; } /** * Don't use this method as it doesn't check member access rights via {@link MemberAccess} interface * - * @param context the current execution context. - * @param target the object to invoke the property name get on. + * @param context the current execution context. + * @param target the object to invoke the property name get on. * @param propertyName the name of the property to be set for target. * @return the result invoking field retrieval of propertyName for target. * @throws NoSuchFieldException if the field does not exist. */ @Deprecated public static Object getFieldValue(OgnlContext context, Object target, String propertyName) - throws NoSuchFieldException - { + throws NoSuchFieldException { return getFieldValue(context, target, propertyName, false); } public static Object getFieldValue(OgnlContext context, Object target, String propertyName, boolean checkAccessAndExistence) - throws NoSuchFieldException - { + throws NoSuchFieldException { Object result = null; final Field f = getField((target == null) ? null : target.getClass(), propertyName); @@ -2485,8 +1893,7 @@ public static Object getFieldValue(OgnlContext context, Object target, String pr } public static boolean setFieldValue(OgnlContext context, Object target, String propertyName, Object value) - throws OgnlException - { + throws OgnlException { boolean result = false; try { @@ -2498,7 +1905,7 @@ public static boolean setFieldValue(OgnlContext context, Object target, String p final Object state = context.getMemberAccess().setup(context, target, f, propertyName); try { if (isTypeCompatible(value, f.getType()) - || ((value = getConvertedType(context, target, f, propertyName, value, f.getType())) != null)) { + || ((value = getConvertedType(context, target, f, propertyName, value, f.getType())) != null)) { f.set(target, value); result = true; } @@ -2513,18 +1920,15 @@ public static boolean setFieldValue(OgnlContext context, Object target, String p return result; } - public static boolean isFieldAccessible(OgnlContext context, Object target, Class inClass, String propertyName) - { + public static boolean isFieldAccessible(OgnlContext context, Object target, Class inClass, String propertyName) { return isFieldAccessible(context, target, getField(inClass, propertyName), propertyName); } - public static boolean isFieldAccessible(OgnlContext context, Object target, Field field, String propertyName) - { + public static boolean isFieldAccessible(OgnlContext context, Object target, Field field, String propertyName) { return context.getMemberAccess().isAccessible(context, target, field, propertyName); } - public static boolean hasField(OgnlContext context, Object target, Class inClass, String propertyName) - { + public static boolean hasField(OgnlContext context, Object target, Class inClass, String propertyName) { Field f = getField(inClass, propertyName); return (f != null) && isFieldAccessible(context, target, f, propertyName); @@ -2537,35 +1941,28 @@ public static boolean hasField(OgnlContext context, Object target, Class inClass * May return the {@link Enum} constant value for the given fieldName when className is an {@link Enum}. * May return a {@link Class} instance when the given fieldName is "class". *

    - * @param context The current ognl context - * @param className The name of the class which contains the field - * @param fieldName The name of the field whose value should be returned * - * @return The value of the (static) fieldName + * @param context The current ognl context + * @param className The name of the class which contains the field + * @param fieldName The name of the field whose value should be returned + * @return The value of the (static) fieldName * @throws OgnlException for lots of different reasons. */ public static Object getStaticField(OgnlContext context, String className, String fieldName) - throws OgnlException - { - Exception reason = null; + throws OgnlException { + Exception reason; try { - final Class c = classForName(context, className); - - if (c == null) { - throw new OgnlException("Unable to find class " + className + " when resolving field name of " + fieldName); - } + final Class c = classForName(context, className); /* * Check for virtual static field "class"; this cannot interfere with normal static * fields because it is a reserved word. */ - if (fieldName.equals("class")) - { + if (fieldName.equals("class")) { return c; - } else if (c.isEnum()) - { + } else if (c.isEnum()) { try { - return Enum.valueOf(c, fieldName); + return Enum.valueOf((Class) c, fieldName); } catch (IllegalArgumentException e) { // ignore it, try static field } @@ -2579,7 +1976,7 @@ public static Object getStaticField(OgnlContext context, String className, Strin throw new OgnlException("Field " + fieldName + " of class " + className + " is not static"); } - Object result = null; + Object result; if (context.getMemberAccess().isAccessible(context, null, f, null)) { final Object state = context.getMemberAccess().setup(context, null, f, null); try { @@ -2588,169 +1985,76 @@ public static Object getStaticField(OgnlContext context, String className, Strin context.getMemberAccess().restore(context, null, f, null, state); } } else { - throw new IllegalAccessException("Access to " + fieldName + " of class " + className + " is forbidden"); + throw new IllegalAccessException("Access to " + fieldName + " of class " + className + " is forbidden"); } return result; - } catch (ClassNotFoundException e) { - reason = e; - } catch (NoSuchFieldException e) { - reason = e; - } catch (SecurityException e) { - reason = e; - } catch (IllegalAccessException e) { + } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalAccessException e) { reason = e; } throw new OgnlException("Could not get static field " + fieldName + " from class " + className, reason); } - private static String capitalizeBeanPropertyName(String propertyName) { - if (propertyName.length() == 1) { - return propertyName.toUpperCase(); - } - // don't capitalize getters/setters - if (propertyName.startsWith(GET_PREFIX) && propertyName.endsWith("()")) { - if (Character.isUpperCase(propertyName.substring(3,4).charAt(0))) { - return propertyName; - } - } - if (propertyName.startsWith(SET_PREFIX) && propertyName.endsWith(")")) { - if (Character.isUpperCase(propertyName.substring(3,4).charAt(0))) { - return propertyName; - } - } - if (propertyName.startsWith(IS_PREFIX) && propertyName.endsWith("()")) { - if (Character.isUpperCase(propertyName.substring(2,3).charAt(0))) { - return propertyName; - } - } - char first = propertyName.charAt(0); - char second = propertyName.charAt(1); - if (Character.isLowerCase(first) && Character.isUpperCase(second)) { - return propertyName; + public static List getDeclaredMethods(Class targetClass, String propertyName, boolean findSets) { + String baseName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); + List methods = new ArrayList<>(); + List methodNames = new ArrayList<>(2); + if (findSets) { + methodNames.add(SET_PREFIX + baseName); } else { - char[] chars = propertyName.toCharArray(); - chars[0] = Character.toUpperCase(chars[0]); - return new String(chars); + methodNames.add(IS_PREFIX + baseName); + methodNames.add(GET_PREFIX + baseName); } - } - - public static List getDeclaredMethods(Class targetClass, String propertyName, boolean findSets) - { - List result = null; - ClassCache cache = _declaredMethods[findSets ? 0 : 1]; - - Map propertyCache = (Map) cache.get(targetClass); - if ((propertyCache == null) || ((result = (List) propertyCache.get(propertyName)) == null)) { - synchronized (cache) { - propertyCache = (Map) cache.get(targetClass); - - if ((propertyCache == null) || ((result = (List) propertyCache.get(propertyName)) == null)) { - - String baseName = capitalizeBeanPropertyName(propertyName); - result = new ArrayList(); - collectAccessors(targetClass, baseName, result, findSets); - - if (propertyCache == null) { - cache.put(targetClass, propertyCache = new HashMap(101)); - } - propertyCache.put(propertyName, result.isEmpty() ? NotFoundList : result); - - return result.isEmpty() ? null : result; - } - } - } - return (result == NotFoundList) ? null : result; - } - - private static void collectAccessors(Class c, String baseName, List result, boolean findSets) - { - Method[] methods; - try { - methods = c.getDeclaredMethods(); - } catch (SecurityException ignored) { - methods = c.getMethods(); - } - for (int i = 0; i < methods.length; i++) { - if (c.isInterface()) { - if (isDefaultMethod(methods[i]) || isNonDefaultPublicInterfaceMethod(methods[i])) { - addIfAccessor(result, methods[i], baseName, findSets); - } - continue; + for (String methodName : methodNames) { + DeclaredMethodCacheEntry key = new DeclaredMethodCacheEntry(targetClass); + List methodList = cache.getMethod(key).get(methodName); + if (methodList != null) { + methods.addAll(methodList); } - - if (!isMethodCallable(methods[i])) - continue; - - addIfAccessor(result, methods[i], baseName, findSets); } - final Class superclass = c.getSuperclass(); - if (superclass != null) - collectAccessors(superclass, baseName, result, findSets); - - for (final Class iface : c.getInterfaces()) - collectAccessors(iface, baseName, result, findSets); - } - - private static void addIfAccessor(List result, Method method, String baseName, boolean findSets) - { - final String ms = method.getName(); - if (ms.endsWith(baseName)) { - boolean isSet = false, isIs = false; - if ((isSet = ms.startsWith(SET_PREFIX)) || ms.startsWith(GET_PREFIX) - || (isIs = ms.startsWith(IS_PREFIX))) { - int prefixLength = (isIs ? 2 : 3); - if (isSet == findSets) { - if (baseName.length() == (ms.length() - prefixLength)) { - result.add(method); - } - } - } - } + return methods; } /** * Convenience used to check if a method is a synthetic method so as to avoid * calling un-callable methods. These methods are not considered callable by * OGNL in almost all circumstances. - * + *

    * This method considers any synthetic method (even bridge methods) as being un-callable. * Even though synthetic and bridge methods can technically be called, by default * OGNL excludes them from consideration. - * + *

    * Synthetic methods should be excluded in general, since calling such methods * could introduce unanticipated risks. * * @param m The method to check. * @return True if the method should be callable (non-synthetic), false otherwise. */ - static boolean isMethodCallable(Method m) - { + public static boolean isMethodCallable(Method m) { return !(m.isSynthetic() || m.isBridge()); } /** * Convenience used to check if a method is either a non-synthetic method or * a bridge method. - * - * Warning: This method should NOT be used as a direct replacement for + *

    + * Warning: This method should NOT be used as a direct replacement for * {@link #isMethodCallable(Method)}. Almost all OGNL processing assumes the - * exlcusion of synthetic methods in order to process correctly. Only + * exclusion of synthetic methods in order to process correctly. Only * use this method to determine method callability for any OGNL processing * after careful consideration. - * + *

    * This method considers synthetic methods that are not also bridge methods * as being un-callable. - * + *

    * Synthetic methods should be excluded in general, since calling such methods * could introduce unanticipated risks. * - * @since 3.2.16 - * * @param m The method to check. - * @return True if the method should be callable (non-synethetic or bridge), false otherwise. + * @return True if the method should be callable (non-synthetic or bridge), false otherwise. + * @since 3.2.16 */ static boolean isMethodCallable_BridgeOrNonSynthetic(Method m) { return !m.isSynthetic() || m.isBridge(); // Reference: See PR#104. @@ -2759,16 +2063,11 @@ static boolean isMethodCallable_BridgeOrNonSynthetic(Method m) { /** * cache get methods * - * @param context the current execution context. - * @param targetClass the Class to invoke the property name "getter" retrieval on. + * @param targetClass the Class to invoke the property name "getter" retrieval on. * @param propertyName the name of the property for which a "getter" is sought. * @return the Method representing a "getter" for propertyName of targetClass. - * @throws OgnlException for lots of different reasons. - * @throws IntrospectionException on errors using {@link Introspector}. */ - public static Method getGetMethod(OgnlContext context, Class targetClass, String propertyName) - throws IntrospectionException, OgnlException - { + public static Method getGetMethod(Class targetClass, String propertyName) { // Cache is a map in two levels, so we provide two keys (see comments in ClassPropertyMethodCache below) Method method = cacheGetMethod.get(targetClass, propertyName); if (method == ClassPropertyMethodCache.NULL_REPLACEMENT) { @@ -2777,7 +2076,7 @@ public static Method getGetMethod(OgnlContext context, Class targetClass, String if (method != null) return method; - method = _getGetMethod(context, targetClass, propertyName); // will be null if not found - will cache it anyway + method = _getGetMethod(targetClass, propertyName); // will be null if not found - will cache it anyway cacheGetMethod.put(targetClass, propertyName, method); return method; @@ -2785,90 +2084,72 @@ public static Method getGetMethod(OgnlContext context, Class targetClass, String /** * Returns a qualifying get (getter) method, if one is available for the given targetClass and propertyName. - * + *

    * Note: From OGNL 3.1.25 onward, this method will attempt to find the first get getter method(s) that match: - * 1) First get (getter) method, whether public or not. - * 2) First public get (getter) method, provided the method's declaring class is also public. - * This may be the same as 1), if 1) is also public and its declaring class is also public. - * 3) First public non-Default interface get (getter) method, provided the method's declaring class is also public. - * The order of preference (priority) for the above matches will be 2 (1st public getter), - * 3 (1st public non-Default interface getter), 1 (1st getter of any kind). - * This updated methodology should help limit the need to modify method accessibility levels in some circumstances. - * - * @param context The current execution context. - * @param targetClass Class to search for a get method (getter). + * 1) First get (getter) method, whether public or not. + * 2) First public get (getter) method, provided the method's declaring class is also public. + * This may be the same as 1), if 1) is also public and its declaring class is also public. + * 3) First public non-Default interface get (getter) method, provided the method's declaring class is also public. + * The order of preference (priority) for the above matches will be 2 (1st public getter), + * 3 (1st public non-Default interface getter), 1 (1st getter of any kind). + * This updated methodology should help limit the need to modify method accessibility levels in some circumstances. + * + * @param targetClass Class to search for a get method (getter). * @param propertyName Name of the property for the get method (getter). - * - * @return - * @throws IntrospectionException - * @throws OgnlException */ - private static Method _getGetMethod(OgnlContext context, Class targetClass, String propertyName) - throws IntrospectionException, OgnlException - { - Method result = null; + private static Method _getGetMethod(Class targetClass, String propertyName) { + Method result; - List methods = getDeclaredMethods(targetClass, propertyName, false /* find 'get' methods */); + List methods = getDeclaredMethods(targetClass, propertyName, false /* find 'get' methods */); - if (methods != null) - { - Method firstGetter = null; - Method firstPublicGetter = null; - Method firstNonDefaultPublicInterfaceGetter = null; - for (int i = 0, icount = methods.size(); i < icount; i++) - { - Method m = (Method) methods.get(i); - Class[] mParameterTypes = findParameterTypes(targetClass, m); //getParameterTypes(m); - - if (mParameterTypes.length == 0) - { - boolean declaringClassIsPublic = Modifier.isPublic(m.getDeclaringClass().getModifiers()); - if (firstGetter == null) { - firstGetter = m; - if (_useFirstMatchGetSetLookup) { - break; // Stop looking (emulate original logic, return 1st match) - } - } - if (firstPublicGetter == null && Modifier.isPublic(m.getModifiers()) && declaringClassIsPublic) { - firstPublicGetter = m; - break; // Stop looking (this is the best possible match) - } - if (firstNonDefaultPublicInterfaceGetter == null && isNonDefaultPublicInterfaceMethod(m) && declaringClassIsPublic) { - firstNonDefaultPublicInterfaceGetter = m; + Method firstGetter = null; + Method firstPublicGetter = null; + Method firstNonDefaultPublicInterfaceGetter = null; + for (Method method : methods) { + Class[] mParameterTypes = findParameterTypes(targetClass, method); //getParameterTypes(m); + + if (mParameterTypes.length == 0) { + boolean declaringClassIsPublic = Modifier.isPublic(method.getDeclaringClass().getModifiers()); + if (firstGetter == null) { + firstGetter = method; + if (_useFirstMatchGetSetLookup) { + break; // Stop looking (emulate original logic, return 1st match) } } + if (Modifier.isPublic(method.getModifiers()) && declaringClassIsPublic) { + firstPublicGetter = method; + break; // Stop looking (this is the best possible match) + } + if (firstNonDefaultPublicInterfaceGetter == null && isNonDefaultPublicInterfaceMethod(method) && declaringClassIsPublic) { + firstNonDefaultPublicInterfaceGetter = method; + } } - result = (firstPublicGetter != null) ? firstPublicGetter : - (firstNonDefaultPublicInterfaceGetter != null) ? firstNonDefaultPublicInterfaceGetter : firstGetter; } + result = (firstPublicGetter != null) ? + firstPublicGetter + : (firstNonDefaultPublicInterfaceGetter != null) ? firstNonDefaultPublicInterfaceGetter + : firstGetter; return result; } - public static boolean isMethodAccessible(OgnlContext context, Object target, Method method, String propertyName) - { + public static boolean isMethodAccessible(OgnlContext context, Object target, Method method, String propertyName) { return (method != null) && context.getMemberAccess().isAccessible(context, target, method, propertyName); } - public static boolean hasGetMethod(OgnlContext context, Object target, Class targetClass, String propertyName) - throws IntrospectionException, OgnlException - { - return isMethodAccessible(context, target, getGetMethod(context, targetClass, propertyName), propertyName); + public static boolean hasGetMethod(OgnlContext context, Object target, Class targetClass, String propertyName) { + return isMethodAccessible(context, target, getGetMethod(targetClass, propertyName), propertyName); } /** * cache set methods method * - * @param context the current execution context. - * @param targetClass the Class to invoke the property name "setter" retrieval on. + * @param context the current execution context. + * @param targetClass the Class to invoke the property name "setter" retrieval on. * @param propertyName the name of the property for which a "setter" is sought. * @return the Method representing a "setter" for propertyName of targetClass. - * @throws IntrospectionException on errors using {@link Introspector}. - * @throws OgnlException for lots of different reasons. */ - public static Method getSetMethod(OgnlContext context, Class targetClass, String propertyName) - throws IntrospectionException, OgnlException - { + public static Method getSetMethod(OgnlContext context, Class targetClass, String propertyName) { // Cache is a map in two levels, so we provide two keys (see comments in ClassPropertyMethodCache below) Method method = cacheSetMethod.get(targetClass, propertyName); if (method == ClassPropertyMethodCache.NULL_REPLACEMENT) { @@ -2889,305 +2170,102 @@ public static Method getSetMethod(OgnlContext context, Class targetClass, String /** * Returns a qualifying set (setter) method, if one is available for the given targetClass and propertyName. - * + *

    * Note: From OGNL 3.1.25 onward, this method will attempt to find the first set setter method(s) that match: - * 1) First set (setter) method, whether public or not. - * 2) First public set (setter) method, provided the method's declaring class is also public. - * This may be the same as 1), if 1) is also public and its declaring class is also public. - * 3) First public non-Default interface set (setter) method, provided the method's declaring class is also public. - * The order of preference (priority) for the above matches will be 2 (1st public setter), - * 3 (1st public non-Default interface setter), 1 (1st setter of any kind). - * This updated methodology should help limit the need to modify method accessibility levels in some circumstances. - * - * @param context The current execution context. - * @param targetClass Class to search for a set method (setter). + * 1) First set (setter) method, whether public or not. + * 2) First public set (setter) method, provided the method's declaring class is also public. + * This may be the same as 1), if 1) is also public and its declaring class is also public. + * 3) First public non-Default interface set (setter) method, provided the method's declaring class is also public. + * The order of preference (priority) for the above matches will be 2 (1st public setter), + * 3 (1st public non-Default interface setter), 1 (1st setter of any kind). + * This updated methodology should help limit the need to modify method accessibility levels in some circumstances. + * + * @param context The current execution context. + * @param targetClass Class to search for a set method (setter). * @param propertyName Name of the property for the set method (setter). - * - * @return - * @throws IntrospectionException - * @throws OgnlException */ - private static Method _getSetMethod(OgnlContext context, Class targetClass, String propertyName) - throws IntrospectionException, OgnlException - { - Method result = null; + private static Method _getSetMethod(OgnlContext context, Class targetClass, String propertyName) { + Method result; - List methods = getDeclaredMethods(targetClass, propertyName, true /* find 'set' methods */); + List methods = getDeclaredMethods(targetClass, propertyName, true /* find 'set' methods */); - if (methods != null) - { - Method firstSetter = null; - Method firstPublicSetter = null; - Method firstNonDefaultPublicInterfaceSetter = null; - for (int i = 0, icount = methods.size(); i < icount; i++) - { - Method m = (Method) methods.get(i); - Class[] mParameterTypes = findParameterTypes(targetClass, m); //getParameterTypes(m); - - if (mParameterTypes.length == 1) { - boolean declaringClassIsPublic = Modifier.isPublic(m.getDeclaringClass().getModifiers()); - if (firstSetter == null) { - firstSetter = m; - if (_useFirstMatchGetSetLookup) { - break; // Stop looking (emulate original logic, return 1st match) - } - } - if (firstPublicSetter == null && Modifier.isPublic(m.getModifiers()) && declaringClassIsPublic) { - firstPublicSetter = m; - break; // Stop looking (this is the best possible match) - } - if (firstNonDefaultPublicInterfaceSetter == null && isNonDefaultPublicInterfaceMethod(m) && declaringClassIsPublic) { - firstNonDefaultPublicInterfaceSetter = m; + Method firstSetter = null; + Method firstPublicSetter = null; + Method firstNonDefaultPublicInterfaceSetter = null; + for (Method method : methods) { + Class[] mParameterTypes = findParameterTypes(targetClass, method); //getParameterTypes(m); + + if (mParameterTypes.length == 1) { + boolean declaringClassIsPublic = Modifier.isPublic(method.getDeclaringClass().getModifiers()); + if (firstSetter == null) { + firstSetter = method; + if (_useFirstMatchGetSetLookup) { + break; // Stop looking (emulate original logic, return 1st match) } } + if (Modifier.isPublic(method.getModifiers()) && declaringClassIsPublic) { + firstPublicSetter = method; + break; // Stop looking (this is the best possible match) + } + if (firstNonDefaultPublicInterfaceSetter == null && isNonDefaultPublicInterfaceMethod(method) && declaringClassIsPublic) { + firstNonDefaultPublicInterfaceSetter = method; + } } - - result = (firstPublicSetter != null) ? firstPublicSetter : - (firstNonDefaultPublicInterfaceSetter != null) ? firstNonDefaultPublicInterfaceSetter : firstSetter; } + result = (firstPublicSetter != null) ? firstPublicSetter : + (firstNonDefaultPublicInterfaceSetter != null) ? firstNonDefaultPublicInterfaceSetter : firstSetter; + return result; } - public static final boolean hasSetMethod(OgnlContext context, Object target, Class targetClass, String propertyName) - throws IntrospectionException, OgnlException - { + public static boolean hasSetMethod(OgnlContext context, Object target, Class targetClass, String propertyName) { return isMethodAccessible(context, target, getSetMethod(context, targetClass, propertyName), propertyName); } - public static final boolean hasGetProperty(OgnlContext context, Object target, Object oname) - throws IntrospectionException, OgnlException - { - Class targetClass = (target == null) ? null : target.getClass(); + public static boolean hasGetProperty(OgnlContext context, Object target, Object oname) throws IntrospectionException { + Class targetClass = (target == null) ? null : target.getClass(); String name = oname.toString(); return hasGetMethod(context, target, targetClass, name) || hasField(context, target, targetClass, name); } - public static final boolean hasSetProperty(OgnlContext context, Object target, Object oname) - throws IntrospectionException, OgnlException - { - Class targetClass = (target == null) ? null : target.getClass(); + public static boolean hasSetProperty(OgnlContext context, Object target, Object oname) throws IntrospectionException { + Class targetClass = (target == null) ? null : target.getClass(); String name = oname.toString(); return hasSetMethod(context, target, targetClass, name) || hasField(context, target, targetClass, name); } - private static final boolean indexMethodCheck(List methods) - { - boolean result = false; - - if (methods.size() > 0) { - Method fm = (Method) methods.get(0); - Class[] fmpt = getParameterTypes(fm); - int fmpc = fmpt.length; - Class lastMethodClass = fm.getDeclaringClass(); - - result = true; - for (int i = 1; result && (i < methods.size()); i++) { - Method m = (Method) methods.get(i); - Class c = m.getDeclaringClass(); - - // Check to see if more than one method implemented per class - if (lastMethodClass == c) { - result = false; - } else { - Class[] mpt = getParameterTypes(fm); - int mpc = fmpt.length; - - if (fmpc != mpc) { - result = false; - } - for (int j = 0; j < fmpc; j++) { - if (fmpt[j] != mpt[j]) { - result = false; - break; - } - } - } - lastMethodClass = c; - } - } - return result; - } - - static void findObjectIndexedPropertyDescriptors(Class targetClass, Map intoMap) - throws OgnlException - { - Map allMethods = getMethods(targetClass, false); - Map pairs = new HashMap(101); - - for (Iterator it = allMethods.keySet().iterator(); it.hasNext();) { - String methodName = (String) it.next(); - List methods = (List) allMethods.get(methodName); - - /* - * Only process set/get where there is exactly one implementation of the method per - * class and those implementations are all the same - */ - if (indexMethodCheck(methods)) { - boolean isGet = false, isSet = false; - Method m = (Method) methods.get(0); - - if (((isSet = methodName.startsWith(SET_PREFIX)) || (isGet = methodName.startsWith(GET_PREFIX))) - && (methodName.length() > 3)) { - String propertyName = Introspector.decapitalize(methodName.substring(3)); - Class[] parameterTypes = getParameterTypes(m); - int parameterCount = parameterTypes.length; - - if (isGet && (parameterCount == 1) && (m.getReturnType() != Void.TYPE)) { - List pair = (List) pairs.get(propertyName); - - if (pair == null) { - pairs.put(propertyName, pair = new ArrayList()); - } - pair.add(m); - } - if (isSet && (parameterCount == 2) && (m.getReturnType() == Void.TYPE)) { - List pair = (List) pairs.get(propertyName); - - if (pair == null) { - pairs.put(propertyName, pair = new ArrayList()); - } - pair.add(m); - } - } - } - } - - for (Iterator it = pairs.keySet().iterator(); it.hasNext();) { - String propertyName = (String) it.next(); - List methods = (List) pairs.get(propertyName); - - if (methods.size() == 2) { - Method method1 = (Method) methods.get(0), method2 = (Method) methods.get(1), setMethod = (method1 - .getParameterTypes().length == 2) ? method1 : method2, getMethod = (setMethod == method1) ? method2 - : method1; - Class keyType = getMethod.getParameterTypes()[0], propertyType = getMethod.getReturnType(); - - if (keyType == setMethod.getParameterTypes()[0]) { - if (propertyType == setMethod.getParameterTypes()[1]) { - ObjectIndexedPropertyDescriptor propertyDescriptor; - - try { - propertyDescriptor = new ObjectIndexedPropertyDescriptor(propertyName, propertyType, - getMethod, setMethod); - } catch (Exception ex) { - throw new OgnlException("creating object indexed property descriptor for '" + propertyName - + "' in " + targetClass, ex); - } - intoMap.put(propertyName, propertyDescriptor); - } - } - - } - } - } - /** * This method returns the property descriptors for the given class as a Map. * * @param targetClass The class to get the descriptors for. - * @return Map map of property descriptors for class. - * - * @throws IntrospectionException on errors using {@link Introspector}. - * @throws OgnlException On general errors. + * @return Map of property descriptors for class. */ - public static Map getPropertyDescriptors(Class targetClass) - throws IntrospectionException, OgnlException - { - Map result; - - if ((result = (Map) _propertyDescriptorCache.get(targetClass)) == null) - { - synchronized (_propertyDescriptorCache) { - if ((result = (Map) _propertyDescriptorCache.get(targetClass)) == null) - { - PropertyDescriptor[] pda = Introspector.getBeanInfo(targetClass).getPropertyDescriptors(); - - result = new HashMap(101); - for (int i = 0, icount = pda.length; i < icount; i++) - { - // workaround for Introspector bug 6528714 (bugs.sun.com) - if (pda[i].getReadMethod() != null && !isMethodCallable(pda[i].getReadMethod())) - { - pda[i].setReadMethod(findClosestMatchingMethod(targetClass, pda[i].getReadMethod(), pda[i].getName(), - pda[i].getPropertyType(), true)); - } - if (pda[i].getWriteMethod() != null && !isMethodCallable(pda[i].getWriteMethod())) - { - pda[i].setWriteMethod(findClosestMatchingMethod(targetClass, pda[i].getWriteMethod(), pda[i].getName(), - pda[i].getPropertyType(), false)); - } - - result.put(pda[i].getName(), pda[i]); - } - - findObjectIndexedPropertyDescriptors(targetClass, result); - _propertyDescriptorCache.put(targetClass, result); - } - } - } - return result; + public static Map getPropertyDescriptors(Class targetClass) { + return cache.getPropertyDescriptor(targetClass); } /** * This method returns a PropertyDescriptor for the given class and property name using a Map * lookup (using getPropertyDescriptorsMap()). * - * @param targetClass the class to get the descriptors for. + * @param targetClass the class to get the descriptors for. * @param propertyName the property name of targetClass for which a Descriptor is requested. * @return the PropertyDescriptor for propertyName of targetClass. - * @throws IntrospectionException on errors using {@link Introspector}. * @throws OgnlException On general errors. */ - public static PropertyDescriptor getPropertyDescriptor(Class targetClass, String propertyName) - throws IntrospectionException, OgnlException - { + public static PropertyDescriptor getPropertyDescriptor(Class targetClass, String propertyName) throws OgnlException { if (targetClass == null) return null; - return (PropertyDescriptor) getPropertyDescriptors(targetClass).get(propertyName); + return getPropertyDescriptors(targetClass).get(propertyName); } - static Method findClosestMatchingMethod(Class targetClass, Method m, String propertyName, - Class propertyType, boolean isReadMethod) - { - List methods = getDeclaredMethods(targetClass, propertyName, !isReadMethod); - - if (methods != null) - { - for (Object method1 : methods) - { - Method method = (Method) method1; - - if (method.getName().equals(m.getName()) - && m.getReturnType().isAssignableFrom(m.getReturnType()) - && method.getReturnType() == propertyType - && method.getParameterTypes().length == m.getParameterTypes().length) { - return method; - } - } - } - return m; - } - - public static PropertyDescriptor[] getPropertyDescriptorsArray(Class targetClass) - throws IntrospectionException - { - PropertyDescriptor[] result = null; - - if (targetClass != null) { - if ((result = (PropertyDescriptor[]) _propertyDescriptorCache.get(targetClass)) == null) { - synchronized (_propertyDescriptorCache) { - if ((result = (PropertyDescriptor[]) _propertyDescriptorCache.get(targetClass)) == null) { - _propertyDescriptorCache.put(targetClass, result = Introspector.getBeanInfo(targetClass) - .getPropertyDescriptors()); - } - } - } - } - return result; + public static PropertyDescriptor[] getPropertyDescriptorsArray(Class targetClass) { + Collection propertyDescriptors = getPropertyDescriptors(targetClass).values(); + return propertyDescriptors.toArray(new PropertyDescriptor[0]); } /** @@ -3196,148 +2274,67 @@ public static PropertyDescriptor[] getPropertyDescriptorsArray(Class targetClass * @param targetClass Class for which property descriptor is desired * @param name Name of property * @return PropertyDescriptor of the named property or null if the class has no property with - * the given name - * @throws IntrospectionException on errors using {@link Introspector}. + * the given name */ - public static PropertyDescriptor getPropertyDescriptorFromArray(Class targetClass, String name) - throws IntrospectionException - { + public static PropertyDescriptor getPropertyDescriptorFromArray(Class targetClass, String name) { PropertyDescriptor result = null; - PropertyDescriptor[] pda = getPropertyDescriptorsArray(targetClass); + PropertyDescriptor[] propertyDescriptors = getPropertyDescriptorsArray(targetClass); - for (int i = 0, icount = pda.length; (result == null) && (i < icount); i++) { - if (pda[i].getName().compareTo(name) == 0) { - result = pda[i]; + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + if (result != null) { + break; + } + if (propertyDescriptor.getName().compareTo(name) == 0) { + result = propertyDescriptor; } } return result; } - public static void setMethodAccessor(Class cls, MethodAccessor accessor) - { - synchronized (_methodAccessors) { - _methodAccessors.put(cls, accessor); - } - } - - public static MethodAccessor getMethodAccessor(Class cls) - throws OgnlException - { - MethodAccessor answer = (MethodAccessor) getHandler(cls, _methodAccessors); - if (answer != null) - return answer; - throw new OgnlException("No method accessor for " + cls); + public static void setMethodAccessor(Class clazz, MethodAccessor accessor) { + cache.setMethodAccessor(clazz, accessor); } - public static void setPropertyAccessor(Class cls, PropertyAccessor accessor) - { - synchronized (_propertyAccessors) { - _propertyAccessors.put(cls, accessor); - } + public static MethodAccessor getMethodAccessor(Class clazz) + throws OgnlException { + return cache.getMethodAccessor(clazz); } - public static PropertyAccessor getPropertyAccessor(Class cls) - throws OgnlException - { - PropertyAccessor answer = (PropertyAccessor) getHandler(cls, _propertyAccessors); - if (answer != null) - return answer; - - throw new OgnlException("No property accessor for class " + cls); + public static void setPropertyAccessor(Class clazz, PropertyAccessor accessor) { + cache.setPropertyAccessor(clazz, accessor); } - public static ElementsAccessor getElementsAccessor(Class cls) - throws OgnlException - { - ElementsAccessor answer = (ElementsAccessor) getHandler(cls, _elementsAccessors); - if (answer != null) - return answer; - throw new OgnlException("No elements accessor for class " + cls); + public static PropertyAccessor getPropertyAccessor(Class clazz) + throws OgnlException { + return cache.getPropertyAccessor(clazz); } - public static void setElementsAccessor(Class cls, ElementsAccessor accessor) - { - synchronized (_elementsAccessors) { - _elementsAccessors.put(cls, accessor); - } + public static ElementsAccessor getElementsAccessor(Class clazz) + throws OgnlException { + return cache.getElementsAccessor(clazz); } - public static NullHandler getNullHandler(Class cls) - throws OgnlException - { - NullHandler answer = (NullHandler) getHandler(cls, _nullHandlers); - if (answer != null) - return answer; - throw new OgnlException("No null handler for class " + cls); + public static void setElementsAccessor(Class clazz, ElementsAccessor accessor) { + cache.setElementsAccessor(clazz, accessor); } - public static void setNullHandler(Class cls, NullHandler handler) - { - synchronized (_nullHandlers) { - _nullHandlers.put(cls, handler); - } + public static NullHandler getNullHandler(Class clazz) + throws OgnlException { + return cache.getNullHandler(clazz); } - private static Object getHandler(Class forClass, ClassCache handlers) - { - Object answer = null; - - if ((answer = handlers.get(forClass)) == null) { - synchronized (handlers) { - if ((answer = handlers.get(forClass)) == null) { - Class keyFound; - - if (forClass.isArray()) { - answer = handlers.get(Object[].class); - keyFound = null; - } else { - keyFound = forClass; - outer: - for (Class c = forClass; c != null; c = c.getSuperclass()) { - answer = handlers.get(c); - if (answer == null) { - Class[] interfaces = c.getInterfaces(); - for (int index = 0, count = interfaces.length; index < count; ++index) { - Class iface = interfaces[index]; - - answer = handlers.get(iface); - if (answer == null) { - /* Try super-interfaces */ - answer = getHandler(iface, handlers); - } - if (answer != null) { - keyFound = iface; - break outer; - } - } - } else { - keyFound = c; - break; - } - } - } - if (answer != null) { - if (keyFound != forClass) { - handlers.put(forClass, answer); - } - } - } - } - } - return answer; + public static void setNullHandler(Class clazz, NullHandler handler) { + cache.setNullHandler(clazz, handler); } public static Object getProperty(OgnlContext context, Object source, Object name) - throws OgnlException - { + throws OgnlException { PropertyAccessor accessor; - if (source == null) - { + if (source == null) { throw new OgnlException("source is null for getProperty(null, \"" + name + "\")"); } - if ((accessor = getPropertyAccessor(getTargetClass(source))) == null) - { + if ((accessor = getPropertyAccessor(getTargetClass(source))) == null) { throw new OgnlException("No property accessor for " + getTargetClass(source).getName()); } @@ -3345,8 +2342,7 @@ public static Object getProperty(OgnlContext context, Object source, Object name } public static void setProperty(OgnlContext context, Object target, Object name, Object value) - throws OgnlException - { + throws OgnlException { PropertyAccessor accessor; if (target == null) { @@ -3366,15 +2362,12 @@ public static void setProperty(OgnlContext context, Object target, Object name, * property patterns (returns INDEXED_PROPERTY_INT) or if it conforms to the * OGNL arbitrary object indexable (returns INDEXED_PROPERTY_OBJECT). * - * @param context the current execution context. * @param sourceClass the Class to invoke indexed property type retrieval on. - * @param name the name of the property for which an indexed property type is sought. + * @param name the name of the property for which an indexed property type is sought. * @return the indexed property type (int) for the property name of sourceClass. Returns INDEXED_PROPERTY_NONE if name is not an indexed property. * @throws OgnlException for lots of different reasons. */ - public static int getIndexedPropertyType(OgnlContext context, Class sourceClass, String name) - throws OgnlException - { + public static int getIndexedPropertyType(Class sourceClass, String name) throws OgnlException { int result = INDEXED_PROPERTY_NONE; try { @@ -3395,9 +2388,8 @@ public static int getIndexedPropertyType(OgnlContext context, Class sourceClass, } public static Object getIndexedProperty(OgnlContext context, Object source, String name, Object index) - throws OgnlException - { - Object[] args = _objectArrayPool.create(index); + throws OgnlException { + Object[] args = new Object[]{index}; try { PropertyDescriptor pd = getPropertyDescriptor((source == null) ? null : source.getClass(), name); @@ -3419,16 +2411,12 @@ public static Object getIndexedProperty(OgnlContext context, Object source, Stri throw ex; } catch (Exception ex) { throw new OgnlException("getting indexed property descriptor for '" + name + "'", ex); - } finally { - _objectArrayPool.recycle(args); } } - public static void setIndexedProperty(OgnlContext context, Object source, String name, Object index, - Object value) - throws OgnlException - { - Object[] args = _objectArrayPool.create(index, value); + public static void setIndexedProperty(OgnlContext context, Object source, String name, Object index, Object value) throws OgnlException { + + Object[] args = new Object[]{index, value}; try { PropertyDescriptor pd = getPropertyDescriptor((source == null) ? null : source.getClass(), name); @@ -3450,54 +2438,32 @@ public static void setIndexedProperty(OgnlContext context, Object source, String throw ex; } catch (Exception ex) { throw new OgnlException("getting indexed property descriptor for '" + name + "'", ex); - } finally { - _objectArrayPool.recycle(args); } } - public static EvaluationPool getEvaluationPool() - { + public static EvaluationPool getEvaluationPool() { return _evaluationPool; } - public static ObjectArrayPool getObjectArrayPool() - { - return _objectArrayPool; - } - /** * Registers the specified {@link ClassCacheInspector} with all class reflection based internal * caches. This may have a significant performance impact so be careful using this in production scenarios. * - * @param inspector - * The inspector instance that will be registered with all internal cache instances. + * @param inspector The inspector instance that will be registered with all internal cache instances. */ - public static void setClassCacheInspector(ClassCacheInspector inspector) - { - _cacheInspector = inspector; - - _propertyDescriptorCache.setClassInspector(_cacheInspector); - _constructorCache.setClassInspector(_cacheInspector); - _staticMethodCache.setClassInspector(_cacheInspector); - _instanceMethodCache.setClassInspector(_cacheInspector); - _invokePermissionCache.setClassInspector(_cacheInspector); - _fieldCache.setClassInspector(_cacheInspector); - _declaredMethods[0].setClassInspector(_cacheInspector); - _declaredMethods[1].setClassInspector(_cacheInspector); - } - - public static Method getMethod(OgnlContext context, Class target, String name, - Node[] children, boolean includeStatic) - throws Exception - { - Class[] parms; - if (children != null && children.length > 0) - { + public static void setClassCacheInspector(ClassCacheInspector inspector) { + cache.setClassCacheInspector(inspector); + } + + public static Method getMethod(OgnlContext context, Class target, String name, Node[] children, boolean includeStatic) + throws Exception { + Class[] parms; + if (children != null && children.length > 0) { parms = new Class[children.length]; // used to reset context after loop - Class currType = context.getCurrentType(); - Class currAccessor = context.getCurrentAccessor(); + Class currType = context.getCurrentType(); + Class currAccessor = context.getCurrentAccessor(); Object cast = context.get(ExpressionCompiler.PRE_CAST); context.setCurrentObject(context.getRoot()); @@ -3505,8 +2471,7 @@ public static Method getMethod(OgnlContext context, Class target, String name, context.setCurrentAccessor(null); context.setPreviousType(null); - for (int i=0; i < children.length; i++) - { + for (int i = 0; i < children.length; i++) { children[i].toGetSourceString(context, context.getRoot()); parms[i] = context.getCurrentType(); } @@ -3516,33 +2481,28 @@ public static Method getMethod(OgnlContext context, Class target, String name, context.setCurrentType(currType); context.setCurrentAccessor(currAccessor); context.setCurrentObject(target); - } else - { + } else { parms = EMPTY_CLASS_ARRAY; } - List methods = OgnlRuntime.getMethods(target, name, includeStatic); + List methods = OgnlRuntime.getMethods(target, name, includeStatic); if (methods == null) return null; - for (int i = 0; i < methods.size(); i++) - { - Method m = (Method) methods.get(i); - boolean varArgs = m.isVarArgs(); + for (Method method : methods) { + boolean varArgs = method.isVarArgs(); - if (parms.length != m.getParameterTypes().length && !varArgs) + if (parms.length != method.getParameterTypes().length && !varArgs) continue; - Class[] mparms = m.getParameterTypes(); + Class[] mparms = method.getParameterTypes(); boolean matched = true; - for (int p = 0; p < mparms.length; p++) - { - if (varArgs && mparms[p].isArray()){ + for (int p = 0; p < mparms.length; p++) { + if (varArgs && mparms[p].isArray()) { continue; } - if (parms[p] == null) - { + if (parms[p] == null) { matched = false; break; } @@ -3551,10 +2511,9 @@ public static Method getMethod(OgnlContext context, Class target, String name, continue; if (mparms[p].isPrimitive() - && Character.TYPE != mparms[p] && Byte.TYPE != mparms[p] - && Number.class.isAssignableFrom(parms[p]) - && OgnlRuntime.getPrimitiveWrapperClass(parms[p]) == mparms[p]) - { + && Character.TYPE != mparms[p] && Byte.TYPE != mparms[p] + && Number.class.isAssignableFrom(parms[p]) + && OgnlRuntime.getPrimitiveWrapperClass(parms[p]) == mparms[p]) { continue; } @@ -3563,7 +2522,7 @@ public static Method getMethod(OgnlContext context, Class target, String name, } if (matched) - return m; + return method; } return null; @@ -3574,22 +2533,18 @@ public static Method getMethod(OgnlContext context, Class target, String name, * name. * *

    - * The name matched will also try different combinations like is + name, has + name, get + name, etc.. + * The name matched will also try different combinations like is + name, has + name, get + name, etc.. *

    * - * @param target - * The class to find a matching method against. - * @param name - * The name of the method. + * @param target The class to find a matching method against. + * @param name The name of the method. * @return The most likely matching {@link Method}, or null if none could be found. */ - public static Method getReadMethod(Class target, String name) - { + public static Method getReadMethod(Class target, String name) { return getReadMethod(target, name, null); } - public static Method getReadMethod(Class target, String name, Class[] argClasses) - { + public static Method getReadMethod(Class target, String name, Class[] argClasses) { try { if (name.indexOf('"') >= 0) name = name.replaceAll("\"", ""); @@ -3599,22 +2554,20 @@ public static Method getReadMethod(Class target, String name, Class[] argClasses Method[] methods = target.getMethods(); // exact matches first - ArrayList candidates = new ArrayList(); + ArrayList candidates = new ArrayList<>(); - for (int i = 0; i < methods.length; i++) - { + for (Method method : methods) { // Consider bridge methods as callable (also) for Read methods. - if (!isMethodCallable_BridgeOrNonSynthetic(methods[i])) { + if (!isMethodCallable_BridgeOrNonSynthetic(method)) { continue; } - if ((methods[i].getName().equalsIgnoreCase(name) - || methods[i].getName().toLowerCase().equals("get" + name) - || methods[i].getName().toLowerCase().equals("has" + name) - || methods[i].getName().toLowerCase().equals("is" + name)) - && !methods[i].getName().startsWith("set")) - { - candidates.add(methods[i]); + if ((method.getName().equalsIgnoreCase(name) + || method.getName().toLowerCase().equals("get" + name) + || method.getName().toLowerCase().equals("has" + name) + || method.getName().toLowerCase().equals("is" + name)) + && !method.getName().startsWith("set")) { + candidates.add(method); } } if (!candidates.isEmpty()) { @@ -3623,23 +2576,22 @@ public static Method getReadMethod(Class target, String name, Class[] argClasses return mm.mMethod; } - for (int i = 0; i < methods.length; i++) - { + for (Method method : methods) { // Consider bridge methods as callable (also) for Read methods. - if (!isMethodCallable_BridgeOrNonSynthetic(methods[i])) { + if (!isMethodCallable_BridgeOrNonSynthetic(method)) { continue; } - if (methods[i].getName().equalsIgnoreCase(name) - && !methods[i].getName().startsWith("set") - && !methods[i].getName().startsWith("get") - && !methods[i].getName().startsWith("is") - && !methods[i].getName().startsWith("has") - && methods[i].getReturnType() != Void.TYPE) { + if (method.getName().equalsIgnoreCase(name) + && !method.getName().startsWith("set") + && !method.getName().startsWith("get") + && !method.getName().startsWith("is") + && !method.getName().startsWith("has") + && method.getReturnType() != Void.TYPE) { - Method m = methods[i]; - if (!candidates.contains(m)) - candidates.add(m); + if (!candidates.contains(method)) { + candidates.add(method); + } } } @@ -3660,49 +2612,46 @@ public static Method getReadMethod(Class target, String name, Class[] argClasses if (!candidates.isEmpty()) { // we need to do conversions. // TODO we have to find out which conversions are possible! - int reqArgCount = argClasses==null?0:argClasses.length; + int reqArgCount = argClasses == null ? 0 : argClasses.length; for (Method m : candidates) { if (m.getParameterTypes().length == reqArgCount) return m; } } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } return null; } - public static Method getWriteMethod(Class target, String name) - { + public static Method getWriteMethod(Class target, String name) { return getWriteMethod(target, name, null); } - public static Method getWriteMethod(Class target, String name, Class[] argClasses) - { + public static Method getWriteMethod(Class target, String name, Class[] argClasses) { try { - if (name.indexOf('"') >= 0) + if (name.indexOf('"') >= 0) { name = name.replaceAll("\"", ""); + } BeanInfo info = Introspector.getBeanInfo(target); MethodDescriptor[] methods = info.getMethodDescriptors(); - ArrayList candidates = new ArrayList(); + ArrayList candidates = new ArrayList<>(); - for (int i = 0; i < methods.length; i++) { + for (MethodDescriptor method : methods) { // Consider bridge methods as callable (also) for Write methods. - if (!isMethodCallable_BridgeOrNonSynthetic(methods[i].getMethod())) { + if (!isMethodCallable_BridgeOrNonSynthetic(method.getMethod())) { continue; } - if ((methods[i].getName().equalsIgnoreCase(name) - || methods[i].getName().toLowerCase().equals(name.toLowerCase()) - || methods[i].getName().toLowerCase().equals("set" + name.toLowerCase())) - && !methods[i].getName().startsWith("get")) { + if ((method.getName().equalsIgnoreCase(name) + || method.getName().toLowerCase().equals("set" + name.toLowerCase())) + && !method.getName().startsWith("get")) { - candidates.add(methods[i].getMethod()); + candidates.add(method.getMethod()); } } @@ -3711,23 +2660,21 @@ public static Method getWriteMethod(Class target, String name, Class[] argClasse if (mm != null) return mm.mMethod; } - // try again on pure class - Method[] cmethods = target.getClass().getMethods(); - for (int i = 0; i < cmethods.length; i++) { + // try again on pure class + Method[] cmethods = target.getMethods(); + for (Method cmethod : cmethods) { // Consider bridge methods as callable (also) for Write methods. - if (!isMethodCallable_BridgeOrNonSynthetic(cmethods[i])) { + if (!isMethodCallable_BridgeOrNonSynthetic(cmethod)) { continue; } - if ((cmethods[i].getName().equalsIgnoreCase(name) - || cmethods[i].getName().toLowerCase().equals(name.toLowerCase()) - || cmethods[i].getName().toLowerCase().equals("set" + name.toLowerCase())) - && !cmethods[i].getName().startsWith("get")) { + if ((cmethod.getName().equalsIgnoreCase(name) + || cmethod.getName().toLowerCase().equals("set" + name.toLowerCase())) + && !cmethod.getName().startsWith("get")) { - Method m = methods[i].getMethod(); - if (!candidates.contains(m)) - candidates.add(m); + if (!candidates.contains(cmethod)) + candidates.add(cmethod); } } @@ -3736,8 +2683,8 @@ public static Method getWriteMethod(Class target, String name, Class[] argClasse if (mm != null) return mm.mMethod; } - // try one last time adding a set to beginning + // try one last time adding a set to beginning if (!name.startsWith("set")) { Method ret = OgnlRuntime.getReadMethod(target, "set" + name, argClasses); if (ret != null) @@ -3747,63 +2694,55 @@ public static Method getWriteMethod(Class target, String name, Class[] argClasse if (!candidates.isEmpty()) { // we need to do conversions. // TODO we have to find out which conversions are possible! - int reqArgCount = argClasses==null?0:argClasses.length; + int reqArgCount = argClasses == null ? 0 : argClasses.length; for (Method m : candidates) { if (m.getParameterTypes().length == reqArgCount) return m; } - if ( argClasses == null && candidates.size() == 1 ) { + if (argClasses == null && candidates.size() == 1) { // this seems to be the TestCase TestOgnlRuntime.test_Complicated_Inheritance() - is this a real world use case? return candidates.get(0); } } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } return null; } - public static PropertyDescriptor getProperty(Class target, String name) - { + public static PropertyDescriptor getProperty(Class target, String name) { try { BeanInfo info = Introspector.getBeanInfo(target); PropertyDescriptor[] pds = info.getPropertyDescriptors(); - for (int i = 0; i < pds.length; i++) { - - if (pds[i].getName().equalsIgnoreCase(name) - || pds[i].getName().toLowerCase().equals(name.toLowerCase()) - || pds[i].getName().toLowerCase().endsWith(name.toLowerCase())) - return pds[i]; + for (PropertyDescriptor pd : pds) { + if (pd.getName().equalsIgnoreCase(name) || pd.getName().toLowerCase().endsWith(name.toLowerCase())) + return pd; } - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } return null; } - public static boolean isBoolean(String expression) - { + public static boolean isBoolean(String expression) { if (expression == null) return false; - if ("true".equals(expression) || "false".equals(expression) - || "!true".equals(expression) || "!false".equals(expression) - || "(true)".equals(expression) - || "!(true)".equals(expression) - || "(false)".equals(expression) - || "!(false)".equals(expression) - || expression.startsWith("ognl.OgnlOps")) - return true; - - return false; + return "true".equals(expression) + || "false".equals(expression) + || "!true".equals(expression) + || "!false".equals(expression) + || "(true)".equals(expression) + || "!(true)".equals(expression) + || "(false)".equals(expression) + || "!(false)".equals(expression) + || expression.startsWith("ognl.OgnlOps"); } /** @@ -3811,103 +2750,70 @@ public static boolean isBoolean(String expression) * on the stack to determine if a numeric expression should force object conversion. *

    * Normally used in conjunction with the forceConversion parameter of - * {@link OgnlRuntime#getChildSource(OgnlContext,Object,Node,boolean)}. + * {@link OgnlRuntime#getChildSource(OgnlContext, Object, Node)}. *

    * * @param context The current context. * @return True, if the class types on the stack wouldn't be comparable in a pure numeric expression such as o1 >= o2. */ - public static boolean shouldConvertNumericTypes(OgnlContext context) - { + public static boolean shouldConvertNumericTypes(OgnlContext context) { if (context.getCurrentType() == null || context.getPreviousType() == null) return true; if (context.getCurrentType() == context.getPreviousType() - && context.getCurrentType().isPrimitive() && context.getPreviousType().isPrimitive()) + && context.getCurrentType().isPrimitive() && context.getPreviousType().isPrimitive()) return false; return context.getCurrentType() != null && !context.getCurrentType().isArray() - && context.getPreviousType() != null && !context.getPreviousType().isArray(); + && context.getPreviousType() != null && !context.getPreviousType().isArray(); } /** * Attempts to get the java source string represented by the specific child expression - * via the {@link JavaSource#toGetSourceString(OgnlContext,Object)} interface method. + * via the {@link JavaSource#toGetSourceString(OgnlContext, Object)} interface method. * * @param context The ognl context to pass to the child. * @param target The current object target to use. * @param child The child expression. - * @return The result of calling {@link JavaSource#toGetSourceString(OgnlContext,Object)} plus additional - * enclosures of {@link OgnlOps#convertValue(Object,Class,boolean)} for conversions. - * @throws OgnlException Mandatory exception throwing catching.. (blehh) - */ - public static String getChildSource(OgnlContext context, Object target, Node child) - throws OgnlException - { - return getChildSource(context, target, child, false); - } - - /** - * Attempts to get the java source string represented by the specific child expression - * via the {@link JavaSource#toGetSourceString(OgnlContext,Object)} interface method. - * - * @param context The ognl context to pass to the child. - * @param target The current object target to use. - * @param child The child expression. - * @param forceConversion If true, forces {@link OgnlOps#convertValue(Object,Class)} conversions on the objects. - * @return The result of calling {@link JavaSource#toGetSourceString(OgnlContext,Object)} plus additional - * enclosures of {@link OgnlOps#convertValue(Object,Class,boolean)} for conversions. - * @throws OgnlException Mandatory exception throwing catching.. (blehh) + * @return The result of calling {@link JavaSource#toGetSourceString(OgnlContext, Object)} plus additional + * enclosures of {@link OgnlOps#convertValue(Object, Class, boolean)} for conversions. */ - public static String getChildSource(OgnlContext context, Object target, Node child, boolean forceConversion) - throws OgnlException - { + public static String getChildSource(OgnlContext context, Object target, Node child) { String pre = (String) context.get("_currentChain"); if (pre == null) pre = ""; - try - { + try { child.getValue(context, target); - } catch (NullPointerException e) - { + } catch (NullPointerException e) { // ignore - } catch (ArithmeticException e) - { + } catch (ArithmeticException e) { context.setCurrentType(int.class); return "0"; - } catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } - String source = null; - - try - { + String source; + try { source = child.toGetSourceString(context, target); - } - catch (Throwable t) - { + } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } // handle root / method expressions that may not have proper root java source access - if (!ASTConst.class.isInstance(child) - && (target == null || context.getRoot() != target)) - { + if (!(child instanceof ASTConst) + && (target == null || context.getRoot() != target)) { source = pre + source; } - if (context.getRoot() != null) - { + if (context.getRoot() != null) { source = ExpressionCompiler.getRootExpression(child, context.getRoot(), context) + source; context.setCurrentAccessor(context.getRoot().getClass()); } - if (ASTChain.class.isInstance(child)) - { + if (child instanceof ASTChain) { String cast = (String) context.remove(ExpressionCompiler.PRE_CAST); if (cast == null) cast = ""; @@ -3922,7 +2828,6 @@ public static String getChildSource(OgnlContext context, Object target, Node chi } - /* * The idea behind this class is to provide a very fast way to cache getter/setter methods indexed by their class * and property name. @@ -3943,49 +2848,40 @@ private static final class ClassPropertyMethodCache { // a replacement for signaling when the true cached value is 'null' private static final Method NULL_REPLACEMENT; - private final ConcurrentHashMap,ConcurrentHashMap> cache = - new ConcurrentHashMap,ConcurrentHashMap>(); + private final ConcurrentHashMap, ConcurrentHashMap> cache = + new ConcurrentHashMap<>(); - static - { - try - { + static { + try { NULL_REPLACEMENT = - ClassPropertyMethodCache.class.getDeclaredMethod("get", new Class[] {Class.class,String.class}); - } catch (NoSuchMethodException e) - { + ClassPropertyMethodCache.class.getDeclaredMethod("get", Class.class, String.class); + } catch (NoSuchMethodException e) { throw new RuntimeException(e); // Will never happen, it's our own method, we know it exists } } - ClassPropertyMethodCache() - { + ClassPropertyMethodCache() { super(); } - Method get(Class clazz, String propertyName) - { - ConcurrentHashMap methodsByPropertyName = this.cache.get(clazz); - if (methodsByPropertyName == null) - { + Method get(Class clazz, String propertyName) { + ConcurrentHashMap methodsByPropertyName = this.cache.get(clazz); + if (methodsByPropertyName == null) { return null; } - Method method = methodsByPropertyName.get(propertyName); - return method; + return methodsByPropertyName.get(propertyName); } - void put(Class clazz, String propertyName, Method method) - { - ConcurrentHashMap methodsByPropertyName = this.cache.get(clazz); - if (methodsByPropertyName == null) - { - methodsByPropertyName = new ConcurrentHashMap(); - ConcurrentHashMap old = this.cache.putIfAbsent(clazz, methodsByPropertyName); + void put(Class clazz, String propertyName, Method method) { + ConcurrentHashMap methodsByPropertyName = this.cache.get(clazz); + if (methodsByPropertyName == null) { + methodsByPropertyName = new ConcurrentHashMap<>(); + ConcurrentHashMap old = this.cache.putIfAbsent(clazz, methodsByPropertyName); if (null != old) { methodsByPropertyName = old; } } - methodsByPropertyName.putIfAbsent(propertyName, (method == null? NULL_REPLACEMENT : method)); + methodsByPropertyName.putIfAbsent(propertyName, (method == null ? NULL_REPLACEMENT : method)); } @@ -4002,12 +2898,11 @@ void clear() { /** * Detect the (reported) Major Java version running OGNL. - * + *

    * Should support naming conventions of pre-JDK9 and JDK9+. * See JEP 223: New Version-String Scheme for details. * * @return Detected Major Java Version, or 5 (minimum supported version for OGNL) if unable to detect. - * * @since 3.1.25 */ static int detectMajorJavaVersion() { @@ -4026,31 +2921,30 @@ static int detectMajorJavaVersion() { /** * Parse a Java version string to determine the Major Java version. - * + *

    * Should support naming conventions of pre-JDK9 and JDK9+. * See JEP 223: New Version-String Scheme for details. * * @return Detected Major Java Version, or 5 (minimum supported version for OGNL) if unable to detect. - * * @since 3.1.25 */ static int parseMajorJavaVersion(String versionString) { int majorVersion = -1; try { if (versionString != null && versionString.length() > 0) { - final String[] sections = versionString.split("[\\.\\-\\+]"); + final String[] sections = versionString.split("[.\\-+]"); final int firstSection; final int secondSection; if (sections.length > 0) { // Should not happen, guard anyway if (sections[0].length() > 0) { - if (sections.length > 1 && sections[1].length() > 0) { + if (sections.length > 1 && sections[1].length() > 0) { firstSection = Integer.parseInt(sections[0]); if (sections[1].matches("\\d+")) { secondSection = Integer.parseInt(sections[1]); } else { secondSection = -1; } - } else { + } else { firstSection = Integer.parseInt(sections[0]); secondSection = -1; } @@ -4074,12 +2968,11 @@ static int parseMajorJavaVersion(String versionString) { /** * Returns the value of the flag indicating whether the JDK9+ access handler has been - * been requested (it can then be used if the Major Java Version number is 9+). - * - * Note: Value is controlled by a Java option flag {@link OgnlRuntime#USE_JDK9PLUS_ACESS_HANDLER}. + * been requested (it can then be used if the Major Java Version number is 9+). + *

    + * Note: Value is controlled by a Java option flag {@link OgnlRuntime#USE_JDK9PLUS_ACCESS_HANDLER}. * * @return true if a request to use the JDK9+ access handler is requested, false otherwise (always use pre-JDK9 handler). - * * @since 3.1.25 */ public static boolean getUseJDK9PlusAccessHandlerValue() { @@ -4088,12 +2981,11 @@ public static boolean getUseJDK9PlusAccessHandlerValue() { /** * Returns the value of the flag indicating whether "stricter" invocation is - * in effect or not. - * + * in effect or not. + *

    * Note: Value is controlled by a Java option flag {@link OgnlRuntime#USE_STRICTER_INVOCATION}. * * @return true if stricter invocation is in effect, false otherwise. - * * @since 3.1.25 */ public static boolean getUseStricterInvocationValue() { @@ -4102,15 +2994,13 @@ public static boolean getUseStricterInvocationValue() { /** * Returns the value of the flag indicating whether the OGNL SecurityManager was disabled - * on initialization or not. - * + * on initialization or not. + *

    * Note: Value is controlled by a Java option flag {@link OgnlRuntime#OGNL_SECURITY_MANAGER} using - * the value {@link OgnlRuntime#OGNL_SM_FORCE_DISABLE_ON_INIT}. + * the value {@link OgnlRuntime#OGNL_SM_FORCE_DISABLE_ON_INIT}. * * @return true if OGNL SecurityManager was disabled on initialization, false otherwise. - * * @since 3.1.25 - * */ public static boolean getDisableOgnlSecurityManagerOnInitValue() { return _disableOgnlSecurityManagerOnInit; @@ -4118,12 +3008,11 @@ public static boolean getDisableOgnlSecurityManagerOnInitValue() { /** * Returns an indication as to whether the current state indicates the - * JDK9+ (9 and later) access handler is being used / should be used. This - * is based on a combination of the detected Major Java Version and the - * Java option flag {@link OgnlRuntime#USE_JDK9PLUS_ACESS_HANDLER}. + * JDK9+ (9 and later) access handler is being used / should be used. This + * is based on a combination of the detected Major Java Version and the + * Java option flag {@link OgnlRuntime#USE_JDK9PLUS_ACCESS_HANDLER}. * * @return true if the JDK9 and later access handler is being used / should be used, false otherwise. - * * @since 3.1.25 */ public static boolean usingJDK9PlusAccessHandler() { @@ -4132,12 +3021,11 @@ public static boolean usingJDK9PlusAccessHandler() { /** * Returns the value of the flag indicating whether the old "first match" lookup for - * getters/setters is in effect or not. - * + * getters/setters is in effect or not. + *

    * Note: Value is controlled by a Java option flag {@link OgnlRuntime#USE_FIRSTMATCH_GETSET_LOOKUP}. * * @return true if the old "first match" lookup is in effect, false otherwise. - * * @since 3.1.25 */ public static boolean getUseFirstMatchGetSetLookupValue() { diff --git a/src/main/java/ognl/ParseException.java b/src/main/java/ognl/ParseException.java deleted file mode 100644 index 903ed35d..00000000 --- a/src/main/java/ognl/ParseException.java +++ /dev/null @@ -1,211 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 4.1 */ -/* JavaCCOptions:KEEP_LINE_COL=null */ -package ognl; - -/** - * 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. - */ -public class ParseException extends Exception { - - /** - * 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> - * - * @param currentTokenVal the current Token being processed. - * @param expectedTokenSequencesVal the int[] array containing the expected token sequence values. - * @param tokenImageVal the Token Image value array providing additional state information about the parse failure. - */ - public ParseException(Token currentTokenVal, - int[][] expectedTokenSequencesVal, - String[] tokenImageVal - ) - { - super(""); - specialConstructor = true; - currentToken = currentTokenVal; - expectedTokenSequences = expectedTokenSequencesVal; - tokenImage = tokenImageVal; - } - - /** - * 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. - */ - - public ParseException() { - super(); - specialConstructor = false; - } - - /** - * Constructor with message. - * - * @param message a simple String message indicating the type of parse failure. - */ - public ParseException(String message) { - super(message); - specialConstructor = false; - } - - /** - * This variable determines which constructor was used to create - * this object and thereby affects the semantics of the - * "getMessage" method (see below). - */ - protected boolean specialConstructor; - - /** - * 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. - */ - public Token currentToken; - - /** - * 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. - */ - public int[][] expectedTokenSequences; - - /** - * 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. - */ - public String[] tokenImage; - - /** - * 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. - * - * @return a String message describing the conditions of a parse failure. - */ - public String getMessage() { - if (!specialConstructor) { - return super.getMessage(); - } - StringBuffer expected = new StringBuffer(); - 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.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); - } - if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { - expected.append("..."); - } - expected.append(eol).append(" "); - } - 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 += " " + tokenImage[tok.kind]; - retval += " \""; - retval += add_escapes(tok.image); - retval += " \""; - 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.toString(); - return retval; - } - - /** - * The end of line string for this machine. - */ - protected String eol = System.getProperty("line.separator", "\n"); - - /** - * Used to convert raw characters to their escaped version - * when these raw version cannot be used as part of an ASCII - * string literal. - * - * @param str the String to which escape sequences should be applied. - * @return the String result of str after undergoing escaping. - */ - protected String add_escapes(String str) { - StringBuffer retval = new StringBuffer(); - char ch; - for (int i = 0; i < str.length(); i++) { - switch (str.charAt(i)) - { - case 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.charAt(i)) < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval.append("\\u" + s.substring(s.length() - 4, s.length())); - } else { - retval.append(ch); - } - continue; - } - } - return retval.toString(); - } - -} -/* JavaCC - OriginalChecksum=a0a2f59968d58ccc3e57dbd91056ba6e (do not edit this line) */ diff --git a/src/main/java/ognl/PrimitiveDefaults.java b/src/main/java/ognl/PrimitiveDefaults.java new file mode 100644 index 00000000..de3bf7af --- /dev/null +++ b/src/main/java/ognl/PrimitiveDefaults.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + +class PrimitiveDefaults { + + private final Map, Object> PRIMITIVE_DEFAULTS = new HashMap, Object>(13); + + PrimitiveDefaults() { + PRIMITIVE_DEFAULTS.put(Boolean.TYPE, Boolean.FALSE); + PRIMITIVE_DEFAULTS.put(Boolean.class, Boolean.FALSE); + PRIMITIVE_DEFAULTS.put(Byte.TYPE, (byte) 0); + PRIMITIVE_DEFAULTS.put(Byte.class, (byte) 0); + PRIMITIVE_DEFAULTS.put(Short.TYPE, (short) 0); + PRIMITIVE_DEFAULTS.put(Short.class, (short) 0); + PRIMITIVE_DEFAULTS.put(Character.TYPE, (char) 0); + PRIMITIVE_DEFAULTS.put(Integer.TYPE, 0); + PRIMITIVE_DEFAULTS.put(Long.TYPE, 0L); + PRIMITIVE_DEFAULTS.put(Float.TYPE, 0.0f); + PRIMITIVE_DEFAULTS.put(Double.TYPE, 0.0); + PRIMITIVE_DEFAULTS.put(BigInteger.class, BigInteger.ZERO); + PRIMITIVE_DEFAULTS.put(BigDecimal.class, BigDecimal.ZERO); + } + + Object get(Class cls) { + return PRIMITIVE_DEFAULTS.get(cls); + } + +} diff --git a/src/main/java/ognl/PrimitiveTypes.java b/src/main/java/ognl/PrimitiveTypes.java new file mode 100644 index 00000000..f95416be --- /dev/null +++ b/src/main/java/ognl/PrimitiveTypes.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl; + +import java.util.HashMap; +import java.util.Map; + +class PrimitiveTypes { + + private final Map> PRIMITIVE_TYPES = new HashMap<>(8); + + PrimitiveTypes() { + PRIMITIVE_TYPES.put("boolean", Boolean.TYPE); + PRIMITIVE_TYPES.put("byte", Byte.TYPE); + PRIMITIVE_TYPES.put("short", Short.TYPE); + PRIMITIVE_TYPES.put("char", Character.TYPE); + PRIMITIVE_TYPES.put("int", Integer.TYPE); + PRIMITIVE_TYPES.put("long", Long.TYPE); + PRIMITIVE_TYPES.put("float", Float.TYPE); + PRIMITIVE_TYPES.put("double", Double.TYPE); + } + + Class get(String className) { + return PRIMITIVE_TYPES.get(className); + } + +} diff --git a/src/main/java/ognl/PrimitiveWrapperClasses.java b/src/main/java/ognl/PrimitiveWrapperClasses.java new file mode 100644 index 00000000..ded94d83 --- /dev/null +++ b/src/main/java/ognl/PrimitiveWrapperClasses.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl; + +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * Used to provide primitive type equivalent conversions into and out of native / object types. + */ +class PrimitiveWrapperClasses { + + private final Map, Class> PRIMITIVE_WRAPPER_CLASSES = new IdentityHashMap<>(16); + + PrimitiveWrapperClasses() { + PRIMITIVE_WRAPPER_CLASSES.put(Boolean.TYPE, Boolean.class); + PRIMITIVE_WRAPPER_CLASSES.put(Boolean.class, Boolean.TYPE); + PRIMITIVE_WRAPPER_CLASSES.put(Byte.TYPE, Byte.class); + PRIMITIVE_WRAPPER_CLASSES.put(Byte.class, Byte.TYPE); + PRIMITIVE_WRAPPER_CLASSES.put(Character.TYPE, Character.class); + PRIMITIVE_WRAPPER_CLASSES.put(Character.class, Character.TYPE); + PRIMITIVE_WRAPPER_CLASSES.put(Short.TYPE, Short.class); + PRIMITIVE_WRAPPER_CLASSES.put(Short.class, Short.TYPE); + PRIMITIVE_WRAPPER_CLASSES.put(Integer.TYPE, Integer.class); + PRIMITIVE_WRAPPER_CLASSES.put(Integer.class, Integer.TYPE); + PRIMITIVE_WRAPPER_CLASSES.put(Long.TYPE, Long.class); + PRIMITIVE_WRAPPER_CLASSES.put(Long.class, Long.TYPE); + PRIMITIVE_WRAPPER_CLASSES.put(Float.TYPE, Float.class); + PRIMITIVE_WRAPPER_CLASSES.put(Float.class, Float.TYPE); + PRIMITIVE_WRAPPER_CLASSES.put(Double.TYPE, Double.class); + PRIMITIVE_WRAPPER_CLASSES.put(Double.class, Double.TYPE); + } + + Class get(Class cls) { + return PRIMITIVE_WRAPPER_CLASSES.get(cls); + } + +} diff --git a/src/main/java/ognl/PropertyAccessor.java b/src/main/java/ognl/PropertyAccessor.java index dcab5176..e8935c0c 100644 --- a/src/main/java/ognl/PropertyAccessor.java +++ b/src/main/java/ognl/PropertyAccessor.java @@ -1,37 +1,23 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.Map; - /** * This interface defines methods for setting and getting a property from a target object. A * "property" in this case is a named data value that takes the generic form of an Object---the same @@ -48,59 +34,38 @@ * require properties' names to be Strings, while others may allow them to be other types---for * example, ArrayPropertyAccessor treats Number names as indexes into the target object, which must * be an array. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public interface PropertyAccessor -{ +public interface PropertyAccessor { /** * Extracts and returns the property of the given name from the given target object. * - * @param context - * The current execution context. - * @param target - * the object to get the property from - * @param name - * the name of the property to get. - * + * @param context The current execution context. + * @param target the object to get the property from + * @param name the name of the property to get. * @return the current value of the given property in the given object - * @exception OgnlException - * if there is an error locating the property in the given object + * @throws OgnlException if there is an error locating the property in the given object */ - Object getProperty(Map context, Object target, Object name) - throws OgnlException; + Object getProperty(OgnlContext context, Object target, Object name) throws OgnlException; /** * Sets the value of the property of the given name in the given target object. * - * @param context - * The current execution context. - * @param target - * the object to set the property in - * @param name - * the name of the property to set - * @param value - * the new value for the property. - * - * @exception OgnlException - * if there is an error setting the property in the given object + * @param context The current execution context. + * @param target the object to set the property in + * @param name the name of the property to set + * @param value the new value for the property. + * @throws OgnlException if there is an error setting the property in the given object */ - void setProperty(Map context, Object target, Object name, Object value) - throws OgnlException; + void setProperty(OgnlContext context, Object target, Object name, Object value) throws OgnlException; /** * Returns a java string representing the textual method that should be called to access a * particular element. (ie "get") * - * @param context - * The current execution context. - * @param target - * The current object target on the expression tree being evaluated. - * @param index - * The index object that will be placed inside the string to access the value. - * + * @param context The current execution context. + * @param target The current object target on the expression tree being evaluated. + * @param index The index object that will be placed inside the string to access the value. * @return The source accessor method to call. */ String getSourceAccessor(OgnlContext context, Object target, Object index); @@ -109,12 +74,9 @@ void setProperty(Map context, Object target, Object name, Object value) * Returns a java string representing the textual method that should be called to set a * particular element. (ie "set") * - * @param context - * The current execution context. - * @param target - * The current object target on the expression tree being evaluated. - * @param index - * The index object that will be placed inside the string to set the value. + * @param context The current execution context. + * @param target The current object target on the expression tree being evaluated. + * @param index The index object that will be placed inside the string to set the value. * @return The source setter method to call. */ String getSourceSetter(OgnlContext context, Object target, Object index); diff --git a/src/main/java/ognl/SetPropertyAccessor.java b/src/main/java/ognl/SetPropertyAccessor.java index c0ccc07e..38b1104d 100644 --- a/src/main/java/ognl/SetPropertyAccessor.java +++ b/src/main/java/ognl/SetPropertyAccessor.java @@ -1,56 +1,39 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.util.Map; import java.util.Set; /** * Implementation of PropertyAccessor that uses numbers and dynamic subscripts as * properties to index into Lists. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public class SetPropertyAccessor extends ObjectPropertyAccessor - implements PropertyAccessor // This is here to make javadoc show this class as an implementor -{ - public Object getProperty( Map context, Object target, Object name ) throws OgnlException - { - Set set = (Set)target; +public class SetPropertyAccessor extends ObjectPropertyAccessor implements PropertyAccessor { + + public Object getProperty(OgnlContext context, Object target, Object name) throws OgnlException { + Set set = (Set) target; + + if (name instanceof String) { + Object result; - if ( name instanceof String ) { - Object result; - if (name.equals("size")) { - result = new Integer(set.size()); + result = set.size(); } else { if (name.equals("iterator")) { result = set.iterator(); @@ -58,15 +41,14 @@ public Object getProperty( Map context, Object target, Object name ) throws Ognl if (name.equals("isEmpty")) { result = set.isEmpty() ? Boolean.TRUE : Boolean.FALSE; } else { - result = super.getProperty( context, target, name ); + result = super.getProperty(context, target, name); } } } return result; } - throw new NoSuchPropertyException( target, name ); + throw new NoSuchPropertyException(target, name); } - - + } diff --git a/src/main/java/ognl/SimpleNode.java b/src/main/java/ognl/SimpleNode.java index 94982077..940b321e 100644 --- a/src/main/java/ognl/SimpleNode.java +++ b/src/main/java/ognl/SimpleNode.java @@ -1,33 +1,21 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import ognl.enhance.ExpressionAccessor; @@ -35,72 +23,61 @@ import java.io.PrintWriter; import java.io.Serializable; -/** - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - */ public abstract class SimpleNode implements Node, Serializable { - protected Node _parent; - protected Node[] _children; - protected int _id; - protected OgnlParser _parser; + private static final long serialVersionUID = 996864654828982683L; + + protected Node parent; + protected Node[] children; + protected int id; + protected OgnlParser parser; - private boolean _constantValueCalculated; - private volatile boolean _hasConstantValue; - private Object _constantValue; + private boolean constantValueCalculated; + private volatile boolean hasConstantValue; + private Object constantValue; - private ExpressionAccessor _accessor; + private ExpressionAccessor expressionAccessor; - public SimpleNode(int i) - { - _id = i; + public SimpleNode(int i) { + id = i; } - public SimpleNode(OgnlParser p, int i) - { + public SimpleNode(OgnlParser p, int i) { this(i); - _parser = p; + parser = p; } - public void jjtOpen() - { + public void jjtOpen() { } - public void jjtClose() - { + public void jjtClose() { } - public void jjtSetParent(Node n) - { - _parent = n; + public void jjtSetParent(Node n) { + parent = n; } - public Node jjtGetParent() - { - return _parent; + public Node jjtGetParent() { + return parent; } - public void jjtAddChild(Node n, int i) - { - if (_children == null) { - _children = new Node[i + 1]; - } else if (i >= _children.length) { - Node c[] = new Node[i + 1]; - System.arraycopy(_children, 0, c, 0, _children.length); - _children = c; + public void jjtAddChild(Node n, int i) { + if (children == null) { + children = new Node[i + 1]; + } else if (i >= children.length) { + Node[] c = new Node[i + 1]; + System.arraycopy(children, 0, c, 0, children.length); + children = c; } - _children[i] = n; + children[i] = n; } - public Node jjtGetChild(int i) - { - return _children[i]; + public Node jjtGetChild(int i) { + return children[i]; } - public int jjtGetNumChildren() - { - return (_children == null) ? 0 : _children.length; + public int jjtGetNumChildren() { + return (children == null) ? 0 : children.length; } /* @@ -109,120 +86,100 @@ public int jjtGetNumChildren() * toString(String), otherwise overriding toString() is probably all you need to do. */ - public String toString() - { - return OgnlParserTreeConstants.jjtNodeName[_id]; + public String toString() { + return OgnlParserTreeConstants.jjtNodeName[id]; } // OGNL additions - public String toString(String prefix) - { - return prefix + OgnlParserTreeConstants.jjtNodeName[_id] + " " + toString(); + public String toString(String prefix) { + return prefix + OgnlParserTreeConstants.jjtNodeName[id] + " " + this; } - public String toGetSourceString(OgnlContext context, Object target) - { + public String toGetSourceString(OgnlContext context, Object target) { return toString(); } - public String toSetSourceString(OgnlContext context, Object target) - { + public String toSetSourceString(OgnlContext context, Object target) { return toString(); } /* - * Override this method if you want to customize how the node dumps out its children. - */ + * Override this method if you want to customize how the node dumps out its children. + */ - public void dump(PrintWriter writer, String prefix) - { + public void dump(PrintWriter writer, String prefix) { writer.println(toString(prefix)); - if (_children != null) - { - for (int i = 0; i < _children.length; ++i) - { - SimpleNode n = (SimpleNode) _children[i]; - if (n != null) - { + if (children != null) { + for (Node child : children) { + SimpleNode n = (SimpleNode) child; + if (n != null) { n.dump(writer, prefix + " "); } } } } - public int getIndexInParent() - { + public int getIndexInParent() { int result = -1; - if (_parent != null) - { - int icount = _parent.jjtGetNumChildren(); + if (parent != null) { + int icount = parent.jjtGetNumChildren(); - for (int i = 0; i < icount; i++) - { - if (_parent.jjtGetChild(i) == this) - { + for (int i = 0; i < icount; i++) { + if (parent.jjtGetChild(i) == this) { result = i; break; } } } - + return result; } - public Node getNextSibling() - { + public Node getNextSibling() { Node result = null; int i = getIndexInParent(); - if (i >= 0) - { - int icount = _parent.jjtGetNumChildren(); + if (i >= 0) { + int icount = parent.jjtGetNumChildren(); - if (i < icount) - { - result = _parent.jjtGetChild(i + 1); + if (i < icount) { + result = parent.jjtGetChild(i + 1); } } return result; } protected Object evaluateGetValueBody(OgnlContext context, Object source) - throws OgnlException - { + throws OgnlException { context.setCurrentObject(source); context.setCurrentNode(this); - if (!_constantValueCalculated) - { - _constantValueCalculated = true; + if (!constantValueCalculated) { + constantValueCalculated = true; boolean constant = isConstant(context); - if (constant) - { - _constantValue = getValueBody(context, source); + if (constant) { + constantValue = getValueBody(context, source); } - _hasConstantValue = constant; + hasConstantValue = constant; } - return _hasConstantValue ? _constantValue : getValueBody(context, source); + return hasConstantValue ? constantValue : getValueBody(context, source); } protected void evaluateSetValueBody(OgnlContext context, Object target, Object value) - throws OgnlException - { + throws OgnlException { context.setCurrentObject(target); context.setCurrentNode(this); setValueBody(context, target, value); } public final Object getValue(OgnlContext context, Object source) - throws OgnlException - { + throws OgnlException { Object result = null; if (context.getTraceEvaluations()) { @@ -234,12 +191,7 @@ public final Object getValue(OgnlContext context, Object source) context.pushEvaluation(evaluation); try { result = evaluateGetValueBody(context, source); - } - catch (OgnlException ex) { - evalException = ex; - throw ex; - } - catch (RuntimeException ex) { + } catch (OgnlException | RuntimeException ex) { evalException = ex; throw ex; } finally { @@ -249,10 +201,6 @@ public final Object getValue(OgnlContext context, Object source) if (evalException != null) { eval.setException(evalException); } - if ((evalException == null) && (context.getRootEvaluation() == null) - && !context.getKeepLastEvaluation()) { - pool.recycleAll(eval); - } } } else { result = evaluateGetValueBody(context, source); @@ -263,9 +211,9 @@ public final Object getValue(OgnlContext context, Object source) /** * Subclasses implement this method to do the actual work of extracting the appropriate value from the source object. - * + * * @param context the OgnlContext within which to perform the operation. - * @param source the Object from which to get the value body. + * @param source the Object from which to get the value body. * @return the value body from the source (as appropriate within the provided context). * @throws OgnlException if the value body get fails. */ @@ -273,10 +221,8 @@ protected abstract Object getValueBody(OgnlContext context, Object source) throws OgnlException; public final void setValue(OgnlContext context, Object target, Object value) - throws OgnlException - { - if (context.getTraceEvaluations()) - { + throws OgnlException { + if (context.getTraceEvaluations()) { EvaluationPool pool = OgnlRuntime.getEvaluationPool(); Throwable evalException = null; Evaluation evaluation = pool.create(this, target, true); @@ -284,13 +230,11 @@ public final void setValue(OgnlContext context, Object target, Object value) context.pushEvaluation(evaluation); try { evaluateSetValueBody(context, target, value); - } - catch (OgnlException ex) { + } catch (OgnlException ex) { evalException = ex; ex.setEvaluation(evaluation); throw ex; - } - catch (RuntimeException ex) { + } catch (RuntimeException ex) { evalException = ex; throw ex; } finally { @@ -299,10 +243,6 @@ public final void setValue(OgnlContext context, Object target, Object value) if (evalException != null) { eval.setException(evalException); } - if ((evalException == null) && (context.getRootEvaluation() == null) - && !context.getKeepLastEvaluation()) { - pool.recycleAll(eval); - } } } else { evaluateSetValueBody(context, target, value); @@ -312,60 +252,54 @@ public final void setValue(OgnlContext context, Object target, Object value) /** * Subclasses implement this method to do the actual work of setting the appropriate value in the target object. The default implementation throws an * InappropriateExpressionException, meaning that it cannot be a set expression. - * + * * @param context the OgnlContext within which to perform the operation. - * @param target the Object upon which to set the value body. - * @param value the Object representing the value body to apply to the target. + * @param target the Object upon which to set the value body. + * @param value the Object representing the value body to apply to the target. * @throws OgnlException if the value body set fails. */ protected void setValueBody(OgnlContext context, Object target, Object value) - throws OgnlException - { + throws OgnlException { throw new InappropriateExpressionException(this); } - /** + /** * Returns true iff this node is constant without respect to the children. - * + * * @param context the OgnlContext within which to perform the operation. * @return true if this node is a constant, false otherwise. * @throws OgnlException if the check fails. */ public boolean isNodeConstant(OgnlContext context) - throws OgnlException - { + throws OgnlException { return false; } public boolean isConstant(OgnlContext context) - throws OgnlException - { + throws OgnlException { return isNodeConstant(context); } public boolean isNodeSimpleProperty(OgnlContext context) - throws OgnlException - { + throws OgnlException { return false; } public boolean isSimpleProperty(OgnlContext context) - throws OgnlException - { + throws OgnlException { return isNodeSimpleProperty(context); } public boolean isSimpleNavigationChain(OgnlContext context) - throws OgnlException - { + throws OgnlException { return isSimpleProperty(context); } public boolean isEvalChain(OgnlContext context) throws OgnlException { - if (_children == null) { + if (children == null) { return false; } - for (Node child : _children) { + for (Node child : children) { if (child instanceof SimpleNode) { if (((SimpleNode) child).isEvalChain(context)) { return true; @@ -376,10 +310,10 @@ public boolean isEvalChain(OgnlContext context) throws OgnlException { } public boolean isSequence(OgnlContext context) throws OgnlException { - if (_children == null) { + if (children == null) { return false; } - for (Node child : _children) { + for (Node child : children) { if (child instanceof SimpleNode) { if (((SimpleNode) child).isSequence(context)) { return true; @@ -390,10 +324,10 @@ public boolean isSequence(OgnlContext context) throws OgnlException { } public boolean isOperation(OgnlContext context) throws OgnlException { - if (_children == null) { + if (children == null) { return false; } - for (Node child : _children) { + for (Node child : children) { if (child instanceof SimpleNode) { if (((SimpleNode) child).isOperation(context)) { return true; @@ -404,10 +338,10 @@ public boolean isOperation(OgnlContext context) throws OgnlException { } public boolean isChain(OgnlContext context) throws OgnlException { - if (_children == null) { + if (children == null) { return false; } - for (Node child : _children) { + for (Node child : children) { if (child instanceof SimpleNode) { if (((SimpleNode) child).isChain(context)) { return true; @@ -421,59 +355,51 @@ public boolean isSimpleMethod(OgnlContext context) throws OgnlException { return false; } - protected boolean lastChild(OgnlContext context) - { - return _parent == null || context.get("_lastChild") != null; + protected boolean lastChild(OgnlContext context) { + return parent == null || context.get("_lastChild") != null; } /** * This method may be called from subclasses' jjtClose methods. It flattens the tree under this node by eliminating any children that are of the same class as this * node and copying their children to this node. */ - protected void flattenTree() - { + protected void flattenTree() { boolean shouldFlatten = false; int newSize = 0; - for (int i = 0; i < _children.length; ++i) - if (_children[i].getClass() == getClass()) - { + for (Node child : children) + if (child.getClass() == getClass()) { shouldFlatten = true; - newSize += _children[i].jjtGetNumChildren(); + newSize += child.jjtGetNumChildren(); } else ++newSize; - if (shouldFlatten) - { + if (shouldFlatten) { Node[] newChildren = new Node[newSize]; int j = 0; - for (int i = 0; i < _children.length; ++i) - { - Node c = _children[i]; - if (c.getClass() == getClass()) - { - for (int k = 0; k < c.jjtGetNumChildren(); ++k) + for (Node c : children) { + if (c.getClass() == getClass()) { + for (int k = 0; k < c.jjtGetNumChildren(); ++k) { newChildren[j++] = c.jjtGetChild(k); - - } else + } + } else { newChildren[j++] = c; + } } if (j != newSize) throw new Error("Assertion error: " + j + " != " + newSize); - _children = newChildren; + children = newChildren; } } - public ExpressionAccessor getAccessor() - { - return _accessor; + public ExpressionAccessor getAccessor() { + return expressionAccessor; } - public void setAccessor(ExpressionAccessor accessor) - { - _accessor = accessor; + public void setAccessor(ExpressionAccessor accessor) { + expressionAccessor = accessor; } } diff --git a/src/main/java/ognl/Token.java b/src/main/java/ognl/Token.java deleted file mode 100644 index 9c03d8b4..00000000 --- a/src/main/java/ognl/Token.java +++ /dev/null @@ -1,135 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. Token.java Version 4.1 */ -/* JavaCCOptions:TOKEN_EXTENDS=,KEEP_LINE_COL=null */ -package ognl; - -/** - * Describes the input token stream. - */ - -public class Token { - - /** - * 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. - */ - public int kind; - - /** The line number of the first character of this Token. */ - public int beginLine; - /** The column number of the first character of this Token. */ - public int beginColumn; - /** The line number of the last character of this Token. */ - public int endLine; - /** The column number of the last character of this Token. */ - public int endColumn; - - /** - * The string image of the token. - */ - public String image; - - /** - * 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. - */ - public Token next; - - /** - * 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. - */ - public Token specialToken; - - /** - * An optional attribute value of the Token. - * Tokens which are not used as syntactic sugar will often contain - * meaningful values that will be used later on by the compiler or - * interpreter. This attribute value is often different from the image. - * Any subclass of Token that actually wants to return a non-null value can - * override this method as appropriate. - * - * @return the optional attribute value of this Token. - */ - public Object getValue() { - return null; - } - - /** - * No-argument contructor - */ - public Token() {} - - /** - * Constructs a new token for the specified Image. - * - * @param kind the token Kind. - */ - public Token(int kind) - { - this(kind, null); - } - - /** - * Constructs a new token for the specified Image and Kind. - * - * @param kind the token Kind. - * @param image the token Image String. - */ - public Token(int kind, String image) - { - this.kind = kind; - this.image = image; - } - - /** - * Returns the image. - */ - public String toString() - { - return image; - } - - /** - * 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, simply add something like : - * - * case MyParserConstants.ID : return new IDToken(ofKind, image); - * - * to the following switch statement. Then you can cast matchedToken - * variable to the appropriate type and use sit in your lexical actions. - * - * @param ofKind the token Kind. - * @param image the token Image String. - * @return a new Token of Kind ofKind with Image image. - */ - public static Token newToken(int ofKind, String image) - { - switch(ofKind) - { - default : return new Token(ofKind, image); - } - } - - public static Token newToken(int ofKind) - { - return newToken(ofKind, null); - } - -} -/* JavaCC - OriginalChecksum=771cf4338e4d91b53163152263c004d8 (do not edit this line) */ diff --git a/src/main/java/ognl/TokenMgrError.java b/src/main/java/ognl/TokenMgrError.java deleted file mode 100644 index 843f65d1..00000000 --- a/src/main/java/ognl/TokenMgrError.java +++ /dev/null @@ -1,168 +0,0 @@ -/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 4.1 */ -/* JavaCCOptions: */ -package ognl; - -/** Token Manager Error. */ -public class TokenMgrError extends Error -{ - - /* - * Ordinals for various reasons why an Error of this type can be thrown. - */ - - /** - * Lexical error occurred. - */ - static final int LEXICAL_ERROR = 0; - - /** - * An attempt was made to create a second instance of a static token manager. - */ - static final int STATIC_LEXER_ERROR = 1; - - /** - * Tried to change to an invalid lexical state. - */ - static final int INVALID_LEXICAL_STATE = 2; - - /** - * Detected (and bailed out of) an infinite loop in the token manager. - */ - static final int LOOP_DETECTED = 3; - - /** - * Indicates the reason why the exception is thrown. It will have - * one of the above 4 values. - */ - int errorCode; - - /** - * Replaces unprintable characters by their escaped (or unicode escaped) - * equivalents in the given string - * - * @param str the String to which escape sequences should be applied. - * @return the String result of str after undergoing escaping. - */ - protected static final String addEscapes(String str) { - StringBuffer retval = new StringBuffer(); - char ch; - for (int i = 0; i < str.length(); i++) { - switch (str.charAt(i)) - { - case 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.charAt(i)) < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval.append("\\u" + s.substring(s.length() - 4, s.length())); - } else { - retval.append(ch); - } - continue; - } - } - return retval.toString(); - } - - /** - * 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 lexical error - * curLexState : lexical state in which this error occurred - * errorLine : line number when the error occurred - * errorColumn : column number when the error occurred - * errorAfter : prefix that was seen before this error occurred - * curchar : the offending character - * Note: You can customize the lexical error message by modifying this method. - * - * @param EOFSeen indicates if EOF caused the lexical error. - * @param lexState the lexical state in which this error occurred. - * @param errorLine the line number when the error occurred. - * @param errorColumn the column number when the error occurred. - * @param errorAfter the prefix that was seen before this error occurred. - * @param curChar the offending character that produced the lexical error. - * @return the detail message String for the Error based on the provided parameters. - */ - protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { - return("Lexical error at line " + - errorLine + ", column " + - errorColumn + ". Encountered: " + - (EOFSeen ? " " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + - "after : \"" + addEscapes(errorAfter) + "\""); - } - - /** - * 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. - * - * @return the error message for this TokenMgrError (typically the detailed error message). - */ - public String getMessage() { - return super.getMessage(); - } - - /* - * Constructors of various flavors follow. - */ - - /** No arg constructor. */ - public TokenMgrError() { - } - - /** - * Constructor with message and reason. - * - * @param message the error message String for this error. - * @param reason the reason code for this error. - */ - public TokenMgrError(String message, int reason) { - super(message); - errorCode = reason; - } - - /** - * Full Constructor. - * - * @param EOFSeen indicates if EOF caused the lexical error. - * @param lexState the lexical state in which this error occurred. - * @param errorLine the line number when the error occurred. - * @param errorColumn the column number when the error occurred. - * @param errorAfter the prefix that was seen before this error occurred. - * @param curChar the offending character that produced the lexical error. - * @param reason the reason code for this error. - */ - public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { - this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); - } -} -/* JavaCC - OriginalChecksum=fc24e4c222ec3f01f7c4dd2c636977da (do not edit this line) */ diff --git a/src/main/java/ognl/TypeConverter.java b/src/main/java/ognl/TypeConverter.java index 7447282c..387a1ffd 100644 --- a/src/main/java/ognl/TypeConverter.java +++ b/src/main/java/ognl/TypeConverter.java @@ -1,58 +1,43 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; import java.lang.reflect.Member; -import java.util.Map; /** * Interface for accessing the type conversion facilities within a context. - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) */ -public interface TypeConverter -{ +public interface TypeConverter { /** - * Converts the given value to a given type. The OGNL context, target, member and - * name of property being set are given. This method should be able to handle - * conversion in general without any context, target, member or property name specified. - * @param context OGNL context under which the conversion is being done - * @param target target object in which the property is being set - * @param member member (Constructor, Method or Field) being set - * @param propertyName property name being set - * @param value value to be converted - * @param toType type to which value is converted - * @return Converted value of type toType or TypeConverter.NoConversionPossible to indicate that the - conversion was not possible. + * Converts the given value to a given type. The OGNL context, target, member and + * name of property being set are given. This method should be able to handle + * conversion in general without any context, target, member or property name specified. + * + * @param context OGNL context under which the conversion is being done + * @param target target object in which the property is being set + * @param member member (Constructor, Method or Field) being set + * @param propertyName property name being set + * @param value value to be converted + * @param toType type to which value is converted + * @return Converted value of type toType or TypeConverter.NoConversionPossible to indicate that the + * conversion was not possible. */ - public Object convertValue(Map context, Object target, Member member, String propertyName, Object value, Class toType); + Object convertValue(OgnlContext context, Object target, Member member, String propertyName, Object value, Class toType); } diff --git a/src/main/java/ognl/enhance/ContextClassLoader.java b/src/main/java/ognl/enhance/ContextClassLoader.java index 5440cc3e..59cc7446 100644 --- a/src/main/java/ognl/enhance/ContextClassLoader.java +++ b/src/main/java/ognl/enhance/ContextClassLoader.java @@ -1,55 +1,35 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.enhance; import ognl.OgnlContext; -public class ContextClassLoader extends ClassLoader -{ - private OgnlContext context; +public class ContextClassLoader extends ClassLoader { - /*=================================================================== - Constructors - ===================================================================*/ - public ContextClassLoader(ClassLoader parentClassLoader, OgnlContext context) - { + private final OgnlContext context; + + public ContextClassLoader(ClassLoader parentClassLoader, OgnlContext context) { super(parentClassLoader); this.context = context; } - /*=================================================================== - Overridden methods - ===================================================================*/ - protected Class findClass(String name) throws ClassNotFoundException - { + protected Class findClass(String name) throws ClassNotFoundException { if ((context != null) && (context.getClassResolver() != null)) { return context.getClassResolver().classForName(name, context); } diff --git a/src/main/java/ognl/enhance/EnhancedClassLoader.java b/src/main/java/ognl/enhance/EnhancedClassLoader.java index 88c56b4b..3abf8c2c 100644 --- a/src/main/java/ognl/enhance/EnhancedClassLoader.java +++ b/src/main/java/ognl/enhance/EnhancedClassLoader.java @@ -1,50 +1,31 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.enhance; -public class EnhancedClassLoader extends ClassLoader -{ - /*=================================================================== - Constructors - ===================================================================*/ - public EnhancedClassLoader(ClassLoader parentClassLoader) - { +public class EnhancedClassLoader extends ClassLoader { + + public EnhancedClassLoader(ClassLoader parentClassLoader) { super(parentClassLoader); } - /*=================================================================== - Overridden methods - ===================================================================*/ - public Class defineClass(String enhancedClassName, byte[] byteCode) - { + public Class defineClass(String enhancedClassName, byte[] byteCode) { return defineClass(enhancedClassName, byteCode, 0, byteCode.length); } + } diff --git a/src/main/java/ognl/enhance/ExpressionAccessor.java b/src/main/java/ognl/enhance/ExpressionAccessor.java index 69e1b6f5..ff180021 100644 --- a/src/main/java/ognl/enhance/ExpressionAccessor.java +++ b/src/main/java/ognl/enhance/ExpressionAccessor.java @@ -1,41 +1,48 @@ -/** - * +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package ognl.enhance; import ognl.Node; import ognl.OgnlContext; - /** * Provides pure java expression paths to get/set values from an ognl expression. This * is achieved by taking an existing {@link Node} parsed expression and using bytecode * enhancements to do the same work using pure java vs the ognl interpreter. */ -public interface ExpressionAccessor -{ - +public interface ExpressionAccessor { + /** * Gets the value represented by this expression path, if any. - * - * @param context - * The standard ognl context used for variable substitution/etc. - * @param target - * The root object this expression is meant for. - * @return - * The evaluated value, if any. + * + * @param context The standard ognl context used for variable substitution/etc. + * @param target The root object this expression is meant for. + * @return The evaluated value, if any. */ Object get(OgnlContext context, Object target); - + /** * Sets the value represented by this expression path, if possible. - * - * @param context - * The standard ognl context used for variable substitution/etc. - * @param target - * The root object this expression is meant for. - * @param value - * The new value to set if this expression references a settable property. + * + * @param context The standard ognl context used for variable substitution/etc. + * @param target The root object this expression is meant for. + * @param value The new value to set if this expression references a settable property. */ void set(OgnlContext context, Object target, Object value); @@ -43,8 +50,7 @@ public interface ExpressionAccessor * Used to set the original root expression node on instances where the compiled version * has to fall back to interpreted syntax because of compilation failures. * - * @param expression - * The root expression node used to generate this accessor. + * @param expression The root expression node used to generate this accessor. */ void setExpression(Node expression); } diff --git a/src/main/java/ognl/enhance/ExpressionCompiler.java b/src/main/java/ognl/enhance/ExpressionCompiler.java index cdd0e454..fa137a3e 100644 --- a/src/main/java/ognl/enhance/ExpressionCompiler.java +++ b/src/main/java/ognl/enhance/ExpressionCompiler.java @@ -1,12 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.enhance; -import javassist.*; -import ognl.*; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtField; +import javassist.CtMethod; +import javassist.CtNewConstructor; +import javassist.CtNewMethod; +import javassist.LoaderClassPath; +import javassist.NotFoundException; +import ognl.ASTAnd; +import ognl.ASTChain; +import ognl.ASTConst; +import ognl.ASTCtor; +import ognl.ASTList; +import ognl.ASTMethod; +import ognl.ASTOr; +import ognl.ASTProperty; +import ognl.ASTRootVarRef; +import ognl.ASTStaticField; +import ognl.ASTStaticMethod; +import ognl.ASTVarRef; +import ognl.ClassResolver; +import ognl.ExpressionNode; +import ognl.Node; +import ognl.OgnlContext; +import ognl.OgnlRuntime; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.*; - +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; /** * Responsible for managing/providing functionality related to compiling generated java source @@ -23,35 +69,31 @@ public class ExpressionCompiler implements OgnlExpressionCompiler { /** * {@link ClassLoader} instances. */ - protected Map _loaders = new HashMap(); + protected Map loaders = new HashMap<>(); /** - * Javassist class definition poool. + * Javassist class definition pool. */ - protected ClassPool _pool; + protected ClassPool classPool; - protected int _classCounter = 0; + protected int classCounter = 0; /** * Default constructor, does nothing. */ - public ExpressionCompiler() - { + public ExpressionCompiler() { } /** - * Used by {@link #castExpression(ognl.OgnlContext, ognl.Node, String)} to store the cast java + * Used by {@link #castExpression(OgnlContext, Node, String)} to store the cast java * source string in to the current {@link OgnlContext}. This will either add to the existing * string present if it already exists or create a new instance and store it using the static key * of {@link #PRE_CAST}. * - * @param context - * The current execution context. - * @param cast - * The java source string to store in to the context. + * @param context The current execution context. + * @param cast The java source string to store in to the context. */ - public static void addCastString(OgnlContext context, String cast) - { + public static void addCastString(OgnlContext context, String cast) { String value = (String) context.get(PRE_CAST); if (value != null) @@ -74,11 +116,10 @@ public static void addCastString(OgnlContext context, String cast) * @param type The class to cast a string expression for. * @return The converted raw string version of the class name. */ - public static String getCastString(Class type) - { + public static String getCastString(Class type) { if (type == null) return null; - + return type.isArray() ? type.getComponentType().getName() + "[]" : type.getName(); } @@ -87,48 +128,40 @@ public static String getCastString(Class type) * resolving string for the given node. The callers are mostly ignorant and rely on this method to properly * determine if the expression should be cast at all and take the appropriate actions if it should. * - * @param expression - * The node to check and generate a root expression to if necessary. - * @param root - * The root object for this execution. - * @param context - * The current execution context. + * @param expression The node to check and generate a root expression to if necessary. + * @param root The root object for this execution. + * @param context The current execution context. * @return Either an empty string or a root path java source string compatible with javassist compilations - * from the root object up to the specified {@link Node}. + * from the root object up to the specified {@link Node}. */ - public static String getRootExpression(Node expression, Object root, OgnlContext context) - { + public static String getRootExpression(Node expression, Object root, OgnlContext context) { String rootExpr = ""; if (!shouldCast(expression)) return rootExpr; - if ((!ASTList.class.isInstance(expression) - && !ASTVarRef.class.isInstance(expression) - && !ASTStaticMethod.class.isInstance(expression) - && !ASTStaticField.class.isInstance(expression) - && !ASTConst.class.isInstance(expression) - && !ExpressionNode.class.isInstance(expression) - && !ASTCtor.class.isInstance(expression) - && !ASTStaticMethod.class.isInstance(expression) - && root != null) || (root != null && ASTRootVarRef.class.isInstance(expression))) { - - Class castClass = OgnlRuntime.getCompiler().getRootExpressionClass(expression, context); - - if (castClass.isArray() || ASTRootVarRef.class.isInstance(expression) - || ASTThisVarRef.class.isInstance(expression)) - { + if ((!(expression instanceof ASTList) + && !(expression instanceof ASTVarRef) + && !(expression instanceof ASTStaticMethod) + && !(expression instanceof ASTStaticField) + && !(expression instanceof ASTConst) + && !(expression instanceof ExpressionNode) + && !(expression instanceof ASTCtor) + && root != null) + || + (root != null && expression instanceof ASTRootVarRef)) { + + Class castClass = OgnlRuntime.getCompiler().getRootExpressionClass(expression, context); + + if (castClass.isArray() || expression instanceof ASTRootVarRef) { rootExpr = "((" + getCastString(castClass) + ")$2)"; - if (ASTProperty.class.isInstance(expression) && !((ASTProperty) expression).isIndexedAccess()) + if (expression instanceof ASTProperty && !((ASTProperty) expression).isIndexedAccess()) { rootExpr += "."; - } else if ((ASTProperty.class.isInstance(expression) - && ((ASTProperty) expression).isIndexedAccess()) - || ASTChain.class.isInstance(expression)) - { + } + } else if ((expression instanceof ASTProperty && ((ASTProperty) expression).isIndexedAccess()) || expression instanceof ASTChain) { rootExpr = "((" + getCastString(castClass) + ")$2)"; - } else - { + } else { rootExpr = "((" + getCastString(castClass) + ")$2)."; } } @@ -137,123 +170,108 @@ public static String getRootExpression(Node expression, Object root, OgnlContext } /** - * Used by {@link #getRootExpression(ognl.Node, Object, ognl.OgnlContext)} to determine if the expression + * Used by {@link #getRootExpression(Node, Object, OgnlContext)} to determine if the expression * needs to be cast at all. * - * @param expression - * The node to check against. + * @param expression The node to check against. * @return Yes if the node type should be cast - false otherwise. */ - public static boolean shouldCast(Node expression) - { - if (ASTChain.class.isInstance(expression)) - { + public static boolean shouldCast(Node expression) { + if (expression instanceof ASTChain) { Node child = expression.jjtGetChild(0); - if (ASTConst.class.isInstance(child) - || ASTStaticMethod.class.isInstance(child) - || ASTStaticField.class.isInstance(child) - || (ASTVarRef.class.isInstance(child) && !ASTRootVarRef.class.isInstance(child))) + if (child instanceof ASTConst + || child instanceof ASTStaticMethod + || child instanceof ASTStaticField + || (child instanceof ASTVarRef && !(child instanceof ASTRootVarRef))) return false; } - return !ASTConst.class.isInstance(expression); + return !(expression instanceof ASTConst); } - public String castExpression(OgnlContext context, Node expression, String body) - { + public String castExpression(OgnlContext context, Node expression, String body) { // ok - so this looks really f-ed up ...and it is ..eh if you can do it better I'm all for it :) if (context.getCurrentAccessor() == null - || context.getPreviousType() == null - || context.getCurrentAccessor().isAssignableFrom(context.getPreviousType()) - || (context.getCurrentType() != null + || context.getPreviousType() == null + || context.getCurrentAccessor().isAssignableFrom(context.getPreviousType()) + || (context.getCurrentType() != null && context.getCurrentObject() != null && context.getCurrentType().isAssignableFrom(context.getCurrentObject().getClass()) && context.getCurrentAccessor().isAssignableFrom(context.getPreviousType())) - || body == null || body.trim().length() < 1 - || (context.getCurrentType() != null && context.getCurrentType().isArray() + || body == null || body.trim().length() < 1 + || (context.getCurrentType() != null && context.getCurrentType().isArray() && (context.getPreviousType() == null || context.getPreviousType() != Object.class)) - || ASTOr.class.isInstance(expression) - || ASTAnd.class.isInstance(expression) - || ASTRootVarRef.class.isInstance(expression) - || context.getCurrentAccessor() == Class.class - || (context.get(ExpressionCompiler.PRE_CAST) != null && ((String) context.get(ExpressionCompiler.PRE_CAST)).startsWith("new")) - || ASTStaticField.class.isInstance(expression) - || ASTStaticMethod.class.isInstance(expression) - || (OrderedReturn.class.isInstance(expression) && ((OrderedReturn) expression).getLastExpression() != null)) + || expression instanceof ASTOr + || expression instanceof ASTAnd + || expression instanceof ASTRootVarRef + || context.getCurrentAccessor() == Class.class + || (context.get(ExpressionCompiler.PRE_CAST) != null && ((String) context.get(ExpressionCompiler.PRE_CAST)).startsWith("new")) + || expression instanceof ASTStaticField + || expression instanceof ASTStaticMethod + || (expression instanceof OrderedReturn && ((OrderedReturn) expression).getLastExpression() != null)) return body; -/* System.out.println("castExpression() with expression " + expression + " expr class: " + expression.getClass() + " currentType is: " + context.getCurrentType() - + " previousType: " + context.getPreviousType() - + "\n current Accessor: " + context.getCurrentAccessor() - + " previous Accessor: " + context.getPreviousAccessor() - + " current object " + context.getCurrentObject());*/ - ExpressionCompiler.addCastString(context, "((" + ExpressionCompiler.getCastString(context.getCurrentAccessor()) + ")"); return ")" + body; } - public String getClassName(Class clazz) - { + public String getClassName(Class clazz) { if (clazz.getName().equals("java.util.AbstractList$Itr")) return Iterator.class.getName(); if (Modifier.isPublic(clazz.getModifiers()) && clazz.isInterface()) return clazz.getName(); - return _getClassName(clazz, clazz.getInterfaces()); + return getClassName(clazz, clazz.getInterfaces()); } - private String _getClassName(Class clazz, Class[] intf) - { - for (int i = 0; i < intf.length; i++) - { - if (intf[i].getName().indexOf("util.List") > 0) - return intf[i].getName(); - else if (intf[i].getName().indexOf("Iterator") > 0) - return intf[i].getName(); + private String getClassName(Class clazz, Class[] interfaces) { + for (Class anInterface : interfaces) { + if (anInterface.getName().indexOf("util.List") > 0) { + return anInterface.getName(); + } else if (anInterface.getName().indexOf("Iterator") > 0) { + return anInterface.getName(); + } } - final Class superclazz = clazz.getSuperclass(); - if (superclazz != null) - { - final Class[] superclazzIntf = superclazz.getInterfaces(); - if (superclazzIntf.length > 0) - return _getClassName(superclazz, superclazzIntf); + final Class superClazz = clazz.getSuperclass(); + if (superClazz != null) { + final Class[] superClazzInterfaces = superClazz.getInterfaces(); + if (superClazzInterfaces.length > 0) + return getClassName(superClazz, superClazzInterfaces); } return clazz.getName(); } - public Class getSuperOrInterfaceClass(Method m, Class clazz) - { - Class[] intfs = clazz.getInterfaces(); - if (intfs != null && intfs.length > 0) - { - Class intClass; + public Class getSuperOrInterfaceClass(Method method, Class clazz) { + Class[] interfaces = clazz.getInterfaces(); + if (interfaces.length > 0) { + Class intClass; - for (int i = 0; i < intfs.length; i++) - { - intClass = getSuperOrInterfaceClass(m, intfs[i]); + for (Class anInterface : interfaces) { + intClass = getSuperOrInterfaceClass(method, anInterface); - if (intClass != null) + if (intClass != null) { return intClass; + } - if (Modifier.isPublic(intfs[i].getModifiers()) && containsMethod(m, intfs[i])) - return intfs[i]; + if (Modifier.isPublic(anInterface.getModifiers()) && containsMethod(method, anInterface)) { + return anInterface; + } } } - if (clazz.getSuperclass() != null) - { - Class superClass = getSuperOrInterfaceClass(m, clazz.getSuperclass()); + if (clazz.getSuperclass() != null) { + Class superClass = getSuperOrInterfaceClass(method, clazz.getSuperclass()); if (superClass != null) return superClass; } - if (Modifier.isPublic(clazz.getModifiers()) && containsMethod(m, clazz)) + if (Modifier.isPublic(clazz.getModifiers()) && containsMethod(method, clazz)) return clazz; return null; @@ -263,37 +281,24 @@ public Class getSuperOrInterfaceClass(Method m, Class clazz) * Helper utility method used by compiler to help resolve class->method mappings * during method calls to {@link OgnlExpressionCompiler#getSuperOrInterfaceClass(java.lang.reflect.Method, Class)}. * - * @param m - * The method to check for existance of. - * @param clazz - * The class to check for the existance of a matching method definition to the method passed in. + * @param method The method to check for existance of. + * @param clazz The class to check for the existance of a matching method definition to the method passed in. * @return True if the class contains the specified method, false otherwise. */ - public boolean containsMethod(Method m, Class clazz) - { + public boolean containsMethod(Method method, Class clazz) { Method[] methods = clazz.getMethods(); - if (methods == null) - return false; - - for (int i = 0; i < methods.length; i++) - { - if (methods[i].getName().equals(m.getName()) - && methods[i].getReturnType() == m.getReturnType()) - { - Class[] parms = m.getParameterTypes(); - if (parms == null) - continue; + for (Method value : methods) { + if (value.getName().equals(method.getName()) && value.getReturnType() == method.getReturnType()) { + Class[] parms = method.getParameterTypes(); - Class[] mparms = methods[i].getParameterTypes(); - if (mparms == null || mparms.length != parms.length) + Class[] methodParams = value.getParameterTypes(); + if (methodParams.length != parms.length) continue; boolean parmsMatch = true; - for (int p = 0; p < parms.length; p++) - { - if (parms[p] != mparms[p]) - { + for (int p = 0; p < parms.length; p++) { + if (parms[p] != methodParams[p]) { parmsMatch = false; break; } @@ -302,19 +307,16 @@ public boolean containsMethod(Method m, Class clazz) if (!parmsMatch) continue; - Class[] exceptions = m.getExceptionTypes(); - if (exceptions == null) - continue; + Class[] exceptions = method.getExceptionTypes(); - Class[] mexceptions = methods[i].getExceptionTypes(); - if (mexceptions == null || mexceptions.length != exceptions.length) + Class[] methodExceptions = value.getExceptionTypes(); + if (methodExceptions.length != exceptions.length) { continue; + } boolean exceptionsMatch = true; - for (int e = 0; e < exceptions.length; e++) - { - if (exceptions[e] != mexceptions[e]) - { + for (int e = 0; e < exceptions.length; e++) { + if (exceptions[e] != methodExceptions[e]) { exceptionsMatch = false; break; } @@ -330,77 +332,66 @@ public boolean containsMethod(Method m, Class clazz) return false; } - public Class getInterfaceClass(Class clazz) - { + public Class getInterfaceClass(Class clazz) { if (clazz.getName().equals("java.util.AbstractList$Itr")) return Iterator.class; - if (Modifier.isPublic(clazz.getModifiers()) - && clazz.isInterface() || clazz.isPrimitive()) + if (Modifier.isPublic(clazz.getModifiers()) && clazz.isInterface() || clazz.isPrimitive()) { return clazz; + } - return _getInterfaceClass(clazz, clazz.getInterfaces()); + return getInterfaceClass(clazz, clazz.getInterfaces()); } - private Class _getInterfaceClass(Class clazz, Class[] intf) - { - for (int i = 0; i < intf.length; i++) - { - if (List.class.isAssignableFrom(intf[i])) + private Class getInterfaceClass(Class clazz, Class[] interfaces) { + for (Class anInterface : interfaces) { + if (List.class.isAssignableFrom(anInterface)) return List.class; - else if (Iterator.class.isAssignableFrom(intf[i])) + else if (Iterator.class.isAssignableFrom(anInterface)) return Iterator.class; - else if (Map.class.isAssignableFrom(intf[i])) + else if (Map.class.isAssignableFrom(anInterface)) return Map.class; - else if (Set.class.isAssignableFrom(intf[i])) + else if (Set.class.isAssignableFrom(anInterface)) return Set.class; - else if (Collection.class.isAssignableFrom(intf[i])) + else if (Collection.class.isAssignableFrom(anInterface)) return Collection.class; } - final Class superclazz = clazz.getSuperclass(); - if (superclazz != null) - { - final Class[] superclazzIntf = superclazz.getInterfaces(); - if (superclazzIntf.length > 0) - return _getInterfaceClass(superclazz, superclazzIntf); + final Class superClazz = clazz.getSuperclass(); + if (superClazz != null) { + final Class[] superClazzInterfaces = superClazz.getInterfaces(); + if (superClazzInterfaces.length > 0) + return getInterfaceClass(superClazz, superClazzInterfaces); } return clazz; } - public Class getRootExpressionClass(Node rootNode, OgnlContext context) - { - if (context.getRoot() == null) + public Class getRootExpressionClass(Node rootNode, OgnlContext context) { + if (context.getRoot() == null) { return null; + } - Class ret = context.getRoot().getClass(); + Class ret = context.getRoot().getClass(); - if (context.getFirstAccessor() != null && context.getFirstAccessor().isInstance(context.getRoot())) - { + if (context.getFirstAccessor() != null && context.getFirstAccessor().isInstance(context.getRoot())) { ret = context.getFirstAccessor(); } return ret; } - /* (non-Javadoc) - * @see ognl.enhance.OgnlExpressionCompiler#compileExpression(ognl.OgnlContext, ognl.Node, java.lang.Object) - */ - public void compileExpression(OgnlContext context, Node expression, Object root) - throws Exception - { -// System.out.println("Compiling expr class " + expression.getClass().getName() + " and root " + root); - - if (expression.getAccessor() != null) + public void compileExpression(OgnlContext context, Node expression, Object root) throws Exception { + if (expression.getAccessor() != null) { return; + } String getBody, setBody; EnhancedClassLoader loader = getClassLoader(context); ClassPool pool = getClassPool(context, loader); - CtClass newClass = pool.makeClass(expression.getClass().getName() + expression.hashCode() + _classCounter++ + "Accessor"); + CtClass newClass = pool.makeClass(expression.getClass().getName() + expression.hashCode() + classCounter++ + "Accessor"); newClass.addInterface(getCtClass(ExpressionAccessor.class)); CtClass ognlClass = getCtClass(OgnlContext.class); @@ -415,44 +406,28 @@ public void compileExpression(OgnlContext context, Node expression, Object root) CtMethod setExpression = null; try { - - getBody = generateGetter(context, newClass, objClass, pool, valueGetter, expression, root); - - } catch (UnsupportedCompilationException uc) - { - //uc.printStackTrace(); - + getBody = generateGetter(context, newClass, pool, valueGetter, expression, root); + } catch (UnsupportedCompilationException uc) { nodeMember = new CtField(nodeClass, "_node", newClass); newClass.addField(nodeMember); getBody = generateOgnlGetter(newClass, valueGetter, nodeMember); - if (setExpression == null) - { - setExpression = CtNewMethod.setter("setExpression", nodeMember); - newClass.addMethod(setExpression); - } + setExpression = CtNewMethod.setter("setExpression", nodeMember); + newClass.addMethod(setExpression); } - - try { - - setBody = generateSetter(context, newClass, objClass, pool, valueSetter, expression, root); - - } catch (UnsupportedCompilationException uc) - { - - //uc.printStackTrace(); - if (nodeMember == null) - { + try { + setBody = generateSetter(context, newClass, pool, valueSetter, expression, root); + } catch (UnsupportedCompilationException uc) { + if (nodeMember == null) { nodeMember = new CtField(nodeClass, "_node", newClass); newClass.addField(nodeMember); } setBody = generateOgnlSetter(newClass, valueSetter, nodeMember); - if (setExpression == null) - { + if (setExpression == null) { setExpression = CtNewMethod.setter("setExpression", nodeMember); newClass.addMethod(setExpression); } @@ -461,32 +436,25 @@ public void compileExpression(OgnlContext context, Node expression, Object root) try { newClass.addConstructor(CtNewConstructor.defaultConstructor(newClass)); - Class clazz = pool.toClass(newClass); + Class clazz = pool.toClass(newClass); newClass.detach(); expression.setAccessor((ExpressionAccessor) clazz.newInstance()); // need to set expression on node if the field was just defined. - - if (nodeMember != null) - { + if (nodeMember != null) { expression.getAccessor().setExpression(expression); } } catch (Throwable t) { - //t.printStackTrace(); - throw new RuntimeException("Error compiling expression on object " + root - + " with expression node " + expression + " getter body: " + getBody - + " setter body: " + setBody, t); + + " with expression node " + expression + " getter body: " + getBody + + " setter body: " + setBody, t); } } - protected String generateGetter(OgnlContext context, CtClass newClass, CtClass objClass, ClassPool pool, - CtMethod valueGetter, Node expression, Object root) - throws Exception - { + protected String generateGetter(OgnlContext context, CtClass newClass, ClassPool pool, CtMethod valueGetter, Node expression, Object root) throws Exception { String pre = ""; String post = ""; String body; @@ -503,16 +471,15 @@ protected String generateGetter(OgnlContext context, CtClass newClass, CtClass o String getterCode = expression.toGetSourceString(context, root); if (getterCode == null || getterCode.trim().length() <= 0 - && !ASTVarRef.class.isAssignableFrom(expression.getClass())) + && !ASTVarRef.class.isAssignableFrom(expression.getClass())) getterCode = "null"; String castExpression = (String) context.get(PRE_CAST); if (context.getCurrentType() == null - || context.getCurrentType().isPrimitive() - || Character.class.isAssignableFrom(context.getCurrentType()) - || Object.class == context.getCurrentType()) - { + || context.getCurrentType().isPrimitive() + || Character.class.isAssignableFrom(context.getCurrentType()) + || Object.class == context.getCurrentType()) { pre = pre + " ($w) ("; post = post + ")"; } @@ -520,46 +487,45 @@ protected String generateGetter(OgnlContext context, CtClass newClass, CtClass o String rootExpr = !getterCode.equals("null") ? getRootExpression(expression, root, context) : ""; String noRoot = (String) context.remove("_noRoot"); - if (noRoot != null) + if (noRoot != null) { rootExpr = ""; + } - createLocalReferences(context, pool, newClass, objClass, valueGetter.getParameterTypes()); + createLocalReferences(context, pool, newClass, valueGetter.getParameterTypes()); - if (OrderedReturn.class.isInstance(expression) && ((OrderedReturn) expression).getLastExpression() != null) - { + if (expression instanceof OrderedReturn && ((OrderedReturn) expression).getLastExpression() != null) { body = "{ " - + (ASTMethod.class.isInstance(expression) || ASTChain.class.isInstance(expression) ? rootExpr : "") - + (castExpression != null ? castExpression : "") - + ((OrderedReturn) expression).getCoreExpression() - + " return " + pre + ((OrderedReturn) expression).getLastExpression() - + post - + ";}"; + + (expression instanceof ASTMethod || expression instanceof ASTChain ? rootExpr : "") + + (castExpression != null ? castExpression : "") + + ((OrderedReturn) expression).getCoreExpression() + + " return " + pre + ((OrderedReturn) expression).getLastExpression() + + post + + ";}"; } else { body = "{ return " - + pre - + (castExpression != null ? castExpression : "") - + rootExpr - + getterCode - + post - + ";}"; + + pre + + (castExpression != null ? castExpression : "") + + rootExpr + + getterCode + + post + + ";}"; } - if (body.indexOf("..") >= 0) + if (body.contains("..")) { body = body.replaceAll("\\.\\.", "."); + } -// System.out.println("Getter Body: ===================================\n" + body); valueGetter.setBody(body); newClass.addMethod(valueGetter); return body; } - public String createLocalReference(OgnlContext context, String expression, Class type) - { + public String createLocalReference(OgnlContext context, String expression, Class type) { String referenceName = "ref" + context.incrementLocalReferenceCounter(); - context.addLocalReference(referenceName, new LocalReferenceImpl(referenceName, expression, type)); + context.addLocalReference(referenceName, new OgnlLocalReference(referenceName, expression, type)); String castString = ""; if (!type.isPrimitive()) @@ -568,18 +534,16 @@ public String createLocalReference(OgnlContext context, String expression, Class return castString + referenceName + "($$)"; } - void createLocalReferences(OgnlContext context, ClassPool pool, CtClass clazz, CtClass objClass, CtClass[] params) - throws CannotCompileException, NotFoundException - { - Map referenceMap = context.getLocalReferences(); - if (referenceMap == null || referenceMap.size() < 1) + private void createLocalReferences(OgnlContext context, ClassPool pool, CtClass clazz, CtClass[] params) throws CannotCompileException, NotFoundException { + Map referenceMap = context.getLocalReferences(); + if (referenceMap == null || referenceMap.size() < 1) { return; + } - Iterator it = referenceMap.values().iterator(); + Iterator it = referenceMap.values().iterator(); - while (it.hasNext()) - { - LocalReference ref = (LocalReference) it.next(); + while (it.hasNext()) { + LocalReference ref = it.next(); String widener = ref.getType().isPrimitive() ? " " : " ($w) "; @@ -587,10 +551,9 @@ void createLocalReferences(OgnlContext context, ClassPool pool, CtClass clazz, C body += " return " + widener + ref.getExpression() + ";"; body += "}"; - if (body.indexOf("..") >= 0) + if (body.contains("..")) { body = body.replaceAll("\\.\\.", "."); - -// System.out.println("adding method " + ref.getName() + " with body:\n" + body + " and return type: " + ref.getType()); + } CtMethod method = new CtMethod(pool.get(getCastString(ref.getType())), ref.getName(), params, clazz); method.setBody(body); @@ -601,13 +564,10 @@ void createLocalReferences(OgnlContext context, ClassPool pool, CtClass clazz, C } } - protected String generateSetter(OgnlContext context, CtClass newClass, CtClass objClass, ClassPool pool, - CtMethod valueSetter, Node expression, Object root) - throws Exception - { - if (ExpressionNode.class.isInstance(expression) - || ASTConst.class.isInstance(expression)) + protected String generateSetter(OgnlContext context, CtClass newClass, ClassPool pool, CtMethod valueSetter, Node expression, Object root) throws Exception { + if (expression instanceof ExpressionNode || expression instanceof ASTConst) { throw new UnsupportedCompilationException("Can't compile expression/constant setters."); + } context.setRoot(root); context.remove(PRE_CAST); @@ -629,17 +589,16 @@ protected String generateSetter(OgnlContext context, CtClass newClass, CtClass o if (noRoot != null) pre = ""; - createLocalReferences(context, pool, newClass, objClass, valueSetter.getParameterTypes()); + createLocalReferences(context, pool, newClass, valueSetter.getParameterTypes()); body = "{" - + (castExpression != null ? castExpression : "") - + pre - + setterCode + ";}"; + + (castExpression != null ? castExpression : "") + + pre + + setterCode + ";}"; - if (body.indexOf("..") >= 0) + if (body.contains("..")) { body = body.replaceAll("\\.\\.", "."); - -// System.out.println("Setter Body: ===================================\n" + body); + } valueSetter.setBody(body); newClass.addMethod(valueSetter); @@ -650,21 +609,15 @@ protected String generateSetter(OgnlContext context, CtClass newClass, CtClass o /** * Fail safe getter creation when normal compilation fails. * - * @param clazz - * The javassist class the new method should be attached to. - * @param valueGetter - * The method definition the generated code will be contained within. - * @param node - * The root expression node. + * @param clazz The javassist class the new method should be attached to. + * @param valueGetter The method definition the generated code will be contained within. + * @param node The root expression node. * @return The generated source string for this method, the method will still be - * added via the javassist API either way so this is really a convenience - * for exception reporting / debugging. - * @throws Exception - * If a javassist error occurs. + * added via the javassist API either way so this is really a convenience + * for exception reporting / debugging. + * @throws Exception If a javassist error occurs. */ - protected String generateOgnlGetter(CtClass clazz, CtMethod valueGetter, CtField node) - throws Exception - { + protected String generateOgnlGetter(CtClass clazz, CtMethod valueGetter, CtField node) throws Exception { String body = "return " + node.getName() + ".getValue($1, $2);"; valueGetter.setBody(body); @@ -676,21 +629,16 @@ protected String generateOgnlGetter(CtClass clazz, CtMethod valueGetter, CtField /** * Fail safe setter creation when normal compilation fails. * - * @param clazz - * The javassist class the new method should be attached to. - * @param valueSetter - * The method definition the generated code will be contained within. - * @param node - * The root expression node. + * @param clazz The javassist class the new method should be attached to. + * @param valueSetter The method definition the generated code will be contained within. + * @param node The root expression node. * @return The generated source string for this method, the method will still be - * added via the javassist API either way so this is really a convenience - * for exception reporting / debugging. - * @throws Exception - * If a javassist error occurs. + * added via the javassist API either way so this is really a convenience + * for exception reporting / debugging. + * @throws Exception If a javassist error occurs. */ protected String generateOgnlSetter(CtClass clazz, CtMethod valueSetter, CtField node) - throws Exception - { + throws Exception { String body = node.getName() + ".setValue($1, $2, $3);"; valueSetter.setBody(body); @@ -703,22 +651,20 @@ protected String generateOgnlSetter(CtClass clazz, CtMethod valueSetter, CtField * Creates a {@link ClassLoader} instance compatible with the javassist classloader and normal * OGNL class resolving semantics. * - * @param context - * The current execution context. - * + * @param context The current execution context. * @return The created {@link ClassLoader} instance. */ - protected EnhancedClassLoader getClassLoader(OgnlContext context) - { - EnhancedClassLoader ret = (EnhancedClassLoader) _loaders.get(context.getClassResolver()); + protected EnhancedClassLoader getClassLoader(OgnlContext context) { + EnhancedClassLoader ret = loaders.get(context.getClassResolver()); - if (ret != null) + if (ret != null) { return ret; + } ClassLoader classLoader = new ContextClassLoader(OgnlContext.class.getClassLoader(), context); ret = new EnhancedClassLoader(classLoader); - _loaders.put(context.getClassResolver(), ret); + loaders.put(context.getClassResolver(), ret); return ret; } @@ -726,16 +672,12 @@ protected EnhancedClassLoader getClassLoader(OgnlContext context) /** * Loads a new class definition via javassist for the specified class. * - * @param searchClass - * The class to load. + * @param searchClass The class to load. * @return The javassist class equivalent. - * * @throws NotFoundException When the class definition can't be found. */ - protected CtClass getCtClass(Class searchClass) - throws NotFoundException - { - return _pool.get(searchClass.getName()); + protected CtClass getCtClass(Class searchClass) throws NotFoundException { + return classPool.get(searchClass.getName()); } /** @@ -743,20 +685,18 @@ protected CtClass getCtClass(Class searchClass) * classes. A new class path object is inserted in to the returned {@link ClassPool} using * the passed in loader instance if a new pool needs to be created. * - * @param context - * The current execution context. - * @param loader - * The {@link ClassLoader} instance to use - as returned by {@link #getClassLoader(ognl.OgnlContext)}. + * @param context The current execution context. + * @param loader The {@link ClassLoader} instance to use - as returned by {@link #getClassLoader(OgnlContext)}. * @return The existing or new {@link ClassPool} instance. */ - protected ClassPool getClassPool(OgnlContext context, EnhancedClassLoader loader) - { - if (_pool != null) - return _pool; + protected ClassPool getClassPool(OgnlContext context, EnhancedClassLoader loader) { + if (classPool != null) { + return classPool; + } - _pool = ClassPool.getDefault(); - _pool.insertClassPath(new LoaderClassPath(loader.getParent())); + classPool = ClassPool.getDefault(); + classPool.insertClassPath(new LoaderClassPath(loader.getParent())); - return _pool; + return classPool; } } diff --git a/src/main/java/ognl/enhance/LocalReference.java b/src/main/java/ognl/enhance/LocalReference.java index 86b04478..4299407f 100644 --- a/src/main/java/ognl/enhance/LocalReference.java +++ b/src/main/java/ognl/enhance/LocalReference.java @@ -1,3 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.enhance; /** @@ -15,13 +33,15 @@ public interface LocalReference { /** * The expression that sets the value, ie the part after <class type> refName = <expression>. + * * @return The setting expression. */ String getExpression(); /** * The type of reference. + * * @return The type. */ - Class getType(); + Class getType(); } diff --git a/src/main/java/ognl/enhance/LocalReferenceImpl.java b/src/main/java/ognl/enhance/LocalReferenceImpl.java deleted file mode 100644 index 4b9a9afd..00000000 --- a/src/main/java/ognl/enhance/LocalReferenceImpl.java +++ /dev/null @@ -1,68 +0,0 @@ -package ognl.enhance; - -/** - * Implementation of {@link LocalReference}. - */ -public class LocalReferenceImpl implements LocalReference { - - String _name; - Class _type; - String _expression; - - public LocalReferenceImpl(String name, String expression, Class type) - { - _name = name; - _type = type; - _expression = expression; - } - - public String getName() - { - return _name; - } - - public String getExpression() - { - return _expression; - } - - public Class getType() - { - return _type; - } - - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - LocalReferenceImpl that = (LocalReferenceImpl) o; - - if (_expression != null ? !_expression.equals(that._expression) : that._expression != null) return false; - if (_name != null ? !_name.equals(that._name) : that._name != null) return false; - if (_type != null ? !_type.equals(that._type) : that._type != null) return false; - - return true; - } - - public int hashCode() - { - int result; - result = (_name != null ? _name.hashCode() : 0); - result = 31 * result + (_type != null ? _type.hashCode() : 0); - result = 31 * result + (_expression != null ? _expression.hashCode() : 0); - return result; - } - - public String toString() - { - return "LocalReferenceImpl[" + - "_name='" + _name + '\'' + - '\n' + - ", _type=" + _type + - '\n' + - ", _expression='" + _expression + '\'' + - '\n' + - ']'; - } -} diff --git a/src/main/java/ognl/enhance/OgnlExpressionCompiler.java b/src/main/java/ognl/enhance/OgnlExpressionCompiler.java index 9c8a4ad7..4b13fbe8 100644 --- a/src/main/java/ognl/enhance/OgnlExpressionCompiler.java +++ b/src/main/java/ognl/enhance/OgnlExpressionCompiler.java @@ -1,8 +1,24 @@ -/** +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package ognl.enhance; +import ognl.ASTChain; import ognl.Node; import ognl.OgnlContext; @@ -13,26 +29,24 @@ */ public interface OgnlExpressionCompiler { - /** Static constant used in conjunction with {@link OgnlContext} to store temporary references. */ + /** + * Static constant used in conjunction with {@link OgnlContext} to store temporary references. + */ String ROOT_TYPE = "-ognl-root-type"; /** * The core method executed to compile a specific expression. It is expected that this expression - * always return a {@link Node} with a non null {@link ognl.Node#getAccessor()} instance - unless an exception + * always return a {@link Node} with a non null {@link Node#getAccessor()} instance - unless an exception * is thrown by the method or the statement wasn't compilable in this instance because of missing/null objects * in the expression. These instances may in some cases continue to call this compilation method until the expression * is resolvable. - * - * @param context - * The context of execution. - * @param expression - * The pre-parsed root expression node to compile. - * @param root - * The root object for the expression - may be null in many instances so some implementations - * may exit - * @throws Exception - * If an error occurs compiling the expression and no strategy has been implemented to handle incremental - * expression compilation for incomplete expression members. + * + * @param context The context of execution. + * @param expression The pre-parsed root expression node to compile. + * @param root The root object for the expression - may be null in many instances so some implementations + * may exit + * @throws Exception If an error occurs compiling the expression and no strategy has been implemented to handle incremental + * expression compilation for incomplete expression members. */ void compileExpression(OgnlContext context, Node expression, Object root) throws Exception; @@ -41,12 +55,10 @@ void compileExpression(OgnlContext context, Node expression, Object root) * Gets a javassist safe class string for the given class instance. This is especially * useful for handling array vs. normal class casting strings. * - * @param clazz - * The class to get a string equivalent javassist compatible string reference for. - * + * @param clazz The class to get a string equivalent javassist compatible string reference for. * @return The string equivalent of the class. */ - String getClassName(Class clazz); + String getClassName(Class clazz); /** * Used in places where the preferred {@link #getSuperOrInterfaceClass(java.lang.reflect.Method, Class)} isn't possible @@ -54,53 +66,45 @@ void compileExpression(OgnlContext context, Node expression, Object root) * class so that compiled expressions can reference the interface class of an instance so as not to be compiled in to overly * specific statements. * - * @param clazz - * The class to attempt to find a compatible interface for. + * @param clazz The class to attempt to find a compatible interface for. * @return The same class if no higher level interface could be matched against or the interface equivalent class. */ - Class getInterfaceClass(Class clazz); + Class getInterfaceClass(Class clazz); /** * For the given {@link Method} and class finds the highest level interface class this combination can be cast to. * - * @param m - * The method the class must implement. - * @param clazz - * The current class being worked with. + * @param method The method the class must implement. + * @param clazz The current class being worked with. * @return The highest level interface / class that the referenced {@link Method} is declared in. */ - Class getSuperOrInterfaceClass(Method m, Class clazz); + Class getSuperOrInterfaceClass(Method method, Class clazz); /** * For a given root object type returns the base class type to be used in root referenced expressions. This * helps in some instances where the root objects themselves are compiled javassist instances that need more generic * class equivalents to cast to. * - * @param rootNode - * The root expression node. - * @param context - * The current execution context. + * @param rootNode The root expression node. + * @param context The current execution context. * @return The root expression class type to cast to for this node. */ - Class getRootExpressionClass(Node rootNode, OgnlContext context); + Class getRootExpressionClass(Node rootNode, OgnlContext context); /** - * Used primarily by AST types like {@link ognl.ASTChain} where foo.bar.id type references + * Used primarily by AST types like {@link ASTChain} where foo.bar.id type references * may need to be cast multiple times in order to properly resolve the members in a compiled statement. * *

    - * This method should be using the various {@link ognl.OgnlContext#getCurrentType()} / {@link ognl.OgnlContext#getCurrentAccessor()} methods + * This method should be using the various {@link OgnlContext#getCurrentType()} / {@link OgnlContext#getCurrentAccessor()} methods * to inspect the type stack and properly cast to the right classes - but only when necessary. *

    * - * @param context - * The current execution context. - * @param expression - * The node being checked for casting. - * @param body - * The java source string generated by the given node. + * @param context The current execution context. + * @param expression The node being checked for casting. + * @param body The java source string generated by the given node. * @return The body string parameter plus any additional casting syntax needed to make the expression - * resolvable. + * resolvable. */ String castExpression(OgnlContext context, Node expression, String body); @@ -115,14 +119,11 @@ void compileExpression(OgnlContext context, Node expression, Object root) * accessor / setter methods in the base compiled root object. *

    * - * @param context - * The current execution context. - * @param expression - * The java source expression to dump in to a seperate method reference. - * @param type - * The return type that should be specified for the new method. + * @param context The current execution context. + * @param expression The java source expression to dump in to a seperate method reference. + * @param type The return type that should be specified for the new method. * @return The method name that will be used to reference the sub expression in place of the actual sub expression - * itself. + * itself. */ - String createLocalReference(OgnlContext context, String expression, Class type); + String createLocalReference(OgnlContext context, String expression, Class type); } diff --git a/src/main/java/ognl/enhance/OgnlLocalReference.java b/src/main/java/ognl/enhance/OgnlLocalReference.java new file mode 100644 index 00000000..80f995f5 --- /dev/null +++ b/src/main/java/ognl/enhance/OgnlLocalReference.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.enhance; + +import java.util.Objects; + +/** + * Implementation of {@link LocalReference}. + */ +public class OgnlLocalReference implements LocalReference { + + private final String name; + private final Class clazzType; + private final String expression; + + public OgnlLocalReference(String name, String expression, Class clazzType) { + this.name = name; + this.clazzType = clazzType; + this.expression = expression; + } + + public String getName() { + return name; + } + + public String getExpression() { + return expression; + } + + public Class getType() { + return clazzType; + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + OgnlLocalReference that = (OgnlLocalReference) o; + + if (!Objects.equals(expression, that.expression)) { + return false; + } + if (!Objects.equals(name, that.name)) { + return false; + } + return Objects.equals(clazzType, that.clazzType); + } + + public int hashCode() { + int result; + result = (name != null ? name.hashCode() : 0); + result = 31 * result + (clazzType != null ? clazzType.hashCode() : 0); + result = 31 * result + (expression != null ? expression.hashCode() : 0); + return result; + } + + public String toString() { + return "LocalReferenceImpl[" + + "_name='" + name + '\'' + + '\n' + + ", _type=" + clazzType + + '\n' + + ", _expression='" + expression + '\'' + + '\n' + + ']'; + } +} diff --git a/src/main/java/ognl/enhance/OrderedReturn.java b/src/main/java/ognl/enhance/OrderedReturn.java index 44a7793a..473e29f5 100644 --- a/src/main/java/ognl/enhance/OrderedReturn.java +++ b/src/main/java/ognl/enhance/OrderedReturn.java @@ -1,26 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.enhance; import ognl.Node; - /** - * Marks an ognl expression {@link Node} as needing to have the return portion of a + * Marks an ognl expression {@link Node} as needing to have the return portion of a * getter method happen in a specific part of the generated expression vs just having * the whole expression returned in one chunk. */ -public interface OrderedReturn -{ - +public interface OrderedReturn { + /** * Get the core expression to execute first before any return foo logic is started. - * + * * @return The core standalone expression that shouldn't be pre-pended with a return keyword. */ String getCoreExpression(); - + /** * Gets the last expression to be pre-pended with a return <expression> block. - * + * * @return The expression representing the return portion of a statement; */ String getLastExpression(); diff --git a/src/main/java/ognl/enhance/UnsupportedCompilationException.java b/src/main/java/ognl/enhance/UnsupportedCompilationException.java index 9aa40f9d..1150dd4e 100644 --- a/src/main/java/ognl/enhance/UnsupportedCompilationException.java +++ b/src/main/java/ognl/enhance/UnsupportedCompilationException.java @@ -1,29 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.enhance; - - /** * Thrown during bytecode enhancement conversions of ognl expressions to indicate * that a certain expression isn't currently supported as a pure java bytecode enhanced - * version. - * + * version. + * *

    - * If this exception is thrown it is expected that ognl will fall back to default ognl - * evaluation of the expression. + * If this exception is thrown it is expected that ognl will fall back to default ognl + * evaluation of the expression. *

    - * - * @author jkuhnert */ -public class UnsupportedCompilationException extends RuntimeException -{ - - public UnsupportedCompilationException(String message) - { +public class UnsupportedCompilationException extends RuntimeException { + + private static final long serialVersionUID = 37018630558258414L; + + public UnsupportedCompilationException(String message) { super(message); } - public UnsupportedCompilationException(String message, Throwable cause) - { + public UnsupportedCompilationException(String message, Throwable cause) { super(message, cause); } } diff --git a/src/main/java/ognl/internal/Cache.java b/src/main/java/ognl/internal/Cache.java new file mode 100644 index 00000000..e2fe58c5 --- /dev/null +++ b/src/main/java/ognl/internal/Cache.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal; + +public interface Cache { + + void clear(); + + int getSize(); + + V get(K key) throws CacheException; + + V put(K key, V value); + +} diff --git a/src/main/java/ognl/internal/CacheException.java b/src/main/java/ognl/internal/CacheException.java new file mode 100644 index 00000000..54a906ad --- /dev/null +++ b/src/main/java/ognl/internal/CacheException.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal; + +public class CacheException extends RuntimeException { + + private static final long serialVersionUID = 3909399641531596633L; + + public CacheException(Throwable e) { + super(e.getMessage(), e); + } + +} diff --git a/src/main/java/ognl/internal/CacheFactory.java b/src/main/java/ognl/internal/CacheFactory.java new file mode 100644 index 00000000..42ad3090 --- /dev/null +++ b/src/main/java/ognl/internal/CacheFactory.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal; + +import ognl.internal.entry.CacheEntryFactory; +import ognl.internal.entry.ClassCacheEntryFactory; + +public interface CacheFactory { + + Cache createCache(CacheEntryFactory entryFactory); + + ClassCache createClassCache(); + + ClassCache createClassCache(ClassCacheEntryFactory entryFactory); + +} diff --git a/src/main/java/ognl/internal/ClassCache.java b/src/main/java/ognl/internal/ClassCache.java index 818d8bd8..c0292fd2 100644 --- a/src/main/java/ognl/internal/ClassCache.java +++ b/src/main/java/ognl/internal/ClassCache.java @@ -1,3 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.internal; import ognl.ClassCacheInspector; @@ -5,15 +23,8 @@ /** * This is a highly specialized map for storing values keyed by Class objects. */ -public interface ClassCache { +public interface ClassCache extends Cache, V> { void setClassInspector(ClassCacheInspector inspector); - void clear(); - - int getSize(); - - Object get(Class key); - - Object put(Class key, Object value); } diff --git a/src/main/java/ognl/internal/ClassCacheHandler.java b/src/main/java/ognl/internal/ClassCacheHandler.java new file mode 100644 index 00000000..26190a1a --- /dev/null +++ b/src/main/java/ognl/internal/ClassCacheHandler.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal; + +public class ClassCacheHandler { + + private ClassCacheHandler() { + } + + public static T getHandler(Class forClass, ClassCache handlers) throws CacheException { + T answer; + + synchronized (handlers) { + answer = handlers.get(forClass); + if (answer == null) { + Class keyFound; + + if (forClass.isArray()) { + answer = handlers.get(Object[].class); + keyFound = null; + } else { + keyFound = forClass; + outer: + for (Class clazz = forClass; clazz != null; clazz = clazz.getSuperclass()) { + answer = handlers.get(clazz); + if (answer != null) { + keyFound = clazz; + break; + } + Class[] interfaces = clazz.getInterfaces(); + for (Class iface : interfaces) { + answer = handlers.get(iface); + if (answer == null) { + /* Try super-interfaces */ + answer = getHandler(iface, handlers); + } + if (answer != null) { + keyFound = iface; + break outer; + } + } + } + } + if (answer != null && keyFound != forClass) { + handlers.put(forClass, answer); + } + } + } + return answer; + } + +} diff --git a/src/main/java/ognl/internal/ClassCacheImpl.java b/src/main/java/ognl/internal/ClassCacheImpl.java deleted file mode 100644 index c882602d..00000000 --- a/src/main/java/ognl/internal/ClassCacheImpl.java +++ /dev/null @@ -1,120 +0,0 @@ -package ognl.internal; - -import ognl.ClassCacheInspector; - -import java.util.Arrays; - -/** - * Implementation of {@link ClassCache}. - */ -public class ClassCacheImpl implements ClassCache { - - /* this MUST be a power of 2 */ - private static final int TABLE_SIZE = 512; - /* ...and now you see why. The table size is used as a mask for generating hashes */ - private static final int TABLE_SIZE_MASK = TABLE_SIZE - 1; - - private Entry[] _table; - private ClassCacheInspector _classInspector; - private int _size = 0; - - public ClassCacheImpl() - { - _table = new Entry[TABLE_SIZE]; - } - - public void setClassInspector(ClassCacheInspector inspector) - { - _classInspector = inspector; - } - - public void clear() - { - for (int i=0; i < _table.length; i++) - { - _table[i] = null; - } - - _size = 0; - } - - public int getSize() - { - return _size; - } - - public final Object get(Class key) - { - Object result = null; - int i = key.hashCode() & TABLE_SIZE_MASK; - - for (Entry entry = _table[i]; entry != null; entry = entry.next) - { - if (entry.key == key) - { - result = entry.value; - break; - } - } - - return result; - } - - public final Object put(Class key, Object value) - { - if (_classInspector != null && !_classInspector.shouldCache(key)) - return value; - - Object result = null; - int i = key.hashCode() & TABLE_SIZE_MASK; - Entry entry = _table[i]; - - if (entry == null) - { - _table[i] = new Entry(key, value); - _size++; - } else - { - if (entry.key == key) - { - result = entry.value; - entry.value = value; - } else - { - while (true) - { - if (entry.key == key) - { - /* replace value */ - result = entry.value; - entry.value = value; - break; - } else - { - if (entry.next == null) - { - /* add value */ - entry.next = new Entry(key, value); - break; - } - } - entry = entry.next; - } - } - } - - return result; - } - - public String toString() - { - return "ClassCacheImpl[" + - "_table=" + (_table == null ? null : Arrays.asList(_table)) + - '\n' + - ", _classInspector=" + _classInspector + - '\n' + - ", _size=" + _size + - '\n' + - ']'; - } -} diff --git a/src/main/java/ognl/internal/Entry.java b/src/main/java/ognl/internal/Entry.java deleted file mode 100644 index 7780effe..00000000 --- a/src/main/java/ognl/internal/Entry.java +++ /dev/null @@ -1,29 +0,0 @@ -package ognl.internal; - -/** - * Used by {@link ClassCacheImpl} to store entries in the cache. - */ -class Entry { - - Entry next; - Class key; - Object value; - - public Entry(Class key, Object value) - { - this.key = key; - this.value = value; - } - - public String toString() - { - return "Entry[" + - "next=" + next + - '\n' + - ", key=" + key + - '\n' + - ", value=" + value + - '\n' + - ']'; - } -} diff --git a/src/main/java/ognl/internal/HashMapCache.java b/src/main/java/ognl/internal/HashMapCache.java new file mode 100644 index 00000000..9e93f14f --- /dev/null +++ b/src/main/java/ognl/internal/HashMapCache.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal; + +import ognl.internal.entry.CacheEntryFactory; + +import java.util.HashMap; +import java.util.Map; + +public class HashMapCache implements Cache { + + private final Map cache = new HashMap<>(512); + + private final CacheEntryFactory cacheEntryFactory; + + public HashMapCache(CacheEntryFactory cacheEntryFactory) { + this.cacheEntryFactory = cacheEntryFactory; + } + + public void clear() { + synchronized (cache) { + cache.clear(); + } + } + + public int getSize() { + synchronized (cache) { + return cache.size(); + } + } + + public V get(K key) throws CacheException { + V v = cache.get(key); + if (shouldCreate(cacheEntryFactory, v)) { + synchronized (cache) { + v = cache.get(key); + if (v != null) { + return v; + } + return put(key, cacheEntryFactory.create(key)); + } + } + return v; + } + + protected boolean shouldCreate(CacheEntryFactory cacheEntryFactory, V v) throws CacheException { + return cacheEntryFactory != null && v == null; + } + + public V put(K key, V value) { + synchronized (cache) { + cache.put(key, value); + return value; + } + } + + + public boolean contains(K key) { + return this.cache.containsKey(key); + } + +} diff --git a/src/main/java/ognl/internal/HashMapCacheFactory.java b/src/main/java/ognl/internal/HashMapCacheFactory.java new file mode 100644 index 00000000..9f3964a1 --- /dev/null +++ b/src/main/java/ognl/internal/HashMapCacheFactory.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal; + + +import ognl.internal.entry.CacheEntryFactory; +import ognl.internal.entry.ClassCacheEntryFactory; + +public class HashMapCacheFactory implements CacheFactory { + + public Cache createCache(CacheEntryFactory entryFactory) { + return new HashMapCache<>(entryFactory); + } + + public ClassCache createClassCache() { + return createClassCache(null); + } + + public ClassCache createClassCache(ClassCacheEntryFactory entryFactory) { + return new HashMapClassCache<>(entryFactory); + } + +} diff --git a/src/main/java/ognl/internal/HashMapClassCache.java b/src/main/java/ognl/internal/HashMapClassCache.java new file mode 100644 index 00000000..ac850309 --- /dev/null +++ b/src/main/java/ognl/internal/HashMapClassCache.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal; + +import ognl.ClassCacheInspector; +import ognl.internal.entry.CacheEntryFactory; + +public class HashMapClassCache extends HashMapCache, T> implements ClassCache { + + private ClassCacheInspector inspector; + + public HashMapClassCache(CacheEntryFactory, T> entryFactory) { + super(entryFactory); + } + + public void setClassInspector(ClassCacheInspector inspector) { + this.inspector = inspector; + } + + public T put(Class key, T value) { + if (inspector != null && !inspector.shouldCache(key)) { + return value; + } + return super.put(key, value); + } + +} diff --git a/src/main/java/ognl/internal/entry/CacheEntry.java b/src/main/java/ognl/internal/entry/CacheEntry.java new file mode 100644 index 00000000..6fe27ff6 --- /dev/null +++ b/src/main/java/ognl/internal/entry/CacheEntry.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +public interface CacheEntry { +} diff --git a/src/main/java/ognl/internal/entry/CacheEntryFactory.java b/src/main/java/ognl/internal/entry/CacheEntryFactory.java new file mode 100644 index 00000000..8bcd1db8 --- /dev/null +++ b/src/main/java/ognl/internal/entry/CacheEntryFactory.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import ognl.internal.CacheException; + +public interface CacheEntryFactory { + + V create(K key) throws CacheException; + +} diff --git a/src/main/java/ognl/internal/entry/ClassCacheEntryFactory.java b/src/main/java/ognl/internal/entry/ClassCacheEntryFactory.java new file mode 100644 index 00000000..1b8b391c --- /dev/null +++ b/src/main/java/ognl/internal/entry/ClassCacheEntryFactory.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +public interface ClassCacheEntryFactory extends CacheEntryFactory, T> { +} diff --git a/src/main/java/ognl/internal/entry/DeclaredMethodCacheEntry.java b/src/main/java/ognl/internal/entry/DeclaredMethodCacheEntry.java new file mode 100644 index 00000000..b4484ab7 --- /dev/null +++ b/src/main/java/ognl/internal/entry/DeclaredMethodCacheEntry.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +public class DeclaredMethodCacheEntry extends MethodCacheEntry { + + MethodType type; + + public enum MethodType { + STATIC, NON_STATIC + } + + public DeclaredMethodCacheEntry(Class targetClass) { + super(targetClass); + } + + public DeclaredMethodCacheEntry(Class targetClass, MethodType type) { + super(targetClass); + this.type = type; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof DeclaredMethodCacheEntry)) { + return false; + } + if (!super.equals(o)) { + return false; + } + + DeclaredMethodCacheEntry that = (DeclaredMethodCacheEntry) o; + + return type == that.type; + + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (type != null ? type.hashCode() : 0); + return result; + } + +} diff --git a/src/main/java/ognl/internal/entry/DeclaredMethodCacheEntryFactory.java b/src/main/java/ognl/internal/entry/DeclaredMethodCacheEntryFactory.java new file mode 100644 index 00000000..6b62f890 --- /dev/null +++ b/src/main/java/ognl/internal/entry/DeclaredMethodCacheEntryFactory.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public class DeclaredMethodCacheEntryFactory extends MethodCacheEntryFactory { + + @Override + protected boolean shouldCache(DeclaredMethodCacheEntry key, Method method) { + if (key.type == null) { + return true; + } + boolean isStatic = Modifier.isStatic(method.getModifiers()); + if (key.type == DeclaredMethodCacheEntry.MethodType.STATIC) { + return isStatic; + } + return !isStatic; + } + +} diff --git a/src/main/java/ognl/internal/entry/FieldCacheEntryFactory.java b/src/main/java/ognl/internal/entry/FieldCacheEntryFactory.java new file mode 100644 index 00000000..33f2b5ac --- /dev/null +++ b/src/main/java/ognl/internal/entry/FieldCacheEntryFactory.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import ognl.internal.CacheException; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +public class FieldCacheEntryFactory implements ClassCacheEntryFactory> { + + public Map create(Class key) throws CacheException { + Field[] declaredFields = key.getDeclaredFields(); + Map result = new HashMap<>(declaredFields.length); + for (Field field : declaredFields) { + result.put(field.getName(), field); + } + return result; + } + +} + diff --git a/src/main/java/ognl/internal/entry/GenericMethodParameterTypeCacheEntry.java b/src/main/java/ognl/internal/entry/GenericMethodParameterTypeCacheEntry.java new file mode 100644 index 00000000..9c28db01 --- /dev/null +++ b/src/main/java/ognl/internal/entry/GenericMethodParameterTypeCacheEntry.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import java.lang.reflect.Method; + +public class GenericMethodParameterTypeCacheEntry implements CacheEntry { + + final Method method; + final Class type; + + public GenericMethodParameterTypeCacheEntry(Method method, Class type) { + this.method = method; + this.type = type; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof GenericMethodParameterTypeCacheEntry)) { + return false; + } + + GenericMethodParameterTypeCacheEntry that = (GenericMethodParameterTypeCacheEntry) o; + + return method.equals(that.method) && type.equals(that.type); + } + + @Override + public int hashCode() { + int result = method.hashCode(); + result = 31 * result + type.hashCode(); + return result; + } + +} diff --git a/src/main/java/ognl/internal/entry/GenericMethodParameterTypeFactory.java b/src/main/java/ognl/internal/entry/GenericMethodParameterTypeFactory.java new file mode 100644 index 00000000..b5979d86 --- /dev/null +++ b/src/main/java/ognl/internal/entry/GenericMethodParameterTypeFactory.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import ognl.internal.CacheException; + +import java.lang.reflect.Array; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; + +public class GenericMethodParameterTypeFactory implements CacheEntryFactory[]> { + + public Class[] create(GenericMethodParameterTypeCacheEntry entry) throws CacheException { + Class[] types; + + ParameterizedType param = (ParameterizedType) entry.type.getGenericSuperclass(); + Type[] genTypes = entry.method.getGenericParameterTypes(); + TypeVariable[] declaredTypes = entry.method.getDeclaringClass().getTypeParameters(); + + types = new Class[genTypes.length]; + + for (int i = 0; i < genTypes.length; i++) { + TypeVariable paramType = null; + + if (genTypes[i] instanceof TypeVariable) { + paramType = (TypeVariable) genTypes[i]; + } else if (genTypes[i] instanceof GenericArrayType) { + paramType = (TypeVariable) ((GenericArrayType) genTypes[i]).getGenericComponentType(); + } else if (genTypes[i] instanceof ParameterizedType) { + types[i] = (Class) ((ParameterizedType) genTypes[i]).getRawType(); + continue; + } else if (genTypes[i] instanceof Class) { + types[i] = (Class) genTypes[i]; + continue; + } + + Class resolved = resolveType(param, paramType, declaredTypes); + + if (resolved != null) { + if (genTypes[i] instanceof GenericArrayType) { + resolved = Array.newInstance(resolved, 0).getClass(); + } + + types[i] = resolved; + continue; + } + types[i] = entry.method.getParameterTypes()[i]; + } + + return types; + } + + private Class resolveType(ParameterizedType param, TypeVariable var, TypeVariable[] declaredTypes) { + if (param.getActualTypeArguments().length < 1) { + return null; + } + + for (int i = 0; i < declaredTypes.length; i++) { + if (!(param.getActualTypeArguments()[i] instanceof TypeVariable) + && declaredTypes[i].getName().equals(var.getName())) { + return (Class) param.getActualTypeArguments()[i]; + } + } + + return null; + } + +} diff --git a/src/main/java/ognl/internal/entry/MethodAccessCacheEntryFactory.java b/src/main/java/ognl/internal/entry/MethodAccessCacheEntryFactory.java new file mode 100644 index 00000000..3f90add2 --- /dev/null +++ b/src/main/java/ognl/internal/entry/MethodAccessCacheEntryFactory.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import ognl.internal.CacheException; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public class MethodAccessCacheEntryFactory implements CacheEntryFactory { + + public static final MethodAccessEntryValue INACCESSIBLE_NON_PUBLIC_METHOD = new MethodAccessEntryValue(false, true); + + public static final MethodAccessEntryValue ACCESSIBLE_NON_PUBLIC_METHOD = new MethodAccessEntryValue(true, true); + + public static final MethodAccessEntryValue PUBLIC_METHOD = new MethodAccessEntryValue(true); + + public MethodAccessEntryValue create(Method method) throws CacheException { + final boolean notPublic = !Modifier.isPublic(method.getModifiers()) + || !Modifier.isPublic(method.getDeclaringClass().getModifiers()); + if (!notPublic) { + return PUBLIC_METHOD; + } + if (!method.isAccessible()) { + return INACCESSIBLE_NON_PUBLIC_METHOD; + } + return ACCESSIBLE_NON_PUBLIC_METHOD; + } + +} diff --git a/src/main/java/ognl/internal/entry/MethodAccessEntryValue.java b/src/main/java/ognl/internal/entry/MethodAccessEntryValue.java new file mode 100644 index 00000000..cfa2d0b2 --- /dev/null +++ b/src/main/java/ognl/internal/entry/MethodAccessEntryValue.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +public class MethodAccessEntryValue { + + private final boolean isAccessible; + private boolean notPublic; + + public MethodAccessEntryValue(boolean accessible) { + this.isAccessible = accessible; + } + + public MethodAccessEntryValue(boolean accessible, boolean notPublic) { + isAccessible = accessible; + this.notPublic = notPublic; + } + + public boolean isAccessible() { + return isAccessible; + } + + public boolean isNotPublic() { + return notPublic; + } + +} diff --git a/src/main/java/ognl/internal/entry/MethodCacheEntry.java b/src/main/java/ognl/internal/entry/MethodCacheEntry.java new file mode 100644 index 00000000..24de8d04 --- /dev/null +++ b/src/main/java/ognl/internal/entry/MethodCacheEntry.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +public class MethodCacheEntry implements CacheEntry { + + public final Class targetClass; + + public MethodCacheEntry(Class targetClass) { + this.targetClass = targetClass; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof MethodCacheEntry)) { + return false; + } + + MethodCacheEntry that = (MethodCacheEntry) o; + + return targetClass.equals(that.targetClass); + } + + @Override + public int hashCode() { + return targetClass.hashCode(); + } + +} diff --git a/src/main/java/ognl/internal/entry/MethodCacheEntryFactory.java b/src/main/java/ognl/internal/entry/MethodCacheEntryFactory.java new file mode 100644 index 00000000..d2a04d3b --- /dev/null +++ b/src/main/java/ognl/internal/entry/MethodCacheEntryFactory.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import ognl.OgnlRuntime; +import ognl.internal.CacheException; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class MethodCacheEntryFactory implements CacheEntryFactory>> { + + public Map> create(T key) throws CacheException { + Map> result = new HashMap<>(23); + + collectMethods(key, key.targetClass, result); + + return result; + } + + protected abstract boolean shouldCache(T key, Method method); + + private void collectMethods(T key, Class c, Map> result) { + Method[] ma; + try { + ma = c.getDeclaredMethods(); + } catch (SecurityException ignored) { + ma = c.getMethods(); + } + for (Method method : ma) { + if (!OgnlRuntime.isMethodCallable(method)) + continue; + + if (shouldCache(key, method)) { + List ml = result.computeIfAbsent(method.getName(), k -> new ArrayList<>()); + ml.add(method); + } + } + final Class superclass = c.getSuperclass(); + if (superclass != null) { + collectMethods(key, superclass, result); + } + + for (final Class iface : c.getInterfaces()) { + collectMethods(key, iface, result); + } + } + +} diff --git a/src/main/java/ognl/internal/entry/MethodPermCacheEntryFactory.java b/src/main/java/ognl/internal/entry/MethodPermCacheEntryFactory.java new file mode 100644 index 00000000..eb6a5f18 --- /dev/null +++ b/src/main/java/ognl/internal/entry/MethodPermCacheEntryFactory.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import ognl.OgnlRuntime; +import ognl.internal.CacheException; + +import java.lang.reflect.Method; + +public class MethodPermCacheEntryFactory implements CacheEntryFactory { + + private SecurityManager securityManager; + + public MethodPermCacheEntryFactory(SecurityManager securityManager) { + this.securityManager = securityManager; + } + + public Boolean create(Method key) throws CacheException { + try { + securityManager.checkPermission(OgnlRuntime.getPermission(key)); + return true; + } catch (SecurityException ex) { + return false; + } + } + + public void setSecurityManager(SecurityManager securityManager) { + this.securityManager = securityManager; + } + +} diff --git a/src/main/java/ognl/internal/entry/PermissionCacheEntry.java b/src/main/java/ognl/internal/entry/PermissionCacheEntry.java new file mode 100644 index 00000000..6689808e --- /dev/null +++ b/src/main/java/ognl/internal/entry/PermissionCacheEntry.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import java.lang.reflect.Method; +import java.util.Objects; + +public class PermissionCacheEntry implements CacheEntry { + + public final Method method; + + public PermissionCacheEntry(Method method) { + this.method = method; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof PermissionCacheEntry)) { + return false; + } + + PermissionCacheEntry that = (PermissionCacheEntry) o; + + return Objects.equals(method, that.method); + } + + @Override + public int hashCode() { + return method != null ? method.hashCode() : 0; + } + +} diff --git a/src/main/java/ognl/internal/entry/PermissionCacheEntryFactory.java b/src/main/java/ognl/internal/entry/PermissionCacheEntryFactory.java new file mode 100644 index 00000000..b05f78dd --- /dev/null +++ b/src/main/java/ognl/internal/entry/PermissionCacheEntryFactory.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import ognl.OgnlInvokePermission; +import ognl.internal.CacheException; + +import java.security.Permission; + +public class PermissionCacheEntryFactory implements CacheEntryFactory { + + public Permission create(PermissionCacheEntry key) throws CacheException { + return new OgnlInvokePermission("invoke." + key.method.getDeclaringClass().getName() + "." + key.method.getName()); + } + +} + diff --git a/src/main/java/ognl/internal/entry/PropertyDescriptorCacheEntryFactory.java b/src/main/java/ognl/internal/entry/PropertyDescriptorCacheEntryFactory.java new file mode 100644 index 00000000..cc64b683 --- /dev/null +++ b/src/main/java/ognl/internal/entry/PropertyDescriptorCacheEntryFactory.java @@ -0,0 +1,183 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.internal.entry; + +import ognl.ObjectIndexedPropertyDescriptor; +import ognl.OgnlException; +import ognl.OgnlRuntime; +import ognl.internal.CacheException; + +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PropertyDescriptorCacheEntryFactory implements ClassCacheEntryFactory> { + + public Map create(Class targetClass) throws CacheException { + Map result = new HashMap<>(101); + PropertyDescriptor[] pda; + try { + pda = Introspector.getBeanInfo(targetClass).getPropertyDescriptors(); + + for (PropertyDescriptor aPda : pda) { + // workaround for Introspector bug 6528714 (bugs.sun.com) + if (aPda.getReadMethod() != null && !OgnlRuntime.isMethodCallable(aPda.getReadMethod())) { + aPda.setReadMethod( + findClosestMatchingMethod(targetClass, aPda.getReadMethod(), aPda.getName(), + aPda.getPropertyType(), true)); + } + if (aPda.getWriteMethod() != null && !OgnlRuntime.isMethodCallable(aPda.getWriteMethod())) { + aPda.setWriteMethod( + findClosestMatchingMethod(targetClass, aPda.getWriteMethod(), aPda.getName(), + aPda.getPropertyType(), false)); + } + + result.put(aPda.getName(), aPda); + } + + findObjectIndexedPropertyDescriptors(targetClass, result); + } catch (IntrospectionException | OgnlException e) { + throw new CacheException(e); + } + return result; + } + + static Method findClosestMatchingMethod( + Class targetClass, + Method method, + String propertyName, + Class propertyType, + boolean isReadMethod + ) throws OgnlException { + List methods = OgnlRuntime.getDeclaredMethods(targetClass, propertyName, !isReadMethod); + + for (Method closestMethod : methods) { + if (closestMethod.getName().equals(method.getName()) + && method.getReturnType().isAssignableFrom(method.getReturnType()) + && closestMethod.getReturnType() == propertyType + && closestMethod.getParameterTypes().length == method.getParameterTypes().length) { + return closestMethod; + } + } + + return method; + } + + private static void findObjectIndexedPropertyDescriptors( + Class targetClass, Map intoMap + ) throws OgnlException { + Map> allMethods = OgnlRuntime.getMethods(targetClass, false); + Map> pairs = new HashMap<>(101); + + for (Map.Entry> entry : allMethods.entrySet()) { + String methodName = entry.getKey(); + List methods = entry.getValue(); + + /* + * Only process set/get where there is exactly one implementation of the method per class and those + * implementations are all the same + */ + if (indexMethodCheck(methods)) { + boolean isGet = false, isSet; + Method method = methods.get(0); + + if (((isSet = methodName.startsWith(OgnlRuntime.SET_PREFIX)) || (isGet = methodName.startsWith(OgnlRuntime.GET_PREFIX))) + && (methodName.length() > 3)) { + String propertyName = Introspector.decapitalize(methodName.substring(3)); + Class[] parameterTypes = OgnlRuntime.getParameterTypes(method); + int parameterCount = parameterTypes.length; + + if (isGet && (parameterCount == 1) && (method.getReturnType() != Void.TYPE)) { + List pair = pairs.computeIfAbsent(propertyName, k -> new ArrayList<>()); + + pair.add(method); + } + if (isSet && (parameterCount == 2) && (method.getReturnType() == Void.TYPE)) { + List pair = pairs.computeIfAbsent(propertyName, k -> new ArrayList<>()); + + pair.add(method); + } + } + } + } + + for (Map.Entry> entry : pairs.entrySet()) { + String propertyName = entry.getKey(); + List methods = entry.getValue(); + + if (methods.size() == 2) { + Method method1 = methods.get(0), method2 = methods.get(1), setMethod = + (method1.getParameterTypes().length == 2) ? method1 : method2, getMethod = + (setMethod == method1) ? method2 : method1; + Class keyType = getMethod.getParameterTypes()[0], propertyType = getMethod.getReturnType(); + + if (keyType == setMethod.getParameterTypes()[0] && propertyType == setMethod.getParameterTypes()[1]) { + ObjectIndexedPropertyDescriptor propertyDescriptor; + + try { + propertyDescriptor = new ObjectIndexedPropertyDescriptor(propertyName, propertyType, getMethod, setMethod); + } catch (Exception ex) { + throw new OgnlException( + "creating object indexed property descriptor for '" + propertyName + "' in " + + targetClass, ex); + } + intoMap.put(propertyName, propertyDescriptor); + } + } + } + } + + private static boolean indexMethodCheck(List methods) { + boolean result = false; + + if (!methods.isEmpty()) { + Method method = methods.get(0); + Class[] parameterTypes = OgnlRuntime.getParameterTypes(method); + int numParameterTypes = parameterTypes.length; + Class lastMethodClass = method.getDeclaringClass(); + + result = true; + for (int i = 1; result && (i < methods.size()); i++) { + Class clazz = methods.get(i).getDeclaringClass(); + + // Check to see if more than one method implemented per class + if (lastMethodClass == clazz) { + result = false; + } else { + Class[] mpt = OgnlRuntime.getParameterTypes(method); + for (int j = 0; j < numParameterTypes; j++) { + if (parameterTypes[j] != mpt[j]) { + result = false; + break; + } + } + } + lastMethodClass = clazz; + } + } + return result; + } + +} diff --git a/src/main/java/ognl/package.html b/src/main/java/ognl/package.html index 766ba6a3..3f2c1807 100644 --- a/src/main/java/ognl/package.html +++ b/src/main/java/ognl/package.html @@ -1,52 +1,40 @@ -OGNL Overview + OGNL Overview -

    OGNL stands for Object-Graph Navigation Language; it is an expression language +

    OGNL stands for Object-Graph Navigation Language; it is an expression language for getting and setting properties of Java objects. You use the same expression for both getting and setting the value of a property.

    -

    OGNL started out as a way to set up associations between UI - components and controllers using property names. As the desire for +

    OGNL started out as a way to set up associations between UI + components and controllers using property names. As the desire for more complicated associations grew, Drew Davidson created what he called KVCL, for Key-Value Coding Language, egged on by Luke - Blanshard. Luke then reimplemented the language using ANTLR, came up + Blanshard. Luke then reimplemented the language using ANTLR, came up with the new name, and, egged on by Drew, filled it out to its current state.

    -

    We pronounce OGNL as a word, like the last syllables of a drunken +

    We pronounce OGNL as a word, like the last syllables of a drunken pronunciation of "orthogonal" or like "ogg-null".

    diff --git a/src/main/java/ognl/security/OgnlSecurityManager.java b/src/main/java/ognl/security/OgnlSecurityManager.java index a60d47d8..ac219cdd 100644 --- a/src/main/java/ognl/security/OgnlSecurityManager.java +++ b/src/main/java/ognl/security/OgnlSecurityManager.java @@ -1,13 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.security; import java.io.FilePermission; -import java.security.*; +import java.security.Permission; +import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; /** * Wraps current security manager with JDK security manager if is inside OgnlRuntime user's methods body execution. - * + *

    * Add the `-Dognl.security.manager` to JVM options to enable. * *

    Note: Due to potential performance and concurrency issues, try this only if you afraid your app can have an @@ -20,26 +39,26 @@ * also honors previous security manager and policies if any set, as parent, and rolls back to them after method * execution finished.

    * - * @author Yasser Zamani * @since 3.1.24 */ public class OgnlSecurityManager extends SecurityManager { + private static final String OGNL_SANDBOX_CLASS_NAME = "ognl.security.UserMethod"; private static final Class CLASS_LOADER_CLASS = ClassLoader.class; private static final Class FILE_PERMISSION_CLASS = FilePermission.class; - private SecurityManager parentSecurityManager; - private List residents = new ArrayList(); - private SecureRandom rnd = new SecureRandom(); + private final SecurityManager parentSecurityManager; + private final List residents = new ArrayList<>(); + private final SecureRandom rnd = new SecureRandom(); public OgnlSecurityManager(SecurityManager parentSecurityManager) { this.parentSecurityManager = parentSecurityManager; } private boolean isAccessDenied(Permission perm) { - Class[] classContext = getClassContext(); + Class[] classContext = getClassContext(); Boolean isInsideClassLoader = null; - for (Class c : classContext) { + for (Class c : classContext) { if (isInsideClassLoader == null && CLASS_LOADER_CLASS.isAssignableFrom(c)) { if (FILE_PERMISSION_CLASS.equals(perm.getClass()) && "read".equals(perm.getActions())) { // TODO: might be risky but we have to - fix it if any POC discovered diff --git a/src/main/java/ognl/security/OgnlSecurityManagerFactory.java b/src/main/java/ognl/security/OgnlSecurityManagerFactory.java index 08d4abba..5e460c5f 100644 --- a/src/main/java/ognl/security/OgnlSecurityManagerFactory.java +++ b/src/main/java/ognl/security/OgnlSecurityManagerFactory.java @@ -1,3 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.security; import java.io.ByteArrayOutputStream; @@ -8,17 +26,18 @@ import java.security.PermissionCollection; import java.security.ProtectionDomain; import java.security.SecureClassLoader; +import java.util.Objects; /** * Builds and provides a JVM wide singleton shared thread-safe with all permissions granted security manager for ognl * - * @author Yasser Zamani * @since 3.1.24 */ public class OgnlSecurityManagerFactory extends SecureClassLoader { - private static Object ognlSecurityManager; - private Class ognlSecurityManagerClass; + private static volatile Object ognlSecurityManager; + + private final Class ognlSecurityManagerClass; public static Object getOgnlSecurityManager() { if (ognlSecurityManager == null) { @@ -47,14 +66,12 @@ private OgnlSecurityManagerFactory() throws IOException { pc.add(new AllPermission()); // grant all permissions to simulate JDK itself SecurityManager ProtectionDomain pd = new ProtectionDomain(null, pc); - byte[] byteArray = toByteArray(getParent().getResourceAsStream( - OgnlSecurityManager.class.getName().replace('.', '/') + ".class")); + byte[] byteArray = toByteArray(Objects.requireNonNull(getParent().getResourceAsStream( + OgnlSecurityManager.class.getName().replace('.', '/') + ".class"))); ognlSecurityManagerClass = defineClass(null, byteArray, 0, byteArray.length, pd); } - private Object build(SecurityManager parentSecurityManager) throws NoSuchMethodException, IllegalAccessException, - InvocationTargetException, InstantiationException { - + private Object build(SecurityManager parentSecurityManager) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { return ognlSecurityManagerClass.getConstructor(SecurityManager.class).newInstance(parentSecurityManager); } @@ -62,7 +79,7 @@ private static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); int n; byte[] buffer = new byte[4096]; - while(-1 != (n = input.read(buffer))) { + while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } diff --git a/src/main/java/ognl/security/UserMethod.java b/src/main/java/ognl/security/UserMethod.java index 3136508f..871e0cb7 100644 --- a/src/main/java/ognl/security/UserMethod.java +++ b/src/main/java/ognl/security/UserMethod.java @@ -1,3 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * and/or LICENSE file distributed with this work for additional + * information regarding copyright ownership. The ASF licenses + * this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl.security; import java.lang.reflect.Method; @@ -6,10 +24,10 @@ /** * A signature for {@link OgnlSecurityManager#isAccessDenied(java.security.Permission)}. Also executes user methods with not any permission. * - * @author Yasser Zamani * @since 3.1.24 */ public class UserMethod implements PrivilegedExceptionAction { + private final Object target; private final Method method; private final Object[] argsArray; diff --git a/src/etc/ognl.jj b/src/main/javacc/ognl.jj similarity index 96% rename from src/etc/ognl.jj rename to src/main/javacc/ognl.jj index 0d936dd7..b5cae0b5 100644 --- a/src/etc/ognl.jj +++ b/src/main/javacc/ognl.jj @@ -1,34 +1,24 @@ /*@bgen(jjtree) Generated By:JJTree: Do not edit this line. src/java/ognl/ognl.jj */ -/*@egen*///-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/*@egen*/ + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ /* * This file defines the syntax of OGNL, the Object-Graph Navigation Language. This @@ -48,9 +38,9 @@ options { JAVA_UNICODE_ESCAPE = true; UNICODE_INPUT = true; - - - + + + } PARSER_BEGIN(OgnlParser) @@ -385,7 +375,7 @@ void equalityExpression() : {} jjtree.closeNodeScope(jjtn001, 2); } } -/*@egen*/ +/*@egen*/ | ("!=" | "neq")/*@bgen(jjtree) #NotEq( 2) */ { @@ -414,7 +404,7 @@ void equalityExpression() : {} jjtree.closeNodeScope(jjtn002, 2); } } -/*@egen*/ +/*@egen*/ )* } @@ -451,7 +441,7 @@ void relationalExpression() : {} jjtree.closeNodeScope(jjtn001, 2); } } -/*@egen*/ +/*@egen*/ | (">" | "gt")/*@bgen(jjtree) #Greater( 2) */ { @@ -480,7 +470,7 @@ void relationalExpression() : {} jjtree.closeNodeScope(jjtn002, 2); } } -/*@egen*/ +/*@egen*/ | ("<=" | "lte")/*@bgen(jjtree) #LessEq( 2) */ { @@ -509,7 +499,7 @@ void relationalExpression() : {} jjtree.closeNodeScope(jjtn003, 2); } } -/*@egen*/ +/*@egen*/ | (">=" | "gte")/*@bgen(jjtree) #GreaterEq( 2) */ { @@ -538,7 +528,7 @@ void relationalExpression() : {} jjtree.closeNodeScope(jjtn004, 2); } } -/*@egen*/ +/*@egen*/ | "in"/*@bgen(jjtree) #In( 2) */ { @@ -567,7 +557,7 @@ void relationalExpression() : {} jjtree.closeNodeScope(jjtn005, 2); } } -/*@egen*/ +/*@egen*/ | "not" "in"/*@bgen(jjtree) #NotIn( 2) */ { @@ -596,7 +586,7 @@ void relationalExpression() : {} jjtree.closeNodeScope(jjtn006, 2); } } -/*@egen*/ +/*@egen*/ )* } @@ -633,7 +623,7 @@ void shiftExpression() : {} jjtree.closeNodeScope(jjtn001, 2); } } -/*@egen*/ +/*@egen*/ | (">>" | "shr")/*@bgen(jjtree) #ShiftRight( 2) */ { @@ -662,7 +652,7 @@ void shiftExpression() : {} jjtree.closeNodeScope(jjtn002, 2); } } -/*@egen*/ +/*@egen*/ | (">>>" | "ushr")/*@bgen(jjtree) #UnsignedShiftRight( 2) */ { @@ -691,7 +681,7 @@ void shiftExpression() : {} jjtree.closeNodeScope(jjtn003, 2); } } -/*@egen*/ +/*@egen*/ )* } @@ -728,7 +718,7 @@ void additiveExpression() : {} jjtree.closeNodeScope(jjtn001, 2); } } -/*@egen*/ +/*@egen*/ | "-"/*@bgen(jjtree) #Subtract( 2) */ { @@ -757,7 +747,7 @@ void additiveExpression() : {} jjtree.closeNodeScope(jjtn002, 2); } } -/*@egen*/ +/*@egen*/ )* } @@ -794,7 +784,7 @@ void multiplicativeExpression() : {} jjtree.closeNodeScope(jjtn001, 2); } } -/*@egen*/ +/*@egen*/ | "/"/*@bgen(jjtree) #Divide( 2) */ { @@ -823,7 +813,7 @@ void multiplicativeExpression() : {} jjtree.closeNodeScope(jjtn002, 2); } } -/*@egen*/ +/*@egen*/ | "%"/*@bgen(jjtree) #Remainder( 2) */ { @@ -852,7 +842,7 @@ void multiplicativeExpression() : {} jjtree.closeNodeScope(jjtn003, 2); } } -/*@egen*/ +/*@egen*/ )* } @@ -891,7 +881,7 @@ void unaryExpression() : { jjtree.closeNodeScope(jjtn001, 1); } } -/*@egen*/ +/*@egen*/ | "+" unaryExpression() // Just leave it there | @@ -922,7 +912,7 @@ void unaryExpression() : { jjtree.closeNodeScope(jjtn002, 1); } } -/*@egen*/ +/*@egen*/ | ("!" | "not")/*@bgen(jjtree) #Not( 1) */ { @@ -951,7 +941,7 @@ void unaryExpression() : { jjtree.closeNodeScope(jjtn003, 1); } } -/*@egen*/ +/*@egen*/ | navigationChain() [ @@ -974,7 +964,7 @@ void unaryExpression() : { jjtree.closeNodeScope(jjtn004, 1); } } -/*@egen*/ +/*@egen*/ ( "." t = { sb.append('.').append( t.image ); } )* { ionode.setTargetType( new String(sb) ); } ] @@ -1019,7 +1009,7 @@ void navigationChain() : {} jjtree.closeNodeScope(jjtn001, 2); } } -/*@egen*/ +/*@egen*/ |/*@bgen(jjtree) #Chain( 2) */ { @@ -1048,7 +1038,7 @@ void navigationChain() : {} jjtree.closeNodeScope(jjtn002, 2); } } -/*@egen*/ +/*@egen*/ | "(" expression()/*@bgen(jjtree) #Eval( 2) */ { @@ -1063,7 +1053,7 @@ void navigationChain() : {} jjtree.closeNodeScope(jjtn003, 2); } } -/*@egen*/ +/*@egen*/ /* Using parentheses to indicate evaluation of the current object makes this language ambiguous, because the @@ -1102,7 +1092,7 @@ void primaryExpression() : { jjtree.closeNodeScope(jjtn001, 0); } } -/*@egen*/ +/*@egen*/ | "true"/*@bgen(jjtree) #Const( 0) */ { @@ -1122,7 +1112,7 @@ void primaryExpression() : { jjtree.closeNodeScope(jjtn002, 0); } } -/*@egen*/ +/*@egen*/ | "false"/*@bgen(jjtree) #Const( 0) */ { @@ -1142,7 +1132,7 @@ void primaryExpression() : { jjtree.closeNodeScope(jjtn003, 0); } } -/*@egen*/ +/*@egen*/ |/*@bgen(jjtree) #Const( 0) */ { ASTConst jjtn004 = new ASTConst(JJTCONST); @@ -1177,7 +1167,7 @@ void primaryExpression() : { jjtree.closeNodeScope(jjtn005, 0); } } -/*@egen*/ +/*@egen*/ | LOOKAHEAD(2) "#root"/*@bgen(jjtree) #RootVarRef( 0) */ { @@ -1197,7 +1187,7 @@ void primaryExpression() : { jjtree.closeNodeScope(jjtn006, 0); } } -/*@egen*/ +/*@egen*/ | LOOKAHEAD(2) "#" t=/*@bgen(jjtree) #VarRef( 0) */ { @@ -1217,7 +1207,7 @@ void primaryExpression() : { jjtree.closeNodeScope(jjtn007, 0); } } -/*@egen*/ +/*@egen*/ | LOOKAHEAD(2) ":" "[" expression() "]"/*@bgen(jjtree) #Const( 1) */ { @@ -1237,7 +1227,7 @@ void primaryExpression() : { jjtree.closeNodeScope(jjtn008, 1); } } -/*@egen*/ +/*@egen*/ | staticReference() | @@ -1306,7 +1296,7 @@ void primaryExpression() : { jjtree.closeNodeScope(jjtn010, true); } } -/*@egen*/ +/*@egen*/ ) } @@ -1339,7 +1329,7 @@ void keyValueExpression() : {} jjtree.closeNodeScope(jjtn001, true); } } -/*@egen*/ +/*@egen*/ } void staticReference() : { @@ -1370,7 +1360,7 @@ void staticReference() : { jjtree.closeNodeScope(jjtn001, 0); } } -/*@egen*/ +/*@egen*/ ) } diff --git a/src/etc/ognl.jjt b/src/main/jjtree/ognl.jjt similarity index 90% rename from src/etc/ognl.jjt rename to src/main/jjtree/ognl.jjt index cf452aaf..34ce24b0 100644 --- a/src/etc/ognl.jjt +++ b/src/main/jjtree/ognl.jjt @@ -1,33 +1,21 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ /* * This file defines the syntax of OGNL, the Object-Graph Navigation Language. This diff --git a/src/test/java/ClassInDefaultPackage.java b/src/test/java/ClassInDefaultPackage.java index 87b11e55..e326c354 100644 --- a/src/test/java/ClassInDefaultPackage.java +++ b/src/test/java/ClassInDefaultPackage.java @@ -1,4 +1,3 @@ - class ClassInDefaultPackage { public static final int CONST = 99; } diff --git a/src/test/java/ognl/DefaultMemberAccess.java b/src/test/java/ognl/DefaultMemberAccess.java index 8d6ad769..dcc10c70 100644 --- a/src/test/java/ognl/DefaultMemberAccess.java +++ b/src/test/java/ognl/DefaultMemberAccess.java @@ -1,37 +1,26 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package ognl; -import java.lang.reflect.*; -import java.util.*; +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Member; +import java.lang.reflect.Modifier; /** * This class provides methods for setting up and restoring @@ -40,85 +29,63 @@ * coarse-grained access controls to allow access to private, protected * and package protected members. This will apply to all classes * and members. - * - * @author Luke Blanshard (blanshlu@netscape.net) - * @author Drew Davidson (drew@ognl.org) - * @version 15 October 1999 */ -public class DefaultMemberAccess implements MemberAccess -{ +public class DefaultMemberAccess implements MemberAccess { /* * Assign an accessibility modification mechanism, based on Major Java Version. - * Note: Can be override using a Java option flag {@link OgnlRuntime#USE_PREJDK9_ACESS_HANDLER}. + * Note: Can be overridden using a Java option flag {@link OgnlRuntime#USE_PREJDK9_ACESS_HANDLER}. */ private static final AccessibleObjectHandler _accessibleObjectHandler; + static { _accessibleObjectHandler = OgnlRuntime.usingJDK9PlusAccessHandler() ? AccessibleObjectHandlerJDK9Plus.createHandler() : - AccessibleObjectHandlerPreJDK9.createHandler(); + AccessibleObjectHandlerPreJDK9.createHandler(); + } + + public boolean allowPrivateAccess = false; + public boolean allowProtectedAccess = false; + public boolean allowPackageProtectedAccess = false; + + public DefaultMemberAccess(boolean allowAllAccess) { + this(allowAllAccess, allowAllAccess, allowAllAccess); + } + + public DefaultMemberAccess(boolean allowPrivateAccess, boolean allowProtectedAccess, boolean allowPackageProtectedAccess) { + super(); + this.allowPrivateAccess = allowPrivateAccess; + this.allowProtectedAccess = allowProtectedAccess; + this.allowPackageProtectedAccess = allowPackageProtectedAccess; + } + + public boolean getAllowPrivateAccess() { + return allowPrivateAccess; + } + + public void setAllowPrivateAccess(boolean value) { + allowPrivateAccess = value; } - public boolean allowPrivateAccess = false; - public boolean allowProtectedAccess = false; - public boolean allowPackageProtectedAccess = false; - - /*=================================================================== - Constructors - ===================================================================*/ - public DefaultMemberAccess(boolean allowAllAccess) - { - this(allowAllAccess, allowAllAccess, allowAllAccess); - } - - public DefaultMemberAccess(boolean allowPrivateAccess, boolean allowProtectedAccess, boolean allowPackageProtectedAccess) - { - super(); - this.allowPrivateAccess = allowPrivateAccess; - this.allowProtectedAccess = allowProtectedAccess; - this.allowPackageProtectedAccess = allowPackageProtectedAccess; - } - - /*=================================================================== - Public methods - ===================================================================*/ - public boolean getAllowPrivateAccess() - { - return allowPrivateAccess; - } - - public void setAllowPrivateAccess(boolean value) - { - allowPrivateAccess = value; - } - - public boolean getAllowProtectedAccess() - { - return allowProtectedAccess; - } - - public void setAllowProtectedAccess(boolean value) - { - allowProtectedAccess = value; - } - - public boolean getAllowPackageProtectedAccess() - { - return allowPackageProtectedAccess; - } - - public void setAllowPackageProtectedAccess(boolean value) - { - allowPackageProtectedAccess = value; - } - - /*=================================================================== - MemberAccess interface - ===================================================================*/ - public Object setup(Map context, Object target, Member member, String propertyName) - { - Object result = null; + public boolean getAllowProtectedAccess() { + return allowProtectedAccess; + } + + public void setAllowProtectedAccess(boolean value) { + allowProtectedAccess = value; + } + + public boolean getAllowPackageProtectedAccess() { + return allowPackageProtectedAccess; + } + + public void setAllowPackageProtectedAccess(boolean value) { + allowPackageProtectedAccess = value; + } + + public Object setup(OgnlContext context, Object target, Member member, String propertyName) { + Object result = null; if (isAccessible(context, target, member, propertyName)) { - AccessibleObject accessible = (AccessibleObject) member; + AccessibleObject accessible = (AccessibleObject) member; if (!accessible.isAccessible()) { result = Boolean.FALSE; @@ -128,46 +95,44 @@ public Object setup(Map context, Object target, Member member, String propertyNa return result; } - public void restore(Map context, Object target, Member member, String propertyName, Object state) - { + public void restore(OgnlContext context, Object target, Member member, String propertyName, Object state) { if (state != null) { - final AccessibleObject accessible = (AccessibleObject) member; - final boolean stateboolean = ((Boolean) state).booleanValue(); // Using twice (avoid unboxing) + final AccessibleObject accessible = (AccessibleObject) member; + final boolean stateboolean = ((Boolean) state).booleanValue(); // Using twice (avoid unboxing) if (!stateboolean) { _accessibleObjectHandler.setAccessible(accessible, stateboolean); } else { throw new IllegalArgumentException("Improper restore state [" + stateboolean + "] for target [" + target + - "], member [" + member + "], propertyName [" + propertyName + "]"); + "], member [" + member + "], propertyName [" + propertyName + "]"); } } } /** - Returns true if the given member is accessible or can be made accessible - by this object. + * Returns true if the given member is accessible or can be made accessible + * by this object. * - * @param context the current execution context (not used). - * @param target the Object to test accessibility for (not used). - * @param member the Member to test accessibility for. + * @param context the current execution context (not used). + * @param target the Object to test accessibility for (not used). + * @param member the Member to test accessibility for. * @param propertyName the property to test accessibility for (not used). * @return true if the member is accessible in the context, false otherwise. */ - public boolean isAccessible(Map context, Object target, Member member, String propertyName) - { - int modifiers = member.getModifiers(); - boolean result = Modifier.isPublic(modifiers); - - if (!result) { - if (Modifier.isPrivate(modifiers)) { - result = getAllowPrivateAccess(); - } else { - if (Modifier.isProtected(modifiers)) { - result = getAllowProtectedAccess(); - } else { - result = getAllowPackageProtectedAccess(); - } - } - } - return result; - } + public boolean isAccessible(OgnlContext context, Object target, Member member, String propertyName) { + int modifiers = member.getModifiers(); + boolean result = Modifier.isPublic(modifiers); + + if (!result) { + if (Modifier.isPrivate(modifiers)) { + result = getAllowPrivateAccess(); + } else { + if (Modifier.isProtected(modifiers)) { + result = getAllowProtectedAccess(); + } else { + result = getAllowPackageProtectedAccess(); + } + } + } + return result; + } } diff --git a/src/test/java/ognl/OgnlRuntimeTest.java b/src/test/java/ognl/OgnlRuntimeTest.java index 46387082..15eb69df 100644 --- a/src/test/java/ognl/OgnlRuntimeTest.java +++ b/src/test/java/ognl/OgnlRuntimeTest.java @@ -32,6 +32,7 @@ class ExampleStringSubclass extends ExampleStringClass { class ExampleTwoMethodClass { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -39,6 +40,7 @@ public void bar(final String parameter2) { class ExampleTwoMethodClass2 { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -46,6 +48,7 @@ public void bar(final String parameter2) { class ExampleTwoMethodClass3 { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -53,6 +56,7 @@ public void bar(final String parameter2) { class ExampleTwoMethodClass4 { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -60,6 +64,7 @@ public void bar(final String parameter2) { class ExampleTwoMethodClass5 { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -67,6 +72,7 @@ public void bar(final String parameter2) { class ExampleTwoMethodClass6 { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -74,6 +80,7 @@ public void bar(final String parameter2) { class ExampleTwoMethodClass7 { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -81,6 +88,7 @@ public void bar(final String parameter2) { class ExampleTwoMethodClass8 { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -88,6 +96,7 @@ public void bar(final String parameter2) { class ExampleTwoMethodClass9 { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -95,6 +104,7 @@ public void bar(final String parameter2) { class ExampleTwoMethodClass10 { public void foo(final Integer parameter1, final Date parameter2) { } + public void bar(final String parameter2) { } } @@ -127,7 +137,7 @@ public Class[] call() throws Exception { } private void runTest(final Class clazz, final Method method, final int invocationCount, final int threadCount, - final Class[] expected) throws Exception { + final Class[] expected) throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(threadCount); final List[]>> futures = new ArrayList[]>>(threadCount); totalNumberOfRunTestRuns++; @@ -152,37 +162,37 @@ private void runTest(final Class clazz, final Method method, final int invoca @Test public void testPerformanceRealGenericSingleThread() throws Exception { final Method barMethod = ExampleStringClass.class.getMethod("bar", Object.class); - runTest(ExampleStringClass.class, barMethod, 10000000, 1, new Class[] { String.class }); + runTest(ExampleStringClass.class, barMethod, 10000000, 1, new Class[]{String.class}); } @Test public void testPerformanceFakeGenericSingleThread() throws Exception { final Method fooMethod = ExampleStringClass.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleStringClass.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleStringClass.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); } @Test public void testPerformanceNonGenericSingleThread() throws Exception { final Method fooMethod = ExampleStringSubclass.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleStringSubclass.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleStringSubclass.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); } @Test public void testPerformanceRealGenericMultipleThreads() throws Exception { final Method barMethod = ExampleStringClass.class.getMethod("bar", Object.class); - runTest(ExampleStringClass.class, barMethod, 100000, 100, new Class[] { String.class }); + runTest(ExampleStringClass.class, barMethod, 100000, 100, new Class[]{String.class}); } @Test public void testPerformanceFakeGenericMultipleThreads() throws Exception { final Method fooMethod = ExampleStringClass.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleStringClass.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleStringClass.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); } @Test public void testPerformanceNotGenericMultipleThreads() throws Exception { final Method fooMethod = ExampleStringSubclass.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleStringSubclass.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleStringSubclass.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); } @Test @@ -191,53 +201,53 @@ public void testPerformanceMultipleClassesMultipleMethodsSingleThread() throws E Method barMethod = ExampleTwoMethodClass.class.getMethod("bar", String.class); Method fooMethod = ExampleTwoMethodClass.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass2.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass2.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass2.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass2.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass2.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass2.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass3.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass3.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass3.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass3.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass3.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass3.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass4.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass4.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass4.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass4.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass4.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass4.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass5.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass5.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass5.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass5.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass5.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass5.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass6.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass6.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass6.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass6.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass6.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass6.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass7.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass7.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass7.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass7.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass7.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass7.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass8.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass8.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass8.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass8.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass8.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass8.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass9.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass9.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass9.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass9.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass9.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass9.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass10.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass10.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass10.class, barMethod, 10000000, 1, new Class[] { String.class }); - runTest(ExampleTwoMethodClass10.class, fooMethod, 10000000, 1, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass10.class, barMethod, 10000000, 1, new Class[]{String.class}); + runTest(ExampleTwoMethodClass10.class, fooMethod, 10000000, 1, new Class[]{Integer.class, Date.class}); final long testEndNanoTime = System.nanoTime(); final long elapsedTestNanoTime = testEndNanoTime - testStartNanoTime; @@ -259,53 +269,53 @@ public void testPerformanceMultipleClassesMultipleMethodsMultipleThreads() throw Method barMethod = ExampleTwoMethodClass.class.getMethod("bar", String.class); Method fooMethod = ExampleTwoMethodClass.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass2.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass2.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass2.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass2.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass2.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass2.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass3.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass3.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass3.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass3.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass3.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass3.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass4.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass4.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass4.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass4.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass4.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass4.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass5.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass5.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass5.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass5.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass5.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass5.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass6.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass6.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass6.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass6.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass6.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass6.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass7.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass7.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass7.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass7.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass7.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass7.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass8.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass8.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass8.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass8.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass8.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass8.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass9.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass9.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass9.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass9.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass9.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass9.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); barMethod = ExampleTwoMethodClass10.class.getMethod("bar", String.class); fooMethod = ExampleTwoMethodClass10.class.getMethod("foo", Integer.class, Date.class); - runTest(ExampleTwoMethodClass10.class, barMethod, 100000, 100, new Class[] { String.class }); - runTest(ExampleTwoMethodClass10.class, fooMethod, 100000, 100, new Class[] { Integer.class, Date.class }); + runTest(ExampleTwoMethodClass10.class, barMethod, 100000, 100, new Class[]{String.class}); + runTest(ExampleTwoMethodClass10.class, fooMethod, 100000, 100, new Class[]{Integer.class, Date.class}); final long testEndNanoTime = System.nanoTime(); final long elapsedTestNanoTime = testEndNanoTime - testStartNanoTime; @@ -375,7 +385,7 @@ public void testMajorJavaVersionCheck() { /** * Test OgnlRuntime value for _useJDK9PlusAccessHandler based on the System property - * represented by {@link OgnlRuntime#USE_JDK9PLUS_ACESS_HANDLER}. + * represented by {@link OgnlRuntime#USE_JDK9PLUS_ACCESS_HANDLER}. */ @Test public void testAccessHanderStateFlag() { @@ -384,7 +394,7 @@ public void testAccessHanderStateFlag() { boolean optionDefinedInEnvironment = false; // Track if option defined in environment boolean flagValueFromEnvironment = false; // Value result from environment retrieval try { - final String propertyString = System.getProperty(OgnlRuntime.USE_JDK9PLUS_ACESS_HANDLER); + final String propertyString = System.getProperty(OgnlRuntime.USE_JDK9PLUS_ACCESS_HANDLER); if (propertyString != null && propertyString.length() > 0) { optionDefinedInEnvironment = true; flagValueFromEnvironment = Boolean.parseBoolean(propertyString); @@ -393,9 +403,9 @@ public void testAccessHanderStateFlag() { // Unavailable (SecurityException, etc.) } if (optionDefinedInEnvironment) { - System.out.println("System property " + OgnlRuntime.USE_JDK9PLUS_ACESS_HANDLER + " value: " + flagValueFromEnvironment); + System.out.println("System property " + OgnlRuntime.USE_JDK9PLUS_ACCESS_HANDLER + " value: " + flagValueFromEnvironment); } else { - System.out.println("System property " + OgnlRuntime.USE_JDK9PLUS_ACESS_HANDLER + " not present. Default value should be: " + defaultValue); + System.out.println("System property " + OgnlRuntime.USE_JDK9PLUS_ACCESS_HANDLER + " not present. Default value should be: " + defaultValue); } System.out.println("Current OGNL value for use JDK9+ Access Handler: " + OgnlRuntime.getUseJDK9PlusAccessHandlerValue()); Assert.assertEquals("Mismatch between system property (or default) and OgnlRuntime _usJDK9PlusAccessHandler flag state ?", @@ -404,7 +414,7 @@ public void testAccessHanderStateFlag() { /** * Test OgnlRuntime value for _useStricterInvocation based on the System properties - * represented by {@link OgnlRuntime#USE_STRICTER_INVOCATION}. + * represented by {@link OgnlRuntime#USE_STRICTER_INVOCATION}. */ @Test public void testUseStricterInvocationStateFlag() { @@ -439,13 +449,13 @@ public void testStricterInvocationMode() { // Ensure no exceptions, basic ouput for test report and sanity check on flag state. // Note: If stricter invocation mode is disabled (due to a system property being set for // the JVM running the test) this test will not fail, but just skip the test. - if ( OgnlRuntime.getUseStricterInvocationValue()) { + if (OgnlRuntime.getUseStricterInvocationValue()) { try { final Class[] singleClassArgument = new Class[1]; singleClassArgument[0] = int.class; final Method exitMethod = System.class.getMethod("exit", singleClassArgument); try { - OgnlRuntime.invokeMethod(System.class, exitMethod, new Object[] { -1 }); + OgnlRuntime.invokeMethod(System.class, exitMethod, new Object[]{-1}); Assert.fail("Somehow got past invocation of a restricted exit call (nonsensical result) ?"); } catch (IllegalAccessException iae) { // Expected failure (failed during invocation) @@ -458,7 +468,7 @@ public void testStricterInvocationMode() { singleClassArgument[0] = String.class; final Method execMethod = Runtime.class.getMethod("exec", singleClassArgument); try { - OgnlRuntime.invokeMethod(Runtime.getRuntime(), execMethod, new Object[] { "fakeCommand" }); + OgnlRuntime.invokeMethod(Runtime.getRuntime(), execMethod, new Object[]{"fakeCommand"}); Assert.fail("Somehow got past invocation of a restricted exec call ?"); } catch (IllegalAccessException iae) { // Expected failure (failed during invocation) @@ -477,7 +487,7 @@ public void testStricterInvocationMode() { /** * Test OgnlRuntime value for _useFirstMatchGetSetLookup based on the System property - * represented by {@link OgnlRuntime#USE_FIRSTMATCH_GETSET_LOOKUP}. + * represented by {@link OgnlRuntime#USE_FIRSTMATCH_GETSET_LOOKUP}. */ @Test public void testUseFirstMatchGetSetStateFlag() { @@ -504,7 +514,7 @@ public void testUseFirstMatchGetSetStateFlag() { optionDefinedInEnvironment ? flagValueFromEnvironment : defaultValue, OgnlRuntime.getUseFirstMatchGetSetLookupValue()); } - private Map defaultContext = Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); + private final OgnlContext defaultContext = Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); @Test // Success public void testForArray() throws Exception { @@ -532,19 +542,24 @@ static class Bean { public void setChars(Character[] chars) { this.chars = chars; } + public Character[] getChars() { return chars; } + public void setStrings(String... strings) { this.strings = strings; } + public String[] getStrings() { return strings; } + public void setMix(Integer index, String... strings) { this.index = index; this.strings = strings; } + public Integer getIndex() { return index; } @@ -612,12 +627,11 @@ public Long get() { } @Test - public void shouldSameMethodOfDifferentParentsBeCallable() - throws Exception { + public void shouldSameMethodOfDifferentParentsBeCallable() throws Exception { Map root = new HashMap<>(); root.put("d1", java.sql.Date.valueOf("2022-01-01")); root.put("d2", java.sql.Date.valueOf("2022-01-02")); - Assert.assertEquals(-1, - Ognl.getValue("d1.compareTo(d2)", defaultContext, root)); + Assert.assertEquals(-1, Ognl.getValue("d1.compareTo(d2)", defaultContext, root)); } + } diff --git a/src/test/java/ognl/TestOgnlRuntime.java b/src/test/java/ognl/TestOgnlRuntime.java index a46be5e9..81834b9c 100644 --- a/src/test/java/ognl/TestOgnlRuntime.java +++ b/src/test/java/ognl/TestOgnlRuntime.java @@ -1,7 +1,23 @@ package ognl; import junit.framework.TestCase; -import org.ognl.test.objects.*; +import ognl.test.objects.BaseGeneric; +import ognl.test.objects.Bean2; +import ognl.test.objects.FormImpl; +import ognl.test.objects.GameGeneric; +import ognl.test.objects.GameGenericObject; +import ognl.test.objects.GenericCracker; +import ognl.test.objects.GenericService; +import ognl.test.objects.GenericServiceImpl; +import ognl.test.objects.GetterMethods; +import ognl.test.objects.IComponent; +import ognl.test.objects.IForm; +import ognl.test.objects.ListSource; +import ognl.test.objects.ListSourceImpl; +import ognl.test.objects.OtherEnum; +import ognl.test.objects.Root; +import ognl.test.objects.SetterReturns; +import ognl.test.objects.SubclassSyntheticObject; import java.beans.PropertyDescriptor; import java.io.Serializable; @@ -10,7 +26,6 @@ import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; -import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -18,20 +33,18 @@ import java.util.concurrent.atomic.AtomicInteger; /** - * Tests various methods / functionality of {@link ognl.OgnlRuntime}. + * Tests various methods / functionality of {@link OgnlRuntime}. */ public class TestOgnlRuntime extends TestCase { - - private Map context; + private OgnlContext context; public void setUp() throws Exception { super.setUp(); context = Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); } - public void test_Get_Super_Or_Interface_Class() throws Exception - { + public void test_Get_Super_Or_Interface_Class() { ListSource list = new ListSourceImpl(); Method m = OgnlRuntime.getReadMethod(list.getClass(), "total"); @@ -40,9 +53,8 @@ public void test_Get_Super_Or_Interface_Class() throws Exception assertEquals(ListSource.class, OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, list.getClass())); } - public void test_Get_Private_Class() throws Exception - { - List list = Arrays.asList(new String[]{"hello", "world"}); + public void test_Get_Private_Class() { + List list = Arrays.asList("hello", "world"); Method m = OgnlRuntime.getReadMethod(list.getClass(), "iterator"); assertNotNull(m); @@ -50,8 +62,7 @@ public void test_Get_Private_Class() throws Exception assertEquals(Iterable.class, OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, list.getClass())); } - public void test_Complicated_Inheritance() throws Exception - { + public void test_Complicated_Inheritance() { IForm form = new FormImpl(); Method m = OgnlRuntime.getWriteMethod(form.getClass(), "clientId"); @@ -60,18 +71,14 @@ public void test_Complicated_Inheritance() throws Exception assertEquals(IComponent.class, OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, form.getClass())); } - public void test_Get_Read_Method() - throws Exception - { + public void test_Get_Read_Method() { Method m = OgnlRuntime.getReadMethod(Bean2.class, "pageBreakAfter"); assertNotNull(m); assertEquals("isPageBreakAfter", m.getName()); } - public void test_Get_Read_Field() - throws Exception - { + public void test_Get_Read_Field() { Method m = OgnlRuntime.getReadMethod(Bean2.class, "code"); assertNull(m); @@ -80,14 +87,12 @@ public void test_Get_Read_Field() assertEquals("code", field.getName()); } - class TestGetters { - public boolean isEditorDisabled() - { + static class TestGetters { + public boolean isEditorDisabled() { return false; } - public boolean isDisabled() - { + public boolean isDisabled() { return true; } @@ -100,18 +105,14 @@ public boolean isAvailable() { } } - public void test_Get_Read_Method_Multiple() - throws Exception - { + public void test_Get_Read_Method_Multiple() { Method m = OgnlRuntime.getReadMethod(TestGetters.class, "disabled"); assertNotNull(m); assertEquals("isDisabled", m.getName()); } - public void test_Get_Read_Method_Multiple_Boolean_Getters() - throws Exception - { + public void test_Get_Read_Method_Multiple_Boolean_Getters() { Method m = OgnlRuntime.getReadMethod(TestGetters.class, "available"); assertNotNull(m); @@ -123,9 +124,7 @@ public void test_Get_Read_Method_Multiple_Boolean_Getters() assertEquals("isNotAvailable", m.getName()); } - public void test_Find_Method_Mixed_Boolean_Getters() - throws Exception - { + public void test_Find_Method_Mixed_Boolean_Getters() { Method m = OgnlRuntime.getReadMethod(GetterMethods.class, "allowDisplay"); assertNotNull(m); @@ -133,70 +132,65 @@ public void test_Find_Method_Mixed_Boolean_Getters() } public void test_Get_Appropriate_Method() - throws Exception - { + throws Exception { ListSource list = new ListSourceImpl(); - OgnlContext context = (OgnlContext) this.context; + OgnlContext context = this.context; + + Object ret = OgnlRuntime.callMethod(context, list, "addValue", new String[]{null}); - Object ret = OgnlRuntime.callMethod(context, list, "addValue", new String[] {null}); - assert ret != null; } - public void test_Call_Static_Method_Invalid_Class() - { + public void test_Call_Static_Method_Invalid_Class() { try { - OgnlContext context = (OgnlContext) this.context; + OgnlContext context = this.context; OgnlRuntime.callStaticMethod(context, "made.up.Name", "foo", null); fail("ClassNotFoundException should have been thrown by previous reference to class."); } catch (Exception et) { - assertTrue(MethodFailedException.class.isInstance(et)); - assertTrue(et.getMessage().indexOf("made.up.Name") > -1); + assertTrue(et instanceof MethodFailedException); + assertTrue(et.getMessage().contains("made.up.Name")); } } public void test_Setter_Returns() - throws Exception - { - OgnlContext context = (OgnlContext) this.context; + throws Exception { + OgnlContext context = this.context; SetterReturns root = new SetterReturns(); Method m = OgnlRuntime.getWriteMethod(root.getClass(), "value"); - assertTrue(m != null); + assertNotNull(m); Ognl.setValue("value", context, root, "12__"); assertEquals(Ognl.getValue("value", context, root), "12__"); } public void test_Call_Method_VarArgs() - throws Exception - { - OgnlContext context = (OgnlContext) this.context; + throws Exception { + OgnlContext context = this.context; GenericService service = new GenericServiceImpl(); GameGenericObject argument = new GameGenericObject(); - Object[] args = OgnlRuntime.getObjectArrayPool().create(2); + Object[] args = new Object[2]; args[0] = argument; assertEquals("Halo 3", OgnlRuntime.callMethod(context, service, "getFullMessageFor", args)); } - public void test_Call_Method_In_JDK_Sandbox() - throws Exception { - if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue() == true) { + public void test_Call_Method_In_JDK_Sandbox() { + if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue()) { System.out.println("OGNL SecurityManager sandbox disabled by JVM option. Skipping test_Call_Method_In_JDK_Sandbox() -invocation test."); return; // JVM option was set to disable sandbox, do not attempt invocation. } - OgnlContext context = (OgnlContext) this.context; + OgnlContext context = this.context; GenericService service = new GenericServiceImpl(); - Object[] args = OgnlRuntime.getObjectArrayPool().create(1); + Object[] args = new Object[1]; args[0] = 0; boolean temporaryEnabled = false; @@ -212,7 +206,7 @@ public void test_Call_Method_In_JDK_Sandbox() fail("JDK sandbox should block execution"); } catch (Exception ex) { assertTrue(ex.getCause() instanceof InvocationTargetException); - assertTrue(((InvocationTargetException)ex.getCause()).getTargetException().getMessage().contains("execute")); + assertTrue(((InvocationTargetException) ex.getCause()).getTargetException().getMessage().contains("execute")); } finally { if (temporaryEnabled) { System.clearProperty(OgnlRuntime.OGNL_SECURITY_MANAGER); @@ -222,12 +216,12 @@ public void test_Call_Method_In_JDK_Sandbox() public void test_Call_Method_In_JDK_Sandbox_Thread_Safety() throws Exception { - if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue() == true) { + if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue()) { System.out.println("OGNL SecurityManager sandbox disabled by JVM option. Skipping test_Call_Method_In_JDK_Sandbox_Thread_Safety() invocation test."); return; // JVM option was set to disable sandbox, do not attempt invocation. } - final OgnlContext context = (OgnlContext) this.context; + final OgnlContext context = this.context; final GenericService service = new GenericServiceImpl(); boolean temporaryEnabled = false; @@ -245,32 +239,30 @@ public void test_Call_Method_In_JDK_Sandbox_Thread_Safety() final CountDownLatch allThreadsWaitOnThis = new CountDownLatch(1); final AtomicInteger numThreadsFailedTest = new AtomicInteger(0); for (int i = 0; i < NUM_THREADS; ++i) { - exec.submit(new Runnable() { - public void run() { - try { - allThreadsWaitOnThis.await(); - } catch (InterruptedException ignored) { - } - - try { - Thread.sleep((long) (Math.random() * MAX_WAIT_MS)); - } catch (InterruptedException ignored) { - } + exec.submit(() -> { + try { + allThreadsWaitOnThis.await(); + } catch (InterruptedException ignored) { + } - Object[] args = OgnlRuntime.getObjectArrayPool().create(1); - args[0] = Math.random() * MAX_WAIT_MS; + try { + Thread.sleep((long) (Math.random() * MAX_WAIT_MS)); + } catch (InterruptedException ignored) { + } - try { - OgnlRuntime.callMethod(context, service, "exec", args); + Object[] args = new Object[1]; + args[0] = Math.random() * MAX_WAIT_MS; + + try { + OgnlRuntime.callMethod(context, service, "exec", args); + numThreadsFailedTest.incrementAndGet(); + } catch (Exception ex) { + if (!((ex.getCause() instanceof InvocationTargetException && + ((InvocationTargetException) ex.getCause()).getTargetException().getMessage().contains("execute")) + || + (ex.getCause() instanceof SecurityException && + ex.getCause().getMessage().contains("createClassLoader")))) { numThreadsFailedTest.incrementAndGet(); - } catch (Exception ex) { - if (!((ex.getCause() instanceof InvocationTargetException && - ((InvocationTargetException)ex.getCause()).getTargetException().getMessage().contains("execute")) - || - (ex.getCause() instanceof SecurityException && - ex.getCause().getMessage().contains("createClassLoader")))) { - numThreadsFailedTest.incrementAndGet(); - } } } }); @@ -292,17 +284,16 @@ public void run() { } } - public void test_Disable_JDK_Sandbox() - throws Exception { - if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue() == true) { + public void test_Disable_JDK_Sandbox() { + if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue()) { System.out.println("OGNL SecurityManager sandbox disabled by JVM option. Skipping test_Disable_JDK_Sandbox() invocation test."); return; // JVM option was set to disable sandbox, do not attempt invocation. } - OgnlContext context = (OgnlContext) this.context; + OgnlContext context = this.context; GenericService service = new GenericServiceImpl(); - Object[] args = OgnlRuntime.getObjectArrayPool().create(0); + Object[] args = new Object[]{}; boolean temporaryEnabled = false; try { @@ -317,8 +308,8 @@ public void test_Disable_JDK_Sandbox() fail("JDK sandbox should block execution"); } catch (Exception ex) { assertTrue(ex.getCause() instanceof InvocationTargetException); - assertTrue(((InvocationTargetException)ex.getCause()).getTargetException().getMessage().contains(OgnlRuntime.OGNL_SECURITY_MANAGER)); - assertTrue(((InvocationTargetException)ex.getCause()).getTargetException().getMessage().contains("write")); + assertTrue(((InvocationTargetException) ex.getCause()).getTargetException().getMessage().contains(OgnlRuntime.OGNL_SECURITY_MANAGER)); + assertTrue(((InvocationTargetException) ex.getCause()).getTargetException().getMessage().contains("write")); } finally { if (temporaryEnabled) { System.clearProperty(OgnlRuntime.OGNL_SECURITY_MANAGER); @@ -357,8 +348,8 @@ public void test_Disable_JDK_Sandbox() fail("JDK sandbox should block execution"); } catch (Exception ex) { assertTrue(ex.getCause() instanceof InvocationTargetException); - assertTrue(((InvocationTargetException)ex.getCause()).getTargetException() instanceof SecurityException); - assertNull(((InvocationTargetException)ex.getCause()).getTargetException().getMessage()); + assertTrue(((InvocationTargetException) ex.getCause()).getTargetException() instanceof SecurityException); + assertNull(((InvocationTargetException) ex.getCause()).getTargetException().getMessage()); } finally { if (temporaryEnabled) { System.clearProperty(OgnlRuntime.OGNL_SECURITY_MANAGER); @@ -366,17 +357,16 @@ public void test_Disable_JDK_Sandbox() } } - public void test_Exit_JDK_Sandbox() - throws Exception { - if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue() == true) { + public void test_Exit_JDK_Sandbox() { + if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue()) { System.out.println("OGNL SecurityManager sandbox disabled by JVM option. Skipping test_Exit_JDK_Sandbox() invocation test."); return; // JVM option was set to disable sandbox, do not attempt invocation. } - OgnlContext context = (OgnlContext) this.context; + OgnlContext context = this.context; GenericService service = new GenericServiceImpl(); - Object[] args = OgnlRuntime.getObjectArrayPool().create(0); + Object[] args = new Object[]{}; boolean temporaryEnabled = false; try { @@ -391,7 +381,7 @@ public void test_Exit_JDK_Sandbox() fail("JDK sandbox should block execution"); } catch (Exception ex) { assertTrue(ex.getCause() instanceof InvocationTargetException); - assertTrue(((InvocationTargetException)ex.getCause()).getTargetException().getMessage().contains("exit")); + assertTrue(((InvocationTargetException) ex.getCause()).getTargetException().getMessage().contains("exit")); } finally { if (temporaryEnabled) { System.clearProperty(OgnlRuntime.OGNL_SECURITY_MANAGER); @@ -399,17 +389,16 @@ public void test_Exit_JDK_Sandbox() } } - public void test_Call_Method_In_JDK_Sandbox_Privileged() - throws Exception { - if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue() == true) { + public void test_Call_Method_In_JDK_Sandbox_Privileged() throws Exception { + if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue()) { System.out.println("OGNL SecurityManager sandbox disabled by JVM option. Skipping test_Call_Method_In_JDK_Sandbox_Privileged() invocation test."); return; // JVM option was set to disable sandbox, do not attempt invocation. } - OgnlContext context = (OgnlContext) this.context; + OgnlContext context = this.context; GenericService service = new GenericServiceImpl(); - Object[] args = OgnlRuntime.getObjectArrayPool().create(0); + Object[] args = new Object[]{}; boolean temporaryEnabled = false; try { @@ -452,17 +441,16 @@ public void test_Call_Method_In_JDK_Sandbox_Privileged() } } - public void test_Class_Loader_Direct_Access() - throws Exception { - if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue() == true) { + public void test_Class_Loader_Direct_Access() { + if (OgnlRuntime.getDisableOgnlSecurityManagerOnInitValue()) { System.out.println("OGNL SecurityManager sandbox disabled by JVM option. Skipping test_Class_Loader_Direct_Access() invocation test."); return; // JVM option was set to disable sandbox, do not attempt invocation. } - OgnlContext context = (OgnlContext) this.context; + OgnlContext context = this.context; ClassLoader classLoader = getClass().getClassLoader(); - Object[] args = OgnlRuntime.getObjectArrayPool().create(1); + Object[] args = new Object[1]; args[0] = "test.properties"; boolean temporaryEnabled = false; @@ -478,7 +466,7 @@ public void test_Class_Loader_Direct_Access() fail("JDK sandbox should block execution"); } catch (Exception ex) { assertTrue(ex.getCause() instanceof IllegalAccessException); - if (OgnlRuntime.getUseStricterInvocationValue() == true) { + if (OgnlRuntime.getUseStricterInvocationValue()) { // Blocked by stricter invocation check first, if active. assertTrue("Didn't find expected stricter invocation mode exception message ?", ex.getCause().getMessage().endsWith("] cannot be called from within OGNL invokeMethod() under stricter invocation mode.")); @@ -494,152 +482,129 @@ public void test_Class_Loader_Direct_Access() } public void test_Class_Cache_Inspector() - throws Exception - { + throws Exception { OgnlRuntime.clearCache(); OgnlRuntime.clearAdditionalCache(); // Testing no exception only. - assertEquals(0, OgnlRuntime._propertyDescriptorCache.getSize()); - assertEquals(0, OgnlRuntime._genericMethodParameterTypesCache.size()); + assertEquals(0, OgnlRuntime.cache.propertyDescriptorCache.getSize()); + assertEquals(0, OgnlRuntime.cache.genericMethodParameterTypesCache.getSize()); Root root = new Root(); - OgnlContext context = (OgnlContext) this.context; + OgnlContext context = this.context; Node expr = Ognl.compileExpression(context, root, "property.bean3.value != null"); - assertTrue((Boolean)expr.getAccessor().get(context, root)); + assertTrue((Boolean) expr.getAccessor().get(context, root)); - int size = OgnlRuntime._propertyDescriptorCache.getSize(); + int size = OgnlRuntime.cache.propertyDescriptorCache.getSize(); assertTrue(size > 0); OgnlRuntime.clearCache(); OgnlRuntime.clearAdditionalCache(); // Testing no exception only. - assertEquals(0, OgnlRuntime._propertyDescriptorCache.getSize()); - assertEquals(0, OgnlRuntime._genericMethodParameterTypesCache.size()); + assertEquals(0, OgnlRuntime.cache.propertyDescriptorCache.getSize()); + assertEquals(0, OgnlRuntime.cache.genericMethodParameterTypesCache.getSize()); // now register class cache prevention OgnlRuntime.setClassCacheInspector(new TestCacheInspector()); expr = Ognl.compileExpression(context, root, "property.bean3.value != null"); - assertTrue((Boolean)expr.getAccessor().get(context, root)); + assertTrue((Boolean) expr.getAccessor().get(context, root)); - assertEquals((size - 1), OgnlRuntime._propertyDescriptorCache.getSize()); + assertEquals((size - 1), OgnlRuntime.cache.propertyDescriptorCache.getSize()); } - class TestCacheInspector implements ClassCacheInspector { - - public boolean shouldCache(Class type) - { - if (type == null || type == Root.class) - return false; + static class TestCacheInspector implements ClassCacheInspector { - return true; + public boolean shouldCache(Class type) { + return type != null && type != Root.class; } } - public void test_Set_Generic_Parameter_Types() - throws Exception - { - OgnlContext context = (OgnlContext) this.context; + public void test_Set_Generic_Parameter_Types() { + OgnlContext context = this.context; Method m = OgnlRuntime.getSetMethod(context, GenericCracker.class, "param"); assertNotNull(m); - Class[] types = m.getParameterTypes(); + Class[] types = m.getParameterTypes(); assertEquals(1, types.length); assertEquals(Integer.class, types[0]); } - public void test_Get_Generic_Parameter_Types() - throws Exception - { - OgnlContext context = (OgnlContext) this.context; + public void test_Get_Generic_Parameter_Types() { - Method m = OgnlRuntime.getGetMethod(context, GenericCracker.class, "param"); + Method m = OgnlRuntime.getGetMethod(GenericCracker.class, "param"); assertNotNull(m); assertEquals(Integer.class, m.getReturnType()); } - public void test_Find_Parameter_Types() - throws Exception - { - OgnlContext context = (OgnlContext) this.context; + public void test_Find_Parameter_Types() { + OgnlContext context = this.context; Method m = OgnlRuntime.getSetMethod(context, GameGeneric.class, "ids"); assertNotNull(m); - Class[] types = OgnlRuntime.findParameterTypes(GameGeneric.class, m); + Class[] types = OgnlRuntime.findParameterTypes(GameGeneric.class, m); assertEquals(1, types.length); - assertEquals(new Long[0].getClass(), types[0]); + assertEquals(Long[].class, types[0]); } - public void test_Find_Parameter_Types_Superclass() - throws Exception - { - OgnlContext context = (OgnlContext) this.context; + public void test_Find_Parameter_Types_Superclass() { + OgnlContext context = this.context; Method m = OgnlRuntime.getSetMethod(context, BaseGeneric.class, "ids"); assertNotNull(m); - Class[] types = OgnlRuntime.findParameterTypes(BaseGeneric.class, m); + Class[] types = OgnlRuntime.findParameterTypes(BaseGeneric.class, m); assertEquals(1, types.length); - assertEquals(new Serializable[0].getClass(), types[0]); + assertEquals(Serializable[].class, types[0]); } - public void test_Get_Declared_Methods_With_Synthetic_Methods() - throws Exception - { - List result = OgnlRuntime.getDeclaredMethods(SubclassSyntheticObject.class, "list", false); + public void test_Get_Declared_Methods_With_Synthetic_Methods() { + List result = OgnlRuntime.getDeclaredMethods(SubclassSyntheticObject.class, "list", false); - // synthetic method would be "public volatile java.util.List org.ognl.test.objects.SubclassSyntheticObject.getList()", + // synthetic method would be "public volatile java.util.List ognl.test.objects.SubclassSyntheticObject.getList()", // causing method return size to be 3 - + assertEquals(2, result.size()); } public void test_Get_Property_Descriptors_With_Synthetic_Methods() - throws Exception - { + throws Exception { PropertyDescriptor pd = OgnlRuntime.getPropertyDescriptor(SubclassSyntheticObject.class, "list"); assert pd != null; assert OgnlRuntime.isMethodCallable(pd.getReadMethod()); } - private static class GenericParent - { - public void save(T entity) - { - - } - } + private static class GenericParent { + public void save(T entity) { + } + } - private static class StringChild extends GenericParent - { + private static class StringChild extends GenericParent { - } + } - private static class LongChild extends GenericParent - { + private static class LongChild extends GenericParent { - } + } - /** - * Tests OGNL parameter discovery. - */ - public void testOGNLParameterDiscovery() throws NoSuchMethodException - { - Method saveMethod = GenericParent.class.getMethod("save", Object.class); - System.out.println(saveMethod); + /** + * Tests OGNL parameter discovery. + */ + public void testOGNLParameterDiscovery() throws NoSuchMethodException { + Method saveMethod = GenericParent.class.getMethod("save", Object.class); + System.out.println(saveMethod); - Class[] longClass = OgnlRuntime.findParameterTypes(LongChild.class, saveMethod); - assertNotSame(longClass[0], String.class); - assertSame(longClass[0], Long.class); + Class[] longClass = OgnlRuntime.findParameterTypes(LongChild.class, saveMethod); + assertNotSame(longClass[0], String.class); + assertSame(longClass[0], Long.class); - Class[] stringClass = OgnlRuntime.findParameterTypes(StringChild.class, saveMethod); - assertNotSame("The cached parameter types from previous calls are used", stringClass[0], Long.class); - assertSame(stringClass[0], String.class); - } + Class[] stringClass = OgnlRuntime.findParameterTypes(StringChild.class, saveMethod); + assertNotSame("The cached parameter types from previous calls are used", stringClass[0], Long.class); + assertSame(stringClass[0], String.class); + } public void testBangOperator() throws Exception { Object value = Ognl.getValue("!'false'", context, new Object()); @@ -647,33 +612,31 @@ public void testBangOperator() throws Exception { } public void testGetStaticField() throws Exception { - OgnlContext context = (OgnlContext) this.context; - Object obj = OgnlRuntime.getStaticField(context, "org.ognl.test.objects.Root", "SIZE_STRING"); + OgnlContext context = this.context; + Object obj = OgnlRuntime.getStaticField(context, "ognl.test.objects.Root", "SIZE_STRING"); assertEquals(Root.SIZE_STRING, obj); } public void testGetStaticFieldEnum() throws Exception { - OgnlContext context = (OgnlContext) this.context; - Object obj = OgnlRuntime.getStaticField(context, "org.ognl.test.objects.OtherEnum", "ONE"); + OgnlContext context = this.context; + Object obj = OgnlRuntime.getStaticField(context, "ognl.test.objects.OtherEnum", "ONE"); assertEquals(OtherEnum.ONE, obj); } public void testGetStaticFieldEnumStatic() throws Exception { - OgnlContext context = (OgnlContext) this.context; - Object obj = OgnlRuntime.getStaticField(context, "org.ognl.test.objects.OtherEnum", "STATIC_STRING"); + OgnlContext context = this.context; + Object obj = OgnlRuntime.getStaticField(context, "ognl.test.objects.OtherEnum", "STATIC_STRING"); assertEquals(OtherEnum.STATIC_STRING, obj); } /** * This test indirectly confirms an error output (syserr) is no longer produced when OgnlRuntime - * encounters the condition reported in issue #17. {@link OgnlRuntime#findBestMethod} can find - * two appropriate methods with the same score where one is abstract and one is concrete. Either + * encounters the condition reported in issue #17. {@link OgnlRuntime#findBestMethod(List, Class, String, Class[])} + * can find two appropriate methods with the same score where one is abstract and one is concrete. Either * choice in that scenario actually worked when invoked, but produced the unwanted syserr output. - * - * @throws Exception */ public void testAbstractConcreteMethodScoringNoSysErr() throws Exception { - OgnlContext context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); + OgnlContext context = Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); ObjectMethodAccessor methodAccessor = new ObjectMethodAccessor(); ConcreteTestClass concreteTestClass = new ConcreteTestClass(); Object result = methodAccessor.callMethod(context, concreteTestClass, "testMethod", new Object[]{"Test", 1}); @@ -686,15 +649,15 @@ public void testAbstractConcreteMethodScoringNoSysErr() throws Exception { * * @param */ - abstract class AbstractTestClass { - public abstract String testMethod (T element, int i); + abstract static class AbstractTestClass { + public abstract String testMethod(T element, int i); } /** * Concrete test class for issue #42 - equal score syserr output for abstract class/method hierarchy. */ - class ConcreteTestClass extends AbstractTestClass < String > { - public String testMethod (String element, int i) { + static class ConcreteTestClass extends AbstractTestClass { + public String testMethod(String element, int i) { return element + i; } } @@ -705,6 +668,7 @@ public String testMethod (String element, int i) { protected static class ProtectedParent { public void setName(String name) { } + public String getName() { return "name"; } @@ -718,24 +682,20 @@ public static class PublicChild extends ProtectedParent { /** * Test that synthetic bridge read methods can be found successfully. - * + *

    * Note: Only bridge methods should qualify, non-bridge synthetic methods should not. - * - * @throws Exception */ - public void testSyntheticBridgeReadMethod() throws Exception { + public void testSyntheticBridgeReadMethod() { assertNotNull(OgnlRuntime.getReadMethod(PublicChild.class, "name")); } /** * Test that synthetic bridge write methods can be found successfully. - * + *

    * Note: Only bridge methods should qualify, non-bridge synthetic methods should not. - * - * @throws Exception */ - public void testSyntheticBridgeWriteMethod() throws Exception { - assertNotNull(OgnlRuntime.getWriteMethod(PublicChild.class, "name")); + public void testSyntheticBridgeWriteMethod() { + assertNotNull(OgnlRuntime.getWriteMethod(PublicChild.class, "name", new Class[]{String.class})); } /** @@ -753,7 +713,8 @@ public String getName() { * Public class with non-public nested class for "is callable" method tests. */ public static class SimpleNestingClass { - class NestedClass { + static class NestedClass { + // do not use "final" private String name = "nested name contents"; } @@ -773,7 +734,7 @@ public void testConfirmStandardMethodCallability() { fail("SimplePublicClass.getName() method retrieval by reflection failed (NoSuchMethodException) ?"); } assertNotNull("getName() method retrieval failed ?", method); - assertTrue("SimplePublicClass.getName() is a synthetic or bridge method ?", !(method.isBridge() || method.isSynthetic())); + assertFalse("SimplePublicClass.getName() is a synthetic or bridge method ?", method.isBridge() || method.isSynthetic()); assertTrue("SimplePublicClass.getName() is not considered callable by isMethodCallable() ?", OgnlRuntime.isMethodCallable(method)); assertTrue("SimplePublicClass.getName() is not considered callable by isMethodCallable_BridgeOrNonSynthetic() ?", OgnlRuntime.isMethodCallable_BridgeOrNonSynthetic(method)); } diff --git a/src/test/java/org/ognl/test/ASTChainTest.java b/src/test/java/ognl/test/ASTChainTest.java similarity index 84% rename from src/test/java/org/ognl/test/ASTChainTest.java rename to src/test/java/ognl/test/ASTChainTest.java index 855f6952..a86b65a7 100644 --- a/src/test/java/org/ognl/test/ASTChainTest.java +++ b/src/test/java/ognl/test/ASTChainTest.java @@ -1,13 +1,14 @@ -package org.ognl.test; +package ognl.test; import junit.framework.TestCase; +import ognl.ASTChain; import ognl.DefaultMemberAccess; import ognl.Ognl; import ognl.OgnlContext; -import org.ognl.test.objects.IndexedSetObject; +import ognl.test.objects.IndexedSetObject; /** - * Tests for {@link ognl.ASTChain}. + * Tests for {@link ASTChain}. */ public class ASTChainTest extends TestCase { @@ -21,7 +22,7 @@ public void test_Get_Indexed_Value() throws Exception { assertEquals(1, Ognl.getValue(expr, context, root)); Ognl.setValue(expr, context, root, new Integer(2)); - + assertEquals(2, Ognl.getValue(expr, context, root)); } } diff --git a/src/test/java/org/ognl/test/ASTMethodTest.java b/src/test/java/ognl/test/ASTMethodTest.java similarity index 86% rename from src/test/java/org/ognl/test/ASTMethodTest.java rename to src/test/java/ognl/test/ASTMethodTest.java index dd95c7ac..abbd63c9 100644 --- a/src/test/java/org/ognl/test/ASTMethodTest.java +++ b/src/test/java/ognl/test/ASTMethodTest.java @@ -1,16 +1,23 @@ -package org.ognl.test; +package ognl.test; import junit.framework.TestCase; -import ognl.*; +import ognl.ASTConst; +import ognl.ASTMethod; +import ognl.ASTProperty; +import ognl.DefaultMemberAccess; +import ognl.Ognl; +import ognl.OgnlContext; +import ognl.OgnlRuntime; +import ognl.SimpleNode; import ognl.enhance.ExpressionCompiler; -import org.ognl.test.objects.Bean2; -import org.ognl.test.objects.Bean3; -import org.ognl.test.objects.Root; +import ognl.test.objects.Bean2; +import ognl.test.objects.Bean3; +import ognl.test.objects.Root; import java.util.Map; /** - * Tests {@link ognl.ASTMethod}. + * Tests {@link ASTMethod}. */ public class ASTMethodTest extends TestCase { @@ -22,41 +29,40 @@ public void setUp() throws Exception { } public void test_Context_Types() - throws Throwable - { + throws Throwable { ASTMethod p = new ASTMethod(0); p.setMethodName("get"); - + ASTConst pRef = new ASTConst(0); pRef.setValue("value"); p.jjtAddChild(pRef, 0); - + Root root = new Root(); OgnlContext context = (OgnlContext) this.context; context.setRoot(root.getMap()); context.setCurrentObject(root.getMap()); context.setCurrentType(root.getMap().getClass()); - + assertEquals(p.toGetSourceString(context, root.getMap()), ".get(\"value\")"); assertEquals(context.getCurrentType(), Object.class); assertEquals(root.getMap().get("value"), context.getCurrentObject()); assert Map.class.isAssignableFrom(context.getCurrentAccessor()); assert Map.class.isAssignableFrom(context.getPreviousType()); assert context.getPreviousAccessor() == null; - - assertEquals(OgnlRuntime.getCompiler().castExpression(context, p, ".get(\"value\")"), ".get(\"value\")"); + + assertEquals(OgnlRuntime.getCompiler().castExpression(context, p, ".get(\"value\")"), ".get(\"value\")"); assert context.get(ExpressionCompiler.PRE_CAST) == null; - + // now test one context level further to see casting work properly on base object types - + ASTProperty prop = new ASTProperty(0); ASTConst propRef = new ASTConst(0); propRef.setValue("bean3"); prop.jjtAddChild(propRef, 0); - Bean2 val = (Bean2)root.getMap().get("value"); - + Bean2 val = (Bean2) root.getMap().get("value"); + assertEquals(prop.toGetSourceString(context, root.getMap().get("value")), ".getBean3()"); assertEquals(context.getCurrentObject(), val.getBean3()); @@ -64,9 +70,9 @@ public void test_Context_Types() assertEquals(context.getCurrentAccessor(), Bean2.class); assertEquals(Object.class, context.getPreviousType()); assert Map.class.isAssignableFrom(context.getPreviousAccessor()); - + assertEquals(OgnlRuntime.getCompiler().castExpression(context, prop, ".getBean3()"), ").getBean3()"); - + } public void test_isSimpleMethod() throws Exception { diff --git a/src/test/java/org/ognl/test/ASTPropertyTest.java b/src/test/java/ognl/test/ASTPropertyTest.java similarity index 81% rename from src/test/java/org/ognl/test/ASTPropertyTest.java rename to src/test/java/ognl/test/ASTPropertyTest.java index 9c70cb2c..eb9aef8c 100644 --- a/src/test/java/org/ognl/test/ASTPropertyTest.java +++ b/src/test/java/ognl/test/ASTPropertyTest.java @@ -1,15 +1,27 @@ -package org.ognl.test; +package ognl.test; import junit.framework.TestCase; -import ognl.*; -import static org.ognl.test.OgnlTestCase.isEqual; -import org.ognl.test.objects.*; +import ognl.ASTChain; +import ognl.ASTConst; +import ognl.ASTProperty; +import ognl.DefaultMemberAccess; +import ognl.Ognl; +import ognl.OgnlContext; +import ognl.OgnlRuntime; +import ognl.SimpleNode; +import ognl.test.objects.BaseGeneric; +import ognl.test.objects.GameGeneric; +import ognl.test.objects.GameGenericObject; +import ognl.test.objects.GenericRoot; +import ognl.test.objects.Root; import java.util.List; import java.util.Map; +import static ognl.test.OgnlTestCase.isEqual; + /** - * Tests functionality of {@link ognl.ASTProperty}. + * Tests functionality of {@link ASTProperty}. */ public class ASTPropertyTest extends TestCase { @@ -20,8 +32,7 @@ public void setUp() throws Exception { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); } - public void test_Get_Indexed_Property_Type() throws Exception - { + public void test_Get_Indexed_Property_Type() throws Exception { ASTProperty p = new ASTProperty(0); p.setIndexedAccess(false); ASTConst pRef = new ASTConst(0); @@ -50,8 +61,7 @@ public void test_Get_Indexed_Property_Type() throws Exception assertEquals(null, context.getPreviousAccessor()); } - public void test_Get_Value_Body() throws Exception - { + public void test_Get_Value_Body() throws Exception { ASTProperty p = new ASTProperty(0); p.setIndexedAccess(false); ASTConst pRef = new ASTConst(0); @@ -81,8 +91,7 @@ public void test_Get_Value_Body() throws Exception } public void test_Get_Source() - throws Throwable - { + throws Throwable { ASTProperty p = new ASTProperty(0); p.setIndexedAccess(false); ASTConst pRef = new ASTConst(0); @@ -91,11 +100,11 @@ public void test_Get_Source() p.jjtAddChild(pRef, 0); Map root = new Root().getMap(); - + context.setRoot(root); context.setCurrentObject(root); context.setCurrentNode(pRef); - + assertEquals(".get(\"nested\")", p.toGetSourceString(context, root)); assertEquals(Object.class, context.getCurrentType()); assertEquals(Map.class, context.getCurrentAccessor()); @@ -111,21 +120,20 @@ public void test_Get_Source() } public void test_Set_Source() - throws Throwable - { + throws Throwable { ASTProperty p = new ASTProperty(0); p.setIndexedAccess(false); ASTConst pRef = new ASTConst(0); pRef.setValue("nested"); pRef.jjtSetParent(p); p.jjtAddChild(pRef, 0); - + Map root = new Root().getMap(); context.setRoot(root); context.setCurrentObject(root); context.setCurrentNode(pRef); - + assertEquals(".put(\"nested\", $3)", p.toSetSourceString(context, root)); assertEquals(Object.class, context.getCurrentType()); assertEquals(root.get("nested"), context.getCurrentObject()); @@ -137,10 +145,9 @@ public void test_Set_Source() } public void test_Indexed_Object_Type() - throws Throwable - { + throws Throwable { //ASTChain chain = new ASTChain(0); - + ASTProperty listp = new ASTProperty(0); listp.setIndexedAccess(false); //listp.jjtSetParent(chain); @@ -161,10 +168,10 @@ public void test_Indexed_Object_Type() pRef.setValue("genericIndex"); pRef.jjtSetParent(pindex); pindex.jjtAddChild(pRef, 0); - + p.jjtAddChild(pindex, 0); //chain.jjtAddChild(p, 1); - + Root root = new Root(); context.setRoot(root); @@ -179,7 +186,7 @@ public void test_Indexed_Object_Type() assertEquals(root.getList(), context.getCurrentObject()); // re test with chain - + context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); context.setRoot(root); context.setCurrentObject(root); @@ -199,33 +206,31 @@ public void test_Indexed_Object_Type() // test with only getIndex - assertEquals(".get(ognl.OgnlOps#getIntValue(((org.ognl.test.objects.Root)$2)..getGenericIndex().toString()))", p.toGetSourceString(context, root.getList())); + assertEquals(".get(ognl.OgnlOps#getIntValue(((ognl.test.objects.Root)$2)..getGenericIndex().toString()))", p.toGetSourceString(context, root.getList())); assertEquals(root.getArray(), context.getCurrentObject()); assertEquals(Object.class, context.getCurrentType()); } - public void test_Complicated_List() throws Exception - { + public void test_Complicated_List() throws Exception { Root root = new Root(); SimpleNode node = (SimpleNode) Ognl.compileExpression(context, root, - "{ new org.ognl.test.objects.MenuItem('Home', 'Main', " - + "{ new org.ognl.test.objects.MenuItem('Help', 'Help'), " - + "new org.ognl.test.objects.MenuItem('Contact', 'Contact') }), " // end first item - + "new org.ognl.test.objects.MenuItem('UserList', getMessages().getMessage('menu.members')), " + - "new org.ognl.test.objects.MenuItem('account/BetSlipList', getMessages().getMessage('menu.account'), " + - "{ new org.ognl.test.objects.MenuItem('account/BetSlipList', 'My Bets'), " + - "new org.ognl.test.objects.MenuItem('account/TransactionList', 'My Transactions') }), " + - "new org.ognl.test.objects.MenuItem('About', 'About'), " + - "new org.ognl.test.objects.MenuItem('admin/Admin', getMessages().getMessage('menu.admin'), " + - "{ new org.ognl.test.objects.MenuItem('admin/AddEvent', 'Add event'), " + - "new org.ognl.test.objects.MenuItem('admin/AddResult', 'Add result') })}"); - + "{ new ognl.test.objects.MenuItem('Home', 'Main', " + + "{ new ognl.test.objects.MenuItem('Help', 'Help'), " + + "new ognl.test.objects.MenuItem('Contact', 'Contact') }), " // end first item + + "new ognl.test.objects.MenuItem('UserList', getMessages().getMessage('menu.members')), " + + "new ognl.test.objects.MenuItem('account/BetSlipList', getMessages().getMessage('menu.account'), " + + "{ new ognl.test.objects.MenuItem('account/BetSlipList', 'My Bets'), " + + "new ognl.test.objects.MenuItem('account/TransactionList', 'My Transactions') }), " + + "new ognl.test.objects.MenuItem('About', 'About'), " + + "new ognl.test.objects.MenuItem('admin/Admin', getMessages().getMessage('menu.admin'), " + + "{ new ognl.test.objects.MenuItem('admin/AddEvent', 'Add event'), " + + "new ognl.test.objects.MenuItem('admin/AddResult', 'Add result') })}"); + assertTrue(List.class.isAssignableFrom(node.getAccessor().get(context, root).getClass())); } - public void test_Set_Chain_Indexed_Property() throws Exception - { + public void test_Set_Chain_Indexed_Property() throws Exception { Root root = new Root(); context.setRoot(root); @@ -235,8 +240,7 @@ public void test_Set_Chain_Indexed_Property() throws Exception node.setValue(context, root, Boolean.FALSE); } - public void test_Set_Generic_Property() throws Exception - { + public void test_Set_Generic_Property() throws Exception { GenericRoot root = new GenericRoot(); context.setRoot(root); @@ -245,15 +249,14 @@ public void test_Set_Generic_Property() throws Exception SimpleNode node = (SimpleNode) Ognl.parseExpression("cracker.param"); node.setValue(context, root, "0"); - assertEquals( new Integer(0), root.getCracker().getParam()); + assertEquals(new Integer(0), root.getCracker().getParam()); node.setValue(context, root, "10"); assertEquals(new Integer(10), root.getCracker().getParam()); } - public void test_Get_Generic_Property() throws Exception - { + public void test_Get_Generic_Property() throws Exception { GenericRoot root = new GenericRoot(); context.setRoot(root); @@ -269,17 +272,16 @@ public void test_Get_Generic_Property() throws Exception assertEquals(new Integer(10), node.getValue(context, root)); } - public void test_Set_Get_Multiple_Generic_Types_Property() throws Exception - { + public void test_Set_Get_Multiple_Generic_Types_Property() throws Exception { BaseGeneric root = new GameGeneric(); context.setRoot(root); context.setCurrentObject(root); SimpleNode node = (SimpleNode) Ognl.parseExpression("ids"); - node.setValue(context, root, new String[] {"0", "20", "43"}); + node.setValue(context, root, new String[]{"0", "20", "43"}); - isEqual(new Long[] {new Long(0), new Long(20), new Long(43)}, root.getIds()); + isEqual(new Long[]{new Long(0), new Long(20), new Long(43)}, root.getIds()); isEqual(node.getValue(context, root), root.getIds()); } } diff --git a/src/test/java/org/ognl/test/ASTSequenceTest.java b/src/test/java/ognl/test/ASTSequenceTest.java similarity index 90% rename from src/test/java/org/ognl/test/ASTSequenceTest.java rename to src/test/java/ognl/test/ASTSequenceTest.java index 01d7b4fb..4f8ce5c9 100644 --- a/src/test/java/org/ognl/test/ASTSequenceTest.java +++ b/src/test/java/ognl/test/ASTSequenceTest.java @@ -1,13 +1,14 @@ -package org.ognl.test; +package ognl.test; import junit.framework.TestCase; +import ognl.ASTSequence; import ognl.DefaultMemberAccess; import ognl.Ognl; import ognl.OgnlContext; import ognl.SimpleNode; /** - * Tests for {@link ognl.ASTSequence}. + * Tests for {@link ASTSequence}. */ public class ASTSequenceTest extends TestCase { diff --git a/src/test/java/ognl/test/ArithmeticAndLogicalOperatorsTest.java b/src/test/java/ognl/test/ArithmeticAndLogicalOperatorsTest.java new file mode 100644 index 00000000..c6e64c44 --- /dev/null +++ b/src/test/java/ognl/test/ArithmeticAndLogicalOperatorsTest.java @@ -0,0 +1,298 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; + +import java.math.BigDecimal; + +public class ArithmeticAndLogicalOperatorsTest extends OgnlTestCase { + + public enum EnumNoBody {ENUM1, ENUM2;} + + ; // Basic enumeration + + public enum EnumEmptyBody {ENUM1 {}, ENUM2 {};} + + ; // Enumeration whose elements have (empty) bodies + + public enum EnumBasicBody { + ENUM1 { + public final Integer value() { + return Integer.valueOf(10); + } + }, + ENUM2 { + public final Integer value() { + return Integer.valueOf(20); + } + }; + } + + ; // Enumeration whose elements have bodies + protected static final String FULLY_QUALIFIED_CLASSNAME = ArithmeticAndLogicalOperatorsTest.class.getName(); + + private static Object[][] TESTS = { + // Double-valued arithmetic expressions + {"-1d", new Double(-1)}, + {"+1d", new Double(1)}, + {"--1f", new Double(1)}, + {"2*2.0", new Double(4.0)}, + {"5/2.", new Double(2.5)}, + {"5+2D", new Double(7)}, + {"5f-2F", new Double(3.0)}, + {"5.+2*3", new Double(11)}, + {"(5.+2)*3", new Double(21)}, + + // BigDecimal-valued arithmetic expressions + {"-1b", new Integer(-1)}, + {"+1b", new Integer(1)}, + {"--1b", new Integer(1)}, + {"2*2.0b", new Double(4.0)}, + {"5/2.B", new Integer(2)}, + {"5.0B/2", new Double(2.5)}, + {"5+2b", new Integer(7)}, + {"5-2B", new Integer(3)}, + {"5.+2b*3", new Double(11)}, + {"(5.+2b)*3", new Double(21)}, + + // Integer-valued arithmetic expressions + {"-1", new Integer(-1)}, + {"+1", new Integer(1)}, + {"--1", new Integer(1)}, + {"2*2", new Integer(4)}, + {"5/2", new Integer(2)}, + {"5+2", new Integer(7)}, + {"5-2", new Integer(3)}, + {"5+2*3", new Integer(11)}, + {"(5+2)*3", new Integer(21)}, + {"~1", new Integer(~1)}, + {"5%2", new Integer(1)}, + {"5<<2", new Integer(20)}, + {"5>>2", new Integer(1)}, + {"5>>1+1", new Integer(1)}, + {"-5>>>2", new Integer(-5 >>> 2)}, + {"-5L>>>2", new Long(-5L >>> 2)}, + {"5. & 3", new Long(1)}, + {"5 ^3", new Integer(6)}, + {"5l&3|5^3", new Long(7)}, + {"5&(3|5^3)", new Long(5)}, + {"true ? 1 : 1/0", new Integer(1)}, + + // BigInteger-valued arithmetic expressions + {"-1h", Integer.valueOf(-1)}, + {"+1H", Integer.valueOf(1)}, + {"--1h", Integer.valueOf(1)}, + {"2h*2", Integer.valueOf(4)}, + {"5/2h", Integer.valueOf(2)}, + {"5h+2", Integer.valueOf(7)}, + {"5-2h", Integer.valueOf(3)}, + {"5+2H*3", Integer.valueOf(11)}, + {"(5+2H)*3", Integer.valueOf(21)}, + {"~1h", Integer.valueOf(~1)}, + {"5h%2", Integer.valueOf(1)}, + {"5h<<2", Integer.valueOf(20)}, + {"5h>>2", Integer.valueOf(1)}, + {"5h>>1+1", Integer.valueOf(1)}, + {"-5h>>>2", Integer.valueOf(-2)}, + {"5.b & 3", new Long(1)}, + {"5h ^3", Integer.valueOf(6)}, + {"5h&3|5^3", new Long(7)}, + {"5H&(3|5^3)", new Long(5)}, + + // Logical expressions + {"!1", Boolean.FALSE}, + {"!null", Boolean.TRUE}, + {"5<2", Boolean.FALSE}, + {"5>2", Boolean.TRUE}, + {"5<=5", Boolean.TRUE}, + {"5>=3", Boolean.TRUE}, + {"5<-5>>>2", Boolean.TRUE}, + {"5==5.0", Boolean.TRUE}, + {"5!=5.0", Boolean.FALSE}, + {"null in {true,false,null}", Boolean.TRUE}, + {"null not in {true,false,null}", Boolean.FALSE}, + {"null in {true,false,null}.toArray()", Boolean.TRUE}, + {"5 in {true,false,null}", Boolean.FALSE}, + {"5 not in {true,false,null}", Boolean.TRUE}, + {"5 instanceof java.lang.Integer", Boolean.TRUE}, + {"5. instanceof java.lang.Integer", Boolean.FALSE}, + {"!false || true", Boolean.TRUE}, + {"!(true && true)", Boolean.FALSE}, + {"(1 > 0 && true) || 2 > 0", Boolean.TRUE}, + + // Logical expressions (string versions) + {"2 or 0", Integer.valueOf(2)}, + {"1 and 0", Integer.valueOf(0)}, + {"1 bor 0", new Integer(1)}, + {"true && 12", Integer.valueOf(12)}, + {"1 xor 0", new Integer(1)}, {"1 band 0", new Long(0)}, {"1 eq 1", Boolean.TRUE}, + {"1 neq 1", Boolean.FALSE}, {"1 lt 5", Boolean.TRUE}, {"1 lte 5", Boolean.TRUE}, + {"1 gt 5", Boolean.FALSE}, {"1 gte 5", Boolean.FALSE}, {"1 lt 5", Boolean.TRUE}, + {"1 shl 2", new Integer(4)}, {"4 shr 2", new Integer(1)}, {"4 ushr 2", new Integer(1)}, + {"not null", Boolean.TRUE}, {"not 1", Boolean.FALSE}, + + // Equality on identity; Object does not implement Comparable + {"#a = new java.lang.Object(), #a == #a", Boolean.TRUE}, + {"#a = new java.lang.Object(), #b = new java.lang.Object(), #a == #b", Boolean.FALSE}, + + // Comparable and non-Comparable + {"#a = new java.lang.Object(), #a == ''", Boolean.FALSE}, + {"#a = new java.lang.Object(), '' == #a", Boolean.FALSE}, + + {"#x > 0", Boolean.TRUE}, + {"#x < 0", Boolean.FALSE}, + {"#x == 0", Boolean.FALSE}, + {"#x == 1", Boolean.TRUE}, + {"0 > #x", Boolean.FALSE}, + {"0 < #x", Boolean.TRUE}, + {"0 == #x", Boolean.FALSE}, + {"1 == #x", Boolean.TRUE}, + {"\"1\" > 0", Boolean.TRUE}, + {"\"1\" < 0", Boolean.FALSE}, + {"\"1\" == 0", Boolean.FALSE}, + {"\"1\" == 1", Boolean.TRUE}, + {"0 > \"1\"", Boolean.FALSE}, + {"0 < \"1\"", Boolean.TRUE}, + {"0 == \"1\"", Boolean.FALSE}, + {"1 == \"1\"", Boolean.TRUE}, + {"#x + 1", "11"}, + {"1 + #x", "11"}, + {"#y == 1", Boolean.TRUE}, + {"#y == \"1\"", Boolean.TRUE}, + {"#y + \"1\"", "11"}, + {"\"1\" + #y", "11"}, + + // Enumerated type equality and inequality comparisons (with and without element bodies, reversing order for completeness). + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", Boolean.FALSE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", Boolean.FALSE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", Boolean.FALSE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", Boolean.FALSE}, + + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", Boolean.FALSE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", Boolean.FALSE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", Boolean.FALSE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", Boolean.FALSE}, + + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", Boolean.FALSE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", Boolean.FALSE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", Boolean.FALSE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", Boolean.TRUE}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", Boolean.FALSE}, + + // As per JDK JavaDocs it is only possible to compare Enum elements of the same type. Attempting to compare different types + // will normally result in ClassCastExceptions. However, OGNL should avoid that and produce an IllegalArgumentException instead. + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class}, + + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", IllegalArgumentException.class}, + + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class}, + + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class}, + {"@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class} + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new ArithmeticAndLogicalOperatorsTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, + (String) TESTS[i][0], TESTS[i][1])); + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public ArithmeticAndLogicalOperatorsTest() { + super(); + } + + public ArithmeticAndLogicalOperatorsTest(String name) { + super(name); + } + + public ArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public ArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public ArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } + + /* + * =================================================================== Overridden methods + * =================================================================== + */ + protected void setUp() { + super.setUp(); + _context.put("x", "1"); + _context.put("y", new BigDecimal(1)); + } +} diff --git a/src/test/java/ognl/test/ArrayCreationTest.java b/src/test/java/ognl/test/ArrayCreationTest.java new file mode 100644 index 00000000..b43ade4a --- /dev/null +++ b/src/test/java/ognl/test/ArrayCreationTest.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.ExpressionSyntaxException; +import ognl.test.objects.Entry; +import ognl.test.objects.Root; +import ognl.test.objects.Simple; + +public class ArrayCreationTest extends OgnlTestCase { + + private static Root ROOT = new Root(); + + private static Object[][] TESTS = { + // Array creation + {ROOT, "new String[] { \"one\", \"two\" }", new String[]{"one", "two"}}, + {ROOT, "new String[] { 1, 2 }", new String[]{"1", "2"}}, + {ROOT, "new Integer[] { \"1\", 2, \"3\" }", + new Integer[]{new Integer(1), new Integer(2), new Integer(3)}}, + {ROOT, "new String[10]", new String[10]}, + {ROOT, "new Object[4] { #root, #this }", ExpressionSyntaxException.class}, + {ROOT, "new Object[4]", new Object[4]}, + {ROOT, "new Object[] { #root, #this }", new Object[]{ROOT, ROOT}}, + {ROOT, + "new ognl.test.objects.Simple[] { new ognl.test.objects.Simple(), new ognl.test.objects.Simple(\"foo\", 1.0f, 2) }", + new Simple[]{new Simple(), new Simple("foo", 1.0f, 2)}}, + {ROOT, "new ognl.test.objects.Simple[5]", new Simple[5]}, + {ROOT, "new ognl.test.objects.Simple(new Object[5])", new Simple(new Object[5])}, + {ROOT, "new ognl.test.objects.Simple(new String[5])", new Simple(new String[5])}, + {ROOT, "objectIndex ? new ognl.test.objects.Entry[] { new ognl.test.objects.Entry(), new ognl.test.objects.Entry()} " + + ": new ognl.test.objects.Entry[] { new ognl.test.objects.Entry(), new ognl.test.objects.Entry()} ", + new Entry[]{new Entry(), new Entry()}} + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new ArrayCreationTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new ArrayCreationTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new ArrayCreationTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public ArrayCreationTest() { + super(); + } + + public ArrayCreationTest(String name) { + super(name); + } + + public ArrayCreationTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, + Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public ArrayCreationTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public ArrayCreationTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/org/ognl/test/ArrayElementsTest.java b/src/test/java/ognl/test/ArrayElementsTest.java similarity index 59% rename from src/test/java/org/ognl/test/ArrayElementsTest.java rename to src/test/java/ognl/test/ArrayElementsTest.java index a958b6e8..2043758d 100644 --- a/src/test/java/org/ognl/test/ArrayElementsTest.java +++ b/src/test/java/ognl/test/ArrayElementsTest.java @@ -1,38 +1,26 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; import ognl.TypeConverter; -import org.ognl.test.objects.Root; +import ognl.test.objects.Root; import java.util.Arrays; @@ -54,33 +42,32 @@ public class ArrayElementsTest extends OgnlTestCase { {null, "\"{Hello}\".toCharArray()[6]", new Character('}')}, {null, "\"Tapestry\".toCharArray()[2]", new Character('p')}, {null, "{'1','2','3'}", Arrays.asList(new Object[]{new Character('1'), new Character('2'), new Character('3')})}, - {null, "{ true, !false }", Arrays.asList(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) } + {null, "{ true, !false }", Arrays.asList(new Boolean[]{Boolean.TRUE, Boolean.TRUE})} }; /* - * =================================================================== Private static methods - * =================================================================== - */ + * =================================================================== Private static methods + * =================================================================== + */ /* * =================================================================== Public static methods * =================================================================== */ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { if (TESTS[i].length == 3) { result.addTest(new ArrayElementsTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); + TESTS[i][2])); } else { if (TESTS[i].length == 4) { result.addTest(new ArrayElementsTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3])); + TESTS[i][2], TESTS[i][3])); } else { if (TESTS[i].length == 5) { result.addTest(new ArrayElementsTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3], TESTS[i][4])); + TESTS[i][2], TESTS[i][3], TESTS[i][4])); } else { throw new RuntimeException("don't understand TEST format"); } @@ -94,29 +81,24 @@ public static TestSuite suite() * =================================================================== Constructors * =================================================================== */ - public ArrayElementsTest() - { + public ArrayElementsTest() { super(); } - public ArrayElementsTest(String name) - { + public ArrayElementsTest(String name) { super(name); } public ArrayElementsTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { + Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } - public ArrayElementsTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { + public ArrayElementsTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public ArrayElementsTest(String name, Object root, String expressionString, Object expectedResult) - { + public ArrayElementsTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } @@ -124,8 +106,7 @@ public ArrayElementsTest(String name, Object root, String expressionString, Obje * =================================================================== Overridden methods * =================================================================== */ - protected void setUp() - { + protected void setUp() { TypeConverter arrayConverter; super.setUp(); diff --git a/src/test/java/org/ognl/test/ChainTest.java b/src/test/java/ognl/test/ChainTest.java similarity index 98% rename from src/test/java/org/ognl/test/ChainTest.java rename to src/test/java/ognl/test/ChainTest.java index cff794a5..fcba6297 100644 --- a/src/test/java/org/ognl/test/ChainTest.java +++ b/src/test/java/ognl/test/ChainTest.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.ognl.test; +package ognl.test; import junit.framework.TestCase; import ognl.DefaultMemberAccess; diff --git a/src/test/java/ognl/test/ClassMethodTest.java b/src/test/java/ognl/test/ClassMethodTest.java new file mode 100644 index 00000000..5a812b85 --- /dev/null +++ b/src/test/java/ognl/test/ClassMethodTest.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.CorrectedObject; + +public class ClassMethodTest extends OgnlTestCase { + + private static CorrectedObject CORRECTED = new CorrectedObject(); + + private static Object[][] TESTS = { + // Methods on Class + {CORRECTED, "getClass().getName()", CORRECTED.getClass().getName()}, + {CORRECTED, "getClass().getInterfaces()", CORRECTED.getClass().getInterfaces()}, + {CORRECTED, "getClass().getInterfaces().length", new Integer(CORRECTED.getClass().getInterfaces().length)}, + {null, "@System@class.getInterfaces()", System.class.getInterfaces()}, + {null, "@Class@class.getName()", Class.class.getName()}, + {null, "@java.awt.image.ImageObserver@class.getName()", java.awt.image.ImageObserver.class.getName()}, + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new ClassMethodTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public ClassMethodTest() { + super(); + } + + public ClassMethodTest(String name) { + super(name); + } + + public ClassMethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, + Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public ClassMethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public ClassMethodTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/org/ognl/test/CollectionDirectPropertyTest.java b/src/test/java/ognl/test/CollectionDirectPropertyTest.java similarity index 63% rename from src/test/java/org/ognl/test/CollectionDirectPropertyTest.java rename to src/test/java/ognl/test/CollectionDirectPropertyTest.java index bb87a300..b23382f5 100644 --- a/src/test/java/org/ognl/test/CollectionDirectPropertyTest.java +++ b/src/test/java/ognl/test/CollectionDirectPropertyTest.java @@ -1,37 +1,25 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; -import org.ognl.test.objects.Root; +import ognl.test.objects.Root; import java.util.Arrays; @@ -64,8 +52,7 @@ public class CollectionDirectPropertyTest extends OgnlTestCase { * =================================================================== Public static methods * =================================================================== */ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { @@ -93,30 +80,25 @@ public static TestSuite suite() * =================================================================== Constructors * =================================================================== */ - public CollectionDirectPropertyTest() - { + public CollectionDirectPropertyTest() { super(); } - public CollectionDirectPropertyTest(String name) - { + public CollectionDirectPropertyTest(String name) { super(name); } public CollectionDirectPropertyTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { + Object setValue, Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } public CollectionDirectPropertyTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { + Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public CollectionDirectPropertyTest(String name, Object root, String expressionString, Object expectedResult) - { + public CollectionDirectPropertyTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } } diff --git a/src/test/java/org/ognl/test/CompilingPropertyAccessor.java b/src/test/java/ognl/test/CompilingPropertyAccessor.java similarity index 59% rename from src/test/java/org/ognl/test/CompilingPropertyAccessor.java rename to src/test/java/ognl/test/CompilingPropertyAccessor.java index b479c7f5..f1b340f9 100644 --- a/src/test/java/org/ognl/test/CompilingPropertyAccessor.java +++ b/src/test/java/ognl/test/CompilingPropertyAccessor.java @@ -1,46 +1,35 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 1998-2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.LoaderClassPath; +import ognl.ClassResolver; import ognl.ObjectPropertyAccessor; import ognl.OgnlContext; import ognl.OgnlException; import ognl.OgnlRuntime; import ognl.enhance.ContextClassLoader; import ognl.enhance.EnhancedClassLoader; -import org.ognl.test.util.NameFactory; +import ognl.test.util.NameFactory; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -52,35 +41,22 @@ * Implementation of PropertyAccessor that uses Javassist to compile a property accessor * specifically tailored to the property. */ -public class CompilingPropertyAccessor extends ObjectPropertyAccessor -{ - - private static NameFactory NAME_FACTORY = new NameFactory("ognl.PropertyAccessor", "v"); - private static Getter NotFoundGetter = new Getter() - { - - public Object get(OgnlContext context, Object target, String propertyName) - { - return null; - } - }; - private static Getter DefaultGetter = new Getter() - { +public class CompilingPropertyAccessor extends ObjectPropertyAccessor { - public Object get(OgnlContext context, Object target, String propertyName) - { - try { - return OgnlRuntime.getMethodValue(context, target, propertyName, true); - } catch (Exception ex) { - throw new RuntimeException(ex); - } + private static final NameFactory NAME_FACTORY = new NameFactory("ognl.PropertyAccessor", "v"); + private static final Getter NotFoundGetter = (context, target, propertyName) -> null; + private static final Getter DefaultGetter = (context, target, propertyName) -> { + try { + return OgnlRuntime.getMethodValue(context, target, propertyName, true); + } catch (Exception ex) { + throw new RuntimeException(ex); } }; - private static Map pools = new HashMap(); - private static Map loaders = new HashMap(); + private static final Map pools = new HashMap<>(); + private static final Map loaders = new HashMap<>(); - private static java.util.IdentityHashMap PRIMITIVE_WRAPPER_CLASSES = new IdentityHashMap(); - private java.util.IdentityHashMap seenGetMethods = new java.util.IdentityHashMap(); + private static final Map, Class> PRIMITIVE_WRAPPER_CLASSES = new IdentityHashMap<>(); + private final Map, Map> seenGetMethods = new IdentityHashMap<>(); static { PRIMITIVE_WRAPPER_CLASSES.put(Boolean.TYPE, Boolean.class); @@ -101,35 +77,31 @@ public Object get(OgnlContext context, Object target, String propertyName) PRIMITIVE_WRAPPER_CLASSES.put(Double.class, Double.TYPE); } - public static Class getPrimitiveWrapperClass(Class primitiveClass) - { - return (Class) PRIMITIVE_WRAPPER_CLASSES.get(primitiveClass); + public static Class getPrimitiveWrapperClass(Class primitiveClass) { + return PRIMITIVE_WRAPPER_CLASSES.get(primitiveClass); } - public interface Getter - { - public Object get(OgnlContext context, Object target, String propertyName); + public interface Getter { + Object get(OgnlContext context, Object target, String propertyName); } - public static Getter generateGetter(OgnlContext context, String code) - throws OgnlException - { + public static Getter generateGetter(OgnlContext context, String code) throws OgnlException { String className = NAME_FACTORY.getNewClassName(); try { - ClassPool pool = (ClassPool) pools.get(context.getClassResolver()); - EnhancedClassLoader loader = (EnhancedClassLoader) loaders.get(context.getClassResolver()); + ClassPool pool = pools.get(context.getClassResolver()); + EnhancedClassLoader loader = loaders.get(context.getClassResolver()); CtClass newClass; CtClass ognlContextClass; CtClass objectClass; CtClass stringClass; CtMethod method; byte[] byteCode; - Class compiledClass; + Class compiledClass; if ((pool == null) || (loader == null)) { ClassLoader classLoader = new ContextClassLoader(OgnlContext.class.getClassLoader(), context); - + pool = ClassPool.getDefault(); pool.insertClassPath(new LoaderClassPath(classLoader)); pools.put(context.getClassResolver(), pool); @@ -144,7 +116,7 @@ public static Getter generateGetter(OgnlContext context, String code) stringClass = pool.get(String.class.getName()); newClass.addInterface(pool.get(Getter.class.getName())); - method = new CtMethod(objectClass, "get", new CtClass[] { ognlContextClass, objectClass, stringClass }, + method = new CtMethod(objectClass, "get", new CtClass[]{ognlContextClass, objectClass, stringClass}, newClass); method.setBody("{" + code + "}"); newClass.addMethod(method); @@ -156,20 +128,18 @@ public static Getter generateGetter(OgnlContext context, String code) } } - private Getter getGetter(OgnlContext context, Object target, String propertyName) - throws OgnlException - { + private Getter getGetter(OgnlContext context, Object target, String propertyName) throws OgnlException { Getter result; - Class targetClass = target.getClass(); - Map propertyMap; + Class targetClass = target.getClass(); + Map propertyMap; - if ((propertyMap = (Map) seenGetMethods.get(targetClass)) == null) { - propertyMap = new HashMap(101); + if ((propertyMap = seenGetMethods.get(targetClass)) == null) { + propertyMap = new HashMap<>(101); seenGetMethods.put(targetClass, propertyMap); } - if ((result = (Getter) propertyMap.get(propertyName)) == null) { + if ((result = propertyMap.get(propertyName)) == null) { try { - Method method = OgnlRuntime.getGetMethod(context, targetClass, propertyName); + Method method = OgnlRuntime.getGetMethod(targetClass, propertyName); if (method != null) { if (Modifier.isPublic(method.getModifiers())) { @@ -205,20 +175,17 @@ private Getter getGetter(OgnlContext context, Object target, String propertyName /** * Returns OgnlRuntime.NotFound if the property does not exist. */ - public Object getPossibleProperty(Map context, Object target, String name) - throws OgnlException - { + public Object getPossibleProperty(OgnlContext context, Object target, String name) throws OgnlException { Object result; - OgnlContext ognlContext = (OgnlContext) context; if (context.get("_compile") != null) { - Getter getter = getGetter(ognlContext, target, name); + Getter getter = getGetter(context, target, name); if (getter != NotFoundGetter) { - result = getter.get(ognlContext, target, name); + result = getter.get(context, target, name); } else { try { - result = OgnlRuntime.getFieldValue(ognlContext, target, name, true); + result = OgnlRuntime.getFieldValue(context, target, name, true); } catch (Exception ex) { throw new OgnlException(name, ex); } diff --git a/src/test/java/ognl/test/ConstantTest.java b/src/test/java/ognl/test/ConstantTest.java new file mode 100644 index 00000000..b2bd1ae6 --- /dev/null +++ b/src/test/java/ognl/test/ConstantTest.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.ExpressionSyntaxException; + +import java.util.Arrays; + +public class ConstantTest extends OgnlTestCase { + + private static Object[][] TESTS = { + {"12345", new Integer(12345)}, + {"0x100", new Integer(256)}, + {"0xfE", new Integer(254)}, + {"01000", new Integer(512)}, + {"1234L", new Integer(1234)}, + {"12.34", new Double(12.34)}, + {".1234", new Double(.12340000000000)}, + {"12.34f", Double.valueOf(12.34)}, + {"12.", new Double(12)}, + {"12e+1d", new Double(120)}, + {"'x'", new Character('x')}, + {"'\\n'", new Character('\n')}, + {"'\\u048c'", new Character('\u048c')}, + {"'\\47'", new Character('\47')}, + {"'\\367'", new Character('\367')}, + {"'\\367", ExpressionSyntaxException.class}, + {"'\\x'", ExpressionSyntaxException.class}, + {"\"hello world\"", "hello world"}, + {"\"\\u00a0\\u0068ell\\'o\\\\\\n\\r\\f\\t\\b\\\"\\167orld\\\"\"", "\u00a0hell'o\\\n\r\f\t\b\"world\""}, + {"\"hello world", ExpressionSyntaxException.class}, + {"\"hello\\x world\"", ExpressionSyntaxException.class}, + {"null", null}, + {"true", Boolean.TRUE}, + {"false", Boolean.FALSE}, + {"{ false, true, null, 0, 1. }", + Arrays.asList(new Object[]{Boolean.FALSE, Boolean.TRUE, null, new Integer(0), new Double(1)})}, + {"'HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"'", + "HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\""}, + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new ConstantTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, + (String) TESTS[i][0], TESTS[i][1])); + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public ConstantTest() { + super(); + } + + public ConstantTest(String name) { + super(name); + } + + public ConstantTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, + Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public ConstantTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public ConstantTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/ConstantTreeTest.java b/src/test/java/ognl/test/ConstantTreeTest.java new file mode 100644 index 00000000..4ff34d70 --- /dev/null +++ b/src/test/java/ognl/test/ConstantTreeTest.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.Ognl; + +public class ConstantTreeTest extends OgnlTestCase { + + public static int nonFinalStaticVariable = 15; + + private static Object[][] TESTS = { + {"true", Boolean.TRUE}, + {"55", Boolean.TRUE}, + {"@java.awt.Color@black", Boolean.TRUE}, + {"@ognl.test.ConstantTreeTest@nonFinalStaticVariable", Boolean.FALSE}, + {"@ognl.test.ConstantTreeTest@nonFinalStaticVariable + 10", Boolean.FALSE}, + {"55 + 24 + @java.awt.Event@ALT_MASK", Boolean.TRUE}, + {"name", Boolean.FALSE}, + {"name[i]", Boolean.FALSE}, + {"name[i].property", Boolean.FALSE}, + {"name.{? foo }", Boolean.FALSE}, + {"name.{ foo }", Boolean.FALSE}, + {"name.{ 25 }", Boolean.FALSE} + + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new ConstantTreeTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, + (String) TESTS[i][0], TESTS[i][1])); + } + return result; + } + + /* + * =================================================================== Overridden methods + * =================================================================== + */ + protected void runTest() + throws Exception { + assertTrue(Ognl.isConstant(getExpression(), _context) == ((Boolean) getExpectedResult()).booleanValue()); + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public ConstantTreeTest() { + super(); + } + + public ConstantTreeTest(String name) { + super(name); + } + + public ConstantTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, + Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public ConstantTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public ConstantTreeTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/ContextVariableTest.java b/src/test/java/ognl/test/ContextVariableTest.java new file mode 100644 index 00000000..c21af15b --- /dev/null +++ b/src/test/java/ognl/test/ContextVariableTest.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Simple; + +public class ContextVariableTest extends OgnlTestCase { + + private static Object ROOT = new Simple(); + private static Object[][] TESTS = { + // Naming and referring to names + {"#root", ROOT}, // Special root reference + {"#this", ROOT}, // Special this reference + {"#f=5, #s=6, #f + #s", new Integer(11)}, + {"#six=(#five=5, 6), #five + #six", new Integer(11)}, + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new ContextVariableTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", ROOT, + (String) TESTS[i][0], TESTS[i][1])); + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public ContextVariableTest() { + super(); + } + + public ContextVariableTest(String name) { + super(name); + } + + public ContextVariableTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public ContextVariableTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public ContextVariableTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/CorrectedObjectNullHandler.java b/src/test/java/ognl/test/CorrectedObjectNullHandler.java new file mode 100644 index 00000000..e71aca34 --- /dev/null +++ b/src/test/java/ognl/test/CorrectedObjectNullHandler.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import ognl.NullHandler; +import ognl.OgnlContext; + +public class CorrectedObjectNullHandler implements NullHandler { + + private final String defaultValue; + + public CorrectedObjectNullHandler(String defaultValue) { + super(); + this.defaultValue = defaultValue; + } + + public Object nullMethodResult(OgnlContext context, Object target, String methodName, Object[] args) { + if (methodName.equals("getStringValue")) { + return defaultValue; + } + return null; + } + + public Object nullPropertyValue(OgnlContext context, Object target, Object property) { + if (property.equals("stringValue")) { + return defaultValue; + } + return null; + } +} diff --git a/src/test/java/ognl/DefaultClassResolverTest.java b/src/test/java/ognl/test/DefaultClassResolverTest.java similarity index 92% rename from src/test/java/ognl/DefaultClassResolverTest.java rename to src/test/java/ognl/test/DefaultClassResolverTest.java index 34346f01..50faa431 100644 --- a/src/test/java/ognl/DefaultClassResolverTest.java +++ b/src/test/java/ognl/test/DefaultClassResolverTest.java @@ -1,6 +1,10 @@ -package ognl; +package ognl.test; import junit.framework.TestCase; +import ognl.DefaultClassResolver; +import ognl.DefaultMemberAccess; +import ognl.Ognl; +import ognl.OgnlContext; public class DefaultClassResolverTest extends TestCase { diff --git a/src/test/java/org/ognl/test/GenericsTest.java b/src/test/java/ognl/test/GenericsTest.java similarity index 60% rename from src/test/java/org/ognl/test/GenericsTest.java rename to src/test/java/ognl/test/GenericsTest.java index 31e5ee67..bc6b37cd 100644 --- a/src/test/java/org/ognl/test/GenericsTest.java +++ b/src/test/java/ognl/test/GenericsTest.java @@ -1,35 +1,31 @@ -package org.ognl.test; +package ognl.test; import junit.framework.TestSuite; -import org.ognl.test.objects.BaseGeneric; -import org.ognl.test.objects.GameGeneric; -import org.ognl.test.objects.GameGenericObject; -import org.ognl.test.objects.GenericRoot; +import ognl.test.objects.BaseGeneric; +import ognl.test.objects.GameGeneric; +import ognl.test.objects.GameGenericObject; +import ognl.test.objects.GenericRoot; /** * Tests java >= 1.5 generics support in ognl. */ -public class GenericsTest extends OgnlTestCase -{ +public class GenericsTest extends OgnlTestCase { static GenericRoot ROOT = new GenericRoot(); static BaseGeneric GENERIC = new GameGeneric(); static Object[][] TESTS = { /* { ROOT, "cracker.param", null, new Integer(2), new Integer(2)}, */ - { GENERIC, "ids", null, new Long[] {1l, 101l}, new Long[] {1l, 101l}}, + {GENERIC, "ids", null, new Long[]{1l, 101l}, new Long[]{1l, 101l}}, /* { GENERIC, "ids", new Long[] {1l, 101l}, new String[] {"2", "34"}, new Long[]{2l, 34l}}, */ }; - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); - for(int i = 0; i < TESTS.length; i++) - { - if (TESTS[i].length == 5) - { + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 5) { result.addTest(new GenericsTest((String) TESTS[i][1] + " (" + TESTS[i][2] + ")", TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3], TESTS[i][4])); + TESTS[i][2], TESTS[i][3], TESTS[i][4])); } } @@ -37,8 +33,7 @@ public static TestSuite suite() } public GenericsTest(String name, Object root, String expressionString, - Object expectedResult, Object setValue, Object expectedAfterSetResult) - { + Object expectedResult, Object setValue, Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } } diff --git a/src/test/java/ognl/InExpressionTest.java b/src/test/java/ognl/test/InExpressionTest.java similarity index 80% rename from src/test/java/ognl/InExpressionTest.java rename to src/test/java/ognl/test/InExpressionTest.java index 20e00a63..22115277 100644 --- a/src/test/java/ognl/InExpressionTest.java +++ b/src/test/java/ognl/test/InExpressionTest.java @@ -1,6 +1,9 @@ -package ognl; +package ognl.test; import junit.framework.TestCase; +import ognl.DefaultMemberAccess; +import ognl.Ognl; +import ognl.OgnlContext; /** * Test for OGNL-118. @@ -8,8 +11,7 @@ public class InExpressionTest extends TestCase { public void test_String_In() - throws Exception - { + throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); Object node = Ognl.parseExpression("#name in {\"Greenland\", \"Austin\", \"Africa\", \"Rome\"}"); Object root = null; diff --git a/src/test/java/org/ognl/test/IndexAccessTest.java b/src/test/java/ognl/test/IndexAccessTest.java similarity index 52% rename from src/test/java/org/ognl/test/IndexAccessTest.java rename to src/test/java/ognl/test/IndexAccessTest.java index c690e750..efd32b32 100644 --- a/src/test/java/org/ognl/test/IndexAccessTest.java +++ b/src/test/java/ognl/test/IndexAccessTest.java @@ -1,40 +1,28 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; import ognl.MethodFailedException; import ognl.NoSuchPropertyException; -import org.ognl.test.objects.IndexedSetObject; -import org.ognl.test.objects.Root; +import ognl.test.objects.IndexedSetObject; +import ognl.test.objects.Root; public class IndexAccessTest extends OgnlTestCase { @@ -44,11 +32,11 @@ public class IndexAccessTest extends OgnlTestCase { private static Object[][] TESTS = { {ROOT, "list[index]", ROOT.getList().get(ROOT.getIndex())}, {ROOT, "list[objectIndex]", ROOT.getList().get(ROOT.getObjectIndex().intValue())}, - {ROOT, "array[objectIndex]", ROOT.getArray()[ROOT.getObjectIndex().intValue()] }, - {ROOT, "array[getObjectIndex()]", ROOT.getArray()[ROOT.getObjectIndex().intValue()] }, - {ROOT, "array[genericIndex]", ROOT.getArray()[((Integer)ROOT.getGenericIndex()).intValue()] }, - {ROOT, "booleanArray[self.objectIndex]", Boolean.FALSE }, - {ROOT, "booleanArray[getObjectIndex()]", Boolean.FALSE }, + {ROOT, "array[objectIndex]", ROOT.getArray()[ROOT.getObjectIndex().intValue()]}, + {ROOT, "array[getObjectIndex()]", ROOT.getArray()[ROOT.getObjectIndex().intValue()]}, + {ROOT, "array[genericIndex]", ROOT.getArray()[((Integer) ROOT.getGenericIndex()).intValue()]}, + {ROOT, "booleanArray[self.objectIndex]", Boolean.FALSE}, + {ROOT, "booleanArray[getObjectIndex()]", Boolean.FALSE}, {ROOT, "booleanArray[nullIndex]", NoSuchPropertyException.class}, {ROOT, "list[size() - 1]", MethodFailedException.class}, {ROOT, "(index == (array.length - 3)) ? 'toggle toggleSelected' : 'toggle'", "toggle toggleSelected"}, @@ -66,18 +54,14 @@ public class IndexAccessTest extends OgnlTestCase { * =================================================================== Public static methods * =================================================================== */ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); - for (int i = 0; i < TESTS.length; i++) - { - if (TESTS[i].length == 5) - { + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 5) { result.addTest(new IndexAccessTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], - TESTS[i][3], TESTS[i][4])); - } else - { + TESTS[i][3], TESTS[i][4])); + } else { result.addTest(new IndexAccessTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); } } @@ -85,37 +69,31 @@ public static TestSuite suite() } /* - * =================================================================== Constructors - * =================================================================== - */ - public IndexAccessTest() - { + * =================================================================== Constructors + * =================================================================== + */ + public IndexAccessTest() { super(); } - public IndexAccessTest(String name) - { + public IndexAccessTest(String name) { super(name); } public IndexAccessTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { + Object setValue, Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } - public IndexAccessTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { + public IndexAccessTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public IndexAccessTest(String name, Object root, String expressionString, Object expectedResult) - { + public IndexAccessTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } - public void setUp() - { + public void setUp() { super.setUp(); } } diff --git a/src/test/java/org/ognl/test/IndexedPropertyTest.java b/src/test/java/ognl/test/IndexedPropertyTest.java similarity index 66% rename from src/test/java/org/ognl/test/IndexedPropertyTest.java rename to src/test/java/ognl/test/IndexedPropertyTest.java index c2dba879..679dca9c 100644 --- a/src/test/java/org/ognl/test/IndexedPropertyTest.java +++ b/src/test/java/ognl/test/IndexedPropertyTest.java @@ -1,38 +1,26 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; -import org.ognl.test.objects.Indexed; -import org.ognl.test.objects.Root; +import ognl.test.objects.Indexed; +import ognl.test.objects.Root; public class IndexedPropertyTest extends OgnlTestCase { diff --git a/src/test/java/ognl/test/InheritedMethodsTest.java b/src/test/java/ognl/test/InheritedMethodsTest.java new file mode 100644 index 00000000..03a225f5 --- /dev/null +++ b/src/test/java/ognl/test/InheritedMethodsTest.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestCase; +import ognl.DefaultMemberAccess; +import ognl.Node; +import ognl.Ognl; +import ognl.OgnlContext; +import ognl.test.objects.BaseBean; +import ognl.test.objects.FirstBean; +import ognl.test.objects.Root; +import ognl.test.objects.SecondBean; + +/** + * Tests functionality of casting inherited method expressions. + */ +public class InheritedMethodsTest extends TestCase { + + private static final Root ROOT = new Root(); + + public void test_Base_Inheritance() throws Exception { + OgnlContext context = Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); + String expression = "map.bean.name"; + BaseBean first = new FirstBean(); + BaseBean second = new SecondBean(); + + ROOT.getMap().put("bean", first); + + Node node = Ognl.compileExpression(context, ROOT, expression); + + assertEquals(first.getName(), node.getAccessor().get(context, ROOT)); + + ROOT.getMap().put("bean", second); + + assertEquals(second.getName(), node.getAccessor().get(context, ROOT)); + } +} diff --git a/src/test/java/org/ognl/test/InterfaceInheritanceTest.java b/src/test/java/ognl/test/InterfaceInheritanceTest.java similarity index 57% rename from src/test/java/org/ognl/test/InterfaceInheritanceTest.java rename to src/test/java/ognl/test/InterfaceInheritanceTest.java index a50b509d..9351ba79 100644 --- a/src/test/java/org/ognl/test/InterfaceInheritanceTest.java +++ b/src/test/java/ognl/test/InterfaceInheritanceTest.java @@ -1,38 +1,31 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; import ognl.OgnlRuntime; -import org.ognl.test.objects.*; +import ognl.test.objects.Bean1; +import ognl.test.objects.BeanProvider; +import ognl.test.objects.BeanProviderAccessor; +import ognl.test.objects.EvenOdd; +import ognl.test.objects.ListSourceImpl; +import ognl.test.objects.Root; import java.util.List; @@ -70,7 +63,7 @@ public class InterfaceInheritanceTest extends OgnlTestCase { {ROOT, "map.comp.form.clientId", "form1"}, {ROOT, "map.comp.getCount(genericIndex)", Integer.valueOf(0)}, {ROOT, "map.customList.total", Integer.valueOf(1)}, - {ROOT, "myTest.theMap['key']", "value" }, + {ROOT, "myTest.theMap['key']", "value"}, {ROOT, "contentProvider.hasChildren(property)", Boolean.TRUE}, {ROOT, "objectIndex instanceof java.lang.Object", Boolean.TRUE} }; @@ -79,22 +72,21 @@ public class InterfaceInheritanceTest extends OgnlTestCase { * =================================================================== Public static methods * =================================================================== */ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { if (TESTS[i].length == 3) { result.addTest(new InterfaceInheritanceTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); + TESTS[i][2])); } else { if (TESTS[i].length == 4) { result.addTest(new InterfaceInheritanceTest((String) TESTS[i][1], TESTS[i][0], - (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); + (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); } else { if (TESTS[i].length == 5) { result.addTest(new InterfaceInheritanceTest((String) TESTS[i][1], TESTS[i][0], - (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); } else { throw new RuntimeException("don't understand TEST format"); } @@ -106,38 +98,32 @@ public static TestSuite suite() } /* - * =================================================================== Constructors - * =================================================================== - */ - public InterfaceInheritanceTest() - { + * =================================================================== Constructors + * =================================================================== + */ + public InterfaceInheritanceTest() { super(); } - public InterfaceInheritanceTest(String name) - { + public InterfaceInheritanceTest(String name) { super(name); } public InterfaceInheritanceTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { + Object setValue, Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } public InterfaceInheritanceTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { + Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public InterfaceInheritanceTest(String name, Object root, String expressionString, Object expectedResult) - { + public InterfaceInheritanceTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } - public void setUp() - { + public void setUp() { super.setUp(); OgnlRuntime.setPropertyAccessor(BeanProvider.class, new BeanProviderAccessor()); diff --git a/src/test/java/ognl/IsTruckTest.java b/src/test/java/ognl/test/IsTruckTest.java similarity index 72% rename from src/test/java/ognl/IsTruckTest.java rename to src/test/java/ognl/test/IsTruckTest.java index 5aff4755..d9d40d60 100644 --- a/src/test/java/ognl/IsTruckTest.java +++ b/src/test/java/ognl/test/IsTruckTest.java @@ -1,12 +1,13 @@ -package ognl; +package ognl.test; import junit.framework.TestCase; - -import java.util.List; +import ognl.DefaultMemberAccess; +import ognl.Ognl; +import ognl.OgnlContext; public class IsTruckTest extends TestCase { - public void testIsTruckMethod() throws Exception{ + public void testIsTruckMethod() throws Exception { OgnlContext context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); boolean actual = (Boolean) Ognl.getValue("isTruck", context, new TruckHolder()); diff --git a/src/test/java/ognl/Java8Test.java b/src/test/java/ognl/test/Java8Test.java similarity index 68% rename from src/test/java/ognl/Java8Test.java rename to src/test/java/ognl/test/Java8Test.java index 5b086d66..c90c4be3 100644 --- a/src/test/java/ognl/Java8Test.java +++ b/src/test/java/ognl/test/Java8Test.java @@ -1,11 +1,13 @@ -package ognl; +package ognl.test; + +import junit.framework.TestCase; +import ognl.OgnlException; +import ognl.OgnlRuntime; import java.beans.IntrospectionException; import java.lang.reflect.Method; import java.util.List; -import junit.framework.TestCase; - public class Java8Test extends TestCase { public void testDefaultMethodOnClass() { @@ -24,18 +26,20 @@ public void testDefaultMethodOnSubClass() { assertNotNull(method); } - public void testGetDeclaredMethods() throws IntrospectionException, OgnlException{ - List defaultMethod = OgnlRuntime.getDeclaredMethods(SubClassWithDefaults.class, "name", false); - assertNotNull(defaultMethod); - defaultMethod = OgnlRuntime.getDeclaredMethods(ClassWithDefaults.class, "name", false); - assertNotNull(defaultMethod); + public void testGetDeclaredMethods() throws IntrospectionException, OgnlException { + List defaultMethod = OgnlRuntime.getDeclaredMethods(SubClassWithDefaults.class, "name", false); + assertNotNull(defaultMethod); + defaultMethod = OgnlRuntime.getDeclaredMethods(ClassWithDefaults.class, "name", false); + assertNotNull(defaultMethod); } } class SubClassWithDefaults extends ClassWithDefaults { - public String getName() { return "name"; } + public String getName() { + return "name"; + } } @@ -44,8 +48,13 @@ class ClassWithDefaults implements SubInterfaceWithDefaults { } interface InterfaceWithDefaults { - default void defaultMethod() { } - default String getName() { return "name"; } + default void defaultMethod() { + } + + default String getName() { + return "name"; + } } + interface SubInterfaceWithDefaults extends InterfaceWithDefaults { } diff --git a/src/test/java/org/ognl/test/LambdaExpressionTest.java b/src/test/java/ognl/test/LambdaExpressionTest.java similarity index 53% rename from src/test/java/org/ognl/test/LambdaExpressionTest.java rename to src/test/java/ognl/test/LambdaExpressionTest.java index 9a35303e..0ae66b00 100644 --- a/src/test/java/org/ognl/test/LambdaExpressionTest.java +++ b/src/test/java/ognl/test/LambdaExpressionTest.java @@ -1,34 +1,22 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; @@ -55,8 +43,7 @@ public class LambdaExpressionTest extends OgnlTestCase { * =================================================================== Public static methods * =================================================================== */ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { @@ -70,30 +57,25 @@ public static TestSuite suite() * =================================================================== Constructors * =================================================================== */ - public LambdaExpressionTest() - { + public LambdaExpressionTest() { super(); } - public LambdaExpressionTest(String name) - { + public LambdaExpressionTest(String name) { super(name); } public LambdaExpressionTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { + Object setValue, Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } public LambdaExpressionTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { + Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public LambdaExpressionTest(String name, Object root, String expressionString, Object expectedResult) - { + public LambdaExpressionTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } } diff --git a/src/test/java/org/ognl/test/MapCreationTest.java b/src/test/java/ognl/test/MapCreationTest.java similarity index 61% rename from src/test/java/org/ognl/test/MapCreationTest.java rename to src/test/java/ognl/test/MapCreationTest.java index 6b58d82f..0da24946 100644 --- a/src/test/java/org/ognl/test/MapCreationTest.java +++ b/src/test/java/ognl/test/MapCreationTest.java @@ -1,37 +1,25 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; -import org.ognl.test.objects.Root; +import ognl.test.objects.Root; import java.util.HashMap; import java.util.LinkedHashMap; @@ -78,8 +66,7 @@ public class MapCreationTest extends OgnlTestCase { * =================================================================== Public static methods * =================================================================== */ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { @@ -108,29 +95,24 @@ public static TestSuite suite() * =================================================================== Constructors * =================================================================== */ - public MapCreationTest() - { + public MapCreationTest() { super(); } - public MapCreationTest(String name) - { + public MapCreationTest(String name) { super(name); } public MapCreationTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { + Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } - public MapCreationTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { + public MapCreationTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public MapCreationTest(String name, Object root, String expressionString, Object expectedResult) - { + public MapCreationTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } } diff --git a/src/test/java/org/ognl/test/MemberAccessTest.java b/src/test/java/ognl/test/MemberAccessTest.java similarity index 50% rename from src/test/java/org/ognl/test/MemberAccessTest.java rename to src/test/java/ognl/test/MemberAccessTest.java index 28592130..24ccfb26 100644 --- a/src/test/java/org/ognl/test/MemberAccessTest.java +++ b/src/test/java/ognl/test/MemberAccessTest.java @@ -1,55 +1,42 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; import ognl.DefaultMemberAccess; import ognl.Ognl; import ognl.OgnlContext; import ognl.OgnlException; -import org.ognl.test.objects.Simple; +import ognl.test.objects.Simple; import java.lang.reflect.Member; import java.lang.reflect.Method; -import java.util.Map; public class MemberAccessTest extends OgnlTestCase { - private static Simple ROOT = new Simple(); + private static final Simple ROOT = new Simple(); - private static Object[][] TESTS = { + private static final Object[][] TESTS = { {"@Runtime@getRuntime()", OgnlException.class}, {"@System@getProperty('java.specification.version')", System.getProperty("java.specification.version")}, {"bigIntValue", OgnlException.class}, - {"bigIntValue", OgnlException.class, new Integer(25), OgnlException.class}, + {"bigIntValue", OgnlException.class, 25, OgnlException.class}, {"getBigIntValue()", OgnlException.class}, {"stringValue", ROOT.getStringValue()}, }; @@ -57,16 +44,13 @@ public class MemberAccessTest extends OgnlTestCase { * =================================================================== Public static methods * =================================================================== */ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); - for (int i = 0; i < TESTS.length; i++) - { - result.addTest(new MemberAccessTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", ROOT, - (String) TESTS[i][0], TESTS[i][1])); + for (Object[] test : TESTS) { + result.addTest(new MemberAccessTest(test[0] + " (" + test[1] + ")", ROOT, (String) test[0], test[1])); } - + return result; } @@ -74,29 +58,24 @@ public static TestSuite suite() * =================================================================== Constructors * =================================================================== */ - public MemberAccessTest() - { + public MemberAccessTest() { super(); } - public MemberAccessTest(String name) - { + public MemberAccessTest(String name) { super(name); } public MemberAccessTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { + Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } - public MemberAccessTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { + public MemberAccessTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public MemberAccessTest(String name, Object root, String expressionString, Object expectedResult) - { + public MemberAccessTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } @@ -104,14 +83,13 @@ public MemberAccessTest(String name, Object root, String expressionString, Objec * =================================================================== Overridden methods * =================================================================== */ - public void setUp() - { + public void setUp() { super.setUp(); - + /* Should allow access at all to the Simple class except for the bigIntValue property */ DefaultMemberAccess ma = new DefaultMemberAccess(false) { - public boolean isAccessible(Map context, Object target, Member member, String propertyName) { + public boolean isAccessible(OgnlContext context, Object target, Member member, String propertyName) { if (target == Runtime.class) { return false; } @@ -131,6 +109,6 @@ public boolean isAccessible(Map context, Object target, Member member, String pr } }; - _context = (OgnlContext) Ognl.createDefaultContext(null, ma, null, null); + _context = Ognl.createDefaultContext(null, ma, null, null); } } diff --git a/src/test/java/ognl/test/MethodTest.java b/src/test/java/ognl/test/MethodTest.java new file mode 100644 index 00000000..7c656123 --- /dev/null +++ b/src/test/java/ognl/test/MethodTest.java @@ -0,0 +1,141 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.Ognl; +import ognl.OgnlContext; +import ognl.OgnlException; +import ognl.test.objects.BaseGeneric; +import ognl.test.objects.GameGeneric; +import ognl.test.objects.GameGenericObject; +import ognl.test.objects.ListSource; +import ognl.test.objects.ListSourceImpl; +import ognl.test.objects.Simple; + +import java.util.Arrays; +import java.util.List; + +public class MethodTest extends OgnlTestCase { + + private static Simple ROOT = new Simple(); + private static ListSource LIST = new ListSourceImpl(); + private static BaseGeneric GENERIC = new GameGeneric(); + + private static Object[][] TESTS = { + {"hashCode()", new Integer(ROOT.hashCode())}, + {"getBooleanValue() ? \"here\" : \"\"", ""}, + {"getValueIsTrue(!false) ? \"\" : \"here\" ", ""}, + {"messages.format('ShowAllCount', one)", ROOT.getMessages().format("ShowAllCount", ROOT.getOne())}, + {"messages.format('ShowAllCount', {one})", ROOT.getMessages().format("ShowAllCount", new Object[]{ROOT.getOne()})}, + {"messages.format('ShowAllCount', {one, two})", ROOT.getMessages().format("ShowAllCount", new Object[]{ROOT.getOne(), ROOT.getTwo()})}, + {"messages.format('ShowAllCount', one, two)", ROOT.getMessages().format("ShowAllCount", ROOT.getOne(), ROOT.getTwo())}, + {"getTestValue(@ognl.test.objects.SimpleEnum@ONE.value)", new Integer(2)}, + {"@ognl.test.MethodTest@getA().isProperty()", Boolean.FALSE}, + {"isDisabled()", Boolean.TRUE}, + {"isTruck", Boolean.TRUE}, + {"isEditorDisabled()", Boolean.FALSE}, + {LIST, "addValue(name)", Boolean.TRUE}, + {"getDisplayValue(methodsTest.allowDisplay)", "test"}, + {"isThisVarArgsWorking(three, rootValue)", Boolean.TRUE}, + {"isThisVarArgsWorking()", Boolean.TRUE}, + {GENERIC, "service.getFullMessageFor(value, null)", "Halo 3"}, + // TestCase for https://github.com/jkuhnert/ognl/issues/17 - ArrayIndexOutOfBoundsException when trying to access BeanFactory + {"testMethods.getBean('TestBean')", ROOT.getTestMethods().getBean("TestBean")}, + // https://issues.apache.org/jira/browse/OGNL-250 - OnglRuntime getMethodValue fails to find method matching propertyName + {"testMethods.testProperty", ROOT.getTestMethods().testProperty()}, + {"testMethods.argsTest1({one})", ROOT.getTestMethods().argsTest1(Arrays.asList(ROOT.getOne()).toArray())}, // toArray() is automatically done by OGNL type conversion + // we need to cast out generics (insert "Object") + {"testMethods.argsTest2({one})", ROOT.getTestMethods().argsTest2(Arrays.asList((Object) ROOT.getOne()))}, + // Java 'ROOT.getTestMethods().argsTest1(Arrays.asList( ROOT.getOne() )' doesn't compile: + // --> The method argsTest(Object[]) in the type MethodTestMethods is not applicable for the arguments (List) + {"testMethods.argsTest3({one})", "List: [1]"}, + {"testMethods.showList(testMethods.getObjectList())", ROOT.getTestMethods().showList(ROOT.getTestMethods().getObjectList().toArray())}, + {"testMethods.showList(testMethods.getStringList())", ROOT.getTestMethods().showList(ROOT.getTestMethods().getStringList().toArray())}, + {"testMethods.showList(testMethods.getStringArray())", ROOT.getTestMethods().showList(ROOT.getTestMethods().getStringArray())}, + // TODO This one doesn't work - even 'toArray(new String[0]) returns Object[] and so the wrong method is called - currently no idea how to handle this... + // { "testMethods.showList(testMethods.getStringList().toArray(new String[0]))", ROOT.getTestMethods().showList(ROOT.getTestMethods().getStringList().toArray(new String[0])) }, + // but this one works - at least in interpretation mode... + {"testMethods.showStringList(testMethods.getStringList().toArray(new String[0]))", ROOT.getTestMethods().showStringList(ROOT.getTestMethods().getStringList().toArray(new String[0]))}, + + // https://github.com/jkuhnert/ognl/issues/23 - Exception selecting overloaded method in 3.1.4 + {"testMethods.avg({ 5, 5 })", ROOT.getTestMethods().avg((List) Arrays.asList(5, 5))}, + }; + + public void testNullVarArgs() throws OgnlException { + OgnlContext context = Ognl.createDefaultContext(ROOT); + + Object value = Ognl.getValue("isThisVarArgsWorking()", context, ROOT); + + assertTrue(value instanceof Boolean); + assertTrue((Boolean) value); + } + + public static class A { + public boolean isProperty() { + return false; + } + } + + public static A getA() { + return new A(); + } + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new MethodTest((String) TESTS[i][1] + " (" + TESTS[i][2] + ")", TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); + } else { + result.addTest(new MethodTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", ROOT, (String) TESTS[i][0], TESTS[i][1])); + } + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public MethodTest() { + super(); + } + + public MethodTest(String name) { + super(name); + } + + public MethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, + Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public MethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public MethodTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/MethodWithConversionTest.java b/src/test/java/ognl/test/MethodWithConversionTest.java new file mode 100644 index 00000000..f853b442 --- /dev/null +++ b/src/test/java/ognl/test/MethodWithConversionTest.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Simple; + +public class MethodWithConversionTest extends OgnlTestCase { + + private static Simple SIMPLE = new Simple(); + + private static Object[][] TESTS = { + // Method call with conversion + {SIMPLE, "setValues(new Integer(10), \"10.56\", new Double(34.225))", null}, + {SIMPLE, "stringValue", "10"}, + {SIMPLE, "stringValue", "10", new Character('x'), "x"}, + {SIMPLE, "setStringValue('x')", null}, // set by calling setStringValue() directly + {SIMPLE, "floatValue", new Float(10.56)}, + {SIMPLE, "getValueIsTrue(rootValue)", Boolean.TRUE}, + {SIMPLE, "messages.format('Testing', one, two, three)", "blah"} + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new MethodWithConversionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new MethodWithConversionTest((String) TESTS[i][1], TESTS[i][0], + (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new MethodWithConversionTest((String) TESTS[i][1], TESTS[i][0], + (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public MethodWithConversionTest() { + super(); + } + + public MethodWithConversionTest(String name) { + super(name); + } + + public MethodWithConversionTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public MethodWithConversionTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public MethodWithConversionTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/NestedMethodTest.java b/src/test/java/ognl/test/NestedMethodTest.java new file mode 100644 index 00000000..f2cce086 --- /dev/null +++ b/src/test/java/ognl/test/NestedMethodTest.java @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Component; + +public class NestedMethodTest extends OgnlTestCase { + + private static Component COMPONENT = new Component(); + + private static Object[][] TESTS = { + // Expression in a method call argument + {COMPONENT, "toDisplay.pictureUrl", COMPONENT.getToDisplay().getPictureUrl()}, + {COMPONENT, "page.createRelativeAsset(toDisplay.pictureUrl)", + COMPONENT.getPage().createRelativeAsset(COMPONENT.getToDisplay().getPictureUrl())}, + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new NestedMethodTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new NestedMethodTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new NestedMethodTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public NestedMethodTest() { + super(); + } + + public NestedMethodTest(String name) { + super(name); + } + + public NestedMethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, + Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public NestedMethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public NestedMethodTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/NullHandlerTest.java b/src/test/java/ognl/test/NullHandlerTest.java new file mode 100644 index 00000000..b9578b91 --- /dev/null +++ b/src/test/java/ognl/test/NullHandlerTest.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.OgnlRuntime; +import ognl.test.objects.CorrectedObject; + +public class NullHandlerTest extends OgnlTestCase { + private static CorrectedObject CORRECTED = new CorrectedObject(); + + private static Object[][] TESTS = { + // NullHandler + {CORRECTED, "stringValue", "corrected"}, + {CORRECTED, "getStringValue()", "corrected"}, + {CORRECTED, "#root.stringValue", "corrected"}, + {CORRECTED, "#root.getStringValue()", "corrected"}, + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result + .addTest(new NullHandlerTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new NullHandlerTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new NullHandlerTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public NullHandlerTest() { + super(); + } + + public NullHandlerTest(String name) { + super(name); + } + + public NullHandlerTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, + Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public NullHandlerTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public NullHandlerTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } + + /* + * =================================================================== Overridden methods + * =================================================================== + */ + public void setUp() { + super.setUp(); + _compileExpressions = false; + OgnlRuntime.setNullHandler(CorrectedObject.class, new CorrectedObjectNullHandler("corrected")); + } +} diff --git a/src/test/java/ognl/test/NullStringCatenationTest.java b/src/test/java/ognl/test/NullStringCatenationTest.java new file mode 100644 index 00000000..823f8616 --- /dev/null +++ b/src/test/java/ognl/test/NullStringCatenationTest.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Root; + +public class NullStringCatenationTest extends OgnlTestCase { + + public static final String MESSAGE = "blarney"; + + private static Root ROOT = new Root(); + + private static Object[][] TESTS = { + // Null string catenation + {ROOT, "\"bar\" + null", "barnull"}, // Catenate null to a string + {ROOT, "\"bar\" + nullObject", "barnull"}, // Catenate null to a string + {ROOT, "20.56 + nullObject", NullPointerException.class}, // Catenate null to a number + {ROOT, "(true ? 'tabHeader' : '') + (false ? 'tabHeader' : '')", "tabHeader"}, + {ROOT, "theInt == 0 ? '5%' : theInt + '%'", "6%"}, + {ROOT, "'width:' + width + ';'", "width:238px;"}, + {ROOT, "theLong + '_' + index", "4_1"}, + {ROOT, "'javascript:' + @ognl.test.NullStringCatenationTest@MESSAGE", "javascript:blarney"}, + {ROOT, "printDelivery ? '' : 'javascript:deliverySelected(' + property.carrier + ',' + currentDeliveryId + ')'", ""}, + {ROOT, "bean2.id + '_' + theInt", "1_6"} + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new NullStringCatenationTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new NullStringCatenationTest((String) TESTS[i][1], TESTS[i][0], + (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new NullStringCatenationTest((String) TESTS[i][1], TESTS[i][0], + (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public NullStringCatenationTest() { + super(); + } + + public NullStringCatenationTest(String name) { + super(name); + } + + public NullStringCatenationTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public NullStringCatenationTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public NullStringCatenationTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/NumberFormatExceptionTest.java b/src/test/java/ognl/test/NumberFormatExceptionTest.java new file mode 100644 index 00000000..ebb6e930 --- /dev/null +++ b/src/test/java/ognl/test/NumberFormatExceptionTest.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.OgnlException; +import ognl.test.objects.Simple; + +import java.math.BigDecimal; +import java.math.BigInteger; + +public class NumberFormatExceptionTest extends OgnlTestCase { + private static Simple SIMPLE = new Simple(); + + private static Object[][] TESTS = { + // NumberFormatException handling (default is to throw NumberFormatException on bad string conversions) + {SIMPLE, "floatValue", new Float(0f), new Float(10f), new Float(10f)}, + {SIMPLE, "floatValue", new Float(10f), "x10x", OgnlException.class}, + + {SIMPLE, "intValue", new Integer(0), new Integer(34), new Integer(34)}, + {SIMPLE, "intValue", new Integer(34), "foobar", OgnlException.class}, + {SIMPLE, "intValue", new Integer(34), "", OgnlException.class}, + {SIMPLE, "intValue", new Integer(34), " \t", OgnlException.class}, + {SIMPLE, "intValue", new Integer(34), " \t1234\t\t", new Integer(1234)}, + + {SIMPLE, "bigIntValue", BigInteger.valueOf(0), BigInteger.valueOf(34), BigInteger.valueOf(34)}, + {SIMPLE, "bigIntValue", BigInteger.valueOf(34), null, null}, + {SIMPLE, "bigIntValue", null, "", OgnlException.class}, + {SIMPLE, "bigIntValue", null, "foobar", OgnlException.class}, + + {SIMPLE, "bigDecValue", new BigDecimal(0.0), new BigDecimal(34.55), new BigDecimal(34.55)}, + {SIMPLE, "bigDecValue", new BigDecimal(34.55), null, null}, + {SIMPLE, "bigDecValue", null, "", OgnlException.class}, + {SIMPLE, "bigDecValue", null, "foobar", OgnlException.class} + + }; + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new NumberFormatExceptionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new NumberFormatExceptionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new NumberFormatExceptionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public NumberFormatExceptionTest() { + super(); + } + + public NumberFormatExceptionTest(String name) { + super(name); + } + + public NumberFormatExceptionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public NumberFormatExceptionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public NumberFormatExceptionTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/org/ognl/test/NumericConversionTest.java b/src/test/java/ognl/test/NumericConversionTest.java similarity index 82% rename from src/test/java/org/ognl/test/NumericConversionTest.java rename to src/test/java/ognl/test/NumericConversionTest.java index 9c4721f2..2be133b6 100644 --- a/src/test/java/org/ognl/test/NumericConversionTest.java +++ b/src/test/java/ognl/test/NumericConversionTest.java @@ -1,34 +1,22 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; import ognl.OgnlException; @@ -178,8 +166,7 @@ public class NumericConversionTest extends OgnlTestCase { /*=================================================================== Public static methods ===================================================================*/ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { @@ -194,10 +181,9 @@ public static TestSuite suite() /*=================================================================== Constructors ===================================================================*/ - public NumericConversionTest(Object value, Class toClass, Object expectedValue, int scale) - { + public NumericConversionTest(Object value, Class toClass, Object expectedValue, int scale) { super(value + " [" + value.getClass().getName() + "] -> " + toClass.getName() + " == " + expectedValue - + " [" + expectedValue.getClass().getName() + "]" + ((scale >= 0) ? (" (to within " + scale + " decimal places)") : "")); + + " [" + expectedValue.getClass().getName() + "]" + ((scale >= 0) ? (" (to within " + scale + " decimal places)") : "")); this.value = value; this.toClass = toClass; this.expectedValue = expectedValue; @@ -207,8 +193,7 @@ public NumericConversionTest(Object value, Class toClass, Object expectedValue, /*=================================================================== Overridden methods ===================================================================*/ - protected void runTest() throws OgnlException - { + protected void runTest() throws OgnlException { Object result; result = OgnlOps.convertValue(value, toClass); diff --git a/src/test/java/org/ognl/test/ObjectIndexedPropertyTest.java b/src/test/java/ognl/test/ObjectIndexedPropertyTest.java similarity index 61% rename from src/test/java/org/ognl/test/ObjectIndexedPropertyTest.java rename to src/test/java/ognl/test/ObjectIndexedPropertyTest.java index 5bde7484..ee92c112 100644 --- a/src/test/java/org/ognl/test/ObjectIndexedPropertyTest.java +++ b/src/test/java/ognl/test/ObjectIndexedPropertyTest.java @@ -1,39 +1,27 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; import ognl.OgnlException; -import org.ognl.test.objects.Bean1; -import org.ognl.test.objects.ObjectIndexed; +import ognl.test.objects.Bean1; +import ognl.test.objects.ObjectIndexed; public class ObjectIndexedPropertyTest extends OgnlTestCase { @@ -41,7 +29,7 @@ public class ObjectIndexedPropertyTest extends OgnlTestCase { private static Bean1 root = new Bean1(); private static Object[][] TESTS = { // Arbitrary indexed properties - {OBJECT_INDEXED, "attributes[\"bar\"]", "baz"}, // get non-indexed property through + {OBJECT_INDEXED, "attributes[\"bar\"]", "baz"}, // get non-indexed property through // attributes Map {OBJECT_INDEXED, "attribute[\"foo\"]", "bar"}, // get indexed property {OBJECT_INDEXED, "attribute[\"bar\"]", "baz", "newValue", "newValue"}, // set @@ -69,8 +57,7 @@ public class ObjectIndexedPropertyTest extends OgnlTestCase { * =================================================================== Public static methods * =================================================================== */ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { @@ -98,30 +85,25 @@ public static TestSuite suite() * =================================================================== Constructors * =================================================================== */ - public ObjectIndexedPropertyTest() - { + public ObjectIndexedPropertyTest() { super(); } - public ObjectIndexedPropertyTest(String name) - { + public ObjectIndexedPropertyTest(String name) { super(name); } public ObjectIndexedPropertyTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { + Object setValue, Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } public ObjectIndexedPropertyTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { + Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public ObjectIndexedPropertyTest(String name, Object root, String expressionString, Object expectedResult) - { + public ObjectIndexedPropertyTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } } diff --git a/src/test/java/org/ognl/test/ObjectIndexedTest.java b/src/test/java/ognl/test/ObjectIndexedTest.java similarity index 63% rename from src/test/java/org/ognl/test/ObjectIndexedTest.java rename to src/test/java/ognl/test/ObjectIndexedTest.java index ff618f04..3535be5a 100644 --- a/src/test/java/org/ognl/test/ObjectIndexedTest.java +++ b/src/test/java/ognl/test/ObjectIndexedTest.java @@ -1,4 +1,4 @@ -package org.ognl.test; +package ognl.test; import junit.framework.TestCase; import junit.framework.TestSuite; @@ -9,100 +9,80 @@ import ognl.OgnlRuntime; import ognl.SimpleNode; -public class ObjectIndexedTest extends TestCase -{ - protected OgnlContext context; +public class ObjectIndexedTest extends TestCase { + protected OgnlContext context; /*=================================================================== Public static classes ===================================================================*/ - public static interface TestInterface - { + public static interface TestInterface { String getSunk(String index); + void setSunk(String index, String sunk); } - public static class Test1 extends Object implements TestInterface - { - public String getSunk(String index) - { + public static class Test1 extends Object implements TestInterface { + public String getSunk(String index) { return "foo"; } - public void setSunk(String index, String sunk) - { + public void setSunk(String index, String sunk) { /* do nothing */ } } - public static class Test2 extends Test1 - { - public String getSunk(String index) - { + public static class Test2 extends Test1 { + public String getSunk(String index) { return "foo"; } - public void setSunk(String index, String sunk) - { + public void setSunk(String index, String sunk) { /* do nothing */ } } - public static class Test3 extends Test1 - { - public String getSunk(String index) - { + public static class Test3 extends Test1 { + public String getSunk(String index) { return "foo"; } - public void setSunk(String index, String sunk) - { + public void setSunk(String index, String sunk) { /* do nothing */ } - public String getSunk(Object index) - { + public String getSunk(Object index) { return null; } } - public static class Test4 extends Test1 - { - public String getSunk(String index) - { + public static class Test4 extends Test1 { + public String getSunk(String index) { return "foo"; } - public void setSunk(String index, String sunk) - { + public void setSunk(String index, String sunk) { /* do nothing */ } - public void setSunk(Object index, String sunk) - { + public void setSunk(Object index, String sunk) { /* do nothing */ } } - public static class Test5 extends Test1 - { - public String getSunk(String index) - { + public static class Test5 extends Test1 { + public String getSunk(String index) { return "foo"; } - public void setSunk(String index, String sunk) - { + public void setSunk(String index, String sunk) { /* do nothing */ } - public String getSunk(Object index) - { + public String getSunk(Object index) { return null; } - public void setSunk(Object index, String sunk) - { + public void setSunk(Object index, String sunk) { /* do nothing */ } } @@ -110,29 +90,25 @@ public void setSunk(Object index, String sunk) /*=================================================================== Public static methods ===================================================================*/ - public static TestSuite suite() - { + public static TestSuite suite() { return new TestSuite(ObjectIndexedTest.class); } /*=================================================================== Constructors ===================================================================*/ - public ObjectIndexedTest() - { + public ObjectIndexedTest() { super(); } - public ObjectIndexedTest(String name) - { + public ObjectIndexedTest(String name) { super(name); } /*=================================================================== Public methods ===================================================================*/ - public void testPropertyDescriptorReflection() throws Exception - { + public void testPropertyDescriptorReflection() throws Exception { OgnlRuntime.getPropertyDescriptor(java.util.AbstractList.class, ""); OgnlRuntime.getPropertyDescriptor(java.util.AbstractSequentialList.class, ""); OgnlRuntime.getPropertyDescriptor(java.lang.reflect.Array.class, ""); @@ -148,25 +124,22 @@ public void testPropertyDescriptorReflection() throws Exception OgnlRuntime.getPropertyDescriptor(java.util.Vector.class, ""); } - public void testObjectIndexAccess() throws OgnlException - { - SimpleNode expression = (SimpleNode)Ognl.parseExpression("#ka.sunk[#root]"); + public void testObjectIndexAccess() throws OgnlException { + SimpleNode expression = (SimpleNode) Ognl.parseExpression("#ka.sunk[#root]"); context.put("ka", new Test1()); Ognl.getValue(expression, context, "aksdj"); } - public void testObjectIndexInSubclass() throws OgnlException - { - SimpleNode expression = (SimpleNode)Ognl.parseExpression("#ka.sunk[#root]"); + public void testObjectIndexInSubclass() throws OgnlException { + SimpleNode expression = (SimpleNode) Ognl.parseExpression("#ka.sunk[#root]"); context.put("ka", new Test2()); Ognl.getValue(expression, context, "aksdj"); } - public void testMultipleObjectIndexGetters() throws OgnlException - { - SimpleNode expression = (SimpleNode)Ognl.parseExpression("#ka.sunk[#root]"); + public void testMultipleObjectIndexGetters() throws OgnlException { + SimpleNode expression = (SimpleNode) Ognl.parseExpression("#ka.sunk[#root]"); context.put("ka", new Test3()); try { @@ -177,9 +150,8 @@ public void testMultipleObjectIndexGetters() throws OgnlException } } - public void testMultipleObjectIndexSetters() throws OgnlException - { - SimpleNode expression = (SimpleNode)Ognl.parseExpression("#ka.sunk[#root]"); + public void testMultipleObjectIndexSetters() throws OgnlException { + SimpleNode expression = (SimpleNode) Ognl.parseExpression("#ka.sunk[#root]"); context.put("ka", new Test4()); try { @@ -190,9 +162,8 @@ public void testMultipleObjectIndexSetters() throws OgnlException } } - public void testMultipleObjectIndexMethodPairs() throws OgnlException - { - SimpleNode expression = (SimpleNode)Ognl.parseExpression("#ka.sunk[#root]"); + public void testMultipleObjectIndexMethodPairs() throws OgnlException { + SimpleNode expression = (SimpleNode) Ognl.parseExpression("#ka.sunk[#root]"); context.put("ka", new Test5()); try { @@ -203,11 +174,10 @@ public void testMultipleObjectIndexMethodPairs() throws OgnlException } } - /*=================================================================== - Overridden methods - ===================================================================*/ - protected void setUp() - { - context = (OgnlContext)Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); + /*=================================================================== + Overridden methods + ===================================================================*/ + protected void setUp() { + context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); } -} \ No newline at end of file +} diff --git a/src/test/java/ognl/OgnlOpsTest.java b/src/test/java/ognl/test/OgnlOpsTest.java similarity index 98% rename from src/test/java/ognl/OgnlOpsTest.java rename to src/test/java/ognl/test/OgnlOpsTest.java index 3832d043..486c859d 100644 --- a/src/test/java/ognl/OgnlOpsTest.java +++ b/src/test/java/ognl/test/OgnlOpsTest.java @@ -1,6 +1,7 @@ -package ognl; +package ognl.test; import junit.framework.TestCase; +import ognl.OgnlOps; public class OgnlOpsTest extends TestCase { public void testEqualStringsEqual() throws Exception { diff --git a/src/test/java/org/ognl/test/OgnlTestCase.java b/src/test/java/ognl/test/OgnlTestCase.java similarity index 68% rename from src/test/java/org/ognl/test/OgnlTestCase.java rename to src/test/java/ognl/test/OgnlTestCase.java index 8cb4705e..01888828 100644 --- a/src/test/java/org/ognl/test/OgnlTestCase.java +++ b/src/test/java/ognl/test/OgnlTestCase.java @@ -1,34 +1,22 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestCase; import ognl.DefaultMemberAccess; @@ -56,13 +44,13 @@ public abstract class OgnlTestCase extends TestCase { /*=================================================================== Public static methods ===================================================================*/ + /** * Returns true if object1 is equal to object2 in either the * sense that they are the same object or, if both are non-null * if they are equal in the equals() sense. */ - public static boolean isEqual(Object object1, Object object2) - { + public static boolean isEqual(Object object1, Object object2) { boolean result = false; if (object1 == object2) { @@ -87,32 +75,27 @@ public static boolean isEqual(Object object1, Object object2) /*=================================================================== Constructors ===================================================================*/ - public OgnlTestCase() - { + public OgnlTestCase() { super(); } - public OgnlTestCase(String name) - { + public OgnlTestCase(String name) { super(name); } - public OgnlTestCase(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { + public OgnlTestCase(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { this(name, root, expressionString, expectedResult, setValue); this.hasExpectedAfterSetResult = true; this.expectedAfterSetResult = expectedAfterSetResult; } - public OgnlTestCase(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { + public OgnlTestCase(String name, Object root, String expressionString, Object expectedResult, Object setValue) { this(name, root, expressionString, expectedResult); this.hasSetValue = true; this.setValue = setValue; } - public OgnlTestCase(String name, Object root, String expressionString, Object expectedResult) - { + public OgnlTestCase(String name, Object root, String expressionString, Object expectedResult) { this(name); this._root = root; this._expressionString = expressionString; @@ -122,44 +105,37 @@ public OgnlTestCase(String name, Object root, String expressionString, Object ex /*=================================================================== Public methods ===================================================================*/ - public String getExpressionDump(SimpleNode node) - { + public String getExpressionDump(SimpleNode node) { StringWriter writer = new StringWriter(); node.dump(new PrintWriter(writer), " "); return writer.toString(); } - public String getExpressionString() - { + public String getExpressionString() { return _expressionString; } public SimpleNode getExpression() - throws Exception - { - if (_expression == null) - { + throws Exception { + if (_expression == null) { _expression = (SimpleNode) Ognl.parseExpression(_expressionString); } - if (_compileExpressions) - { + if (_compileExpressions) { _expression = (SimpleNode) Ognl.compileExpression(_context, _root, _expressionString); } return _expression; } - public Object getExpectedResult() - { + public Object getExpectedResult() { return _expectedResult; } - public static void assertEquals(Object expected, Object actual) - { + public static void assertEquals(Object expected, Object actual) { if (expected != null && expected.getClass().isArray() - && actual != null && actual.getClass().isArray()) { + && actual != null && actual.getClass().isArray()) { TestCase.assertEquals(Array.getLength(expected), Array.getLength(actual)); @@ -175,8 +151,8 @@ public static void assertEquals(Object expected, Object actual) OgnlTestCase.assertEquals(aexpected, aactual); } } else if (expected != null && actual != null - && Character.class.isInstance(expected) - && Character.class.isInstance(actual)) { + && Character.class.isInstance(expected) + && Character.class.isInstance(actual)) { TestCase.assertEquals(((Character) expected).charValue(), ((Character) actual).charValue()); } else { @@ -188,8 +164,7 @@ public static void assertEquals(Object expected, Object actual) /*=================================================================== Overridden methods ===================================================================*/ - protected void runTest() throws Exception - { + protected void runTest() throws Exception { Object testedResult = null; try { @@ -200,8 +175,7 @@ protected void runTest() throws Exception assertEquals(_expectedResult, Ognl.getValue(expr, _context, _root)); - if (hasSetValue) - { + if (hasSetValue) { testedResult = hasExpectedAfterSetResult ? expectedAfterSetResult : setValue; Ognl.setValue(expr, _context, _root, setValue); @@ -214,19 +188,17 @@ protected void runTest() throws Exception ex.printStackTrace(); if (RuntimeException.class.isInstance(ex) && ((RuntimeException) ex).getCause() != null - && Exception.class.isAssignableFrom(((RuntimeException) ex).getCause().getClass())) + && Exception.class.isAssignableFrom(((RuntimeException) ex).getCause().getClass())) ex = (Exception) ((RuntimeException) ex).getCause(); - if (testedResult instanceof Class) - { + if (testedResult instanceof Class) { assertTrue(Exception.class.isAssignableFrom((Class) testedResult)); } else throw ex; } } - protected void setUp() - { + protected void setUp() { _context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false), null, null); } } diff --git a/src/test/java/org/ognl/test/OperationTest.java b/src/test/java/ognl/test/OperationTest.java similarity index 95% rename from src/test/java/org/ognl/test/OperationTest.java rename to src/test/java/ognl/test/OperationTest.java index 12c05e53..3a2714cb 100644 --- a/src/test/java/org/ognl/test/OperationTest.java +++ b/src/test/java/ognl/test/OperationTest.java @@ -1,4 +1,4 @@ -package org.ognl.test; +package ognl.test; import junit.framework.TestCase; import ognl.DefaultMemberAccess; @@ -7,7 +7,7 @@ import ognl.SimpleNode; /** - * Tests for {@link ognl.SimpleNode#isOperation(OgnlContext)}. + * Tests for {@link SimpleNode#isOperation(OgnlContext)}. */ public class OperationTest extends TestCase { diff --git a/src/test/java/org/ognl/test/OperatorTest.java b/src/test/java/ognl/test/OperatorTest.java similarity index 57% rename from src/test/java/org/ognl/test/OperatorTest.java rename to src/test/java/ognl/test/OperatorTest.java index f1a0d711..8db423bc 100644 --- a/src/test/java/org/ognl/test/OperatorTest.java +++ b/src/test/java/ognl/test/OperatorTest.java @@ -1,34 +1,22 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; @@ -54,8 +42,7 @@ public class OperatorTest extends OgnlTestCase { /*=================================================================== Public static methods ===================================================================*/ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { @@ -79,28 +66,23 @@ public static TestSuite suite() /*=================================================================== Constructors ===================================================================*/ - public OperatorTest() - { + public OperatorTest() { super(); } - public OperatorTest(String name) - { + public OperatorTest(String name) { super(name); } - public OperatorTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { + public OperatorTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } - public OperatorTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { + public OperatorTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public OperatorTest(String name, Object root, String expressionString, Object expectedResult) - { + public OperatorTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } } diff --git a/src/test/java/org/ognl/test/Performance.java b/src/test/java/ognl/test/Performance.java similarity index 70% rename from src/test/java/org/ognl/test/Performance.java rename to src/test/java/ognl/test/Performance.java index 9fc9e67c..712b595b 100644 --- a/src/test/java/org/ognl/test/Performance.java +++ b/src/test/java/ognl/test/Performance.java @@ -1,49 +1,36 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import ognl.DefaultMemberAccess; import ognl.Ognl; import ognl.OgnlContext; import ognl.OgnlException; import ognl.SimpleNode; -import org.ognl.test.objects.Bean1; +import ognl.test.objects.Bean1; import java.io.Serializable; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.text.NumberFormat; -public class Performance extends Object -{ +public class Performance extends Object { private static int MAX_ITERATIONS = -1; private static boolean ITERATIONS_MODE; @@ -65,26 +52,23 @@ public class Performance extends Object private long t1; /* - * =================================================================== Private static classes - * =================================================================== - */ - private static class Results - { + * =================================================================== Private static classes + * =================================================================== + */ + private static class Results { int iterations; long time; boolean mvel; - public Results(int iterations, long time, boolean mvel) - { + public Results(int iterations, long time, boolean mvel) { super(); this.iterations = iterations; this.time = time; this.mvel = mvel; } - public String getFactor(Results otherResults) - { + public String getFactor(Results otherResults) { String ret = null; if (TIME_MODE) { @@ -92,10 +76,10 @@ public String getFactor(Results otherResults) if (iterations < otherResults.iterations) { factor = Math.max((float) otherResults.iterations, (float) iterations) - / Math.min((float) otherResults.iterations, (float) iterations); + / Math.min((float) otherResults.iterations, (float) iterations); } else { factor = Math.min((float) otherResults.iterations, (float) iterations) - / Math.max((float) otherResults.iterations, (float) iterations); + / Math.max((float) otherResults.iterations, (float) iterations); } ret = FACTOR_FORMAT.format(factor); @@ -106,7 +90,7 @@ public String getFactor(Results otherResults) } else { float factor = Math.max((float) otherResults.time, (float) time) - / Math.min((float) otherResults.time, (float) time); + / Math.min((float) otherResults.time, (float) time); ret = FACTOR_FORMAT.format(factor); if (time < otherResults.time) @@ -123,9 +107,8 @@ public String getFactor(Results otherResults) * =================================================================== Public static methods * =================================================================== */ - public static void main(String[] args) - { - for(int i = 0; i < args.length; i++) { + public static void main(String[] args) { + for (int i = 0; i < args.length; i++) { if (args[i].equals("-time")) { TIME_MODE = true; MAX_TIME = Long.parseLong(args[++i]); @@ -140,21 +123,21 @@ public static void main(String[] args) } try { - Performance[] tests = new Performance[] { + Performance[] tests = new Performance[]{ new Performance("Constant", "100 + 20 * 5", "testConstantExpression"), //new Performance("Constant", "100 + 20 * 5", "testConstantExpression", false), new Performance("Single Property", "bean2", "testSinglePropertyExpression"), new Performance("Property Navigation", "bean2.bean3.value", "testPropertyNavigationExpression"), /*new Performance("Property Setting with context key", "bean2.bean3.nullValue", "testPropertyNavigationSetting"), - new Performance("Property Setting with context key", "bean2.bean3.nullValue", "testPropertyNavigationSetting", true), */ + new Performance("Property Setting with context key", "bean2.bean3.nullValue", "testPropertyNavigationSetting", true), */ new Performance("Property Navigation and Comparison", "bean2.bean3.value <= 24", - "testPropertyNavigationAndComparisonExpression"), + "testPropertyNavigationAndComparisonExpression"), /* new Performance("Property Navigation with Indexed Access", "bean2.bean3.indexedValue[25]", "testIndexedPropertyNavigationExpression"), new Performance("Property Navigation with Indexed Access", "bean2.bean3.indexedValue[25]", "testIndexedPropertyNavigationExpression", true), */ new Performance("Property Navigation with Map Access", "bean2.bean3.map['foo']", - "testPropertyNavigationWithMapExpression"), + "testPropertyNavigationWithMapExpression"), /* new Performance("Property Navigation with Map value set", "bean2.bean3.map['foo']", "testPropertyNavigationWithMapSetting"), new Performance("Property Navigation with Map value set", "bean2.bean3.map['foo']", @@ -193,9 +176,8 @@ public static void main(String[] args) } static void runTests(Performance[] tests, boolean output) - throws Exception - { - for(int i = 0; i < tests.length; i++) { + throws Exception { + for (int i = 0; i < tests.length; i++) { Performance perf = tests[i]; try { @@ -211,12 +193,12 @@ static void runTests(Performance[] tests, boolean output) System.out.println(" java: " + javaResults.iterations + " iterations in " + javaResults.time + " ms"); System.out.println(" compiled: " + compiledResults.iterations + " iterations in " - + compiledResults.time + " ms (" - + compiledResults.getFactor(javaResults) + "java)"); + + compiledResults.time + " ms (" + + compiledResults.getFactor(javaResults) + "java)"); System.out.println("interpreted: " + interpretedResults.iterations + " iterations in " - + interpretedResults.time + " ms (" - + interpretedResults.getFactor(javaResults) + "java)"); + + interpretedResults.time + " ms (" + + interpretedResults.getFactor(javaResults) + "java)"); System.out.println(); @@ -227,36 +209,32 @@ static void runTests(Performance[] tests, boolean output) } /* - * =================================================================== Constructors - * =================================================================== - */ + * =================================================================== Constructors + * =================================================================== + */ public Performance(String name, String expressionString, String javaMethodName) - throws Exception - { + throws Exception { this(name, expressionString, javaMethodName, false); } public Performance(String name, String expressionString, String javaMethodName, boolean mvel) - throws Exception - { + throws Exception { _name = name; _isMvel = mvel; _expressionString = expressionString; try { - _method = getClass().getMethod(javaMethodName, new Class[] {}); + _method = getClass().getMethod(javaMethodName, new Class[]{}); } catch (Exception ex) { throw new OgnlException("java method not found", ex); } - if (!_isMvel) - { + if (!_isMvel) { _expression = (SimpleNode) Ognl.parseExpression(expressionString); _compiledExpression = (SimpleNode) Ognl.compileExpression(_context, _root, expressionString); Ognl.getValue(_expression, _context, _root); _context.put("contextValue", "cvalue"); - } else - { + } else { //_mvelCompiled = MVEL.compileExpression(expressionString); } } @@ -265,19 +243,16 @@ public Performance(String name, String expressionString, String javaMethodName, * =================================================================== Protected methods * =================================================================== */ - protected void startTest() - { + protected void startTest() { _iterations = 0; t0 = t1 = System.currentTimeMillis(); } - protected Results endTest() - { + protected Results endTest() { return new Results(_iterations, t1 - t0, _isMvel); } - protected boolean done() - { + protected boolean done() { _iterations++; t1 = System.currentTimeMillis(); @@ -296,126 +271,112 @@ protected boolean done() * =================================================================== Public methods * =================================================================== */ - public String getName() - { + public String getName() { return _name; } - public String getExpression() - { + public String getExpression() { return _expressionString; } public Results testExpression(boolean compiled) - throws Exception - { + throws Exception { startTest(); do { - if (!_isMvel) - { + if (!_isMvel) { if (compiled) Ognl.getValue(_compiledExpression.getAccessor(), _context, _root); else Ognl.getValue(_expression, _context, _root); - } else - { + } else { /* if (compiled) MVEL.executeExpression(_mvelCompiled, _root); else MVEL.eval(_expressionString, _root);*/ } - } while(!done()); + } while (!done()); return endTest(); } public Results testJava() - throws OgnlException - { + throws OgnlException { try { - return (Results) _method.invoke(this, new Object[] {}); + return (Results) _method.invoke(this, new Object[]{}); } catch (Exception ex) { throw new OgnlException("invoking java method '" + _method.getName() + "'", ex); } } public Results testConstantExpression() - throws OgnlException - { + throws OgnlException { startTest(); do { int result = 100 + 20 * 5; - } while(!done()); + } while (!done()); return endTest(); } public Results testSinglePropertyExpression() - throws OgnlException - { + throws OgnlException { startTest(); do { _root.getBean2(); - } while(!done()); + } while (!done()); return endTest(); } public Results testPropertyNavigationExpression() - throws OgnlException - { + throws OgnlException { startTest(); do { _root.getBean2().getBean3().getValue(); - } while(!done()); + } while (!done()); return endTest(); } public Results testPropertyNavigationSetting() - throws OgnlException - { + throws OgnlException { startTest(); do { _root.getBean2().getBean3().setNullValue("a value"); - } while(!done()); + } while (!done()); return endTest(); } public Results testPropertyNavigationAndComparisonExpression() - throws OgnlException - { + throws OgnlException { startTest(); do { boolean result = _root.getBean2().getBean3().getValue() < 24; - } while(!done()); + } while (!done()); return endTest(); } public Results testIndexedPropertyNavigationExpression() - throws OgnlException - { + throws OgnlException { startTest(); do { _root.getBean2().getBean3().getIndexedValue(25); - } while(!done()); + } while (!done()); return endTest(); } public Results testPropertyNavigationWithMapSetting() - throws OgnlException - { + throws OgnlException { startTest(); do { _root.getBean2().getBean3().getMap().put("bam", "bam"); - } while(!done()); + } while (!done()); return endTest(); } public Results testPropertyNavigationWithMapExpression() - throws OgnlException - { + throws OgnlException { startTest(); do { _root.getBean2().getBean3().getMap().get("foo"); - } while(!done()); + } while (!done()); return endTest(); } } diff --git a/src/test/java/org/ognl/test/PrimitiveArrayTest.java b/src/test/java/ognl/test/PrimitiveArrayTest.java similarity index 58% rename from src/test/java/org/ognl/test/PrimitiveArrayTest.java rename to src/test/java/ognl/test/PrimitiveArrayTest.java index e2ca945e..4fbc994a 100644 --- a/src/test/java/org/ognl/test/PrimitiveArrayTest.java +++ b/src/test/java/ognl/test/PrimitiveArrayTest.java @@ -1,37 +1,25 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; -import org.ognl.test.objects.Root; +import ognl.test.objects.Root; public class PrimitiveArrayTest extends OgnlTestCase { private static Root ROOT = new Root(); @@ -58,8 +46,7 @@ public class PrimitiveArrayTest extends OgnlTestCase { /*=================================================================== Public static methods ===================================================================*/ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { @@ -83,28 +70,23 @@ public static TestSuite suite() /*=================================================================== Constructors ===================================================================*/ - public PrimitiveArrayTest() - { + public PrimitiveArrayTest() { super(); } - public PrimitiveArrayTest(String name) - { + public PrimitiveArrayTest(String name) { super(name); } - public PrimitiveArrayTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { + public PrimitiveArrayTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } - public PrimitiveArrayTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { + public PrimitiveArrayTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public PrimitiveArrayTest(String name, Object root, String expressionString, Object expectedResult) - { + public PrimitiveArrayTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } } diff --git a/src/test/java/ognl/test/PrimitiveNullHandlingTest.java b/src/test/java/ognl/test/PrimitiveNullHandlingTest.java new file mode 100644 index 00000000..cf3c1393 --- /dev/null +++ b/src/test/java/ognl/test/PrimitiveNullHandlingTest.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Simple; + +public class PrimitiveNullHandlingTest extends OgnlTestCase { + + private static Simple SIMPLE = new Simple(); + + static { + SIMPLE.setFloatValue(10.56f); + SIMPLE.setIntValue(34); + } + + private static Object[][] TESTS = { + // Primitive null handling + {SIMPLE, "floatValue", new Float(10.56f), null, new Float(0f)}, // set float to + // null, should + // yield 0.0f + {SIMPLE, "intValue", new Integer(34), null, new Integer(0)},// set int to null, + // should yield 0 + {SIMPLE, "booleanValue", Boolean.FALSE, Boolean.TRUE, Boolean.TRUE},// set boolean + // to TRUE, + // should yield + // true + {SIMPLE, "booleanValue", Boolean.TRUE, null, Boolean.FALSE}, // set boolean to null, + // should yield false + + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new PrimitiveNullHandlingTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new PrimitiveNullHandlingTest((String) TESTS[i][1], TESTS[i][0], + (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new PrimitiveNullHandlingTest((String) TESTS[i][1], TESTS[i][0], + (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public PrimitiveNullHandlingTest() { + super(); + } + + public PrimitiveNullHandlingTest(String name) { + super(name); + } + + public PrimitiveNullHandlingTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public PrimitiveNullHandlingTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public PrimitiveNullHandlingTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/PrivateAccessorTest.java b/src/test/java/ognl/test/PrivateAccessorTest.java new file mode 100644 index 00000000..c68f8d5a --- /dev/null +++ b/src/test/java/ognl/test/PrivateAccessorTest.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.DefaultMemberAccess; +import ognl.OgnlContext; +import ognl.test.objects.Root; + +public class PrivateAccessorTest extends OgnlTestCase { + + private static Root ROOT = new Root(); + + private static Object[][] TESTS = { + // Using private get/set methods + {ROOT, "getPrivateAccessorIntValue()", new Integer(67)}, + {ROOT, "privateAccessorIntValue", new Integer(67)}, + {ROOT, "privateAccessorIntValue", new Integer(67), new Integer(100)}, + {ROOT, "privateAccessorIntValue2", new Integer(67)}, + {ROOT, "privateAccessorIntValue2", new Integer(67), new Integer(100)}, + {ROOT, "privateAccessorIntValue3", new Integer(67)}, + {ROOT, "privateAccessorIntValue3", new Integer(67), new Integer(100)}, + {ROOT, "privateAccessorBooleanValue", Boolean.TRUE}, + {ROOT, "privateAccessorBooleanValue", Boolean.TRUE, Boolean.FALSE}, + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new PrivateAccessorTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new PrivateAccessorTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new PrivateAccessorTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public PrivateAccessorTest() { + super(); + } + + public PrivateAccessorTest(String name) { + super(name); + } + + public PrivateAccessorTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public PrivateAccessorTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public PrivateAccessorTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } + + /* + * =================================================================== Overridden methods + * =================================================================== + */ + public void setUp() { + super.setUp(); + _context = new OgnlContext(null, null, new DefaultMemberAccess(true)); + _compileExpressions = false; + } +} diff --git a/src/test/java/org/ognl/test/PrivateMemberTest.java b/src/test/java/ognl/test/PrivateMemberTest.java similarity index 73% rename from src/test/java/org/ognl/test/PrivateMemberTest.java rename to src/test/java/ognl/test/PrivateMemberTest.java index 73b7b8db..fbc8585b 100644 --- a/src/test/java/org/ognl/test/PrivateMemberTest.java +++ b/src/test/java/ognl/test/PrivateMemberTest.java @@ -1,34 +1,22 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestCase; import junit.framework.TestSuite; @@ -42,36 +30,32 @@ * This is a test program for private access in OGNL. * Shows the failures and a summary. */ -public class PrivateMemberTest extends TestCase -{ - private static String _privateStaticProperty = "private static value"; - private String _privateProperty = "private value"; - private final String _privateFinalProperty = "private final value"; - private static final String _privateStaticFinalProperty = "private static final value"; - protected OgnlContext context; - - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { +public class PrivateMemberTest extends TestCase { + private static String _privateStaticProperty = "private static value"; + private String _privateProperty = "private value"; + private final String _privateFinalProperty = "private final value"; + private static final String _privateStaticFinalProperty = "private static final value"; + protected OgnlContext context; + + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { return new TestSuite(PrivateMemberTest.class); } - /*=================================================================== - Constructors - ===================================================================*/ - public PrivateMemberTest(String name) - { - super(name); - } + /*=================================================================== + Constructors + ===================================================================*/ + public PrivateMemberTest(String name) { + super(name); + } - /*=================================================================== - Private methods - ===================================================================*/ - private String getPrivateProperty() - { + /*=================================================================== + Private methods + ===================================================================*/ + private String getPrivateProperty() { return _privateProperty; } @@ -79,48 +63,40 @@ private static String getPrivateStaticProperty() { return _privateStaticProperty; } - private String getPrivateFinalProperty() - { + private String getPrivateFinalProperty() { return _privateFinalProperty; } - private static String getPrivateStaticFinalProperty() - { + private static String getPrivateStaticFinalProperty() { return _privateStaticFinalProperty; } - /*=================================================================== - Public methods - ===================================================================*/ - public void testPrivateAccessor() throws OgnlException - { + /*=================================================================== + Public methods + ===================================================================*/ + public void testPrivateAccessor() throws OgnlException { assertEquals(Ognl.getValue("privateProperty", context, this), getPrivateProperty()); } - public void testPrivateField() throws OgnlException - { + public void testPrivateField() throws OgnlException { assertEquals(Ognl.getValue("_privateProperty", context, this), _privateProperty); } - public void testPrivateFinalAccessor() throws OgnlException - { + public void testPrivateFinalAccessor() throws OgnlException { assertEquals(Ognl.getValue("privateFinalProperty", context, this), getPrivateFinalProperty()); } - public void testPrivateFinalField() throws OgnlException - { + public void testPrivateFinalField() throws OgnlException { assertEquals(Ognl.getValue("_privateFinalProperty", context, this), _privateFinalProperty); } - public void testPrivateStaticAccessor() throws OgnlException - { + public void testPrivateStaticAccessor() throws OgnlException { // Test following PR#59/PR#60 (MemberAccess support private static field). assertEquals(Ognl.getValue("privateStaticProperty", context, this), getPrivateStaticProperty()); // Succeeds due to calling the static getter to retrieve it. } - public void testPrivateStaticFieldNormalAccess() throws OgnlException - { + public void testPrivateStaticFieldNormalAccess() throws OgnlException { // Test following PR#59/PR#60 (MemberAccess support private static field). try { assertEquals(Ognl.getValue("_privateStaticProperty", context, this), _privateStaticProperty); @@ -130,21 +106,18 @@ public void testPrivateStaticFieldNormalAccess() throws OgnlException } } - public void testPrivateStaticFieldStaticAccess() throws OgnlException - { + public void testPrivateStaticFieldStaticAccess() throws OgnlException { // Test following PR#59/PR#60 (MemberAccess support private static field). - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_privateStaticProperty"), _privateStaticProperty); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_privateStaticProperty"), _privateStaticProperty); // Only succeeds due to directly using the runtime to access the field as a static field. } - public void testPrivateStaticFinalAccessor() throws OgnlException - { + public void testPrivateStaticFinalAccessor() throws OgnlException { assertEquals(Ognl.getValue("privateStaticFinalProperty", context, this), getPrivateStaticFinalProperty()); // Succeeds due to calling the static getter to retrieve it. } - public void testPrivateStaticFinalFieldNormalAccess() throws OgnlException - { + public void testPrivateStaticFinalFieldNormalAccess() throws OgnlException { try { assertEquals(Ognl.getValue("_privateStaticFinalProperty", context, this), _privateStaticFinalProperty); fail("Should not be able to access private static _privateStaticFinalProperty through getValue()"); @@ -153,14 +126,12 @@ public void testPrivateStaticFinalFieldNormalAccess() throws OgnlException } } - public void testPrivateStaticFinalFieldStaticAccess() throws OgnlException - { - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_privateStaticFinalProperty"), _privateStaticFinalProperty); + public void testPrivateStaticFinalFieldStaticAccess() throws OgnlException { + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_privateStaticFinalProperty"), _privateStaticFinalProperty); // Only succeeds due to directly using the runtime to access the field as a static field. } - public void testPrivateFieldSet() throws OgnlException - { + public void testPrivateFieldSet() throws OgnlException { final String originalValue = _privateProperty; assertEquals(Ognl.getValue("_privateProperty", context, this), originalValue); Ognl.setValue("_privateProperty", context, this, "changevalue"); @@ -169,8 +140,7 @@ public void testPrivateFieldSet() throws OgnlException assertEquals(Ognl.getValue("_privateProperty", context, this), originalValue); } - public void testPrivateFinalFieldSet() throws OgnlException - { + public void testPrivateFinalFieldSet() throws OgnlException { final String originalValue = _privateFinalProperty; assertEquals(Ognl.getValue("_privateFinalProperty", context, this), originalValue); try { @@ -182,34 +152,31 @@ public void testPrivateFinalFieldSet() throws OgnlException assertEquals(Ognl.getValue("_privateFinalProperty", context, this), originalValue); } - public void testPrivateStaticFieldSet() throws OgnlException - { + public void testPrivateStaticFieldSet() throws OgnlException { final String originalValue = _privateStaticProperty; - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_privateStaticProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_privateStaticProperty"), originalValue); try { Ognl.setValue("_privateStaticProperty", context, this, "changevalue"); fail("Should not be able to modify static property"); } catch (OgnlException oex) { // Fails as test attempts to modify a static property } - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_privateStaticProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_privateStaticProperty"), originalValue); } - public void testPrivateStaticFinalFieldSet() throws OgnlException - { + public void testPrivateStaticFinalFieldSet() throws OgnlException { final String originalValue = _privateStaticFinalProperty; - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_privateStaticFinalProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_privateStaticFinalProperty"), originalValue); try { Ognl.setValue("_privateStaticFinalProperty", context, this, "changevalue"); fail("Should not be able to modify static property"); } catch (OgnlException oex) { // Fails as test attempts to modify a static property } - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_privateStaticFinalProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_privateStaticFinalProperty"), originalValue); } - public void testPrivateFieldSetFail() throws OgnlException - { + public void testPrivateFieldSetFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { Ognl.setValue("_privateProperty", context, this, "changevalue"); @@ -219,8 +186,7 @@ public void testPrivateFieldSetFail() throws OgnlException } } - public void testPrivateFinalFieldSetFail() throws OgnlException - { + public void testPrivateFinalFieldSetFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { Ognl.setValue("_privateFinalProperty", context, this, "changevalue"); @@ -230,8 +196,7 @@ public void testPrivateFinalFieldSetFail() throws OgnlException } } - public void testPrivateStaticFieldSetFail() throws OgnlException - { + public void testPrivateStaticFieldSetFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { Ognl.setValue("_privateStaticProperty", context, this, "changevalue"); @@ -241,8 +206,7 @@ public void testPrivateStaticFieldSetFail() throws OgnlException } } - public void testPrivateStaticFinalFieldSetFail() throws OgnlException - { + public void testPrivateStaticFinalFieldSetFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { Ognl.setValue("_privateStaticFinalProperty", context, this, "changevalue"); @@ -252,8 +216,7 @@ public void testPrivateStaticFinalFieldSetFail() throws OgnlException } } - public void testPrivateAccessorFail() throws OgnlException - { + public void testPrivateAccessorFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { assertEquals(Ognl.getValue("privateProperty", context, this), getPrivateProperty()); @@ -263,8 +226,7 @@ public void testPrivateAccessorFail() throws OgnlException } } - public void testPrivateFieldFail() throws OgnlException - { + public void testPrivateFieldFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { assertEquals(Ognl.getValue("_privateProperty", context, this), _privateProperty); @@ -274,8 +236,7 @@ public void testPrivateFieldFail() throws OgnlException } } - public void testPrivateFinalAccessorFail() throws OgnlException - { + public void testPrivateFinalAccessorFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { assertEquals(Ognl.getValue("privateFinalProperty", context, this), getPrivateFinalProperty()); @@ -285,8 +246,7 @@ public void testPrivateFinalAccessorFail() throws OgnlException } } - public void testPrivateFinalFieldFail() throws OgnlException - { + public void testPrivateFinalFieldFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { assertEquals(Ognl.getValue("_privateFinalProperty", context, this), _privateFinalProperty); @@ -296,8 +256,7 @@ public void testPrivateFinalFieldFail() throws OgnlException } } - public void testPrivateStaticAccessorFail() throws OgnlException - { + public void testPrivateStaticAccessorFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access // Test following PR#59/PR#60 (MemberAccess support private static field). try { @@ -308,8 +267,7 @@ public void testPrivateStaticAccessorFail() throws OgnlException } } - public void testPrivateStaticFieldNormalAccessFail() throws OgnlException - { + public void testPrivateStaticFieldNormalAccessFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access // Test following PR#59/PR#60 (MemberAccess support private static field). try { @@ -320,20 +278,18 @@ public void testPrivateStaticFieldNormalAccessFail() throws OgnlException } } - public void testPrivateStaticFieldStaticAccessFail() throws OgnlException - { + public void testPrivateStaticFieldStaticAccessFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access // Test following PR#59/PR#60 (MemberAccess support private static field). try { - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_privateStaticProperty"), _privateStaticProperty); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_privateStaticProperty"), _privateStaticProperty); fail("Should not be able to access private static property with private access turned off"); } catch (OgnlException oex) { // Fails as test attempts to access a private accessor with private access turned off } } - public void testPrivateStaticFinalAccessorFail() throws OgnlException - { + public void testPrivateStaticFinalAccessorFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { assertEquals(Ognl.getValue("privateStaticFinalProperty", context, this), getPrivateStaticFinalProperty()); @@ -343,8 +299,7 @@ public void testPrivateStaticFinalAccessorFail() throws OgnlException } } - public void testPrivateStaticFinalFieldNormalAccessFail() throws OgnlException - { + public void testPrivateStaticFinalFieldNormalAccessFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { assertEquals(Ognl.getValue("_privateStaticFinalProperty", context, this), _privateStaticFinalProperty); @@ -354,22 +309,20 @@ public void testPrivateStaticFinalFieldNormalAccessFail() throws OgnlException } } - public void testPrivateStaticFinalFieldStaticAccessFail() throws OgnlException - { + public void testPrivateStaticFinalFieldStaticAccessFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, true), null, null); // Prevent private access try { - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_privateStaticFinalProperty"), _privateStaticFinalProperty); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_privateStaticFinalProperty"), _privateStaticFinalProperty); fail("Should not be able to access private static final property with private access turned off"); } catch (OgnlException oex) { // Fails as test attempts to access a private field with private access turned off } } - /*=================================================================== - Overridden methods - ===================================================================*/ - public void setUp() - { + /*=================================================================== + Overridden methods + ===================================================================*/ + public void setUp() { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(true, false, false), null, null); // Permit private access, prevent protected and package access - } + } } diff --git a/src/test/java/ognl/test/ProjectionSelectionTest.java b/src/test/java/ognl/test/ProjectionSelectionTest.java new file mode 100644 index 00000000..a5ed8e6d --- /dev/null +++ b/src/test/java/ognl/test/ProjectionSelectionTest.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Root; + +import java.math.BigInteger; +import java.util.Arrays; + +public class ProjectionSelectionTest extends OgnlTestCase { + private static Root ROOT = new Root(); + + private static Object[][] TESTS = { + // Projection, selection + {ROOT, "array.{class}", + Arrays.asList(new Class[]{Integer.class, Integer.class, Integer.class, Integer.class})}, + {ROOT, "map.array.{? #this > 2 }", Arrays.asList(new Integer[]{new Integer(3), new Integer(4)})}, + {ROOT, "map.array.{^ #this > 2 }", Arrays.asList(new Integer[]{new Integer(3)})}, + {ROOT, "map.array.{$ #this > 2 }", Arrays.asList(new Integer[]{new Integer(4)})}, + {ROOT, "map.array[*].{?true} instanceof java.util.Collection", Boolean.TRUE}, + {null, "#fact=1, 30H.{? #fact = #fact * (#this+1), false }, #fact", + new BigInteger("265252859812191058636308480000000")}, + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new ProjectionSelectionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2])); + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public ProjectionSelectionTest() { + super(); + } + + public ProjectionSelectionTest(String name) { + super(name); + } + + public ProjectionSelectionTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public ProjectionSelectionTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public ProjectionSelectionTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/PropertyArithmeticAndLogicalOperatorsTest.java b/src/test/java/ognl/test/PropertyArithmeticAndLogicalOperatorsTest.java new file mode 100644 index 00000000..f37e5abc --- /dev/null +++ b/src/test/java/ognl/test/PropertyArithmeticAndLogicalOperatorsTest.java @@ -0,0 +1,82 @@ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Root; +import ognl.test.objects.SimpleNumeric; +import ognl.test.objects.TestModel; + +import java.util.Arrays; + +/** + * + */ +public class PropertyArithmeticAndLogicalOperatorsTest extends OgnlTestCase { + + private static Root ROOT = new Root(); + private static TestModel MODEL = new TestModel(); + private static SimpleNumeric NUMERIC = new SimpleNumeric(); + + private static Object[][] TESTS = { + {ROOT, "objectIndex > 0", Boolean.TRUE}, + {ROOT, "false", Boolean.FALSE}, + {ROOT, "!false || true", Boolean.TRUE}, + {ROOT, "property.bean3.value >= 24", Boolean.TRUE}, + {ROOT, "genericIndex-1", new Integer(1)}, + {ROOT, "((renderNavigation ? 0 : 1) + map.size) * theInt", new Integer(((ROOT.getRenderNavigation() ? 0 : 1) + ROOT.getMap().size()) * ROOT.getTheInt())}, + {ROOT, "{theInt + 1}", Arrays.asList(new Integer(ROOT.getTheInt() + 1))}, + {MODEL, "(unassignedCopyModel.optionCount > 0 && canApproveCopy) || entry.copy.size() > 0", Boolean.TRUE}, + {ROOT, " !(printDelivery || @Boolean@FALSE)", Boolean.FALSE}, + {ROOT, "(getIndexedProperty('nested').size - 1) > genericIndex", Boolean.FALSE}, + {ROOT, "(getIndexedProperty('nested').size + 1) >= genericIndex", Boolean.TRUE}, + {ROOT, "(getIndexedProperty('nested').size + 1) == genericIndex", Boolean.TRUE}, + {ROOT, "(getIndexedProperty('nested').size + 1) < genericIndex", Boolean.FALSE}, + {ROOT, "map.size * genericIndex", new Integer(ROOT.getMap().size() * ((Integer) ROOT.getGenericIndex()).intValue())}, + {ROOT, "property == property", Boolean.TRUE}, + {ROOT, "property.bean3.value % 2 == 0", Boolean.TRUE}, + {ROOT, "genericIndex % 3 == 0", Boolean.FALSE}, + {ROOT, "genericIndex % theInt == property.bean3.value", Boolean.FALSE}, + {ROOT, "theInt / 100.0", ROOT.getTheInt() / 100.0}, + {ROOT, "@java.lang.Long@valueOf('100') == @java.lang.Long@valueOf('100')", Boolean.TRUE}, + {NUMERIC, "budget - timeBilled", new Double(NUMERIC.getBudget() - NUMERIC.getTimeBilled())}, + {NUMERIC, "(budget % tableSize) == 0", Boolean.TRUE} + }; + + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 5) { + result.addTest(new PropertyArithmeticAndLogicalOperatorsTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else + result.addTest(new PropertyArithmeticAndLogicalOperatorsTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); + } + + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public PropertyArithmeticAndLogicalOperatorsTest() { + super(); + } + + public PropertyArithmeticAndLogicalOperatorsTest(String name) { + super(name); + } + + public PropertyArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, + Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public PropertyArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, + Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public PropertyArithmeticAndLogicalOperatorsTest(String name, Object root, + String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/org/ognl/test/PropertyNotFoundTest.java b/src/test/java/ognl/test/PropertyNotFoundTest.java similarity index 54% rename from src/test/java/org/ognl/test/PropertyNotFoundTest.java rename to src/test/java/ognl/test/PropertyNotFoundTest.java index 2ebfa37a..08d02610 100644 --- a/src/test/java/org/ognl/test/PropertyNotFoundTest.java +++ b/src/test/java/ognl/test/PropertyNotFoundTest.java @@ -1,34 +1,22 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestSuite; import ognl.OgnlContext; @@ -36,8 +24,6 @@ import ognl.OgnlRuntime; import ognl.PropertyAccessor; -import java.util.Map; - public class PropertyNotFoundTest extends OgnlTestCase { private static final Blah BLAH = new Blah(); @@ -52,47 +38,39 @@ public static class Blah { String x; String y; - public String getX() - { + public String getX() { return x; } - public void setX(String x) - { + public void setX(String x) { this.x = x; } - public String getY() - { + public String getY() { return y; } - public void setY(String y) - { + public void setY(String y) { this.y = y; } } public static class BlahPropertyAccessor implements PropertyAccessor { - public void setProperty(Map context, Object target, Object name, Object value) throws OgnlException - { + public void setProperty(OgnlContext context, Object target, Object name, Object value) throws OgnlException { } - public Object getProperty(Map context, Object target, Object name) throws OgnlException - { + public Object getProperty(OgnlContext context, Object target, Object name) throws OgnlException { if ("x".equals(name) || "y".equals(name)) { - return OgnlRuntime.getProperty((OgnlContext) context, target, name); + return OgnlRuntime.getProperty(context, target, name); } return null; } - public String getSourceAccessor(OgnlContext context, Object target, Object index) - { + public String getSourceAccessor(OgnlContext context, Object target, Object index) { return index.toString(); } - public String getSourceSetter(OgnlContext context, Object target, Object index) - { + public String getSourceSetter(OgnlContext context, Object target, Object index) { return index.toString(); } } @@ -100,8 +78,7 @@ public String getSourceSetter(OgnlContext context, Object target, Object index) /*=================================================================== Public static methods ===================================================================*/ - public static TestSuite suite() - { + public static TestSuite suite() { TestSuite result = new TestSuite(); for (int i = 0; i < TESTS.length; i++) { @@ -125,33 +102,27 @@ public static TestSuite suite() /*=================================================================== Constructors ===================================================================*/ - public PropertyNotFoundTest() - { + public PropertyNotFoundTest() { super(); } - public PropertyNotFoundTest(String name) - { + public PropertyNotFoundTest(String name) { super(name); } - public PropertyNotFoundTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { + public PropertyNotFoundTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); } - public PropertyNotFoundTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { + public PropertyNotFoundTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { super(name, root, expressionString, expectedResult, setValue); } - public PropertyNotFoundTest(String name, Object root, String expressionString, Object expectedResult) - { + public PropertyNotFoundTest(String name, Object root, String expressionString, Object expectedResult) { super(name, root, expressionString, expectedResult); } - protected void setUp() - { + protected void setUp() { super.setUp(); OgnlRuntime.setPropertyAccessor(Blah.class, new BlahPropertyAccessor()); } diff --git a/src/test/java/org/ognl/test/PropertySetterTest.java b/src/test/java/ognl/test/PropertySetterTest.java similarity index 87% rename from src/test/java/org/ognl/test/PropertySetterTest.java rename to src/test/java/ognl/test/PropertySetterTest.java index d82b7219..1a837be5 100644 --- a/src/test/java/org/ognl/test/PropertySetterTest.java +++ b/src/test/java/ognl/test/PropertySetterTest.java @@ -1,4 +1,4 @@ -package org.ognl.test; +package ognl.test; import junit.framework.TestCase; import ognl.DefaultMemberAccess; @@ -23,7 +23,7 @@ public interface TestInterface { } public class TestObject implements TestInterface { - + private String property; private Integer integerProperty = 1; @@ -48,6 +48,7 @@ public Integer getIntegerProperty() { public Map getMap() { return map; } + public String getKey() { return "key"; } @@ -65,16 +66,16 @@ public String getPropertyKey() { } public void testEnhancedOgnl() throws Exception { - OgnlContext context = (OgnlContext)Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); + OgnlContext context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); Node expression = Ognl.compileExpression(context, this, "interfaceObject.property"); Ognl.setValue(expression, context, this, "hello"); - assertEquals("hello", getObject().getProperty() ); + assertEquals("hello", getObject().getProperty()); // Fails if an interface is defined, but succeeds if not context.clear(); expression = Ognl.compileExpression(context, this.getObject(), "property"); Ognl.setValue(expression, context, this.getObject(), "hello"); - assertEquals("hello", getObject().getProperty() ); + assertEquals("hello", getObject().getProperty()); } } diff --git a/src/test/java/ognl/test/PropertyTest.java b/src/test/java/ognl/test/PropertyTest.java new file mode 100644 index 00000000..e0e321ff --- /dev/null +++ b/src/test/java/ognl/test/PropertyTest.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.BaseBean; +import ognl.test.objects.Bean2; +import ognl.test.objects.FirstBean; +import ognl.test.objects.PropertyHolder; +import ognl.test.objects.Root; + +import java.text.SimpleDateFormat; +import java.util.Arrays; + +public class PropertyTest extends OgnlTestCase { + + public static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm a 'CST'"); + public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy"); + public static final String VALUE = "foo"; + + private static Root ROOT = new Root(); + private static BaseBean BEAN = new FirstBean(); + private static PropertyHolder PROPERTY = new PropertyHolder(); + + private static Object[][] TESTS = { + {ROOT, "testString != null && !false", Boolean.TRUE}, + {ROOT, "!getRenderNavigation() and !getReadonly()", Boolean.TRUE}, + {ROOT, "!bean2.pageBreakAfter", Boolean.TRUE}, + {ROOT, "map", ROOT.getMap()}, + {ROOT, "map.test", ROOT}, + {ROOT, "map[\"test\"]", ROOT}, + {ROOT, "map[\"te\" + \"st\"]", ROOT}, + {ROOT, "map[(\"s\" + \"i\") + \"ze\"]", ROOT.getMap().get(Root.SIZE_STRING)}, + {ROOT, "map[\"size\"]", ROOT.getMap().get(Root.SIZE_STRING)}, + {ROOT, "map[@ognl.test.objects.Root@SIZE_STRING]", ROOT.getMap().get(Root.SIZE_STRING)}, + {ROOT, "stringValue != null && stringValue.length() > 0", Boolean.FALSE}, + {ROOT, "indexedStringValue != null && indexedStringValue.length() > 0", Boolean.TRUE}, + {ROOT.getMap(), "list", ROOT.getList()}, + {ROOT, "map.array[0]", new Integer(ROOT.getArray()[0])}, + {ROOT, "map.list[1]", ROOT.getList().get(1)}, + {ROOT, "map[^]", new Integer(99)}, + {ROOT, "map[$]", null}, + {ROOT.getMap(), "array[$]", new Integer(ROOT.getArray()[ROOT.getArray().length - 1])}, + {ROOT, "[\"map\"]", ROOT.getMap()}, + {ROOT.getArray(), "length", new Integer(ROOT.getArray().length)}, + {ROOT, "getMap().list[|]", ROOT.getList().get(ROOT.getList().size() / 2)}, + {ROOT, "map.(array[2] + size())", new Integer(ROOT.getArray()[2] + ROOT.getMap().size())}, + {ROOT, "map.(#this)", ROOT.getMap()}, + {ROOT, "map.(#this != null ? #this['size'] : null)", ROOT.getMap().get(Root.SIZE_STRING)}, + {ROOT, "map[^].(#this == null ? 'empty' : #this)", new Integer(99)}, + {ROOT, "map[$].(#this == null ? 'empty' : #this)", "empty"}, + {ROOT, "map[$].(#root == null ? 'empty' : #root)", ROOT}, + {ROOT, "((selected != null) && (currLocale.toString() == selected.toString())) ? 'first' : 'second'", "first"}, + {ROOT, "{stringValue, getMap()}", Arrays.asList(new Object[]{ROOT.getStringValue(), ROOT.getMap()})}, + {ROOT, "{'stringValue', map[\"test\"].map[\"size\"]}", Arrays.asList(new Object[]{"stringValue", ROOT.getMap().get("size")})}, + {ROOT, "property.bean3.value + '(this.checked)'", "100(this.checked)"}, + {ROOT, "getIndexedProperty(property.bean3.map[\"bar\"])", ROOT.getArray()}, + {ROOT, "getProperty().getBean3()", ((Bean2) ROOT.getProperty()).getBean3()}, + {ROOT, "intValue", new Integer(0), new Integer(2), new Integer(2)}, + {ROOT, "! booleanValue", Boolean.TRUE}, + {ROOT, "booleanValue", Boolean.FALSE, Boolean.TRUE, Boolean.TRUE}, + {ROOT, "! disabled", new Boolean(false)}, + {ROOT, "disabled || readonly", Boolean.TRUE}, + {ROOT, "property.bean3.value != null", Boolean.TRUE}, + {ROOT, "\"background-color:blue; width:\" + (currentLocaleVerbosity / 2) + \"px\"", "background-color:blue; width:43px"}, + {ROOT, "renderNavigation ? '' : 'noborder'", "noborder"}, + {ROOT, "format('key', array)", ROOT.format("key", ROOT.getArray())}, + {ROOT, "format('key', intValue)", ROOT.format("key", /*ROOT.getIntValue()*/ 2)}, // getIntValue() is 0 during startup, but set to 2 during tests! + {ROOT, "format('key', map.size)", ROOT.format("key", ROOT.getMap().size())}, + {ROOT, "'disableButton(this,\"' + map.get('button-testing') + '\");clearElement("testFtpMessage")'", + "disableButton(this,'null');clearElement('testFtpMessage')"}, + {ROOT.getMap(), "!disableWarning", Boolean.TRUE}, + {ROOT.getMap(), "get('value').bean3.value", new Integer(((Bean2) ROOT.getMap().get("value")).getBean3().getValue())}, + {ROOT.getMap(), "\"Tapestry\".toCharArray()[2]", new Character('p')}, + {ROOT.getMap(), "nested.deep.last", Boolean.TRUE}, + {ROOT, "'last ' + getCurrentClass(@ognl.test.PropertyTest@VALUE)", "last foo stop"}, + {ROOT, "@ognl.test.PropertyTest@formatValue(property.millis, true, true)", formatValue((int) ((Bean2) ROOT.getProperty()).getMillis(), true, true)}, + {ROOT, "nullObject || !readonly", Boolean.TRUE}, + {ROOT, "testDate == null ? '-' : @ognl.test.PropertyTest@DATETIME_FORMAT.format(testDate)", DATETIME_FORMAT.format(ROOT.getTestDate())}, + {ROOT, "disabled ? 'disabled' : 'othernot'", "disabled"}, + {BEAN, "two.getMessage(active ? 'ACT' : 'INA')", "[ACT]"}, + {BEAN, "hasChildren('aaa')", Boolean.TRUE}, + {BEAN, "two.hasChildren('aa')", Boolean.FALSE}, + {BEAN, "two.hasChildren('a')", Boolean.FALSE}, + {ROOT, "sorted ? (readonly ? 'currentSortDesc' : 'currentSortAsc') : 'currentSortNone'", "currentSortAsc"}, + {ROOT, "getAsset( (width?'Yes':'No')+'Icon' )", "NoIcon"}, + {ROOT, "flyingMonkey", Boolean.TRUE}, + {ROOT, "expiration == null ? '' : @ognl.test.PropertyTest@DATE_FORMAT.format(expiration)", ""}, + {ROOT, "printDelivery ? 'javascript:toggle(' + bean2.id + ');' : ''", "javascript:toggle(1);"}, + {ROOT, "openTransitionWin", Boolean.FALSE}, + {ROOT, "b.methodOfB(a.methodOfA(b)-1)", new Integer(0)}, + {ROOT, "disabled", Boolean.TRUE}, + {PROPERTY, "value", ""}, + {PROPERTY, "search", "foo"} + }; + + public static String formatValue(int millis, boolean b1, boolean b2) { + return millis + "-formatted"; + } + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + + if (TESTS[i].length == 5) { + + result.addTest(new PropertyTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else + result.addTest(new PropertyTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); + } + + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public PropertyTest() { + super(); + } + + public PropertyTest(String name) { + super(name); + } + + public PropertyTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public PropertyTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public PropertyTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/ProtectedInnerClassTest.java b/src/test/java/ognl/test/ProtectedInnerClassTest.java new file mode 100644 index 00000000..dc6ae478 --- /dev/null +++ b/src/test/java/ognl/test/ProtectedInnerClassTest.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Root; + +public class ProtectedInnerClassTest extends OgnlTestCase { + + private static Root ROOT = new Root(); + + private static Object[][] TESTS = { + // member access of inner class (Arrays.asList() returned protected inner class) + {ROOT, "list.size()", new Integer(ROOT.getList().size())}, + {ROOT, "list[0]", ROOT.getList().get(0)}, + }; + + /* + * =================================================================== Public static methods + * =================================================================== + */ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new ProtectedInnerClassTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], + TESTS[i][2])); + } + return result; + } + + /* + * =================================================================== Constructors + * =================================================================== + */ + public ProtectedInnerClassTest() { + super(); + } + + public ProtectedInnerClassTest(String name) { + super(name); + } + + public ProtectedInnerClassTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public ProtectedInnerClassTest(String name, Object root, String expressionString, Object expectedResult, + Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public ProtectedInnerClassTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/org/ognl/test/ProtectedMemberTest.java b/src/test/java/ognl/test/ProtectedMemberTest.java similarity index 77% rename from src/test/java/org/ognl/test/ProtectedMemberTest.java rename to src/test/java/ognl/test/ProtectedMemberTest.java index 32cf29ae..a06d2c5e 100644 --- a/src/test/java/org/ognl/test/ProtectedMemberTest.java +++ b/src/test/java/ognl/test/ProtectedMemberTest.java @@ -1,34 +1,22 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestCase; import junit.framework.TestSuite; @@ -42,85 +30,72 @@ * This is a test program for protected access in OGNL. * Shows the failures and a summary. */ -public class ProtectedMemberTest extends TestCase -{ - protected String _protectedProperty = "protected value"; - protected final String _protectedFinalProperty = "protected final value"; - protected static String _protectedStaticProperty = "protected static value"; - protected static final String _protectedStaticFinalProperty = "protected static final value"; - protected OgnlContext context; +public class ProtectedMemberTest extends TestCase { + protected String _protectedProperty = "protected value"; + protected final String _protectedFinalProperty = "protected final value"; + protected static String _protectedStaticProperty = "protected static value"; + protected static final String _protectedStaticFinalProperty = "protected static final value"; + protected OgnlContext context; /*=================================================================== Public static methods ===================================================================*/ - public static TestSuite suite() - { + public static TestSuite suite() { return new TestSuite(ProtectedMemberTest.class); } /*=================================================================== Constructors ===================================================================*/ - public ProtectedMemberTest(String name) - { + public ProtectedMemberTest(String name) { super(name); } /*=================================================================== Protected methods ===================================================================*/ - protected String getProtectedProperty() - { + protected String getProtectedProperty() { return _protectedProperty; } - protected String getProtectedFinalProperty() - { + protected String getProtectedFinalProperty() { return _protectedFinalProperty; } - protected static String getProtectedStaticProperty() - { + protected static String getProtectedStaticProperty() { return _protectedStaticProperty; } - protected static String getProtectedStaticFinalProperty() - { + protected static String getProtectedStaticFinalProperty() { return _protectedStaticFinalProperty; } /*=================================================================== Public methods ===================================================================*/ - public void testProtectedAccessor() throws OgnlException - { + public void testProtectedAccessor() throws OgnlException { assertEquals(Ognl.getValue("protectedProperty", context, this), getProtectedProperty()); } - public void testProtectedField() throws OgnlException - { + public void testProtectedField() throws OgnlException { assertEquals(Ognl.getValue("_protectedProperty", context, this), _protectedProperty); } - public void testProtectedFinalAccessor() throws OgnlException - { + public void testProtectedFinalAccessor() throws OgnlException { assertEquals(Ognl.getValue("protectedFinalProperty", context, this), getProtectedFinalProperty()); } - public void testProtectedFinalField() throws OgnlException - { + public void testProtectedFinalField() throws OgnlException { assertEquals(Ognl.getValue("_protectedFinalProperty", context, this), _protectedFinalProperty); } - public void testProtectedStaticAccessor() throws OgnlException - { + public void testProtectedStaticAccessor() throws OgnlException { assertEquals(Ognl.getValue("protectedStaticProperty", context, this), getProtectedStaticProperty()); // Succeeds due to calling the static getter to retrieve it. } - public void testProtectedStaticFieldNormalAccess() throws OgnlException - { + public void testProtectedStaticFieldNormalAccess() throws OgnlException { try { assertEquals(Ognl.getValue("_protectedStaticProperty", context, this), _protectedStaticProperty); fail("Should not be able to access private static _protectedStaticProperty through getValue()"); @@ -129,20 +104,17 @@ public void testProtectedStaticFieldNormalAccess() throws OgnlException } } - public void testProtectedStaticFieldStaticAccess() throws OgnlException - { - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_protectedStaticProperty"), _protectedStaticProperty); + public void testProtectedStaticFieldStaticAccess() throws OgnlException { + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_protectedStaticProperty"), _protectedStaticProperty); // Only succeeds due to directly using the runtime to access the field as a static field. } - public void testProtectedStaticFinalAccessor() throws OgnlException - { + public void testProtectedStaticFinalAccessor() throws OgnlException { assertEquals(Ognl.getValue("protectedStaticFinalProperty", context, this), getProtectedStaticFinalProperty()); // Succeeds due to calling the static getter to retrieve it. } - public void testProtectedStaticFinalFieldNormalAccess() throws OgnlException - { + public void testProtectedStaticFinalFieldNormalAccess() throws OgnlException { try { assertEquals(Ognl.getValue("_protectedStaticFinalProperty", context, this), _protectedStaticFinalProperty); fail("Should not be able to access private static _protectedStaticFinalProperty through getValue()"); @@ -151,14 +123,12 @@ public void testProtectedStaticFinalFieldNormalAccess() throws OgnlException } } - public void testProtectedStaticFinalFieldStaticAccess() throws OgnlException - { - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_protectedStaticFinalProperty"), _protectedStaticFinalProperty); + public void testProtectedStaticFinalFieldStaticAccess() throws OgnlException { + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_protectedStaticFinalProperty"), _protectedStaticFinalProperty); // Only succeeds due to directly using the runtime to access the field as a static field. } - public void testProtectedFieldSet() throws OgnlException - { + public void testProtectedFieldSet() throws OgnlException { final String originalValue = _protectedProperty; assertEquals(Ognl.getValue("_protectedProperty", context, this), originalValue); Ognl.setValue("_protectedProperty", context, this, "changevalue"); @@ -167,8 +137,7 @@ public void testProtectedFieldSet() throws OgnlException assertEquals(Ognl.getValue("_protectedProperty", context, this), originalValue); } - public void testProtectedFinalFieldSet() throws OgnlException - { + public void testProtectedFinalFieldSet() throws OgnlException { final String originalValue = _protectedFinalProperty; assertEquals(Ognl.getValue("_protectedFinalProperty", context, this), originalValue); try { @@ -180,34 +149,31 @@ public void testProtectedFinalFieldSet() throws OgnlException assertEquals(Ognl.getValue("_protectedFinalProperty", context, this), originalValue); } - public void testProtectedStaticFieldSet() throws OgnlException - { + public void testProtectedStaticFieldSet() throws OgnlException { final String originalValue = _protectedStaticProperty; - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_protectedStaticProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_protectedStaticProperty"), originalValue); try { Ognl.setValue("_protectedStaticProperty", context, this, "changevalue"); fail("Should not be able to modify static property"); } catch (OgnlException oex) { // Fails as test attempts to modify a static property } - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_protectedStaticProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_protectedStaticProperty"), originalValue); } - public void testProtectedStaticFinalFieldSet() throws OgnlException - { + public void testProtectedStaticFinalFieldSet() throws OgnlException { final String originalValue = _protectedStaticFinalProperty; - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_protectedStaticFinalProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_protectedStaticFinalProperty"), originalValue); try { Ognl.setValue("_protectedStaticFinalProperty", context, this, "changevalue"); fail("Should not be able to modify static property"); } catch (OgnlException oex) { // Fails as test attempts to modify a static property } - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_protectedStaticFinalProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_protectedStaticFinalProperty"), originalValue); } - public void testProtectedFieldSetFail() throws OgnlException - { + public void testProtectedFieldSetFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { Ognl.setValue("_protectedProperty", context, this, "changevalue"); @@ -217,8 +183,7 @@ public void testProtectedFieldSetFail() throws OgnlException } } - public void testProtectedFinalFieldSetFail() throws OgnlException - { + public void testProtectedFinalFieldSetFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { Ognl.setValue("_protectedFinalProperty", context, this, "changevalue"); @@ -228,8 +193,7 @@ public void testProtectedFinalFieldSetFail() throws OgnlException } } - public void testProtectedStaticFieldSetFail() throws OgnlException - { + public void testProtectedStaticFieldSetFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { Ognl.setValue("_protectedStaticProperty", context, this, "changevalue"); @@ -239,8 +203,7 @@ public void testProtectedStaticFieldSetFail() throws OgnlException } } - public void testProtectedStaticFinalFieldSetFail() throws OgnlException - { + public void testProtectedStaticFinalFieldSetFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { Ognl.setValue("_protectedStaticFinalProperty", context, this, "changevalue"); @@ -250,8 +213,7 @@ public void testProtectedStaticFinalFieldSetFail() throws OgnlException } } - public void testProtectedAccessorFail() throws OgnlException - { + public void testProtectedAccessorFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { assertEquals(Ognl.getValue("protectedProperty", context, this), getProtectedProperty()); @@ -261,8 +223,7 @@ public void testProtectedAccessorFail() throws OgnlException } } - public void testProtectedFieldFail() throws OgnlException - { + public void testProtectedFieldFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { assertEquals(Ognl.getValue("_protectedProperty", context, this), _protectedProperty); @@ -272,8 +233,7 @@ public void testProtectedFieldFail() throws OgnlException } } - public void testProtectedFinalAccessorFail() throws OgnlException - { + public void testProtectedFinalAccessorFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { assertEquals(Ognl.getValue("protectedFinalProperty", context, this), getProtectedFinalProperty()); @@ -283,8 +243,7 @@ public void testProtectedFinalAccessorFail() throws OgnlException } } - public void testProtectedFinalFieldFail() throws OgnlException - { + public void testProtectedFinalFieldFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { assertEquals(Ognl.getValue("_protectedFinalProperty", context, this), _protectedFinalProperty); @@ -294,8 +253,7 @@ public void testProtectedFinalFieldFail() throws OgnlException } } - public void testProtectedStaticAccessorFail() throws OgnlException - { + public void testProtectedStaticAccessorFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { assertEquals(Ognl.getValue("protectedStaticProperty", context, this), getProtectedStaticProperty()); @@ -305,8 +263,7 @@ public void testProtectedStaticAccessorFail() throws OgnlException } } - public void testProtectedStaticFieldNormalAccessFail() throws OgnlException - { + public void testProtectedStaticFieldNormalAccessFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { assertEquals(Ognl.getValue("_protectedStaticProperty", context, this), _protectedStaticProperty); @@ -316,19 +273,17 @@ public void testProtectedStaticFieldNormalAccessFail() throws OgnlException } } - public void testProtectedStaticFieldStaticAccessFail() throws OgnlException - { + public void testProtectedStaticFieldStaticAccessFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_protectedStaticProperty"), _protectedStaticProperty); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_protectedStaticProperty"), _protectedStaticProperty); fail("Should not be able to access protected static property with protected access turned off"); } catch (OgnlException oex) { // Fails as test attempts to access a protected field with protected access turned off } } - public void testProtectedStaticFinalAccessorFail() throws OgnlException - { + public void testProtectedStaticFinalAccessorFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { assertEquals(Ognl.getValue("protectedStaticFinalProperty", context, this), getProtectedStaticFinalProperty()); @@ -338,8 +293,7 @@ public void testProtectedStaticFinalAccessorFail() throws OgnlException } } - public void testProtectedStaticFinalFieldNormalAccessFail() throws OgnlException - { + public void testProtectedStaticFinalFieldNormalAccessFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { assertEquals(Ognl.getValue("_protectedStaticFinalProperty", context, this), _protectedStaticFinalProperty); @@ -349,11 +303,10 @@ public void testProtectedStaticFinalFieldNormalAccessFail() throws OgnlException } } - public void testProtectedStaticFinalFieldStaticAccessFail() throws OgnlException - { + public void testProtectedStaticFinalFieldStaticAccessFail() throws OgnlException { context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent protected access try { - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_protectedStaticFinalProperty"), _protectedStaticFinalProperty); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_protectedStaticFinalProperty"), _protectedStaticFinalProperty); fail("Should not be able to access protected static final property with protected access turned off"); } catch (OgnlException oex) { // Fails as test attempts to access a protected field with protected access turned off @@ -363,8 +316,7 @@ public void testProtectedStaticFinalFieldStaticAccessFail() throws OgnlException /*=================================================================== Overridden methods ===================================================================*/ - public void setUp() - { - context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, false), null, null); // Permit protected access, prevent private and package access + public void setUp() { + context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, true, false), null, null); // Permit protected access, prevent private and package access } } diff --git a/src/test/java/org/ognl/test/PublicMemberTest.java b/src/test/java/ognl/test/PublicMemberTest.java similarity index 57% rename from src/test/java/org/ognl/test/PublicMemberTest.java rename to src/test/java/ognl/test/PublicMemberTest.java index 93863c6c..fd7369cb 100644 --- a/src/test/java/org/ognl/test/PublicMemberTest.java +++ b/src/test/java/ognl/test/PublicMemberTest.java @@ -1,34 +1,22 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; import junit.framework.TestCase; import junit.framework.TestSuite; @@ -42,81 +30,68 @@ * This is a test program for public access in OGNL. * Shows the failures and a summary. */ -public class PublicMemberTest extends TestCase -{ - public String _publicProperty = "public value"; - public final String _publicFinalProperty = "public final value"; - public static String _publicStaticProperty = "public static value"; - public static final String _publicStaticFinalProperty = "public static final value"; - protected OgnlContext context; +public class PublicMemberTest extends TestCase { + public String _publicProperty = "public value"; + public final String _publicFinalProperty = "public final value"; + public static String _publicStaticProperty = "public static value"; + public static final String _publicStaticFinalProperty = "public static final value"; + protected OgnlContext context; /*=================================================================== Public static methods ===================================================================*/ - public static TestSuite suite() - { + public static TestSuite suite() { return new TestSuite(PublicMemberTest.class); } /*=================================================================== Constructors ===================================================================*/ - public PublicMemberTest(String name) - { + public PublicMemberTest(String name) { super(name); } /*=================================================================== Public methods ===================================================================*/ - public String getPublicProperty() - { + public String getPublicProperty() { return _publicProperty; } - public String getPublicFinalProperty() - { + public String getPublicFinalProperty() { return _publicFinalProperty; } - public static String getPublicStaticProperty() - { + public static String getPublicStaticProperty() { return _publicStaticProperty; } - public static String getPublicStaticFinalProperty() - { + public static String getPublicStaticFinalProperty() { return _publicStaticFinalProperty; } - public void testPublicAccessor() throws OgnlException - { + public void testPublicAccessor() throws OgnlException { assertEquals(Ognl.getValue("publicProperty", context, this), getPublicProperty()); } - public void testPublicField() throws OgnlException - { + public void testPublicField() throws OgnlException { assertEquals(Ognl.getValue("_publicProperty", context, this), _publicProperty); } - public void testPublicFinalAccessor() throws OgnlException - { + public void testPublicFinalAccessor() throws OgnlException { assertEquals(Ognl.getValue("publicFinalProperty", context, this), getPublicFinalProperty()); } - public void testPublicFinalField() throws OgnlException - { + public void testPublicFinalField() throws OgnlException { assertEquals(Ognl.getValue("_publicFinalProperty", context, this), _publicFinalProperty); } - public void testPublicStaticAccessor() throws OgnlException - { + public void testPublicStaticAccessor() throws OgnlException { assertEquals(Ognl.getValue("publicStaticProperty", context, this), getPublicStaticProperty()); } - public void testPublicStaticFieldNormalAccessFail() throws OgnlException - { + public void testPublicStaticFieldNormalAccessFail() throws OgnlException { try { assertEquals(Ognl.getValue("_publicStaticProperty", context, this), _publicStaticProperty); fail("Should not be able to access public static _publicStaticProperty through getValue()"); @@ -125,18 +100,15 @@ public void testPublicStaticFieldNormalAccessFail() throws OgnlException } } - public void testPublicStaticFieldStaticAccess() throws OgnlException - { - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_publicStaticProperty"), _publicStaticProperty); + public void testPublicStaticFieldStaticAccess() throws OgnlException { + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_publicStaticProperty"), _publicStaticProperty); } - public void testPublicStaticFinalAccessor() throws OgnlException - { + public void testPublicStaticFinalAccessor() throws OgnlException { assertEquals(Ognl.getValue("publicStaticFinalProperty", context, this), getPublicStaticFinalProperty()); } - public void testPublicStaticFinalFieldNormalAccessFail() throws OgnlException - { + public void testPublicStaticFinalFieldNormalAccessFail() throws OgnlException { try { assertEquals(Ognl.getValue("_publicStaticFinalProperty", context, this), _publicStaticFinalProperty); fail("Should not be able to access public static _publicStaticFinalProperty through getValue()"); @@ -145,13 +117,11 @@ public void testPublicStaticFinalFieldNormalAccessFail() throws OgnlException } } - public void testPublicStaticFinalFieldStaticAccess() throws OgnlException - { - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_publicStaticFinalProperty"), _publicStaticFinalProperty); + public void testPublicStaticFinalFieldStaticAccess() throws OgnlException { + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_publicStaticFinalProperty"), _publicStaticFinalProperty); } - public void testPublicFieldSet() throws OgnlException - { + public void testPublicFieldSet() throws OgnlException { final String originalValue = _publicProperty; assertEquals(Ognl.getValue("_publicProperty", context, this), originalValue); Ognl.setValue("_publicProperty", context, this, "changevalue"); @@ -160,8 +130,7 @@ public void testPublicFieldSet() throws OgnlException assertEquals(Ognl.getValue("_publicProperty", context, this), originalValue); } - public void testPublicFinalFieldSet() throws OgnlException - { + public void testPublicFinalFieldSet() throws OgnlException { final String originalValue = _publicFinalProperty; assertEquals(Ognl.getValue("_publicFinalProperty", context, this), originalValue); try { @@ -173,37 +142,34 @@ public void testPublicFinalFieldSet() throws OgnlException assertEquals(Ognl.getValue("_publicFinalProperty", context, this), originalValue); } - public void testPublicStaticFieldSet() throws OgnlException - { + public void testPublicStaticFieldSet() throws OgnlException { final String originalValue = _publicStaticProperty; - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_publicStaticProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_publicStaticProperty"), originalValue); try { Ognl.setValue("_publicStaticProperty", context, this, "changevalue"); fail("Should not be able to modify static property"); } catch (OgnlException oex) { // Fails as test attempts to modify a static property } - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_publicStaticProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_publicStaticProperty"), originalValue); } - public void testPublicStaticFinalFieldSet() throws OgnlException - { + public void testPublicStaticFinalFieldSet() throws OgnlException { final String originalValue = _publicStaticFinalProperty; - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_publicStaticFinalProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_publicStaticFinalProperty"), originalValue); try { Ognl.setValue("_publicStaticFinalProperty", context, this, "changevalue"); fail("Should not be able to modify static property"); } catch (OgnlException oex) { // Fails as test attempts to modify a static property } - assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName() , "_publicStaticFinalProperty"), originalValue); + assertEquals(OgnlRuntime.getStaticField(context, this.getClass().getName(), "_publicStaticFinalProperty"), originalValue); } /*=================================================================== Overridden methods ===================================================================*/ - public void setUp() - { - context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent non-public access + public void setUp() { + context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false, false, false), null, null); // Prevent non-public access } } diff --git a/src/test/java/ognl/test/QuotingTest.java b/src/test/java/ognl/test/QuotingTest.java new file mode 100644 index 00000000..b789c9fc --- /dev/null +++ b/src/test/java/ognl/test/QuotingTest.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; + +public class QuotingTest extends OgnlTestCase { + private static Object[][] TESTS = { + // Quoting + {null, "`c`", new Character('c')}, + {null, "'s'", new Character('s')}, + {null, "'string'", "string"}, + {null, "\"string\"", "string"}, + {null, "'' + 'bar'", "bar"}, + {null, "'yyyy年MM月dd日'", "yyyy年MM月dd日"} + }; + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new QuotingTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new QuotingTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new QuotingTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public QuotingTest() { + super(); + } + + public QuotingTest(String name) { + super(name); + } + + public QuotingTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public QuotingTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public QuotingTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/RaceConditionTest.java b/src/test/java/ognl/test/RaceConditionTest.java similarity index 97% rename from src/test/java/ognl/RaceConditionTest.java rename to src/test/java/ognl/test/RaceConditionTest.java index 6dadbea6..dce3066e 100644 --- a/src/test/java/ognl/RaceConditionTest.java +++ b/src/test/java/ognl/test/RaceConditionTest.java @@ -1,5 +1,6 @@ -package ognl; +package ognl.test; +import ognl.OgnlRuntime; import org.junit.Assert; import org.junit.Test; @@ -64,4 +65,4 @@ public Boolean call() throws Exception { } } -} \ No newline at end of file +} diff --git a/src/test/java/ognl/test/SetterTest.java b/src/test/java/ognl/test/SetterTest.java new file mode 100644 index 00000000..863f186e --- /dev/null +++ b/src/test/java/ognl/test/SetterTest.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.InappropriateExpressionException; +import ognl.NoSuchPropertyException; +import ognl.test.objects.Root; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +public class SetterTest extends OgnlTestCase { + private static Root ROOT = new Root(); + + static Set _list = new HashSet(); + + static { + _list.add("Test1"); + } + + private static Object[][] TESTS = { + // Setting values + {ROOT.getMap(), "newValue", null, new Integer(101)}, + {ROOT, "settableList[0]", "foo", "quux"}, // absolute indexes + {ROOT, "settableList[0]", "quux"}, + {ROOT, "settableList[2]", "baz", "quux"}, + {ROOT, "settableList[2]", "quux"}, + {ROOT, "settableList[$]", "quux", "oompa"}, // special indexes + {ROOT, "settableList[$]", "oompa"}, + {ROOT, "settableList[^]", "quux", "oompa"}, + {ROOT, "settableList[^]", "oompa"}, + {ROOT, "settableList[|]", "bar", "oompa"}, + {ROOT, "settableList[|]", "oompa"}, + {ROOT, "map.newValue", new Integer(101), new Integer(555)}, + {ROOT, "map", ROOT.getMap(), new HashMap(), NoSuchPropertyException.class}, + {ROOT.getMap(), "newValue2 || put(\"newValue2\",987), newValue2", new Integer(987), new Integer(1002)}, + {ROOT, "map.(someMissingKey || newValue)", new Integer(555), new Integer(666)}, + {ROOT.getMap(), "newValue || someMissingKey", new Integer(666), new Integer(666)}, // no setting happens! + {ROOT, "map.(newValue && aKey)", null, new Integer(54321)}, + {ROOT, "map.(someMissingKey && newValue)", null, null}, // again, no setting + {null, "0", new Integer(0), null, InappropriateExpressionException.class}, // illegal for setting, no property + {ROOT, "map[0]=\"map.newValue\", map[0](#this)", new Integer(666), new Integer(888)}, + {ROOT, "selectedList", null, _list, IllegalArgumentException.class}, + {ROOT, "openTransitionWin", Boolean.FALSE, Boolean.TRUE} + }; + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new SetterTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new SetterTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new SetterTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public SetterTest() { + super(); + } + + public SetterTest(String name) { + super(name); + } + + public SetterTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public SetterTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public SetterTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/SetterWithConversionTest.java b/src/test/java/ognl/test/SetterWithConversionTest.java new file mode 100644 index 00000000..a6ba3708 --- /dev/null +++ b/src/test/java/ognl/test/SetterWithConversionTest.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Root; + +public class SetterWithConversionTest extends OgnlTestCase { + private static Root ROOT = new Root(); + + private static Object[][] TESTS = { + // Property set with conversion + {ROOT, "intValue", new Integer(0), new Double(6.5), new Integer(6)}, + {ROOT, "intValue", new Integer(6), new Double(1025.87645), new Integer(1025)}, + {ROOT, "intValue", new Integer(1025), "654", new Integer(654)}, + {ROOT, "stringValue", null, new Integer(25), "25"}, + {ROOT, "stringValue", "25", new Float(100.25), "100.25"}, + {ROOT, "anotherStringValue", "foo", new Integer(0), "0"}, + {ROOT, "anotherStringValue", "0", new Double(0.5), "0.5"}, + {ROOT, "anotherIntValue", new Integer(123), "5", new Integer(5)}, + {ROOT, "anotherIntValue", new Integer(5), new Double(100.25), new Integer(100)}, + // { ROOT, "anotherIntValue", new Integer(100), new String[] { "55" }, new Integer(55)}, + // { ROOT, "yetAnotherIntValue", new Integer(46), new String[] { "55" }, new Integer(55)}, + + }; + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + if (TESTS[i].length == 3) { + result.addTest(new SetterWithConversionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); + } else { + if (TESTS[i].length == 4) { + result.addTest(new SetterWithConversionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); + } else { + if (TESTS[i].length == 5) { + result.addTest(new SetterWithConversionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); + } else { + throw new RuntimeException("don't understand TEST format"); + } + } + } + } + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public SetterWithConversionTest() { + super(); + } + + public SetterWithConversionTest(String name) { + super(name); + } + + public SetterWithConversionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public SetterWithConversionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public SetterWithConversionTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/ShortCircuitingExpressionTest.java b/src/test/java/ognl/test/ShortCircuitingExpressionTest.java new file mode 100644 index 00000000..31fa6108 --- /dev/null +++ b/src/test/java/ognl/test/ShortCircuitingExpressionTest.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.NoSuchPropertyException; +import ognl.OgnlException; + +public class ShortCircuitingExpressionTest extends OgnlTestCase { + private static Object[][] TESTS = { + {"#root ? someProperty : 99", new Integer(99)}, + {"#root ? 99 : someProperty", OgnlException.class}, + {"(#x=99)? #x.someProperty : #x", NoSuchPropertyException.class}, + {"#xyzzy.doubleValue()", NullPointerException.class}, + {"#xyzzy && #xyzzy.doubleValue()", null}, + {"(#x=99) && #x.doubleValue()", new Double(99)}, + {"#xyzzy || 101", new Integer(101)}, + {"99 || 101", new Integer(99)}, + }; + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new ShortCircuitingExpressionTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, (String) TESTS[i][0], TESTS[i][1])); + } + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public ShortCircuitingExpressionTest() { + super(); + } + + public ShortCircuitingExpressionTest(String name) { + super(name); + } + + public ShortCircuitingExpressionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public ShortCircuitingExpressionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public ShortCircuitingExpressionTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/test/SimpleNavigationChainTreeTest.java b/src/test/java/ognl/test/SimpleNavigationChainTreeTest.java new file mode 100644 index 00000000..c77ad5a5 --- /dev/null +++ b/src/test/java/ognl/test/SimpleNavigationChainTreeTest.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.Ognl; + +public class SimpleNavigationChainTreeTest extends OgnlTestCase { + + private static Object[][] TESTS = { + {"name", Boolean.TRUE}, + {"name[i]", Boolean.FALSE}, + {"name + foo", Boolean.FALSE}, + {"name.foo", Boolean.TRUE} + }; + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new SimpleNavigationChainTreeTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, (String) TESTS[i][0], TESTS[i][1])); + } + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public SimpleNavigationChainTreeTest() { + super(); + } + + public SimpleNavigationChainTreeTest(String name) { + super(name); + } + + public SimpleNavigationChainTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public SimpleNavigationChainTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public SimpleNavigationChainTreeTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } + + /*=================================================================== + Overridden methods + ===================================================================*/ + protected void runTest() throws Exception { + assertTrue(Ognl.isSimpleNavigationChain(getExpression(), _context) == ((Boolean) getExpectedResult()).booleanValue()); + } +} diff --git a/src/test/java/ognl/test/SimplePropertyTreeTest.java b/src/test/java/ognl/test/SimplePropertyTreeTest.java new file mode 100644 index 00000000..036a4569 --- /dev/null +++ b/src/test/java/ognl/test/SimplePropertyTreeTest.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.Ognl; + +public class SimplePropertyTreeTest extends OgnlTestCase { + private static Object[][] TESTS = { + {"name", Boolean.TRUE}, + {"foo", Boolean.TRUE}, + {"name[i]", Boolean.FALSE}, + {"name + foo", Boolean.FALSE}, + {"name.foo", Boolean.FALSE}, + {"name.foo.bar", Boolean.FALSE}, + {"name.{? foo }", Boolean.FALSE}, + {"name.( foo )", Boolean.FALSE} + }; + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new SimplePropertyTreeTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, (String) TESTS[i][0], TESTS[i][1])); + } + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public SimplePropertyTreeTest() { + super(); + } + + public SimplePropertyTreeTest(String name) { + super(name); + } + + public SimplePropertyTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public SimplePropertyTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public SimplePropertyTreeTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } + + /*=================================================================== + Overridden methods + ===================================================================*/ + protected void runTest() throws Exception { + assertTrue(Ognl.isSimpleProperty(getExpression(), _context) == ((Boolean) getExpectedResult()).booleanValue()); + } +} diff --git a/src/test/java/ognl/test/StaticsAndConstructorsTest.java b/src/test/java/ognl/test/StaticsAndConstructorsTest.java new file mode 100644 index 00000000..8c62869b --- /dev/null +++ b/src/test/java/ognl/test/StaticsAndConstructorsTest.java @@ -0,0 +1,160 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test; + +import junit.framework.TestSuite; +import ognl.test.objects.Root; +import ognl.test.objects.Simple; + +public class StaticsAndConstructorsTest extends OgnlTestCase { + private static Root ROOT = new Root(); + + private static Object[][] TESTS = { + {"@java.lang.Class@forName(\"java.lang.Object\")", Object.class}, + {"@java.lang.Integer@MAX_VALUE", new Integer(Integer.MAX_VALUE)}, + {"@@max(3,4)", new Integer(4)}, + {"new java.lang.StringBuffer().append(55).toString()", "55"}, + {"class", ROOT.getClass()}, + {"@ognl.test.objects.Root@class", ROOT.getClass()}, + {"class.getName()", ROOT.getClass().getName()}, + {"@ognl.test.objects.Root@class.getName()", ROOT.getClass().getName()}, + {"@ognl.test.objects.Root@class.name", ROOT.getClass().getName()}, + {"class.getSuperclass()", ROOT.getClass().getSuperclass()}, + {"class.superclass", ROOT.getClass().getSuperclass()}, + {"class.name", ROOT.getClass().getName()}, + {"getStaticInt()", new Integer(Root.getStaticInt())}, + {"@ognl.test.objects.Root@getStaticInt()", new Integer(Root.getStaticInt())}, + {"new ognl.test.objects.Simple(property).getStringValue()", new Simple().getStringValue()}, + {"new ognl.test.objects.Simple(map['test'].property).getStringValue()", new Simple().getStringValue()}, + {"map.test.getCurrentClass(@ognl.test.StaticsAndConstructorsTest@KEY.toString())", "size stop"}, + {"new ognl.test.StaticsAndConstructorsTest$IntWrapper(index)", new IntWrapper(ROOT.getIndex())}, + {"new ognl.test.StaticsAndConstructorsTest$IntObjectWrapper(index)", new IntObjectWrapper(ROOT.getIndex())}, + {"new ognl.test.StaticsAndConstructorsTest$A(#root)", new A(ROOT)}, + {"@ognl.test.StaticsAndConstructorsTest$Animals@values().length != 2", Boolean.TRUE}, + {"isOk(@ognl.test.objects.SimpleEnum@ONE, null)", Boolean.TRUE}, + }; + + public static final String KEY = "size"; + + public static class IntWrapper { + public IntWrapper(int value) { + this.value = value; + } + + private final int value; + + public String toString() { + return Integer.toString(value); + } + + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + IntWrapper that = (IntWrapper) o; + + return value == that.value; + } + } + + public static class IntObjectWrapper { + + public IntObjectWrapper(Integer value) { + this.value = value; + } + + private final Integer value; + + public String toString() { + return value.toString(); + } + + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + IntObjectWrapper that = (IntObjectWrapper) o; + + return value.equals(that.value); + } + } + + public static class A { + String key = "A"; + + public A(Root root) { + + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + A a = (A) o; + + if (key != null ? !key.equals(a.key) : a.key != null) return false; + + return true; + } + } + + public enum Animals { + + Dog, Cat, Wallabee, Bear + } + + /*=================================================================== + Public static methods + ===================================================================*/ + public static TestSuite suite() { + TestSuite result = new TestSuite(); + + for (int i = 0; i < TESTS.length; i++) { + result.addTest(new StaticsAndConstructorsTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", ROOT, (String) TESTS[i][0], TESTS[i][1])); + } + return result; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public StaticsAndConstructorsTest() { + super(); + } + + public StaticsAndConstructorsTest(String name) { + super(name); + } + + public StaticsAndConstructorsTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) { + super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); + } + + public StaticsAndConstructorsTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) { + super(name, root, expressionString, expectedResult, setValue); + } + + public StaticsAndConstructorsTest(String name, Object root, String expressionString, Object expectedResult) { + super(name, root, expressionString, expectedResult); + } +} diff --git a/src/test/java/ognl/TestOgnlException.java b/src/test/java/ognl/test/TestOgnlException.java similarity index 80% rename from src/test/java/ognl/TestOgnlException.java rename to src/test/java/ognl/test/TestOgnlException.java index 83ec03d8..3a7fea56 100644 --- a/src/test/java/ognl/TestOgnlException.java +++ b/src/test/java/ognl/test/TestOgnlException.java @@ -1,14 +1,14 @@ -package ognl; +package ognl.test; import junit.framework.TestCase; +import ognl.OgnlException; /** * Tests {@link OgnlException}. */ public class TestOgnlException extends TestCase { - public void test_Throwable_Reason() - { + public void test_Throwable_Reason() { try { throwException(); } catch (OgnlException e) { @@ -17,8 +17,7 @@ public void test_Throwable_Reason() } void throwException() - throws OgnlException - { + throws OgnlException { try { Integer.parseInt("45ac"); } catch (NumberFormatException et) { diff --git a/src/test/java/org/ognl/test/VarArgsMethodTest.java b/src/test/java/ognl/test/VarArgsMethodTest.java similarity index 80% rename from src/test/java/org/ognl/test/VarArgsMethodTest.java rename to src/test/java/ognl/test/VarArgsMethodTest.java index c3605beb..cb6950c7 100644 --- a/src/test/java/org/ognl/test/VarArgsMethodTest.java +++ b/src/test/java/ognl/test/VarArgsMethodTest.java @@ -13,56 +13,57 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.ognl.test; +package ognl.test; import junit.framework.TestCase; import ognl.Ognl; +import ognl.OgnlContext; import ognl.OgnlException; -import org.ognl.test.objects.Simple; - -import java.util.HashMap; +import ognl.test.objects.Simple; public class VarArgsMethodTest extends TestCase { - private static Simple ROOT = new Simple(); + private static final Simple ROOT = new Simple(); + + private final OgnlContext context = Ognl.createDefaultContext(ROOT); public void testNullVarArgs() throws OgnlException { - Object value = Ognl.getValue("isNullVarArgs()", new HashMap(), ROOT); + Object value = Ognl.getValue("isNullVarArgs()", context, ROOT); assertTrue(value instanceof String); assertEquals("null", value); } public void testVarArgsWithSingleArg() throws Exception { - Object value = Ognl.getValue("isStringVarArgs(new String())", new HashMap(), ROOT); + Object value = Ognl.getValue("isStringVarArgs(new String())", context, ROOT); assertTrue(value instanceof String); assertEquals("args", value); } public void testVarArgsWithMultipleArgs() throws Exception { - Object value = Ognl.getValue("isStringVarArgs(new String(), new String())", new HashMap(), ROOT); + Object value = Ognl.getValue("isStringVarArgs(new String(), new String())", context, ROOT); assertTrue(value instanceof String); assertEquals("args", value); } public void testNestedNullVarArgs() throws OgnlException { - Object value = Ognl.getValue("get().request()", new HashMap(), ROOT); + Object value = Ognl.getValue("get().request()", context, ROOT); assertTrue(value instanceof String); assertEquals("null", value); } public void testNestedSingleVarArgs() throws OgnlException { - Object value = Ognl.getValue("get().request(new String())", new HashMap(), ROOT); + Object value = Ognl.getValue("get().request(new String())", context, ROOT); assertTrue(value instanceof String); assertEquals("args", value); } public void testNestedMultipleVarArgs() throws OgnlException { - Object value = Ognl.getValue("get().request(new String(), new String())", new HashMap(), ROOT); + Object value = Ognl.getValue("get().request(new String(), new String())", context, ROOT); assertTrue(value instanceof String); assertEquals("args", value); diff --git a/src/test/java/org/ognl/test/accessors/ListPropertyAccessorTest.java b/src/test/java/ognl/test/accessors/ListPropertyAccessorTest.java similarity index 88% rename from src/test/java/org/ognl/test/accessors/ListPropertyAccessorTest.java rename to src/test/java/ognl/test/accessors/ListPropertyAccessorTest.java index 8e4b6dff..2c2bcd9e 100644 --- a/src/test/java/org/ognl/test/accessors/ListPropertyAccessorTest.java +++ b/src/test/java/ognl/test/accessors/ListPropertyAccessorTest.java @@ -1,4 +1,4 @@ -package org.ognl.test.accessors; +package ognl.test.accessors; import junit.framework.TestCase; import ognl.DefaultMemberAccess; @@ -6,9 +6,9 @@ import ognl.Ognl; import ognl.OgnlContext; import ognl.enhance.ExpressionCompiler; -import org.ognl.test.objects.ListSource; -import org.ognl.test.objects.ListSourceImpl; -import org.ognl.test.objects.Root; +import ognl.test.objects.ListSource; +import ognl.test.objects.ListSourceImpl; +import ognl.test.objects.Root; import java.util.List; import java.util.Map; @@ -25,8 +25,7 @@ public void setUp() throws Exception { context = Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); } - public void test_Get_Source_String_Number_Index() - { + public void test_Get_Source_String_Number_Index() { ListPropertyAccessor pa = new ListPropertyAccessor(); Root root = new Root(); @@ -44,8 +43,7 @@ public void test_Get_Source_String_Number_Index() assertEquals(null, context.getPreviousAccessor()); } - public void test_Get_Source_Object_Number_Index() - { + public void test_Get_Source_Object_Number_Index() { ListPropertyAccessor pa = new ListPropertyAccessor(); Root root = new Root(); @@ -63,10 +61,9 @@ public void test_Get_Source_Object_Number_Index() assertEquals(null, context.getPreviousAccessor()); } - public void test_List_To_Object_Property_Accessor_Read() throws Exception - { + public void test_List_To_Object_Property_Accessor_Read() throws Exception { ListPropertyAccessor pa = new ListPropertyAccessor(); - + ListSource list = new ListSourceImpl(); OgnlContext context = (OgnlContext) this.context; @@ -78,5 +75,5 @@ public void test_List_To_Object_Property_Accessor_Read() throws Exception assertNull(context.get(ExpressionCompiler.PRE_CAST)); assertEquals(int.class, context.getCurrentType()); assertEquals(ListSource.class, context.getCurrentAccessor()); - } + } } diff --git a/src/test/java/ognl/test/accessors/PropertyAccessTest.java b/src/test/java/ognl/test/accessors/PropertyAccessTest.java new file mode 100644 index 00000000..3c8b2a96 --- /dev/null +++ b/src/test/java/ognl/test/accessors/PropertyAccessTest.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.accessors; + +import junit.framework.TestCase; +import ognl.DefaultMemberAccess; +import ognl.Ognl; +import ognl.OgnlContext; +import ognl.OgnlException; +import ognl.OgnlRuntime; +import ognl.test.objects.BeanProvider; +import ognl.test.objects.BeanProviderAccessor; +import ognl.test.objects.EvenOdd; +import ognl.test.objects.Root; + +public class PropertyAccessTest extends TestCase { + + public void testPropertyAccess() throws OgnlException { + // given + OgnlContext context = Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); + + Root root = new Root(); + root.getBeans().setBean("evenOdd", new EvenOdd()); + + // when + Object result = Ognl.getValue("beans.evenOdd.next", context, root); + + // then + assertEquals("even", result); + } + + public void setUp() { + OgnlRuntime.setPropertyAccessor(BeanProvider.class, new BeanProviderAccessor()); + } + +} diff --git a/src/test/java/org/ognl/test/enhance/TestExpressionCompiler.java b/src/test/java/ognl/test/enhance/TestExpressionCompiler.java similarity index 65% rename from src/test/java/org/ognl/test/enhance/TestExpressionCompiler.java rename to src/test/java/ognl/test/enhance/TestExpressionCompiler.java index 512aab1b..371b6117 100644 --- a/src/test/java/org/ognl/test/enhance/TestExpressionCompiler.java +++ b/src/test/java/ognl/test/enhance/TestExpressionCompiler.java @@ -1,41 +1,44 @@ /** * */ -package org.ognl.test.enhance; +package ognl.test.enhance; import junit.framework.TestCase; import ognl.DefaultMemberAccess; +import ognl.ExpressionSyntaxException; import ognl.Node; import ognl.Ognl; import ognl.OgnlContext; +import ognl.OgnlException; import ognl.enhance.ExpressionCompiler; import ognl.enhance.OgnlExpressionCompiler; -import org.ognl.test.objects.*; +import ognl.test.objects.Bean1; +import ognl.test.objects.GenericRoot; +import ognl.test.objects.IndexedMapObject; +import ognl.test.objects.Inherited; +import ognl.test.objects.Root; +import ognl.test.objects.TestInherited1; +import ognl.test.objects.TestInherited2; import java.util.Collection; import java.util.HashMap; import java.util.Map; -import ognl.ExpressionSyntaxException; -import ognl.OgnlException; /** * Tests functionality of {@link ExpressionCompiler}. */ -public class TestExpressionCompiler extends TestCase -{ +public class TestExpressionCompiler extends TestCase { OgnlExpressionCompiler _compiler; OgnlContext _context = (OgnlContext) Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); - public void setUp() - { + public void setUp() { _compiler = new ExpressionCompiler(); } public void test_Get_Property_Access() - throws Throwable - { - Node expr = (Node)Ognl.parseExpression("bean2"); + throws Throwable { + Node expr = (Node) Ognl.parseExpression("bean2"); Bean1 root = new Bean1(); _compiler.compileExpression(_context, expr, root); @@ -44,9 +47,8 @@ public void test_Get_Property_Access() } public void test_Get_Indexed_Property() - throws Throwable - { - Node expr = (Node)Ognl.parseExpression("bean2.bean3.indexedValue[25]"); + throws Throwable { + Node expr = (Node) Ognl.parseExpression("bean2.bean3.indexedValue[25]"); Bean1 root = new Bean1(); assertNull(Ognl.getValue(expr, _context, root)); @@ -57,9 +59,8 @@ public void test_Get_Indexed_Property() } public void test_Set_Indexed_Property() - throws Throwable - { - Node expr = (Node)Ognl.parseExpression("bean2.bean3.indexedValue[25]"); + throws Throwable { + Node expr = (Node) Ognl.parseExpression("bean2.bean3.indexedValue[25]"); Bean1 root = new Bean1(); assertNull(Ognl.getValue(expr, _context, root)); @@ -72,9 +73,8 @@ public void test_Set_Indexed_Property() } public void test_Expression() - throws Throwable - { - Node expr = (Node)Ognl.parseExpression("bean2.bean3.value <= 24"); + throws Throwable { + Node expr = (Node) Ognl.parseExpression("bean2.bean3.value <= 24"); Bean1 root = new Bean1(); assertEquals(Boolean.FALSE, Ognl.getValue(expr, _context, root)); @@ -85,10 +85,9 @@ public void test_Expression() } public void test_Get_Context_Property() - throws Throwable - { + throws Throwable { _context.put("key", "foo"); - Node expr = (Node)Ognl.parseExpression("bean2.bean3.map[#key]"); + Node expr = (Node) Ognl.parseExpression("bean2.bean3.map[#key]"); Bean1 root = new Bean1(); assertEquals("bar", Ognl.getValue(expr, _context, root)); @@ -102,12 +101,11 @@ public void test_Get_Context_Property() assertEquals("baz", Ognl.getValue(expr, _context, root)); assertEquals("baz", expr.getAccessor().get(_context, root)); } - + public void test_Set_Context_Property() - throws Throwable - { + throws Throwable { _context.put("key", "foo"); - Node expr = (Node)Ognl.parseExpression("bean2.bean3.map[#key]"); + Node expr = (Node) Ognl.parseExpression("bean2.bean3.map[#key]"); Bean1 root = new Bean1(); _compiler.compileExpression(_context, expr, root); @@ -122,8 +120,7 @@ public void test_Set_Context_Property() } public void test_Property_Index() - throws Throwable - { + throws Throwable { Root root = new Root(); Node expr = (Node) Ognl.compileExpression(_context, root, "{index + 1}"); @@ -133,8 +130,7 @@ public void test_Property_Index() } public void test_Root_Expression_Inheritance() - throws Throwable - { + throws Throwable { Inherited obj1 = new TestInherited1(); Inherited obj2 = new TestInherited2(); @@ -145,8 +141,7 @@ public void test_Root_Expression_Inheritance() } public void test_Create_Empty_Collection() - throws Throwable - { + throws Throwable { Node expr = (Node) Ognl.compileExpression(_context, null, "{}"); Object ret = expr.getAccessor().get(_context, null); @@ -155,14 +150,12 @@ public void test_Create_Empty_Collection() assertTrue(Collection.class.isAssignableFrom(ret.getClass())); } - public String getKey() - { + public String getKey() { return "key"; } public void test_Indexed_Property() - throws Throwable - { + throws Throwable { Map map = new HashMap(); map.put("key", "value"); @@ -172,19 +165,16 @@ public void test_Indexed_Property() IndexedMapObject mapObject = new IndexedMapObject("propertyValue"); - public IndexedMapObject getObject() - { + public IndexedMapObject getObject() { return mapObject; } - public String getPropertyKey() - { + public String getPropertyKey() { return "property"; } public void test_Indexed_Map_Property() - throws Throwable - { + throws Throwable { assertEquals("propertyValue", Ognl.getValue("object[propertyKey]", this)); _context.clear(); @@ -196,10 +186,9 @@ public void test_Indexed_Map_Property() assertEquals("propertyValue", expression.getAccessor().get(_context, this)); } - public void test_Set_Generic_Property() throws Exception - { + public void test_Set_Generic_Property() throws Exception { _context.clear(); - + GenericRoot root = new GenericRoot(); Node node = Ognl.compileExpression(_context, root, "cracker.param"); @@ -214,8 +203,8 @@ public void test_Set_Generic_Property() throws Exception /** * Test ApplyExpressionMaxLength() mechanism for OGNL expression parsing. - * - * @throws Exception + * + * @throws Exception */ public void test_ApplyExpressionMaxLength() throws Exception { final OgnlContext context = (OgnlContext) Ognl.createDefaultContext(null); @@ -230,25 +219,25 @@ public void test_ApplyExpressionMaxLength() throws Exception { try { Ognl.parseExpression(shortFakeExpression); } catch (Exception ex) { - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(mediumFakeExpression); } catch (Exception ex) { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(longFakeExpression); } catch (Exception ex) { - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(veryLongFakeExpression); } catch (Exception ex) { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -259,7 +248,7 @@ public void test_ApplyExpressionMaxLength() throws Exception { } catch (IllegalArgumentException iaex) { // Expected result } catch (Exception ex) { - fail ("applyExpressionMaxLength illegal value " + Integer.MIN_VALUE + " failed unexpectedly - Error: " + ex); + fail("applyExpressionMaxLength illegal value " + Integer.MIN_VALUE + " failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -274,25 +263,25 @@ public void test_ApplyExpressionMaxLength() throws Exception { try { Ognl.parseExpression(shortFakeExpression); } catch (Exception ex) { - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(mediumFakeExpression); } catch (Exception ex) { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(longFakeExpression); } catch (Exception ex) { - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(veryLongFakeExpression); } catch (Exception ex) { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -307,25 +296,25 @@ public void test_ApplyExpressionMaxLength() throws Exception { try { Ognl.parseExpression(shortFakeExpression); } catch (Exception ex) { - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(mediumFakeExpression); } catch (Exception ex) { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(longFakeExpression); } catch (Exception ex) { - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(veryLongFakeExpression); } catch (Exception ex) { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -340,32 +329,32 @@ public void test_ApplyExpressionMaxLength() throws Exception { try { Ognl.parseExpression(shortFakeExpression); } catch (Exception ex) { - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(mediumFakeExpression); } catch (Exception ex) { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(longFakeExpression); } catch (Exception ex) { - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(veryLongFakeExpression); - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -380,46 +369,46 @@ public void test_ApplyExpressionMaxLength() throws Exception { try { Ognl.parseExpression(shortFakeExpression); } catch (Exception ex) { - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(mediumFakeExpression); - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(longFakeExpression); - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of longFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of longFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(veryLongFakeExpression); - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -433,54 +422,54 @@ public void test_ApplyExpressionMaxLength() throws Exception { // Test state with shortFakeExpression.length() limit. Only shortFakeExpression should succeed try { Ognl.parseExpression(shortFakeExpression); - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(mediumFakeExpression); - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(longFakeExpression); - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of longFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of longFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(veryLongFakeExpression); - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -497,71 +486,72 @@ public void test_ApplyExpressionMaxLength() throws Exception { } catch (ExpressionSyntaxException esx) { // Expected for an empty expression (acceptable state). } catch (Exception ex) { - fail ("Parse of empty string failed unexpectedly - Error: " + ex); + fail("Parse of empty string failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(shortFakeExpression); - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of shortFakeExpression (" + shortFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(mediumFakeExpression); - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of mediumFakeExpression (" + mediumFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(longFakeExpression); - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of longFakeExpression (" + longFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of longFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of longFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } try { Ognl.parseExpression(veryLongFakeExpression); - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") succeded unexpectedly after limit set below its length ?"); } catch (OgnlException oex) { if (oex.getCause() instanceof SecurityException) { // Expected result } else { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly after limit set below its length - Error: " + oex); } } catch (Exception ex) { - fail ("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); + fail("Parse of veryLongFakeExpression (" + veryLongFakeExpression.length() + ") failed unexpectedly - Error: " + ex); } } finally { try { Ognl.applyExpressionMaxLength(null); // Reset to default state before leaving test. - } catch (Exception ex) {} // Do not care for cleanup + } catch (Exception ex) { + } // Do not care for cleanup } } /** * Test freezing and thawing of maximum expression length mechanism for OGNL expression parsing. - * - * @throws Exception + * + * @throws Exception */ public void test_FreezeThawExpressionMaxLength() throws Exception { final OgnlContext context = (OgnlContext) Ognl.createDefaultContext(null); @@ -578,7 +568,7 @@ public void test_FreezeThawExpressionMaxLength() throws Exception { Ognl.applyExpressionMaxLength(100); Ognl.applyExpressionMaxLength(10); } catch (Exception ex) { - fail ("applyExpressionMaxLength in default (initial) state with legal values failed unexpectedly - Error: " + ex); + fail("applyExpressionMaxLength in default (initial) state with legal values failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -588,10 +578,10 @@ public void test_FreezeThawExpressionMaxLength() throws Exception { Ognl.applyExpressionMaxLength(Integer.MAX_VALUE); Ognl.thawExpressionMaxLength(); } catch (IllegalStateException ise) { - fail ("applyExpressionMaxLength was blocked when thawed ?"); + fail("applyExpressionMaxLength was blocked when thawed ?"); // Expected result } catch (Exception ex) { - fail ("applyExpressionMaxLength (thaw attempt) failed unexpectedly - Error: " + ex); + fail("applyExpressionMaxLength (thaw attempt) failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -599,11 +589,11 @@ public void test_FreezeThawExpressionMaxLength() throws Exception { try { Ognl.freezeExpressionMaxLength(); Ognl.applyExpressionMaxLength(Integer.MAX_VALUE); - fail ("applyExpressionMaxLength was not blocked when frozen ?"); + fail("applyExpressionMaxLength was not blocked when frozen ?"); } catch (IllegalStateException ise) { // Expected result } catch (Exception ex) { - fail ("applyExpressionMaxLength (freeze attempt) failed unexpectedly - Error: " + ex); + fail("applyExpressionMaxLength (freeze attempt) failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -612,27 +602,27 @@ public void test_FreezeThawExpressionMaxLength() throws Exception { Ognl.freezeExpressionMaxLength(); Ognl.freezeExpressionMaxLength(); } catch (Exception ex) { - fail ("freezeExpressionMaxLength failed during repetative freeze operations - Error: " + ex); + fail("freezeExpressionMaxLength failed during repetative freeze operations - Error: " + ex); } // --------------------------------------------------------------------- // Confirm still frozen, then thaw and demonstrate set permitted try { Ognl.applyExpressionMaxLength(Integer.MAX_VALUE); - fail ("applyExpressionMaxLength was not blocked when frozen ?"); + fail("applyExpressionMaxLength was not blocked when frozen ?"); } catch (IllegalStateException ise) { // Expected result } catch (Exception ex) { - fail ("applyExpressionMaxLength (when frozen) failed unexpectedly - Error: " + ex); + fail("applyExpressionMaxLength (when frozen) failed unexpectedly - Error: " + ex); } try { Ognl.thawExpressionMaxLength(); Ognl.applyExpressionMaxLength(Integer.MAX_VALUE); } catch (IllegalStateException ise) { - fail ("applyExpressionMaxLength was blocked when thawed ?"); + fail("applyExpressionMaxLength was blocked when thawed ?"); // Expected result } catch (Exception ex) { - fail ("applyExpressionMaxLength (thaw attempt) failed unexpectedly - Error: " + ex); + fail("applyExpressionMaxLength (thaw attempt) failed unexpectedly - Error: " + ex); } // --------------------------------------------------------------------- @@ -641,15 +631,17 @@ public void test_FreezeThawExpressionMaxLength() throws Exception { Ognl.thawExpressionMaxLength(); Ognl.thawExpressionMaxLength(); } catch (Exception ex) { - fail ("thawExpressionMaxLength failed during repetative thaw operations - Error: " + ex); + fail("thawExpressionMaxLength failed during repetative thaw operations - Error: " + ex); } } finally { try { Ognl.thawExpressionMaxLength(); // Reset to default state before leaving test. - } catch (Exception ex) {} // Do not care for cleanup + } catch (Exception ex) { + } // Do not care for cleanup try { Ognl.applyExpressionMaxLength(null); // Reset to default state before leaving test. - } catch (Exception ex) {} // Do not care for cleanup + } catch (Exception ex) { + } // Do not care for cleanup } } diff --git a/src/test/java/org/ognl/test/objects/BaseBean.java b/src/test/java/ognl/test/objects/BaseBean.java similarity index 57% rename from src/test/java/org/ognl/test/objects/BaseBean.java rename to src/test/java/ognl/test/objects/BaseBean.java index 374e1e30..feedc7f0 100644 --- a/src/test/java/org/ognl/test/objects/BaseBean.java +++ b/src/test/java/ognl/test/objects/BaseBean.java @@ -1,7 +1,7 @@ /** * */ -package org.ognl.test.objects; +package ognl.test.objects; /** @@ -11,28 +11,23 @@ public abstract class BaseBean { public abstract String getName(); - public boolean getActive() - { + public boolean getActive() { return true; } - public boolean isActive2() - { + public boolean isActive2() { return true; } - public Two getTwo() - { + public Two getTwo() { return new Two(); } - public String getMessage(String mes) - { + public String getMessage(String mes) { return "[" + mes + "]"; } - public boolean hasChildren(String name) - { + public boolean hasChildren(String name) { return name.length() > 2; } } diff --git a/src/test/java/org/ognl/test/objects/BaseGeneric.java b/src/test/java/ognl/test/objects/BaseGeneric.java similarity index 62% rename from src/test/java/org/ognl/test/objects/BaseGeneric.java rename to src/test/java/ognl/test/objects/BaseGeneric.java index 0230485b..5ea99966 100644 --- a/src/test/java/org/ognl/test/objects/BaseGeneric.java +++ b/src/test/java/ognl/test/objects/BaseGeneric.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.io.Serializable; @@ -11,38 +11,31 @@ public class BaseGeneric { GenericService _service; protected I[] ids; - public BaseGeneric() - { + public BaseGeneric() { _service = new GenericServiceImpl(); } - public void setIds(I[] ids) - { + public void setIds(I[] ids) { this.ids = ids; } - public I[] getIds() - { + public I[] getIds() { return this.ids; } - public String getMessage() - { + public String getMessage() { return "Message"; } - public E getValue() - { + public E getValue() { return _value; } - public GenericService getService() - { + public GenericService getService() { return _service; } - public String format(Object value) - { + public String format(Object value) { return value.toString(); } } diff --git a/src/test/java/org/ognl/test/objects/BaseIndexed.java b/src/test/java/ognl/test/objects/BaseIndexed.java similarity index 60% rename from src/test/java/org/ognl/test/objects/BaseIndexed.java rename to src/test/java/ognl/test/objects/BaseIndexed.java index 3e13e5d8..b9aaf39a 100644 --- a/src/test/java/org/ognl/test/objects/BaseIndexed.java +++ b/src/test/java/ognl/test/objects/BaseIndexed.java @@ -1,12 +1,11 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * Class used to test inheritance. */ public class BaseIndexed { - public Object getLine(int index) - { + public Object getLine(int index) { return "line:" + index; } } diff --git a/src/test/java/ognl/test/objects/BaseObjectIndexed.java b/src/test/java/ognl/test/objects/BaseObjectIndexed.java new file mode 100644 index 00000000..420c76fb --- /dev/null +++ b/src/test/java/ognl/test/objects/BaseObjectIndexed.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +import java.util.HashMap; +import java.util.Map; + +public class BaseObjectIndexed extends Object { + private Map attributes = new HashMap(); + + public BaseObjectIndexed() { + super(); + } + + public Map getAttributes() { + return attributes; + } + + public Object getAttribute(String name) { + return attributes.get(name); + } + + public void setAttribute(String name, Object value) { + attributes.put(name, value); + } + + /* allow testing property name where types do not match */ + public Object getOtherAttribute(String name) { + return null; + } + + public void setOtherAttribute(Object someObject, Object foo) { + /* do nothing */ + } + + + /* test whether get only is found */ + public Object getSecondaryAttribute(Object name) { + return attributes.get(name); + } +} diff --git a/src/test/java/org/ognl/test/objects/BaseSyntheticObject.java b/src/test/java/ognl/test/objects/BaseSyntheticObject.java similarity index 74% rename from src/test/java/org/ognl/test/objects/BaseSyntheticObject.java rename to src/test/java/ognl/test/objects/BaseSyntheticObject.java index 09c0eb2c..11ae9a38 100644 --- a/src/test/java/org/ognl/test/objects/BaseSyntheticObject.java +++ b/src/test/java/ognl/test/objects/BaseSyntheticObject.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.ArrayList; import java.util.List; @@ -8,8 +8,7 @@ */ public abstract class BaseSyntheticObject { - protected List getList() - { + protected List getList() { return new ArrayList(); } } diff --git a/src/test/java/ognl/test/objects/Bean1.java b/src/test/java/ognl/test/objects/Bean1.java new file mode 100644 index 00000000..a0571137 --- /dev/null +++ b/src/test/java/ognl/test/objects/Bean1.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +public class Bean1 extends Object { + private Bean2 bean2 = new Bean2(); + + public Bean2 getBean2() { + return bean2; + } +} diff --git a/src/test/java/ognl/test/objects/Bean2.java b/src/test/java/ognl/test/objects/Bean2.java new file mode 100644 index 00000000..a967b9dd --- /dev/null +++ b/src/test/java/ognl/test/objects/Bean2.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +public class Bean2 extends Object { + private Bean3 bean3 = new Bean3(); + + private boolean _pageBreakAfter = false; + + public String code = "code"; + + public Long getId() { + return 1l; + } + + public Bean3 getBean3() { + return bean3; + } + + public long getMillis() { + return 1000 * 60 * 2; + } + + public boolean isCarrier() { + return false; + } + + public boolean isPageBreakAfter() { + return _pageBreakAfter; + } + + public void setPageBreakAfter(boolean value) { + _pageBreakAfter = value; + } + + public void togglePageBreakAfter() { + _pageBreakAfter ^= true; + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Bean2 bean2 = (Bean2) o; + + if (_pageBreakAfter != bean2._pageBreakAfter) return false; + + return true; + } + + public int hashCode() { + return (_pageBreakAfter ? 1 : 0); + } +} diff --git a/src/test/java/ognl/test/objects/Bean3.java b/src/test/java/ognl/test/objects/Bean3.java new file mode 100644 index 00000000..a62c70f8 --- /dev/null +++ b/src/test/java/ognl/test/objects/Bean3.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +import java.util.HashMap; +import java.util.Map; + +public class Bean3 extends Object { + private int value = 100; + + private Map map; + + { + map = new HashMap(); + map.put("foo", "bar"); + map.put("bar", "baz"); + } + + private String _nullValue; + private Object _indexValue; + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public Object getIndexedValue(int index) { + return _indexValue; + } + + public void setIndexedValue(int index, Object value) { + _indexValue = value; + } + + public Map getMap() { + return map; + } + + public void setNullValue(String value) { + _nullValue = value; + } + + public String getNullValue() { + return _nullValue; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_indexValue == null) ? 0 : _indexValue.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + final Bean3 other = (Bean3) obj; + if (_indexValue == null) { + if (other._indexValue != null) return false; + } else if (!_indexValue.equals(other._indexValue)) return false; + return true; + } +} diff --git a/src/test/java/ognl/test/objects/BeanProvider.java b/src/test/java/ognl/test/objects/BeanProvider.java new file mode 100644 index 00000000..9a850a1f --- /dev/null +++ b/src/test/java/ognl/test/objects/BeanProvider.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +/** + * Test interface to be used with a custom property accessor. + */ +public interface BeanProvider { + + /** + * Gets a bean by name. + */ + Object getBean(String name); + + /** + * Sets a new bean mapping. + */ + void setBean(String name, Object bean); +} diff --git a/src/test/java/org/ognl/test/objects/BeanProviderAccessor.java b/src/test/java/ognl/test/objects/BeanProviderAccessor.java similarity index 52% rename from src/test/java/org/ognl/test/objects/BeanProviderAccessor.java rename to src/test/java/ognl/test/objects/BeanProviderAccessor.java index 16c4eb4c..d93dfcb2 100644 --- a/src/test/java/org/ognl/test/objects/BeanProviderAccessor.java +++ b/src/test/java/ognl/test/objects/BeanProviderAccessor.java @@ -1,65 +1,56 @@ /** - * + * */ -package org.ognl.test.objects; +package ognl.test.objects; -import ognl.*; +import ognl.ObjectPropertyAccessor; +import ognl.OgnlContext; +import ognl.OgnlException; +import ognl.OgnlRuntime; +import ognl.PropertyAccessor; import ognl.enhance.ExpressionCompiler; import ognl.enhance.UnsupportedCompilationException; -import java.util.Map; - - /** * Implementation of provider that works with {@link BeanProvider} instances. */ -public class BeanProviderAccessor extends ObjectPropertyAccessor implements PropertyAccessor -{ - public Object getProperty(Map context, Object target, Object name) - throws OgnlException - { - BeanProvider provider = (BeanProvider)target; - String beanName = (String)name; - +public class BeanProviderAccessor extends ObjectPropertyAccessor implements PropertyAccessor { + public Object getProperty(OgnlContext context, Object target, Object name) throws OgnlException { + BeanProvider provider = (BeanProvider) target; + String beanName = (String) name; + return provider.getBean(beanName); } /** - * Returns true if the name matches a bean provided by the provider. - * Otherwise invokes the super implementation. - * + * Returns true if the name matches a bean provided by the provider. + * Otherwise invokes the super implementation. **/ - - public boolean hasGetProperty(Map context, Object target, Object oname) - throws OgnlException - { - BeanProvider provider = (BeanProvider)target; - String beanName = ((String)oname).replaceAll("\"", ""); - + public boolean hasGetProperty(OgnlContext context, Object target, Object oname) throws OgnlException { + BeanProvider provider = (BeanProvider) target; + String beanName = ((String) oname).replaceAll("\"", ""); + return provider.getBean(beanName) != null; } - - public String getSourceAccessor(OgnlContext context, Object target, Object name) - { - BeanProvider provider = (BeanProvider)target; - String beanName = ((String)name).replaceAll("\"", ""); - - if (provider.getBean(beanName) != null) - { + + public String getSourceAccessor(OgnlContext context, Object target, Object name) { + BeanProvider provider = (BeanProvider) target; + String beanName = ((String) name).replaceAll("\"", ""); + + if (provider.getBean(beanName) != null) { context.setCurrentAccessor(BeanProvider.class); context.setCurrentType(provider.getBean(beanName).getClass()); ExpressionCompiler.addCastString(context, "((" + OgnlRuntime.getCompiler().getInterfaceClass(provider.getBean(beanName).getClass()).getName() + ")"); - + return ".getBean(\"" + beanName + "\"))"; } - + return super.getSourceAccessor(context, target, name); } - - public String getSourceSetter(OgnlContext context, Object target, Object name) - { + + public String getSourceSetter(OgnlContext context, Object target, Object name) { throw new UnsupportedCompilationException("Can't set beans on BeanProvider."); } } diff --git a/src/test/java/org/ognl/test/objects/BeanProviderImpl.java b/src/test/java/ognl/test/objects/BeanProviderImpl.java similarity index 62% rename from src/test/java/org/ognl/test/objects/BeanProviderImpl.java rename to src/test/java/ognl/test/objects/BeanProviderImpl.java index efc06901..3fcdd6db 100644 --- a/src/test/java/org/ognl/test/objects/BeanProviderImpl.java +++ b/src/test/java/ognl/test/objects/BeanProviderImpl.java @@ -1,7 +1,7 @@ /** - * + * */ -package org.ognl.test.objects; +package ognl.test.objects; import java.io.Serializable; import java.util.HashMap; @@ -11,19 +11,17 @@ /** * Implementation of {@link BeanProvider}. */ -public class BeanProviderImpl implements Serializable, BeanProvider -{ +public class BeanProviderImpl implements Serializable, BeanProvider { private Map _map = new HashMap(); - - public BeanProviderImpl() {} - - public Object getBean(String name) - { + + public BeanProviderImpl() { + } + + public Object getBean(String name) { return _map.get(name); } - - public void setBean(String name, Object bean) - { + + public void setBean(String name, Object bean) { _map.put(name, bean); } } diff --git a/src/test/java/ognl/test/objects/Component.java b/src/test/java/ognl/test/objects/Component.java new file mode 100644 index 00000000..d3f10275 --- /dev/null +++ b/src/test/java/ognl/test/objects/Component.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +public class Component extends Object { + private URLStorage toDisplay = new URLStorage(); + private Page page = new Page(); + + public static class URLStorage extends Object { + private String pictureUrl = "http://www.picturespace.com/pictures/100"; + + public String getPictureUrl() { + return pictureUrl; + } + + public void setPictureUrl(String value) { + pictureUrl = value; + } + } + + public static class Page extends Object { + public Object createRelativeAsset(String value) { + return "/toplevel/" + value; + } + } + + public Component() { + super(); + } + + public Page getPage() { + return page; + } + + public void setPage(Page value) { + page = value; + } + + public URLStorage getToDisplay() { + return toDisplay; + } + + public void setToDisplay(URLStorage value) { + toDisplay = value; + } +} diff --git a/src/test/java/ognl/test/objects/ComponentImpl.java b/src/test/java/ognl/test/objects/ComponentImpl.java new file mode 100644 index 00000000..e9a64c49 --- /dev/null +++ b/src/test/java/ognl/test/objects/ComponentImpl.java @@ -0,0 +1,26 @@ +package ognl.test.objects; + +/** + * + */ +public class ComponentImpl implements IComponent { + + String _clientId; + int _count = 0; + + public String getClientId() { + return _clientId; + } + + public void setClientId(String id) { + _clientId = id; + } + + public int getCount(String index) { + return _count; + } + + public void setCount(String index, int count) { + _count = count; + } +} diff --git a/src/test/java/org/ognl/test/objects/ComponentSubclass.java b/src/test/java/ognl/test/objects/ComponentSubclass.java similarity index 58% rename from src/test/java/org/ognl/test/objects/ComponentSubclass.java rename to src/test/java/ognl/test/objects/ComponentSubclass.java index 00fcf968..98068d78 100644 --- a/src/test/java/org/ognl/test/objects/ComponentSubclass.java +++ b/src/test/java/ognl/test/objects/ComponentSubclass.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * @@ -7,13 +7,11 @@ public class ComponentSubclass extends ComponentImpl { int _count = 0; - public int getCount() - { + public int getCount() { return _count; } - public void setCount(int count) - { + public void setCount(int count) { _count = count; } } diff --git a/src/test/java/org/ognl/test/objects/Copy.java b/src/test/java/ognl/test/objects/Copy.java similarity index 50% rename from src/test/java/org/ognl/test/objects/Copy.java rename to src/test/java/ognl/test/objects/Copy.java index 4c0814a9..211a0dcc 100644 --- a/src/test/java/org/ognl/test/objects/Copy.java +++ b/src/test/java/ognl/test/objects/Copy.java @@ -1,12 +1,11 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public class Copy { - public int size() - { + public int size() { return 1; } } diff --git a/src/test/java/ognl/test/objects/CorrectedObject.java b/src/test/java/ognl/test/objects/CorrectedObject.java new file mode 100644 index 00000000..c43af4d2 --- /dev/null +++ b/src/test/java/ognl/test/objects/CorrectedObject.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +public class CorrectedObject { + public CorrectedObject() { + } + + public void setStringValue(String value) { + } + + public String getStringValue() { + return null; + } + + public String getIndexedStringValue(String key) { + return null; + } + + public void setIndexedStringValue(String key, String value) { + } +} diff --git a/src/test/java/org/ognl/test/objects/Cracker.java b/src/test/java/ognl/test/objects/Cracker.java similarity index 56% rename from src/test/java/org/ognl/test/objects/Cracker.java rename to src/test/java/ognl/test/objects/Cracker.java index 18081625..059b17f1 100644 --- a/src/test/java/org/ognl/test/objects/Cracker.java +++ b/src/test/java/ognl/test/objects/Cracker.java @@ -1,13 +1,13 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.io.Serializable; /** * Generic test object. */ -public interface Cracker{ +public interface Cracker { T getParam(); - + void setParam(T param); } diff --git a/src/test/java/org/ognl/test/objects/Entry.java b/src/test/java/ognl/test/objects/Entry.java similarity index 68% rename from src/test/java/org/ognl/test/objects/Entry.java rename to src/test/java/ognl/test/objects/Entry.java index fbe17908..12b2c3ea 100644 --- a/src/test/java/org/ognl/test/objects/Entry.java +++ b/src/test/java/ognl/test/objects/Entry.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * @@ -7,18 +7,15 @@ public class Entry { private int _size = 1; - public int size() - { + public int size() { return _size; } - public Copy getCopy() - { + public Copy getCopy() { return new Copy(); } - public boolean equals(Object o) - { + public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) @@ -28,8 +25,7 @@ public boolean equals(Object o) return _size == entry._size; } - public int hashCode() - { + public int hashCode() { return _size; } } diff --git a/src/test/java/ognl/test/objects/EvenOdd.java b/src/test/java/ognl/test/objects/EvenOdd.java new file mode 100644 index 00000000..cbd41848 --- /dev/null +++ b/src/test/java/ognl/test/objects/EvenOdd.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +public class EvenOdd { + + private boolean even = true; + + /** + * Returns "even" or "odd". Whatever it returns on one invocation, it will + * return the opposite on the next. By default, the first value returned is + * "even". + */ + public String getNext() { + String result = even ? "even" : "odd"; + even = !even; + return result; + } + + public boolean isEven() { + return even; + } + + /** + * Overrides the even flag. + */ + public void setEven(boolean value) { + even = value; + } + +} diff --git a/src/test/java/ognl/test/objects/FirstBean.java b/src/test/java/ognl/test/objects/FirstBean.java new file mode 100644 index 00000000..34f14cf3 --- /dev/null +++ b/src/test/java/ognl/test/objects/FirstBean.java @@ -0,0 +1,16 @@ +/** + * + */ +package ognl.test.objects; + + +/** + * + */ +public class FirstBean extends BaseBean { + + public String getName() { + return "FirstBean"; + } + +} diff --git a/src/test/java/org/ognl/test/objects/FormComponentImpl.java b/src/test/java/ognl/test/objects/FormComponentImpl.java similarity index 61% rename from src/test/java/org/ognl/test/objects/FormComponentImpl.java rename to src/test/java/ognl/test/objects/FormComponentImpl.java index 74054328..7bd06bb2 100644 --- a/src/test/java/org/ognl/test/objects/FormComponentImpl.java +++ b/src/test/java/ognl/test/objects/FormComponentImpl.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * @@ -8,13 +8,11 @@ public class FormComponentImpl extends ComponentImpl implements IFormComponent { IForm _form; - public IForm getForm() - { + public IForm getForm() { return _form; } - public void setForm(IForm form) - { + public void setForm(IForm form) { _form = form; } } diff --git a/src/test/java/org/ognl/test/objects/FormImpl.java b/src/test/java/ognl/test/objects/FormImpl.java similarity index 68% rename from src/test/java/org/ognl/test/objects/FormImpl.java rename to src/test/java/ognl/test/objects/FormImpl.java index d3bace80..8a353468 100644 --- a/src/test/java/org/ognl/test/objects/FormImpl.java +++ b/src/test/java/ognl/test/objects/FormImpl.java @@ -1,8 +1,8 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public class FormImpl extends ComponentImpl implements IForm { - + } diff --git a/src/test/java/org/ognl/test/objects/GameGeneric.java b/src/test/java/ognl/test/objects/GameGeneric.java similarity index 68% rename from src/test/java/org/ognl/test/objects/GameGeneric.java rename to src/test/java/ognl/test/objects/GameGeneric.java index 22cbe154..981f8d67 100644 --- a/src/test/java/org/ognl/test/objects/GameGeneric.java +++ b/src/test/java/ognl/test/objects/GameGeneric.java @@ -1,12 +1,11 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public class GameGeneric extends BaseGeneric { - public GameGeneric() - { + public GameGeneric() { _value = new GameGenericObject(); } } diff --git a/src/test/java/org/ognl/test/objects/GameGenericObject.java b/src/test/java/ognl/test/objects/GameGenericObject.java similarity index 51% rename from src/test/java/org/ognl/test/objects/GameGenericObject.java rename to src/test/java/ognl/test/objects/GameGenericObject.java index d580af38..7a1809d5 100644 --- a/src/test/java/org/ognl/test/objects/GameGenericObject.java +++ b/src/test/java/ognl/test/objects/GameGenericObject.java @@ -1,27 +1,23 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public class GameGenericObject implements GenericObject { - public GameGenericObject() - { + public GameGenericObject() { super(); } - public int getId() - { + public int getId() { return 20; } - public String getDisplayName() - { + public String getDisplayName() { return "Halo 3"; } - public String getHappy() - { + public String getHappy() { return "happy"; } } diff --git a/src/test/java/org/ognl/test/objects/GenericCracker.java b/src/test/java/ognl/test/objects/GenericCracker.java similarity index 57% rename from src/test/java/org/ognl/test/objects/GenericCracker.java rename to src/test/java/ognl/test/objects/GenericCracker.java index e171af7c..a70ecb33 100644 --- a/src/test/java/org/ognl/test/objects/GenericCracker.java +++ b/src/test/java/ognl/test/objects/GenericCracker.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * @@ -7,13 +7,11 @@ public class GenericCracker implements Cracker { Integer _param; - public Integer getParam() - { + public Integer getParam() { return _param; } - public void setParam(Integer param) - { + public void setParam(Integer param) { _param = param; } } diff --git a/src/test/java/org/ognl/test/objects/GenericObject.java b/src/test/java/ognl/test/objects/GenericObject.java similarity index 82% rename from src/test/java/org/ognl/test/objects/GenericObject.java rename to src/test/java/ognl/test/objects/GenericObject.java index 0b504ee7..fbec76ed 100644 --- a/src/test/java/org/ognl/test/objects/GenericObject.java +++ b/src/test/java/ognl/test/objects/GenericObject.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * Used by {@link BaseGeneric} to reference a class type. diff --git a/src/test/java/org/ognl/test/objects/GenericRoot.java b/src/test/java/ognl/test/objects/GenericRoot.java similarity index 54% rename from src/test/java/org/ognl/test/objects/GenericRoot.java rename to src/test/java/ognl/test/objects/GenericRoot.java index 7add0a20..005dea81 100644 --- a/src/test/java/org/ognl/test/objects/GenericRoot.java +++ b/src/test/java/ognl/test/objects/GenericRoot.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * @@ -8,23 +8,19 @@ public class GenericRoot { Root _root = new Root(); GenericCracker _cracker = new GenericCracker(); - public Root getRoot() - { + public Root getRoot() { return _root; } - public void setRoot(Root root) - { + public void setRoot(Root root) { _root = root; } - public GenericCracker getCracker() - { + public GenericCracker getCracker() { return _cracker; } - public void setCracker(GenericCracker cracker) - { + public void setCracker(GenericCracker cracker) { _cracker = cracker; } } diff --git a/src/test/java/org/ognl/test/objects/GenericService.java b/src/test/java/ognl/test/objects/GenericService.java similarity index 88% rename from src/test/java/org/ognl/test/objects/GenericService.java rename to src/test/java/ognl/test/objects/GenericService.java index 55db2d3d..3119a424 100644 --- a/src/test/java/org/ognl/test/objects/GenericService.java +++ b/src/test/java/ognl/test/objects/GenericService.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -8,9 +8,9 @@ */ public interface GenericService { - String getFullMessageFor(PersonGenericObject person, Object...arguments); + String getFullMessageFor(PersonGenericObject person, Object... arguments); - String getFullMessageFor(GameGenericObject game, Object...arguments); + String getFullMessageFor(GameGenericObject game, Object... arguments); void exec(long waitMilliseconds) throws InterruptedException, NoSuchMethodException, InvocationTargetException, IllegalAccessException; diff --git a/src/test/java/org/ognl/test/objects/GenericServiceImpl.java b/src/test/java/ognl/test/objects/GenericServiceImpl.java similarity index 95% rename from src/test/java/org/ognl/test/objects/GenericServiceImpl.java rename to src/test/java/ognl/test/objects/GenericServiceImpl.java index 06afd03e..0de78ac7 100644 --- a/src/test/java/org/ognl/test/objects/GenericServiceImpl.java +++ b/src/test/java/ognl/test/objects/GenericServiceImpl.java @@ -1,5 +1,6 @@ -package org.ognl.test.objects; +package ognl.test.objects; +import ognl.OgnlRuntime; import ognl.security.OgnlSecurityManagerFactory; import java.io.IOException; @@ -7,24 +8,24 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.security.*; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.security.SecureRandom; import java.util.List; -import ognl.OgnlRuntime; /** * */ public class GenericServiceImpl implements GenericService { - public String getFullMessageFor(GameGenericObject game, Object... arguments) - { + public String getFullMessageFor(GameGenericObject game, Object... arguments) { game.getHappy(); - + return game.getDisplayName(); } - public String getFullMessageFor(PersonGenericObject person, Object... arguments) - { + public String getFullMessageFor(PersonGenericObject person, Object... arguments) { return person.getDisplayName(); } @@ -57,7 +58,7 @@ public void disableSandboxViaReflectionByField() throws IllegalAccessException, List residents = (List) residentsField.get(ognlSecurityManager); Object[] residentsTokens = residents.toArray(); for (Object token : residentsTokens - ) { + ) { ognlSecurityManager.getClass().getMethod("leave", long.class).invoke(ognlSecurityManager, token); } } diff --git a/src/test/java/ognl/test/objects/GetterMethods.java b/src/test/java/ognl/test/objects/GetterMethods.java new file mode 100644 index 00000000..6f15fd37 --- /dev/null +++ b/src/test/java/ognl/test/objects/GetterMethods.java @@ -0,0 +1,21 @@ +package ognl.test.objects; + +/** + * + */ +public class GetterMethods { + + private int theInt = 1; + + public boolean isAllowDisplay(Object something) { + return true; + } + + public int getAllowDisplay() { + return theInt; + } + + public void setAllowDisplay(int val) { + theInt = val; + } +} diff --git a/src/test/java/org/ognl/test/objects/IComponent.java b/src/test/java/ognl/test/objects/IComponent.java similarity index 83% rename from src/test/java/org/ognl/test/objects/IComponent.java rename to src/test/java/ognl/test/objects/IComponent.java index d89be464..0db0d7d9 100644 --- a/src/test/java/org/ognl/test/objects/IComponent.java +++ b/src/test/java/ognl/test/objects/IComponent.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * @@ -10,6 +10,6 @@ public interface IComponent { void setClientId(String id); int getCount(String index); - + void setCount(String index, int count); } diff --git a/src/test/java/org/ognl/test/objects/IContentProvider.java b/src/test/java/ognl/test/objects/IContentProvider.java similarity index 77% rename from src/test/java/org/ognl/test/objects/IContentProvider.java rename to src/test/java/ognl/test/objects/IContentProvider.java index ff8a9947..00a3e3a4 100644 --- a/src/test/java/org/ognl/test/objects/IContentProvider.java +++ b/src/test/java/ognl/test/objects/IContentProvider.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.List; diff --git a/src/test/java/org/ognl/test/objects/IForm.java b/src/test/java/ognl/test/objects/IForm.java similarity index 61% rename from src/test/java/org/ognl/test/objects/IForm.java rename to src/test/java/ognl/test/objects/IForm.java index 92bba4ea..8253f5b3 100644 --- a/src/test/java/org/ognl/test/objects/IForm.java +++ b/src/test/java/ognl/test/objects/IForm.java @@ -1,8 +1,8 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public interface IForm extends IComponent { - + } diff --git a/src/test/java/org/ognl/test/objects/IFormComponent.java b/src/test/java/ognl/test/objects/IFormComponent.java similarity index 77% rename from src/test/java/org/ognl/test/objects/IFormComponent.java rename to src/test/java/ognl/test/objects/IFormComponent.java index b2f2e5c0..91003760 100644 --- a/src/test/java/org/ognl/test/objects/IFormComponent.java +++ b/src/test/java/ognl/test/objects/IFormComponent.java @@ -1,13 +1,13 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public interface IFormComponent extends IComponent { - + String getClientId(); IForm getForm(); - + void setForm(IForm form); } diff --git a/src/test/java/org/ognl/test/objects/ITreeContentProvider.java b/src/test/java/ognl/test/objects/ITreeContentProvider.java similarity index 87% rename from src/test/java/org/ognl/test/objects/ITreeContentProvider.java rename to src/test/java/ognl/test/objects/ITreeContentProvider.java index 682a5e61..d8d44479 100644 --- a/src/test/java/org/ognl/test/objects/ITreeContentProvider.java +++ b/src/test/java/ognl/test/objects/ITreeContentProvider.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.Collection; diff --git a/src/test/java/ognl/test/objects/Indexed.java b/src/test/java/ognl/test/objects/Indexed.java new file mode 100644 index 00000000..9ab46372 --- /dev/null +++ b/src/test/java/ognl/test/objects/Indexed.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Indexed extends BaseIndexed { + private String[] _values = new String[]{"foo", "bar", "baz"}; + + private List _list = new ArrayList(); + private ListSource _source = new ListSourceImpl(); + + private Map _props = new HashMap(); + + public Indexed() { + _list.add(new Integer(1)); + _list.add(new Integer(2)); + _list.add(new Integer(3)); + + _source.addValue(new Bean2()); + } + + public Indexed(String[] values) { + _values = values; + } + + /* Indexed property "_values" */ + public String[] getValues() { + return _values; + } + + public void setValues(String[] value) { + _values = value; + } + + /** + * This method returns the string from the array and appends "xxx" to + * distinguish the "get" method from the direct array access. + */ + public String getValues(int index) { + return _values[index] + "xxx"; + } + + public void setValues(int index, String value) { + if (value.endsWith("xxx")) { + _values[index] = value.substring(0, value.length() - 3); + } else { + _values[index] = value; + } + } + + public Collection getList() { + return _list; + } + + public String getTitle(int count) { + return "Title count " + count; + } + + public ListSource getSource() { + return _source; + } + + public void setProperty(String property, Object value) { + _props.put(property, value); + } + + public Object getProperty(String property) { + return _props.get(property); + } +} diff --git a/src/test/java/org/ognl/test/objects/IndexedMapObject.java b/src/test/java/ognl/test/objects/IndexedMapObject.java similarity index 75% rename from src/test/java/org/ognl/test/objects/IndexedMapObject.java rename to src/test/java/ognl/test/objects/IndexedMapObject.java index 523ea04e..03ea721a 100644 --- a/src/test/java/org/ognl/test/objects/IndexedMapObject.java +++ b/src/test/java/ognl/test/objects/IndexedMapObject.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * Simple object used to test indexed map references using "#this" references. @@ -7,8 +7,7 @@ public class IndexedMapObject { String property; - public IndexedMapObject(String property) - { + public IndexedMapObject(String property) { this.property = property; } diff --git a/src/test/java/org/ognl/test/objects/IndexedSetObject.java b/src/test/java/ognl/test/objects/IndexedSetObject.java similarity index 56% rename from src/test/java/org/ognl/test/objects/IndexedSetObject.java rename to src/test/java/ognl/test/objects/IndexedSetObject.java index 11aa8b8c..c22f0243 100644 --- a/src/test/java/org/ognl/test/objects/IndexedSetObject.java +++ b/src/test/java/ognl/test/objects/IndexedSetObject.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.HashMap; @@ -7,7 +7,7 @@ */ public class IndexedSetObject { - private final HashMap things = new HashMap(); + private final HashMap things = new HashMap(); public IndexedSetObject() { things.put("x", new Container(1)); @@ -23,8 +23,17 @@ public void setThing(String index, Object value) { public static class Container { private int val; - public Container(int val) { this.val = val; } - public int getVal() { return val; } - public void setVal(int val) { this.val = val; } + + public Container(int val) { + this.val = val; + } + + public int getVal() { + return val; + } + + public void setVal(int val) { + this.val = val; + } } } diff --git a/src/test/java/org/ognl/test/objects/Inherited.java b/src/test/java/ognl/test/objects/Inherited.java similarity index 69% rename from src/test/java/org/ognl/test/objects/Inherited.java rename to src/test/java/ognl/test/objects/Inherited.java index 69946278..e23c0c98 100644 --- a/src/test/java/org/ognl/test/objects/Inherited.java +++ b/src/test/java/ognl/test/objects/Inherited.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * diff --git a/src/test/java/org/ognl/test/objects/ListSource.java b/src/test/java/ognl/test/objects/ListSource.java similarity index 82% rename from src/test/java/org/ognl/test/objects/ListSource.java rename to src/test/java/ognl/test/objects/ListSource.java index f4e1deea..8b775c54 100644 --- a/src/test/java/org/ognl/test/objects/ListSource.java +++ b/src/test/java/ognl/test/objects/ListSource.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * diff --git a/src/test/java/org/ognl/test/objects/ListSourceImpl.java b/src/test/java/ognl/test/objects/ListSourceImpl.java similarity index 55% rename from src/test/java/org/ognl/test/objects/ListSourceImpl.java rename to src/test/java/ognl/test/objects/ListSourceImpl.java index 8892bf00..a46e0921 100644 --- a/src/test/java/org/ognl/test/objects/ListSourceImpl.java +++ b/src/test/java/ognl/test/objects/ListSourceImpl.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.ArrayList; @@ -7,22 +7,18 @@ */ public class ListSourceImpl extends ArrayList implements ListSource { - public ListSourceImpl() - { + public ListSourceImpl() { } - public int getTotal() - { + public int getTotal() { return super.size(); } - public Object addValue(Object value) - { + public Object addValue(Object value) { return super.add(value); } - public Object getName() - { + public Object getName() { return null; } } diff --git a/src/test/java/ognl/test/objects/MenuItem.java b/src/test/java/ognl/test/objects/MenuItem.java new file mode 100644 index 00000000..11500e39 --- /dev/null +++ b/src/test/java/ognl/test/objects/MenuItem.java @@ -0,0 +1,45 @@ +package ognl.test.objects; + +import java.util.ArrayList; +import java.util.List; + +/** + * + */ +public class MenuItem { + + private String page; + private String label; + private List children = new ArrayList(); + + public MenuItem(String page, String label) { + this(page, label, new ArrayList()); + } + + public MenuItem(String page, String label, List children) { + this.page = page; + this.label = label; + this.children = children; + } + + public List getChildren() { + return children; + } + + public String getLabel() { + return label; + } + + public String getPage() { + return page; + } + + public String toString() { + StringBuffer sb = new StringBuffer("MenuItem["); + sb.append("page=" + getPage()); + sb.append(",label=" + getLabel()); + sb.append(",children=" + getChildren().size()); + sb.append("]"); + return sb.toString(); + } +} diff --git a/src/test/java/org/ognl/test/objects/Messages.java b/src/test/java/ognl/test/objects/Messages.java similarity index 53% rename from src/test/java/org/ognl/test/objects/Messages.java rename to src/test/java/ognl/test/objects/Messages.java index 62af597f..1db058ba 100644 --- a/src/test/java/org/ognl/test/objects/Messages.java +++ b/src/test/java/ognl/test/objects/Messages.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.Map; @@ -9,33 +9,27 @@ public class Messages { Map _source; - public Messages(Map source) - { + public Messages(Map source) { _source = source; } - - public String getMessage(String key) - { - return (String)_source.get(key); + + public String getMessage(String key) { + return (String) _source.get(key); } - public String format(String key, Object[] parms) - { + public String format(String key, Object[] parms) { return "foo"; } - public String format(String key, Object param1, Object param2, Object param3) - { + public String format(String key, Object param1, Object param2, Object param3) { return "blah"; } - public String format(String key, Object param1) - { + public String format(String key, Object param1) { return "first"; } - public String format(String key, Object param1, Object param2) - { + public String format(String key, Object param1, Object param2) { return "haha"; } } diff --git a/src/test/java/org/ognl/test/objects/MethodTestMethods.java b/src/test/java/ognl/test/objects/MethodTestMethods.java similarity index 81% rename from src/test/java/org/ognl/test/objects/MethodTestMethods.java rename to src/test/java/ognl/test/objects/MethodTestMethods.java index d814140b..3500d8c5 100644 --- a/src/test/java/org/ognl/test/objects/MethodTestMethods.java +++ b/src/test/java/ognl/test/objects/MethodTestMethods.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.Arrays; import java.util.List; @@ -10,19 +10,19 @@ public class MethodTestMethods { //--------------------------------------------------------------------- public Object getBean(String name) { - return "NamedBean: "+name; + return "NamedBean: " + name; } public T getBean(String name, Class requiredType) { - return (T) ("NamedTypedBean: "+name+" "+requiredType.getSimpleName()); + return (T) ("NamedTypedBean: " + name + " " + requiredType.getSimpleName()); } public T getBean(Class requiredType) { - return (T) ("TypedBean: "+requiredType.getSimpleName()); + return (T) ("TypedBean: " + requiredType.getSimpleName()); } public Object getBean(String name, Object... args) { - return "NamedBeanWithArgs: "+name+" "+Arrays.toString(args); + return "NamedBeanWithArgs: " + name + " " + Arrays.toString(args); } //--------------------------------------------------------------------- @@ -30,7 +30,7 @@ public Object getBean(String name, Object... args) { //--------------------------------------------------------------------- private String testProperty = "Hello World!"; - + public String testProperty() { return testProperty; } @@ -41,19 +41,19 @@ public String testProperty() { //--------------------------------------------------------------------- public String argsTest1(Object[] data) { - return "Array: "+Arrays.toString(data); + return "Array: " + Arrays.toString(data); } public String argsTest2(List data) { - return "List: "+data; + return "List: " + data; } public String argsTest3(Object[] data) { - return "Array: "+Arrays.toString(data); + return "Array: " + Arrays.toString(data); } public String argsTest3(List data) { - return "List: "+data; + return "List: " + data; } //--------------------------------------------------------------------- @@ -67,7 +67,7 @@ public double avg(final Iterable target) { total += element.doubleValue(); size++; } - return total/size; + return total / size; } public double avg(final Number[] target) { @@ -75,7 +75,7 @@ public double avg(final Number[] target) { for (final Number element : target) { total += element.doubleValue(); } - return total/target.length; + return total / target.length; } public double avg(final byte[] target) { @@ -83,7 +83,7 @@ public double avg(final byte[] target) { for (final Number element : target) { total += element.doubleValue(); } - return total/target.length; + return total / target.length; } public double avg(final short[] target) { @@ -91,7 +91,7 @@ public double avg(final short[] target) { for (final Number element : target) { total += element.doubleValue(); } - return total/target.length; + return total / target.length; } public double avg(final int[] target) { @@ -99,7 +99,7 @@ public double avg(final int[] target) { for (final Number element : target) { total += element.doubleValue(); } - return total/target.length; + return total / target.length; } public double avg(final long[] target) { @@ -107,7 +107,7 @@ public double avg(final long[] target) { for (final Number element : target) { total += element.doubleValue(); } - return total/target.length; + return total / target.length; } public double avg(final float[] target) { @@ -115,7 +115,7 @@ public double avg(final float[] target) { for (final Number element : target) { total += element.doubleValue(); } - return total/target.length; + return total / target.length; } public double avg(final double[] target) { @@ -123,11 +123,11 @@ public double avg(final double[] target) { for (final Number element : target) { total += element.doubleValue(); } - return total/target.length; + return total / target.length; } public String[] getStringArray() { - return new String[] { "Hello", "World" }; + return new String[]{"Hello", "World"}; } public List getStringList() { @@ -135,7 +135,7 @@ public List getStringList() { } public List getObjectList() { - return Arrays.asList((Object)"Object"); + return Arrays.asList((Object) "Object"); } public String showList(String[] args) { diff --git a/src/test/java/ognl/test/objects/Model.java b/src/test/java/ognl/test/objects/Model.java new file mode 100644 index 00000000..5c0fce3a --- /dev/null +++ b/src/test/java/ognl/test/objects/Model.java @@ -0,0 +1,11 @@ +package ognl.test.objects; + +/** + * + */ +public class Model { + + public int getOptionCount() { + return 1; + } +} diff --git a/src/test/java/ognl/test/objects/MyMap.java b/src/test/java/ognl/test/objects/MyMap.java new file mode 100644 index 00000000..9b760e7f --- /dev/null +++ b/src/test/java/ognl/test/objects/MyMap.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +import java.util.Map; + +/** + * This tests the interface inheritence test. This is a subinterface + * of Map and therefore should inherit the Map property accessor. + */ +public interface MyMap extends Map { + public String getDescription(); +} diff --git a/src/test/java/ognl/test/objects/MyMapImpl.java b/src/test/java/ognl/test/objects/MyMapImpl.java new file mode 100644 index 00000000..97839ba0 --- /dev/null +++ b/src/test/java/ognl/test/objects/MyMapImpl.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * This tests the interface inheritence test. This test implements + * MyMap->Map but extends Object, therefore should be coded using + * MapPropertyAccessor instead of ObjectPropertyAccessor. + */ +public class MyMapImpl extends Object implements MyMap { + private Map map = new HashMap(); + + public void clear() { + map.clear(); + } + + public boolean containsKey(Object key) { + return map.containsKey(key); + } + + public boolean containsValue(Object value) { + return map.containsValue(value); + } + + public Set entrySet() { + return map.entrySet(); + } + + public boolean equals(Object o) { + return map.equals(o); + } + + public Object get(Object key) { + return map.get(key); + } + + public int hashCode() { + return map.hashCode(); + } + + public boolean isEmpty() { + return map.isEmpty(); + } + + public Set keySet() { + return map.keySet(); + } + + public Object put(Object key, Object value) { + return map.put(key, value); + } + + public void putAll(Map t) { + map.putAll(t); + } + + public Object remove(Object key) { + return map.remove(key); + } + + public int size() { + return map.size(); + } + + public Collection values() { + return map.values(); + } + + public String getDescription() { + return "MyMap implementation"; + } +} diff --git a/src/test/java/ognl/test/objects/ObjectIndexed.java b/src/test/java/ognl/test/objects/ObjectIndexed.java new file mode 100644 index 00000000..ef1819c6 --- /dev/null +++ b/src/test/java/ognl/test/objects/ObjectIndexed.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +public class ObjectIndexed extends BaseObjectIndexed { + public ObjectIndexed() { + super(); + setAttribute("foo", "bar"); + setAttribute("bar", "baz"); + setAttribute("other", new OtherObjectIndexed()); + } +} diff --git a/src/test/java/org/ognl/test/objects/OtherEnum.java b/src/test/java/ognl/test/objects/OtherEnum.java similarity index 61% rename from src/test/java/org/ognl/test/objects/OtherEnum.java rename to src/test/java/ognl/test/objects/OtherEnum.java index 416a68e4..e9bebb23 100644 --- a/src/test/java/org/ognl/test/objects/OtherEnum.java +++ b/src/test/java/ognl/test/objects/OtherEnum.java @@ -1,23 +1,21 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public enum OtherEnum { - ONE (1); + ONE(1); public static final String STATIC_STRING = "string"; private int _value; - private OtherEnum(int value) - { + private OtherEnum(int value) { _value = value; } - public int getValue() - { + public int getValue() { return _value; } } diff --git a/src/test/java/ognl/test/objects/OtherObjectIndexed.java b/src/test/java/ognl/test/objects/OtherObjectIndexed.java new file mode 100644 index 00000000..f0588d11 --- /dev/null +++ b/src/test/java/ognl/test/objects/OtherObjectIndexed.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +public class OtherObjectIndexed extends BaseObjectIndexed { + public OtherObjectIndexed() { + super(); + setAttribute("foo", "bar"); + setAttribute("bar", "baz"); + } +} diff --git a/src/test/java/org/ognl/test/objects/PersonGenericObject.java b/src/test/java/ognl/test/objects/PersonGenericObject.java similarity index 57% rename from src/test/java/org/ognl/test/objects/PersonGenericObject.java rename to src/test/java/ognl/test/objects/PersonGenericObject.java index ba0534dc..be569cdc 100644 --- a/src/test/java/org/ognl/test/objects/PersonGenericObject.java +++ b/src/test/java/ognl/test/objects/PersonGenericObject.java @@ -1,17 +1,15 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public class PersonGenericObject implements GenericObject { - public int getId() - { + public int getId() { return 1; } - public String getDisplayName() - { + public String getDisplayName() { return "Henry Collins"; } } diff --git a/src/test/java/org/ognl/test/objects/PropertyHolder.java b/src/test/java/ognl/test/objects/PropertyHolder.java similarity index 57% rename from src/test/java/org/ognl/test/objects/PropertyHolder.java rename to src/test/java/ognl/test/objects/PropertyHolder.java index a3e21dfb..051e440d 100644 --- a/src/test/java/org/ognl/test/objects/PropertyHolder.java +++ b/src/test/java/ognl/test/objects/PropertyHolder.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * Simple class used to test various kind of property resolutions. @@ -8,32 +8,26 @@ public class PropertyHolder { String _value = ""; String _search = "foo"; - public String getValue() - { + public String getValue() { return _value; } - public void setValue(String value) - { + public void setValue(String value) { _value = value; } - - public boolean hasValue() - { + + public boolean hasValue() { return _value != null && _value.length() > 0; } - public void setSearch(String value) - { + public void setSearch(String value) { _search = value; } - public String getSearch() - { + public String getSearch() { return _search; } - public void search() - { + public void search() { } } diff --git a/src/test/java/ognl/test/objects/Root.java b/src/test/java/ognl/test/objects/Root.java new file mode 100644 index 00000000..50738fa9 --- /dev/null +++ b/src/test/java/ognl/test/objects/Root.java @@ -0,0 +1,469 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +import ognl.DynamicSubscript; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +public class Root extends Object { + public static final String SIZE_STRING = "size"; + public static final int STATIC_INT = 23; + + private int[] array = {1, 2, 3, 4}; + private Map map = new HashMap(23); + private MyMap myMap = new MyMapImpl(); + private List list = Arrays.asList(new Object[]{null, this, array}); + private List settableList = new ArrayList(Arrays.asList(new Object[]{"foo", "bar", "baz"})); + private int index = 1; + private int intValue = 0; + private String stringValue; + private int yetAnotherIntValue = 46; + private boolean privateAccessorBooleanValue = true; + private int privateAccessorIntValue = 67; + private int privateAccessorIntValue2 = 67; + private int privateAccessorIntValue3 = 67; + public String anotherStringValue = "foo"; + public int anotherIntValue = 123; + public int six = 6; + private boolean _disabled; + private Locale _selected = Locale.getDefault(); + private List> _booleanValues = new ArrayList>(); + + private boolean[] _booleanArray = {true, false, true, true}; + private List _list; + private int verbosity = 87; + private BeanProvider _beanProvider = new BeanProviderImpl(); + private boolean _render; + private Boolean _readOnly = Boolean.FALSE; + private Integer _objIndex = new Integer(1); + private Object _genericObjIndex = new Integer(2); + private Date _date = new Date(); + private boolean _openWindow = false; + + private ITreeContentProvider _contentProvider = new TreeContentProvider(); + private Indexed _indexed = new Indexed(); + private SearchTab _tab = new SearchTab(); + + /*=================================================================== + Public static methods + ===================================================================*/ + public static int getStaticInt() { + return STATIC_INT; + } + + /*=================================================================== + Constructors + ===================================================================*/ + public Root() { + super(); + } + + /*=================================================================== + Private methods + ===================================================================*/ { + map.put("test", this); + map.put("array", array); + map.put("list", list); + map.put("size", new Integer(5000)); + map.put(DynamicSubscript.first, new Integer(99)); + map.put("baz", array); + map.put("value", new Bean2()); + map.put("bar", new Bean3()); + map.put(new Long(82), "StringStuff=someValue"); + + IFormComponent comp = new FormComponentImpl(); + comp.setClientId("formComponent"); + + IForm form = new FormImpl(); + form.setClientId("form1"); + comp.setForm(form); + + map.put("comp", comp); + + Map newMap = new HashMap(); + Map chain = new HashMap(); + newMap.put("deep", chain); + + chain.put("last", Boolean.TRUE); + + map.put("nested", newMap); + + /* make myMap identical */ + myMap.putAll(map); + + List bool1 = new ArrayList(); + bool1.add(Boolean.TRUE); + bool1.add(Boolean.FALSE); + bool1.add(Boolean.TRUE); + + _booleanValues.add(bool1); + + List bool2 = new ArrayList(); + bool2.add(Boolean.TRUE); + bool2.add(Boolean.FALSE); + bool2.add(Boolean.TRUE); + + _booleanValues.add(bool2); + } + + private boolean isPrivateAccessorBooleanValue() { + return privateAccessorBooleanValue; + } + + private void setPrivateAccessorBooleanValue(boolean value) { + privateAccessorBooleanValue = value; + } + + private int getPrivateAccessorIntValue() { + return privateAccessorIntValue; + } + + private void setPrivateAccessorIntValue(int value) { + privateAccessorIntValue = value; + } + + /*=================================================================== + Protected methods + ===================================================================*/ + protected int getPrivateAccessorIntValue2() { + return privateAccessorIntValue2; + } + + protected void setPrivateAccessorIntValue2(int value) { + privateAccessorIntValue2 = value; + } + + /*=================================================================== + Package protected methods + ===================================================================*/ + int getPrivateAccessorIntValue3() { + return privateAccessorIntValue3; + } + + void setPrivateAccessorIntValue3(int value) { + privateAccessorIntValue3 = value; + } + + /*=================================================================== + Public methods + ===================================================================*/ + public int[] getArray() { + return array; + } + + public boolean[] getBooleanArray() { + return _booleanArray; + } + + public void setArray(int[] value) { + array = value; + } + + public String format(String key, Object value) { + return format(key, new Object[]{value}); + } + + public String format(String key, Object[] value) { + return "formatted: " + key + " " + Arrays.toString(value); + } + + public String getCurrentClass(String value) { + return value + " stop"; + } + + public Messages getMessages() { + return new Messages(map); + } + + public Map getMap() { + return map; + } + + public MyMap getMyMap() { + return myMap; + } + + public List getList() { + return list; + } + + public Object getAsset(String key) { + return key; + } + + public List getSettableList() { + return settableList; + } + + public int getIndex() { + return index; + } + + public Integer getObjectIndex() { + return _objIndex; + } + + public Integer getNullIndex() { + return null; + } + + public Object getGenericIndex() { + return _genericObjIndex; + } + + public int getIntValue() { + return intValue; + } + + public void setIntValue(int value) { + intValue = value; + } + + public int getTheInt() { + return six; + } + + public String getStringValue() { + return stringValue; + } + + public void setStringValue(String value) { + stringValue = value; + } + + public String getIndexedStringValue() { + return "array"; + } + + public Object getNullObject() { + return null; + } + + public String getTestString() { + return "wiggle"; + } + + public Object getProperty() { + return new Bean2(); + } + + public Bean2 getBean2() { + return new Bean2(); + } + + public Object getIndexedProperty(String name) { + return myMap.get(name); + } + + public Indexed getIndexer() { + return _indexed; + } + + public BeanProvider getBeans() { + return _beanProvider; + } + + public boolean getBooleanValue() { + return _disabled; + } + + public void setBooleanValue(boolean value) { + _disabled = value; + } + + public boolean getDisabled() { + return _disabled; + } + + public void setDisabled(boolean disabled) { + _disabled = disabled; + } + + public Locale getSelected() { + return _selected; + } + + public void setSelected(Locale locale) { + _selected = locale; + } + + public Locale getCurrLocale() { + return Locale.getDefault(); + } + + public int getCurrentLocaleVerbosity() { + return verbosity; + } + + public boolean getRenderNavigation() { + return _render; + } + + public void setSelectedList(List selected) { + _list = selected; + } + + public List getSelectedList() { + return _list; + } + + public Boolean getReadonly() { + return _readOnly; + } + + public void setReadonly(Boolean value) { + _readOnly = value; + } + + public Object getSelf() { + return this; + } + + public Date getTestDate() { + return _date; + } + + public String getWidth() { + return "238px"; + } + + public Long getTheLong() { + return new Long(4); + } + + public boolean isSorted() { + return true; + } + + public TestClass getMyTest() { + return new TestImpl(); + } + + public ITreeContentProvider getContentProvider() { + return _contentProvider; + } + + public boolean isPrintDelivery() { + return true; + } + + public Long getCurrentDeliveryId() { + return 1l; + } + + public Boolean isFlyingMonkey() { + return Boolean.TRUE; + } + + public Boolean isDumb() { + return Boolean.FALSE; + } + + public Date getExpiration() { + return null; + } + + public Long getMapKey() { + return new Long(82); + } + + public Object getArrayValue() { + return new Object[]{new Integer("2"), new Integer("2")}; + } + + public List getResult() { + List list = new ArrayList(); + list.add(new Object[]{new Integer("2"), new Integer("2")}); + list.add(new Object[]{new Integer("2"), new Integer("2")}); + list.add(new Object[]{new Integer("2"), new Integer("2")}); + + return list; + } + + public boolean isEditorDisabled() { + return false; + } + + public boolean isDisabled() { + return true; + } + + public boolean isOpenTransitionWin() { + return _openWindow; + } + + public void setOpenTransitionWin(boolean value) { + _openWindow = value; + } + + public boolean isOk(SimpleEnum value, String otherValue) { + return true; + } + + public List> getBooleanValues() { + return _booleanValues; + } + + public int getIndex1() { + return 1; + } + + public int getIndex2() { + return 1; + } + + public SearchTab getTab() { + return _tab; + } + + public void setTab(SearchTab tab) { + _tab = tab; + } + + public static class A { + public int methodOfA(B b) { + return 0; + } + + public int getIntValue() { + return 1; + } + } + + public static class B { + public int methodOfB(int i) { + return 0; + } + } + + public A getA() { + return new A(); + } + + public B getB() { + return new B(); + } +} diff --git a/src/test/java/org/ognl/test/objects/SearchCriteria.java b/src/test/java/ognl/test/objects/SearchCriteria.java similarity index 57% rename from src/test/java/org/ognl/test/objects/SearchCriteria.java rename to src/test/java/ognl/test/objects/SearchCriteria.java index a6434f36..bc2e91b3 100644 --- a/src/test/java/org/ognl/test/objects/SearchCriteria.java +++ b/src/test/java/ognl/test/objects/SearchCriteria.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * Test for OGNL-131. @@ -7,13 +7,11 @@ public class SearchCriteria { String _displayName; - public SearchCriteria(String name) - { + public SearchCriteria(String name) { _displayName = name; } - public String getDisplayName() - { + public String getDisplayName() { return _displayName; } } diff --git a/src/test/java/org/ognl/test/objects/SearchTab.java b/src/test/java/ognl/test/objects/SearchTab.java similarity index 85% rename from src/test/java/org/ognl/test/objects/SearchTab.java rename to src/test/java/ognl/test/objects/SearchTab.java index c959a412..3e226920 100644 --- a/src/test/java/org/ognl/test/objects/SearchTab.java +++ b/src/test/java/ognl/test/objects/SearchTab.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.ArrayList; import java.util.Arrays; @@ -13,32 +13,35 @@ public class SearchTab { * Flags stating which search criteria are selected */ private List> searchCriteriaSelections = new ArrayList>(); + { - searchCriteriaSelections.add(Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.FALSE)); - searchCriteriaSelections.add(Arrays.asList(Boolean.FALSE, Boolean.TRUE, Boolean.TRUE)); + searchCriteriaSelections.add(Arrays.asList(Boolean.TRUE, Boolean.FALSE, Boolean.FALSE)); + searchCriteriaSelections.add(Arrays.asList(Boolean.FALSE, Boolean.TRUE, Boolean.TRUE)); } - public List> getSearchCriteriaSelections(){ + public List> getSearchCriteriaSelections() { return this.searchCriteriaSelections; } - public void setSearchCriteriaSelections(List> selections){ + + public void setSearchCriteriaSelections(List> selections) { this.searchCriteriaSelections = selections; } - + /** * Filters that can be applied to this tabs searches */ private List searchCriteria = new ArrayList(); + { searchCriteria.add(new SearchCriteria("Crittery critters")); searchCriteria.add(new SearchCriteria("Woodland creatures")); } - public List getSearchCriteria(){ + public List getSearchCriteria() { return this.searchCriteria; } - public void setSearchCriteria(List searchCriteria){ + public void setSearchCriteria(List searchCriteria) { this.searchCriteria = searchCriteria; } @@ -52,7 +55,7 @@ public List> getSearchCriteriaOptions() { } public void setSearchCriteriaOptions(List> searchCriteriaOptions) { - + this.searchCriteriaOptions = searchCriteriaOptions; } } diff --git a/src/test/java/ognl/test/objects/SecondBean.java b/src/test/java/ognl/test/objects/SecondBean.java new file mode 100644 index 00000000..15e046f9 --- /dev/null +++ b/src/test/java/ognl/test/objects/SecondBean.java @@ -0,0 +1,15 @@ +/** + * + */ +package ognl.test.objects; + + +/** + * + */ +public class SecondBean extends BaseBean { + public String getName() { + return "SecondBean"; + } + +} diff --git a/src/test/java/org/ognl/test/objects/SetterReturns.java b/src/test/java/ognl/test/objects/SetterReturns.java similarity index 56% rename from src/test/java/org/ognl/test/objects/SetterReturns.java rename to src/test/java/ognl/test/objects/SetterReturns.java index 54cd5e06..f9ecd0cb 100644 --- a/src/test/java/org/ognl/test/objects/SetterReturns.java +++ b/src/test/java/ognl/test/objects/SetterReturns.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * @@ -7,13 +7,11 @@ public class SetterReturns { private String _value = ""; - public String getValue() - { + public String getValue() { return _value; } - public SetterReturns setValue(String value) - { + public SetterReturns setValue(String value) { _value += value; return this; } diff --git a/src/test/java/ognl/test/objects/Simple.java b/src/test/java/ognl/test/objects/Simple.java new file mode 100644 index 00000000..c9abbe2e --- /dev/null +++ b/src/test/java/ognl/test/objects/Simple.java @@ -0,0 +1,230 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.objects; + +import ognl.test.OgnlTestCase; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + +public class Simple extends Object { + private String stringValue = "test"; + private float floatValue; + private int intValue; + private boolean booleanValue; + private BigInteger bigIntValue = BigInteger.valueOf(0); + private BigDecimal bigDecValue = new BigDecimal(0.0); + + private Root root = new Root(); + + private Bean3 _bean; + private Bean2 _bean2; + + private Object[] _array; + + private Messages _messages; + + public Simple() { + Map src = new HashMap(); + src.put("test", "This is a test"); + + _messages = new Messages(src); + } + + public Simple(Bean3 bean) { + _bean = bean; + } + + public Simple(Bean2 bean) { + _bean2 = bean; + } + + public Simple(Object[] values) { + super(); + } + + public Simple(String stringValue, float floatValue, int intValue) { + super(); + this.stringValue = stringValue; + this.floatValue = floatValue; + this.intValue = intValue; + } + + public void setValues(String stringValue, float floatValue, int intValue) { + this.stringValue = stringValue; + this.floatValue = floatValue; + this.intValue = intValue; + } + + public String getStringValue() { + return stringValue; + } + + public void setStringValue(String value) { + stringValue = value; + } + + public float getFloatValue() { + return floatValue; + } + + public void setFloatValue(float value) { + floatValue = value; + } + + public int getIntValue() { + return intValue; + } + + public void setIntValue(int value) { + intValue = value; + } + + public boolean getValueIsTrue(Object currValue) { + return true; + } + + public boolean getBooleanValue() { + return booleanValue; + } + + public void setBooleanValue(boolean value) { + booleanValue = value; + } + + public BigInteger getBigIntValue() { + return bigIntValue; + } + + public void setArray(Object[] values) { + _array = values; + } + + public Object[] getArray() { + return _array; + } + + public void setBigIntValue(BigInteger value) { + bigIntValue = value; + } + + public BigDecimal getBigDecValue() { + return bigDecValue; + } + + public void setBigDecValue(BigDecimal value) { + bigDecValue = value; + } + + public Root getRootValue() { + return root; + } + + public MethodTestMethods getTestMethods() { + return new MethodTestMethods(); + } + + public Messages getMessages() { + return _messages; + } + + public int getOne() { + return 1; + } + + public int getTwo() { + return 2; + } + + public int getThree() { + return 3; + } + + public int getTestValue(int val) { + return val + 1; + } + + public boolean isEditorDisabled() { + return false; + } + + public boolean isDisabled() { + return true; + } + + public boolean getIsTruck() { + return true; + } + + public GetterMethods getMethodsTest() { + return new GetterMethods(); + } + + public String getDisplayValue(int val) { + return "test"; + } + + public boolean equals(Object other) { + boolean result = false; + + if (other instanceof Simple) { + Simple os = (Simple) other; + + result = OgnlTestCase.isEqual(os.getStringValue(), getStringValue()) && (os.getIntValue() == getIntValue()); + } + return result; + } + + public boolean isThisVarArgsWorking(Object... arguments) { + return true; + } + + public String isNullVarArgs() { + return "null"; + } + + public String isStringVarArgs(String... arguments) { + return "args"; + } + + public TestInterface get() { + return new TestInterface() { + @Override + public String request() { + return "null"; + } + + @Override + public String request(Object... args) { + return "args"; + } + }; + } + + interface TestInterface { + + String request(); + + String request(Object... args); + + } + +} diff --git a/src/test/java/org/ognl/test/objects/SimpleEnum.java b/src/test/java/ognl/test/objects/SimpleEnum.java similarity index 52% rename from src/test/java/org/ognl/test/objects/SimpleEnum.java rename to src/test/java/ognl/test/objects/SimpleEnum.java index 801df796..c2aa1c39 100644 --- a/src/test/java/org/ognl/test/objects/SimpleEnum.java +++ b/src/test/java/ognl/test/objects/SimpleEnum.java @@ -1,21 +1,19 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public enum SimpleEnum { - ONE (1); + ONE(1); private int _value; - private SimpleEnum(int value) - { + private SimpleEnum(int value) { _value = value; } - public int getValue() - { + public int getValue() { return _value; } } diff --git a/src/test/java/ognl/test/objects/SimpleNumeric.java b/src/test/java/ognl/test/objects/SimpleNumeric.java new file mode 100644 index 00000000..2c47d3f2 --- /dev/null +++ b/src/test/java/ognl/test/objects/SimpleNumeric.java @@ -0,0 +1,19 @@ +package ognl.test.objects; + +/** + * Used for {@link ognl.test.PropertyArithmeticAndLogicalOperatorsTest}. + */ +public class SimpleNumeric { + + public double getBudget() { + return 140; + } + + public double getTimeBilled() { + return 24.12; + } + + public String getTableSize() { + return "10"; + } +} diff --git a/src/test/java/org/ognl/test/objects/SubclassSyntheticObject.java b/src/test/java/ognl/test/objects/SubclassSyntheticObject.java similarity index 70% rename from src/test/java/org/ognl/test/objects/SubclassSyntheticObject.java rename to src/test/java/ognl/test/objects/SubclassSyntheticObject.java index 00498ba3..4da4daa9 100644 --- a/src/test/java/org/ognl/test/objects/SubclassSyntheticObject.java +++ b/src/test/java/ognl/test/objects/SubclassSyntheticObject.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.ArrayList; @@ -7,8 +7,7 @@ */ public class SubclassSyntheticObject extends BaseSyntheticObject { - public ArrayList getList() - { + public ArrayList getList() { return new ArrayList(); } } diff --git a/src/test/java/org/ognl/test/objects/TestClass.java b/src/test/java/ognl/test/objects/TestClass.java similarity index 61% rename from src/test/java/org/ognl/test/objects/TestClass.java rename to src/test/java/ognl/test/objects/TestClass.java index c519dec9..6eb58dc5 100644 --- a/src/test/java/org/ognl/test/objects/TestClass.java +++ b/src/test/java/ognl/test/objects/TestClass.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * diff --git a/src/test/java/org/ognl/test/objects/TestImpl.java b/src/test/java/ognl/test/objects/TestImpl.java similarity index 72% rename from src/test/java/org/ognl/test/objects/TestImpl.java rename to src/test/java/ognl/test/objects/TestImpl.java index 7dfe74de..a2ef427e 100644 --- a/src/test/java/org/ognl/test/objects/TestImpl.java +++ b/src/test/java/ognl/test/objects/TestImpl.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.HashMap; import java.util.Map; @@ -8,8 +8,7 @@ */ public class TestImpl extends TestClass { - public Map getTheMap() - { + public Map getTheMap() { Map map = new HashMap(); map.put("key", "value"); return map; diff --git a/src/test/java/org/ognl/test/objects/TestInherited1.java b/src/test/java/ognl/test/objects/TestInherited1.java similarity index 59% rename from src/test/java/org/ognl/test/objects/TestInherited1.java rename to src/test/java/ognl/test/objects/TestInherited1.java index 4a1f701d..439a8b47 100644 --- a/src/test/java/org/ognl/test/objects/TestInherited1.java +++ b/src/test/java/ognl/test/objects/TestInherited1.java @@ -1,12 +1,11 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public class TestInherited1 implements Inherited { - public String getMyString() - { + public String getMyString() { return "inherited1"; } } diff --git a/src/test/java/org/ognl/test/objects/TestInherited2.java b/src/test/java/ognl/test/objects/TestInherited2.java similarity index 59% rename from src/test/java/org/ognl/test/objects/TestInherited2.java rename to src/test/java/ognl/test/objects/TestInherited2.java index d70c5d45..adf7c249 100644 --- a/src/test/java/org/ognl/test/objects/TestInherited2.java +++ b/src/test/java/ognl/test/objects/TestInherited2.java @@ -1,12 +1,11 @@ -package org.ognl.test.objects; +package ognl.test.objects; /** * */ public class TestInherited2 implements Inherited { - public String getMyString() - { + public String getMyString() { return "inherited2"; } } diff --git a/src/test/java/ognl/test/objects/TestModel.java b/src/test/java/ognl/test/objects/TestModel.java new file mode 100644 index 00000000..73492941 --- /dev/null +++ b/src/test/java/ognl/test/objects/TestModel.java @@ -0,0 +1,23 @@ +package ognl.test.objects; + +/** + * + */ +public class TestModel { + + public Copy getCopy() { + return new Copy(); + } + + public Model getUnassignedCopyModel() { + return new Model(); + } + + public boolean isCanApproveCopy() { + return true; + } + + public Entry getEntry() { + return new Entry(); + } +} diff --git a/src/test/java/org/ognl/test/objects/TreeContentProvider.java b/src/test/java/ognl/test/objects/TreeContentProvider.java similarity index 60% rename from src/test/java/org/ognl/test/objects/TreeContentProvider.java rename to src/test/java/ognl/test/objects/TreeContentProvider.java index 4ea113d9..1a32bd96 100644 --- a/src/test/java/org/ognl/test/objects/TreeContentProvider.java +++ b/src/test/java/ognl/test/objects/TreeContentProvider.java @@ -1,4 +1,4 @@ -package org.ognl.test.objects; +package ognl.test.objects; import java.util.Collection; import java.util.Collections; @@ -10,19 +10,15 @@ public class TreeContentProvider implements ITreeContentProvider { - - public Collection getChildren(Object parentElement) - { + public Collection getChildren(Object parentElement) { return Collections.EMPTY_LIST; } - public boolean hasChildren(Object parentElement) - { + public boolean hasChildren(Object parentElement) { return true; } - public List getElements() - { + public List getElements() { return Collections.EMPTY_LIST; } } diff --git a/src/test/java/ognl/test/objects/Two.java b/src/test/java/ognl/test/objects/Two.java new file mode 100644 index 00000000..8bbc85b7 --- /dev/null +++ b/src/test/java/ognl/test/objects/Two.java @@ -0,0 +1,15 @@ +package ognl.test.objects; + +/** + * + */ +public class Two { + + public String getMessage(String mes) { + return "[" + mes + "]"; + } + + public boolean hasChildren(String name) { + return name.length() > 2; + } +} diff --git a/src/test/java/ognl/race/Base.java b/src/test/java/ognl/test/race/Base.java similarity index 88% rename from src/test/java/ognl/race/Base.java rename to src/test/java/ognl/test/race/Base.java index b8b09db4..522c1496 100644 --- a/src/test/java/ognl/race/Base.java +++ b/src/test/java/ognl/test/race/Base.java @@ -1,10 +1,11 @@ -package ognl.race; +package ognl.test.race; /** * */ public class Base { private Boolean yn = true; + public Boolean getYn() { return yn; } diff --git a/src/test/java/ognl/race/Persion.java b/src/test/java/ognl/test/race/Persion.java similarity index 73% rename from src/test/java/ognl/race/Persion.java rename to src/test/java/ognl/test/race/Persion.java index d96572c5..3e35a41e 100644 --- a/src/test/java/ognl/race/Persion.java +++ b/src/test/java/ognl/test/race/Persion.java @@ -1,6 +1,6 @@ -package ognl.race; +package ognl.test.race; -public class Persion extends Base{ +public class Persion extends Base { private String name = "abc"; diff --git a/src/test/java/ognl/race/RaceTestCase.java b/src/test/java/ognl/test/race/RaceTestCase.java similarity index 77% rename from src/test/java/ognl/race/RaceTestCase.java rename to src/test/java/ognl/test/race/RaceTestCase.java index 2ac790c5..fef6c45b 100644 --- a/src/test/java/ognl/race/RaceTestCase.java +++ b/src/test/java/ognl/test/race/RaceTestCase.java @@ -1,4 +1,4 @@ -package ognl.race; +package ognl.test.race; import ognl.DefaultMemberAccess; @@ -15,7 +15,7 @@ public class RaceTestCase { @Test - public void testOgnlRace(){ + public void testOgnlRace() { int concurrent = 128; final int batchCount = 2000; final CountDownLatch start = new CountDownLatch(1); @@ -23,7 +23,7 @@ public void testOgnlRace(){ final AtomicInteger errCount = new AtomicInteger(0); final Persion persion = new Persion(); - for (int i = 0; i < concurrent;i++){ + for (int i = 0; i < concurrent; i++) { Thread thread = new Thread(new Runnable() { @Override public void run() { @@ -32,8 +32,8 @@ public void run() { } catch (InterruptedException e) { e.printStackTrace(); } - for(int j = 0; j < batchCount;j++){ - if(j % 2 == 0) { + for (int j = 0; j < batchCount; j++) { + if (j % 2 == 0) { runValue(persion, "yn", errCount); } else { runValue(persion, "name", errCount); @@ -42,7 +42,7 @@ public void run() { wait.countDown(); } }); - thread.setName("work-"+i); + thread.setName("work-" + i); thread.start(); } start.countDown(); @@ -56,12 +56,11 @@ public void run() { } - - private void runValue(Persion persion,String name,AtomicInteger errCount) { - OgnlContext context = new OgnlContext(null,null,new DefaultMemberAccess(false)); + private void runValue(Persion persion, String name, AtomicInteger errCount) { + OgnlContext context = new OgnlContext(null, null, new DefaultMemberAccess(false)); context.setRoot(persion); try { - Object value = Ognl.getValue(name, context, context.getRoot()); + Object value = Ognl.getValue(name, context, context.getRoot()); // System.out.println(value); } catch (OgnlException e) { diff --git a/src/test/java/ognl/test/util/ContextClassLoader.java b/src/test/java/ognl/test/util/ContextClassLoader.java new file mode 100644 index 00000000..3588279b --- /dev/null +++ b/src/test/java/ognl/test/util/ContextClassLoader.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.util; + +import ognl.OgnlContext; + +public class ContextClassLoader extends ClassLoader { + private OgnlContext context; + + /*=================================================================== + Constructors + ===================================================================*/ + public ContextClassLoader(ClassLoader parentClassLoader, OgnlContext context) { + super(parentClassLoader); + this.context = context; + } + + /*=================================================================== + Overridden methods + ===================================================================*/ + protected Class findClass(String name) throws ClassNotFoundException { + if ((context != null) && (context.getClassResolver() != null)) { + return context.getClassResolver().classForName(name, context); + } + return super.findClass(name); + } + +} diff --git a/src/test/java/ognl/test/util/EnhancedClassLoader.java b/src/test/java/ognl/test/util/EnhancedClassLoader.java new file mode 100644 index 00000000..482efc97 --- /dev/null +++ b/src/test/java/ognl/test/util/EnhancedClassLoader.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.util; + +public class EnhancedClassLoader extends ClassLoader { + /*=================================================================== + Constructors + ===================================================================*/ + public EnhancedClassLoader(ClassLoader parentClassLoader) { + super(parentClassLoader); + } + + /*=================================================================== + Overridden methods + ===================================================================*/ + public Class defineClass(String enhancedClassName, byte[] byteCode) { + return defineClass(enhancedClassName, byteCode, 0, byteCode.length); + } +} diff --git a/src/test/java/ognl/test/util/NameFactory.java b/src/test/java/ognl/test/util/NameFactory.java new file mode 100644 index 00000000..e62a144f --- /dev/null +++ b/src/test/java/ognl/test/util/NameFactory.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package ognl.test.util; + +public class NameFactory extends Object { + private String classBaseName; + private int classNameCounter = 0; + private String variableBaseName; + private int variableNameCounter = 0; + + /*=================================================================== + Constructors + ===================================================================*/ + public NameFactory(String classBaseName, String variableBaseName) { + super(); + this.classBaseName = classBaseName; + this.variableBaseName = variableBaseName; + } + + /*=================================================================== + Public methods + ===================================================================*/ + public String getNewClassName() { + return classBaseName + classNameCounter++; + } + + public String getNewVariableName() { + return variableBaseName + variableNameCounter++; + } +} diff --git a/src/test/java/org/ognl/test/ArithmeticAndLogicalOperatorsTest.java b/src/test/java/org/ognl/test/ArithmeticAndLogicalOperatorsTest.java deleted file mode 100644 index 3546cdf7..00000000 --- a/src/test/java/org/ognl/test/ArithmeticAndLogicalOperatorsTest.java +++ /dev/null @@ -1,300 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; - -import java.math.BigDecimal; - -public class ArithmeticAndLogicalOperatorsTest extends OgnlTestCase -{ - - public enum EnumNoBody { ENUM1, ENUM2; }; // Basic enumeration - public enum EnumEmptyBody { ENUM1{}, ENUM2{}; }; // Enumeration whose elements have (empty) bodies - public enum EnumBasicBody { ENUM1{ public final Integer value() { return Integer.valueOf(10);} }, - ENUM2{ public final Integer value() { return Integer.valueOf(20);} }; }; // Enumeration whose elements have bodies - protected static final String FULLY_QUALIFIED_CLASSNAME = ArithmeticAndLogicalOperatorsTest.class.getName(); - - private static Object[][] TESTS = { - // Double-valued arithmetic expressions - { "-1d", new Double(-1) }, - { "+1d", new Double(1) }, - { "--1f", new Double(1) }, - { "2*2.0", new Double(4.0) }, - { "5/2.", new Double(2.5) }, - { "5+2D", new Double(7) }, - { "5f-2F", new Double(3.0) }, - { "5.+2*3", new Double(11) }, - { "(5.+2)*3", new Double(21) }, - - // BigDecimal-valued arithmetic expressions - { "-1b", new Integer(-1) }, - { "+1b", new Integer(1) }, - { "--1b", new Integer(1) }, - { "2*2.0b", new Double(4.0) }, - { "5/2.B", new Integer(2) }, - { "5.0B/2", new Double(2.5) }, - { "5+2b", new Integer(7) }, - { "5-2B", new Integer(3) }, - { "5.+2b*3", new Double(11) }, - { "(5.+2b)*3", new Double(21) }, - - // Integer-valued arithmetic expressions - { "-1", new Integer(-1) }, - { "+1", new Integer(1) }, - { "--1", new Integer(1) }, - { "2*2", new Integer(4) }, - { "5/2", new Integer(2) }, - { "5+2", new Integer(7) }, - { "5-2", new Integer(3) }, - { "5+2*3", new Integer(11) }, - { "(5+2)*3", new Integer(21) }, - { "~1", new Integer(~1) }, - { "5%2", new Integer(1) }, - { "5<<2", new Integer(20) }, - { "5>>2", new Integer(1) }, - { "5>>1+1", new Integer(1) }, - { "-5>>>2", new Integer(-5 >>> 2)}, - { "-5L>>>2", new Long(-5L >>> 2) }, - { "5. & 3", new Long(1) }, - { "5 ^3", new Integer(6) }, - { "5l&3|5^3", new Long(7) }, - { "5&(3|5^3)", new Long(5) }, - { "true ? 1 : 1/0", new Integer(1) }, - - // BigInteger-valued arithmetic expressions - { "-1h", Integer.valueOf(-1) }, - { "+1H", Integer.valueOf(1) }, - { "--1h", Integer.valueOf(1) }, - { "2h*2", Integer.valueOf(4) }, - { "5/2h", Integer.valueOf(2) }, - { "5h+2", Integer.valueOf(7) }, - { "5-2h", Integer.valueOf(3) }, - { "5+2H*3", Integer.valueOf(11) }, - { "(5+2H)*3", Integer.valueOf(21) }, - { "~1h", Integer.valueOf(~1) }, - { "5h%2", Integer.valueOf(1) }, - { "5h<<2", Integer.valueOf(20) }, - { "5h>>2", Integer.valueOf(1) }, - { "5h>>1+1", Integer.valueOf(1) }, - { "-5h>>>2", Integer.valueOf(-2) }, - { "5.b & 3", new Long(1) }, - { "5h ^3", Integer.valueOf(6) }, - { "5h&3|5^3", new Long(7) }, - { "5H&(3|5^3)", new Long(5) }, - - // Logical expressions - { "!1", Boolean.FALSE }, - { "!null", Boolean.TRUE }, - { "5<2", Boolean.FALSE }, - { "5>2", Boolean.TRUE }, - { "5<=5", Boolean.TRUE }, - { "5>=3", Boolean.TRUE }, - { "5<-5>>>2", Boolean.TRUE }, - { "5==5.0", Boolean.TRUE }, - { "5!=5.0", Boolean.FALSE }, - { "null in {true,false,null}", Boolean.TRUE }, - { "null not in {true,false,null}", Boolean.FALSE }, - { "null in {true,false,null}.toArray()", Boolean.TRUE }, - { "5 in {true,false,null}", Boolean.FALSE }, - { "5 not in {true,false,null}", Boolean.TRUE }, - { "5 instanceof java.lang.Integer", Boolean.TRUE }, - { "5. instanceof java.lang.Integer", Boolean.FALSE }, - { "!false || true", Boolean.TRUE}, - { "!(true && true)", Boolean.FALSE}, - { "(1 > 0 && true) || 2 > 0", Boolean.TRUE}, - - // Logical expressions (string versions) - { "2 or 0", Integer.valueOf(2)}, - { "1 and 0", Integer.valueOf(0) }, - { "1 bor 0", new Integer(1) }, - { "true && 12", Integer.valueOf(12)}, - { "1 xor 0", new Integer(1) }, { "1 band 0", new Long(0) }, { "1 eq 1", Boolean.TRUE }, - { "1 neq 1", Boolean.FALSE }, { "1 lt 5", Boolean.TRUE }, { "1 lte 5", Boolean.TRUE }, - { "1 gt 5", Boolean.FALSE }, { "1 gte 5", Boolean.FALSE }, { "1 lt 5", Boolean.TRUE }, - { "1 shl 2", new Integer(4) }, { "4 shr 2", new Integer(1) }, { "4 ushr 2", new Integer(1) }, - { "not null", Boolean.TRUE }, { "not 1", Boolean.FALSE }, - - // Equality on identity; Object does not implement Comparable - { "#a = new java.lang.Object(), #a == #a", Boolean.TRUE}, - { "#a = new java.lang.Object(), #b = new java.lang.Object(), #a == #b", Boolean.FALSE}, - - // Comparable and non-Comparable - { "#a = new java.lang.Object(), #a == ''", Boolean.FALSE}, - { "#a = new java.lang.Object(), '' == #a", Boolean.FALSE}, - - { "#x > 0", Boolean.TRUE }, - { "#x < 0", Boolean.FALSE }, - { "#x == 0", Boolean.FALSE }, - { "#x == 1", Boolean.TRUE }, - { "0 > #x", Boolean.FALSE }, - { "0 < #x", Boolean.TRUE }, - { "0 == #x", Boolean.FALSE }, - { "1 == #x", Boolean.TRUE }, - { "\"1\" > 0", Boolean.TRUE }, - { "\"1\" < 0", Boolean.FALSE }, - { "\"1\" == 0", Boolean.FALSE }, - { "\"1\" == 1", Boolean.TRUE }, - { "0 > \"1\"", Boolean.FALSE }, - { "0 < \"1\"", Boolean.TRUE }, - { "0 == \"1\"", Boolean.FALSE }, - { "1 == \"1\"", Boolean.TRUE }, - { "#x + 1", "11" }, - { "1 + #x", "11" }, - { "#y == 1", Boolean.TRUE }, - { "#y == \"1\"", Boolean.TRUE }, - { "#y + \"1\"", "11" }, - { "\"1\" + #y", "11" }, - - // Enumerated type equality and inequality comparisons (with and without element bodies, reversing order for completeness). - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", Boolean.FALSE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", Boolean.FALSE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", Boolean.FALSE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", Boolean.FALSE }, - - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", Boolean.FALSE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", Boolean.FALSE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", Boolean.FALSE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", Boolean.FALSE }, - - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", Boolean.FALSE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", Boolean.FALSE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", Boolean.FALSE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", Boolean.TRUE }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", Boolean.FALSE }, - - // As per JDK JavaDocs it is only possible to compare Enum elements of the same type. Attempting to compare different types - // will normally result in ClassCastExceptions. However, OGNL should avoid that and produce an IllegalArgumentException instead. - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class }, - - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumNoBody@ENUM2", IllegalArgumentException.class }, - - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM2", IllegalArgumentException.class }, - - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM1", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 == @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class }, - { "@" + FULLY_QUALIFIED_CLASSNAME + "$EnumBasicBody@ENUM1 != @" + FULLY_QUALIFIED_CLASSNAME + "$EnumEmptyBody@ENUM2", IllegalArgumentException.class } - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - result.addTest(new ArithmeticAndLogicalOperatorsTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, - (String) TESTS[i][0], TESTS[i][1])); - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public ArithmeticAndLogicalOperatorsTest() - { - super(); - } - - public ArithmeticAndLogicalOperatorsTest(String name) - { - super(name); - } - - public ArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public ArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public ArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } - - /* - * =================================================================== Overridden methods - * =================================================================== - */ - protected void setUp() - { - super.setUp(); - _context.put("x", "1"); - _context.put("y", new BigDecimal(1)); - } -} diff --git a/src/test/java/org/ognl/test/ArrayCreationTest.java b/src/test/java/org/ognl/test/ArrayCreationTest.java deleted file mode 100644 index d0299085..00000000 --- a/src/test/java/org/ognl/test/ArrayCreationTest.java +++ /dev/null @@ -1,123 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.ExpressionSyntaxException; -import org.ognl.test.objects.Entry; -import org.ognl.test.objects.Root; -import org.ognl.test.objects.Simple; - -public class ArrayCreationTest extends OgnlTestCase -{ - - private static Root ROOT = new Root(); - - private static Object[][] TESTS = { - // Array creation - { ROOT, "new String[] { \"one\", \"two\" }", new String[] { "one", "two" } }, - { ROOT, "new String[] { 1, 2 }", new String[] { "1", "2" } }, - { ROOT, "new Integer[] { \"1\", 2, \"3\" }", - new Integer[] { new Integer(1), new Integer(2), new Integer(3) } }, - { ROOT, "new String[10]", new String[10] }, - { ROOT, "new Object[4] { #root, #this }", ExpressionSyntaxException.class }, - { ROOT, "new Object[4]", new Object[4] }, - { ROOT, "new Object[] { #root, #this }", new Object[] { ROOT, ROOT } }, - { ROOT, - "new org.ognl.test.objects.Simple[] { new org.ognl.test.objects.Simple(), new org.ognl.test.objects.Simple(\"foo\", 1.0f, 2) }", - new Simple[] { new Simple(), new Simple("foo", 1.0f, 2) } }, - { ROOT, "new org.ognl.test.objects.Simple[5]", new Simple[5] }, - { ROOT, "new org.ognl.test.objects.Simple(new Object[5])", new Simple(new Object[5]) }, - { ROOT, "new org.ognl.test.objects.Simple(new String[5])", new Simple(new String[5]) }, - { ROOT, "objectIndex ? new org.ognl.test.objects.Entry[] { new org.ognl.test.objects.Entry(), new org.ognl.test.objects.Entry()} " - + ": new org.ognl.test.objects.Entry[] { new org.ognl.test.objects.Entry(), new org.ognl.test.objects.Entry()} ", - new Entry[] { new Entry(), new Entry()} } - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new ArrayCreationTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new ArrayCreationTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new ArrayCreationTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public ArrayCreationTest() - { - super(); - } - - public ArrayCreationTest(String name) - { - super(name); - } - - public ArrayCreationTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public ArrayCreationTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public ArrayCreationTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/ClassMethodTest.java b/src/test/java/org/ognl/test/ClassMethodTest.java deleted file mode 100644 index 9f9c4a4a..00000000 --- a/src/test/java/org/ognl/test/ClassMethodTest.java +++ /dev/null @@ -1,94 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.CorrectedObject; - -public class ClassMethodTest extends OgnlTestCase -{ - - private static CorrectedObject CORRECTED = new CorrectedObject(); - - private static Object[][] TESTS = { - // Methods on Class - { CORRECTED, "getClass().getName()", CORRECTED.getClass().getName() }, - { CORRECTED, "getClass().getInterfaces()", CORRECTED.getClass().getInterfaces() }, - { CORRECTED, "getClass().getInterfaces().length", new Integer(CORRECTED.getClass().getInterfaces().length) }, - { null, "@System@class.getInterfaces()", System.class.getInterfaces() }, - { null, "@Class@class.getName()", Class.class.getName() }, - { null, "@java.awt.image.ImageObserver@class.getName()", java.awt.image.ImageObserver.class.getName() }, - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - result.addTest(new ClassMethodTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public ClassMethodTest() - { - super(); - } - - public ClassMethodTest(String name) - { - super(name); - } - - public ClassMethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public ClassMethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public ClassMethodTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/ConstantTest.java b/src/test/java/org/ognl/test/ConstantTest.java deleted file mode 100644 index f99f4e1d..00000000 --- a/src/test/java/org/ognl/test/ConstantTest.java +++ /dev/null @@ -1,116 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.ExpressionSyntaxException; - -import java.util.Arrays; - -public class ConstantTest extends OgnlTestCase -{ - - private static Object[][] TESTS = { - { "12345", new Integer(12345) }, - { "0x100", new Integer(256) }, - { "0xfE", new Integer(254) }, - { "01000", new Integer(512) }, - { "1234L", new Integer(1234) }, - { "12.34", new Double(12.34) }, - { ".1234", new Double(.12340000000000) }, - { "12.34f", Double.valueOf(12.34) }, - { "12.", new Double(12) }, - { "12e+1d", new Double(120) }, - { "'x'", new Character('x') }, - { "'\\n'", new Character('\n') }, - { "'\\u048c'", new Character('\u048c')}, - { "'\\47'", new Character('\47') }, - { "'\\367'", new Character('\367') }, - { "'\\367", ExpressionSyntaxException.class }, - { "'\\x'", ExpressionSyntaxException.class }, - { "\"hello world\"", "hello world" }, - { "\"\\u00a0\\u0068ell\\'o\\\\\\n\\r\\f\\t\\b\\\"\\167orld\\\"\"", "\u00a0hell'o\\\n\r\f\t\b\"world\"" }, - { "\"hello world", ExpressionSyntaxException.class }, - { "\"hello\\x world\"", ExpressionSyntaxException.class }, - { "null", null }, - { "true", Boolean.TRUE }, - { "false", Boolean.FALSE }, - { "{ false, true, null, 0, 1. }", - Arrays.asList(new Object[] { Boolean.FALSE, Boolean.TRUE, null, new Integer(0), new Double(1) }) }, - { "'HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"'", - "HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"" }, - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - result.addTest(new ConstantTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, - (String) TESTS[i][0], TESTS[i][1])); - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public ConstantTest() - { - super(); - } - - public ConstantTest(String name) - { - super(name); - } - - public ConstantTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public ConstantTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public ConstantTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/ConstantTreeTest.java b/src/test/java/org/ognl/test/ConstantTreeTest.java deleted file mode 100644 index 326e5e7a..00000000 --- a/src/test/java/org/ognl/test/ConstantTreeTest.java +++ /dev/null @@ -1,111 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.Ognl; - -public class ConstantTreeTest extends OgnlTestCase -{ - - public static int nonFinalStaticVariable = 15; - - private static Object[][] TESTS = { - { "true", Boolean.TRUE }, - { "55", Boolean.TRUE }, - { "@java.awt.Color@black", Boolean.TRUE }, - { "@org.ognl.test.ConstantTreeTest@nonFinalStaticVariable", Boolean.FALSE }, - { "@org.ognl.test.ConstantTreeTest@nonFinalStaticVariable + 10", Boolean.FALSE }, - { "55 + 24 + @java.awt.Event@ALT_MASK", Boolean.TRUE }, - { "name", Boolean.FALSE }, - { "name[i]", Boolean.FALSE }, - { "name[i].property", Boolean.FALSE }, - { "name.{? foo }", Boolean.FALSE }, - { "name.{ foo }", Boolean.FALSE }, - { "name.{ 25 }", Boolean.FALSE } - - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - result.addTest(new ConstantTreeTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, - (String) TESTS[i][0], TESTS[i][1])); - } - return result; - } - - /* - * =================================================================== Overridden methods - * =================================================================== - */ - protected void runTest() - throws Exception - { - assertTrue(Ognl.isConstant(getExpression(), _context) == ((Boolean) getExpectedResult()).booleanValue()); - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public ConstantTreeTest() - { - super(); - } - - public ConstantTreeTest(String name) - { - super(name); - } - - public ConstantTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public ConstantTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public ConstantTreeTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/ContextVariableTest.java b/src/test/java/org/ognl/test/ContextVariableTest.java deleted file mode 100644 index 8b460aab..00000000 --- a/src/test/java/org/ognl/test/ContextVariableTest.java +++ /dev/null @@ -1,91 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Simple; - -public class ContextVariableTest extends OgnlTestCase { - - private static Object ROOT = new Simple(); - private static Object[][] TESTS = { - // Naming and referring to names - {"#root", ROOT}, // Special root reference - {"#this", ROOT}, // Special this reference - {"#f=5, #s=6, #f + #s", new Integer(11)}, - { "#six=(#five=5, 6), #five + #six", new Integer(11)}, - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - result.addTest(new ContextVariableTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", ROOT, - (String) TESTS[i][0], TESTS[i][1])); - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public ContextVariableTest() - { - super(); - } - - public ContextVariableTest(String name) - { - super(name); - } - - public ContextVariableTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public ContextVariableTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public ContextVariableTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/CorrectedObjectNullHandler.java b/src/test/java/org/ognl/test/CorrectedObjectNullHandler.java deleted file mode 100644 index 0e543a2c..00000000 --- a/src/test/java/org/ognl/test/CorrectedObjectNullHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import ognl.NullHandler; - -import java.util.Map; - -public class CorrectedObjectNullHandler extends Object implements NullHandler -{ - private String defaultValue; - - /*=================================================================== - Constructors - ===================================================================*/ - public CorrectedObjectNullHandler(String defaultValue) - { - super(); - this.defaultValue = defaultValue; - } - - /*=================================================================== - TypeConverter interface (overridden) - ===================================================================*/ - public Object nullMethodResult(Map context, Object target, String methodName, Object[] args) - { - if (methodName.equals("getStringValue")) { - return defaultValue; - } - return null; - } - - public Object nullPropertyValue(Map context, Object target, Object property) - { - Object result = null; - - if (property.equals("stringValue")) { - return defaultValue; - } - return null; - } -} diff --git a/src/test/java/org/ognl/test/InheritedMethodsTest.java b/src/test/java/org/ognl/test/InheritedMethodsTest.java deleted file mode 100644 index 78ed7643..00000000 --- a/src/test/java/org/ognl/test/InheritedMethodsTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * - */ -package org.ognl.test; - -import junit.framework.TestCase; -import ognl.DefaultMemberAccess; -import ognl.Node; -import ognl.Ognl; -import ognl.OgnlContext; -import org.ognl.test.objects.BaseBean; -import org.ognl.test.objects.FirstBean; -import org.ognl.test.objects.Root; -import org.ognl.test.objects.SecondBean; - - -/** - * Tests functionality of casting inherited method expressions. - * - */ -public class InheritedMethodsTest extends TestCase -{ - - private static Root ROOT = new Root(); - - public void test_Base_Inheritance() - throws Exception - { - OgnlContext context = (OgnlContext)Ognl.createDefaultContext(null, new DefaultMemberAccess(false)); - String expression = "map.bean.name"; - BaseBean first = new FirstBean(); - BaseBean second = new SecondBean(); - - ROOT.getMap().put("bean", first); - - Node node = Ognl.compileExpression(context, ROOT, expression); - - assertEquals(first.getName(), node.getAccessor().get(context, ROOT)); - - ROOT.getMap().put("bean", second); - - assertEquals(second.getName(), node.getAccessor().get(context, ROOT)); - } -} diff --git a/src/test/java/org/ognl/test/MethodTest.java b/src/test/java/org/ognl/test/MethodTest.java deleted file mode 100644 index 6af7b064..00000000 --- a/src/test/java/org/ognl/test/MethodTest.java +++ /dev/null @@ -1,159 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -import ognl.Ognl; -import ognl.OgnlException; -import org.ognl.test.objects.*; - -public class MethodTest extends OgnlTestCase -{ - - private static Simple ROOT = new Simple(); - private static ListSource LIST = new ListSourceImpl(); - private static BaseGeneric GENERIC = new GameGeneric(); - - private static Object[][] TESTS = { - { "hashCode()", new Integer(ROOT.hashCode()) } , - { "getBooleanValue() ? \"here\" : \"\"", ""}, - { "getValueIsTrue(!false) ? \"\" : \"here\" ", ""}, - { "messages.format('ShowAllCount', one)", ROOT.getMessages().format("ShowAllCount", ROOT.getOne()) }, - { "messages.format('ShowAllCount', {one})", ROOT.getMessages().format("ShowAllCount", new Object[] { ROOT.getOne() }) }, - { "messages.format('ShowAllCount', {one, two})", ROOT.getMessages().format("ShowAllCount", new Object[] { ROOT.getOne(), ROOT.getTwo() }) }, - { "messages.format('ShowAllCount', one, two)", ROOT.getMessages().format("ShowAllCount", ROOT.getOne(), ROOT.getTwo()) }, - { "getTestValue(@org.ognl.test.objects.SimpleEnum@ONE.value)", new Integer(2)}, - { "@org.ognl.test.MethodTest@getA().isProperty()", Boolean.FALSE}, - { "isDisabled()", Boolean.TRUE}, - { "isTruck", Boolean.TRUE}, - { "isEditorDisabled()", Boolean.FALSE}, - { LIST, "addValue(name)", Boolean.TRUE}, - { "getDisplayValue(methodsTest.allowDisplay)", "test"}, - { "isThisVarArgsWorking(three, rootValue)", Boolean.TRUE}, - { "isThisVarArgsWorking()", Boolean.TRUE }, - { GENERIC, "service.getFullMessageFor(value, null)", "Halo 3"}, - // TestCase for https://github.com/jkuhnert/ognl/issues/17 - ArrayIndexOutOfBoundsException when trying to access BeanFactory - { "testMethods.getBean('TestBean')", ROOT.getTestMethods().getBean("TestBean") } , - // https://issues.apache.org/jira/browse/OGNL-250 - OnglRuntime getMethodValue fails to find method matching propertyName - { "testMethods.testProperty", ROOT.getTestMethods().testProperty() } , - { "testMethods.argsTest1({one})", ROOT.getTestMethods().argsTest1(Arrays.asList( ROOT.getOne() ).toArray()) }, // toArray() is automatically done by OGNL type conversion - // we need to cast out generics (insert "Object") - { "testMethods.argsTest2({one})", ROOT.getTestMethods().argsTest2(Arrays.asList( (Object) ROOT.getOne() )) }, - // Java 'ROOT.getTestMethods().argsTest1(Arrays.asList( ROOT.getOne() )' doesn't compile: - // --> The method argsTest(Object[]) in the type MethodTestMethods is not applicable for the arguments (List) - { "testMethods.argsTest3({one})", "List: [1]" }, - { "testMethods.showList(testMethods.getObjectList())", ROOT.getTestMethods().showList(ROOT.getTestMethods().getObjectList().toArray()) }, - { "testMethods.showList(testMethods.getStringList())", ROOT.getTestMethods().showList(ROOT.getTestMethods().getStringList().toArray()) }, - { "testMethods.showList(testMethods.getStringArray())", ROOT.getTestMethods().showList(ROOT.getTestMethods().getStringArray()) }, - // TODO This one doesn't work - even 'toArray(new String[0]) returns Object[] and so the wrong method is called - currently no idea how to handle this... - // { "testMethods.showList(testMethods.getStringList().toArray(new String[0]))", ROOT.getTestMethods().showList(ROOT.getTestMethods().getStringList().toArray(new String[0])) }, - // but this one works - at least in interpretation mode... - { "testMethods.showStringList(testMethods.getStringList().toArray(new String[0]))", ROOT.getTestMethods().showStringList(ROOT.getTestMethods().getStringList().toArray(new String[0])) }, - - // https://github.com/jkuhnert/ognl/issues/23 - Exception selecting overloaded method in 3.1.4 - { "testMethods.avg({ 5, 5 })", ROOT.getTestMethods().avg((List)Arrays.asList(5, 5)) }, - }; - - public void testNullVarArgs() throws OgnlException { - Object value = Ognl.getValue("isThisVarArgsWorking()", new HashMap(), ROOT); - - assertTrue(value instanceof Boolean); - assertTrue((Boolean) value); - } - - public static class A - { - public boolean isProperty() - { - return false; - } - } - - public static A getA() - { - return new A(); - } - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) - { - result.addTest(new MethodTest((String) TESTS[i][1] + " (" + TESTS[i][2] + ")", TESTS[i][0], (String) TESTS[i][1], TESTS[i][2])); - } else - { - result.addTest(new MethodTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", ROOT, (String) TESTS[i][0], TESTS[i][1])); - } - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public MethodTest() - { - super(); - } - - public MethodTest(String name) - { - super(name); - } - - public MethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public MethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public MethodTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/MethodWithConversionTest.java b/src/test/java/org/ognl/test/MethodWithConversionTest.java deleted file mode 100644 index 49075b65..00000000 --- a/src/test/java/org/ognl/test/MethodWithConversionTest.java +++ /dev/null @@ -1,111 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Simple; - -public class MethodWithConversionTest extends OgnlTestCase -{ - - private static Simple SIMPLE = new Simple(); - - private static Object[][] TESTS = { - // Method call with conversion - { SIMPLE, "setValues(new Integer(10), \"10.56\", new Double(34.225))", null }, - { SIMPLE, "stringValue", "10" }, - { SIMPLE, "stringValue", "10", new Character('x'), "x" }, - { SIMPLE, "setStringValue('x')", null }, // set by calling setStringValue() directly - { SIMPLE, "floatValue", new Float(10.56) }, - { SIMPLE, "getValueIsTrue(rootValue)", Boolean.TRUE}, - { SIMPLE, "messages.format('Testing', one, two, three)", "blah" } - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new MethodWithConversionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new MethodWithConversionTest((String) TESTS[i][1], TESTS[i][0], - (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new MethodWithConversionTest((String) TESTS[i][1], TESTS[i][0], - (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public MethodWithConversionTest() - { - super(); - } - - public MethodWithConversionTest(String name) - { - super(name); - } - - public MethodWithConversionTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public MethodWithConversionTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public MethodWithConversionTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/NestedMethodTest.java b/src/test/java/org/ognl/test/NestedMethodTest.java deleted file mode 100644 index 5f31de4d..00000000 --- a/src/test/java/org/ognl/test/NestedMethodTest.java +++ /dev/null @@ -1,106 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Component; - -public class NestedMethodTest extends OgnlTestCase -{ - - private static Component COMPONENT = new Component(); - - private static Object[][] TESTS = { - // Expression in a method call argument - { COMPONENT, "toDisplay.pictureUrl", COMPONENT.getToDisplay().getPictureUrl() }, - { COMPONENT, "page.createRelativeAsset(toDisplay.pictureUrl)", - COMPONENT.getPage().createRelativeAsset(COMPONENT.getToDisplay().getPictureUrl()) }, - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new NestedMethodTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new NestedMethodTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new NestedMethodTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public NestedMethodTest() - { - super(); - } - - public NestedMethodTest(String name) - { - super(name); - } - - public NestedMethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public NestedMethodTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public NestedMethodTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/NullHandlerTest.java b/src/test/java/org/ognl/test/NullHandlerTest.java deleted file mode 100644 index 501a7daf..00000000 --- a/src/test/java/org/ognl/test/NullHandlerTest.java +++ /dev/null @@ -1,119 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.OgnlRuntime; -import org.ognl.test.objects.CorrectedObject; - -public class NullHandlerTest extends OgnlTestCase -{ - private static CorrectedObject CORRECTED = new CorrectedObject(); - - private static Object[][] TESTS = { - // NullHandler - { CORRECTED, "stringValue", "corrected" }, - { CORRECTED, "getStringValue()", "corrected" }, - { CORRECTED, "#root.stringValue", "corrected" }, - { CORRECTED, "#root.getStringValue()", "corrected" }, - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result - .addTest(new NullHandlerTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new NullHandlerTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new NullHandlerTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public NullHandlerTest() - { - super(); - } - - public NullHandlerTest(String name) - { - super(name); - } - - public NullHandlerTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, - Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public NullHandlerTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public NullHandlerTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } - - /* - * =================================================================== Overridden methods - * =================================================================== - */ - public void setUp() - { - super.setUp(); - _compileExpressions = false; - OgnlRuntime.setNullHandler(CorrectedObject.class, new CorrectedObjectNullHandler("corrected")); - } -} diff --git a/src/test/java/org/ognl/test/NullStringCatenationTest.java b/src/test/java/org/ognl/test/NullStringCatenationTest.java deleted file mode 100644 index 371f854e..00000000 --- a/src/test/java/org/ognl/test/NullStringCatenationTest.java +++ /dev/null @@ -1,115 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Root; - -public class NullStringCatenationTest extends OgnlTestCase { - - public static final String MESSAGE = "blarney"; - - private static Root ROOT = new Root(); - - private static Object[][] TESTS = { - // Null string catenation - {ROOT, "\"bar\" + null", "barnull"}, // Catenate null to a string - {ROOT, "\"bar\" + nullObject", "barnull"}, // Catenate null to a string - {ROOT, "20.56 + nullObject", NullPointerException.class}, // Catenate null to a number - {ROOT, "(true ? 'tabHeader' : '') + (false ? 'tabHeader' : '')", "tabHeader"}, - {ROOT, "theInt == 0 ? '5%' : theInt + '%'", "6%"}, - {ROOT, "'width:' + width + ';'", "width:238px;" }, - {ROOT, "theLong + '_' + index", "4_1"}, - {ROOT, "'javascript:' + @org.ognl.test.NullStringCatenationTest@MESSAGE", "javascript:blarney" }, - {ROOT, "printDelivery ? '' : 'javascript:deliverySelected(' + property.carrier + ',' + currentDeliveryId + ')'", "" }, - {ROOT, "bean2.id + '_' + theInt", "1_6" } - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new NullStringCatenationTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new NullStringCatenationTest((String) TESTS[i][1], TESTS[i][0], - (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new NullStringCatenationTest((String) TESTS[i][1], TESTS[i][0], - (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public NullStringCatenationTest() - { - super(); - } - - public NullStringCatenationTest(String name) - { - super(name); - } - - public NullStringCatenationTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public NullStringCatenationTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public NullStringCatenationTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/NumberFormatExceptionTest.java b/src/test/java/org/ognl/test/NumberFormatExceptionTest.java deleted file mode 100644 index c88938b9..00000000 --- a/src/test/java/org/ognl/test/NumberFormatExceptionTest.java +++ /dev/null @@ -1,119 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.OgnlException; -import org.ognl.test.objects.Simple; - -import java.math.BigDecimal; -import java.math.BigInteger; - -public class NumberFormatExceptionTest extends OgnlTestCase -{ - private static Simple SIMPLE = new Simple(); - - private static Object[][] TESTS = { - // NumberFormatException handling (default is to throw NumberFormatException on bad string conversions) - { SIMPLE, "floatValue", new Float(0f), new Float(10f), new Float(10f) }, - { SIMPLE, "floatValue", new Float(10f), "x10x", OgnlException.class }, - - { SIMPLE, "intValue", new Integer(0), new Integer(34), new Integer(34) }, - { SIMPLE, "intValue", new Integer(34), "foobar", OgnlException.class }, - { SIMPLE, "intValue", new Integer(34), "", OgnlException.class }, - { SIMPLE, "intValue", new Integer(34), " \t", OgnlException.class }, - { SIMPLE, "intValue", new Integer(34), " \t1234\t\t", new Integer(1234) }, - - { SIMPLE, "bigIntValue", BigInteger.valueOf(0), BigInteger.valueOf(34), BigInteger.valueOf(34) }, - { SIMPLE, "bigIntValue", BigInteger.valueOf(34), null, null }, - { SIMPLE, "bigIntValue", null, "", OgnlException.class }, - { SIMPLE, "bigIntValue", null, "foobar", OgnlException.class }, - - { SIMPLE, "bigDecValue", new BigDecimal(0.0), new BigDecimal(34.55), new BigDecimal(34.55) }, - { SIMPLE, "bigDecValue", new BigDecimal(34.55), null, null }, - { SIMPLE, "bigDecValue", null, "", OgnlException.class }, - { SIMPLE, "bigDecValue", null, "foobar", OgnlException.class } - - }; - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new NumberFormatExceptionTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new NumberFormatExceptionTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new NumberFormatExceptionTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public NumberFormatExceptionTest() - { - super(); - } - - public NumberFormatExceptionTest(String name) - { - super(name); - } - - public NumberFormatExceptionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public NumberFormatExceptionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public NumberFormatExceptionTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/PrimitiveNullHandlingTest.java b/src/test/java/org/ognl/test/PrimitiveNullHandlingTest.java deleted file mode 100644 index 9f148e2c..00000000 --- a/src/test/java/org/ognl/test/PrimitiveNullHandlingTest.java +++ /dev/null @@ -1,121 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Simple; - -public class PrimitiveNullHandlingTest extends OgnlTestCase -{ - - private static Simple SIMPLE = new Simple(); - - static { - SIMPLE.setFloatValue(10.56f); - SIMPLE.setIntValue(34); - } - - private static Object[][] TESTS = { - // Primitive null handling - { SIMPLE, "floatValue", new Float(10.56f), null, new Float(0f) }, // set float to - // null, should - // yield 0.0f - { SIMPLE, "intValue", new Integer(34), null, new Integer(0) },// set int to null, - // should yield 0 - { SIMPLE, "booleanValue", Boolean.FALSE, Boolean.TRUE, Boolean.TRUE },// set boolean - // to TRUE, - // should yield - // true - { SIMPLE, "booleanValue", Boolean.TRUE, null, Boolean.FALSE }, // set boolean to null, - // should yield false - - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new PrimitiveNullHandlingTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new PrimitiveNullHandlingTest((String) TESTS[i][1], TESTS[i][0], - (String) TESTS[i][1], TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new PrimitiveNullHandlingTest((String) TESTS[i][1], TESTS[i][0], - (String) TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public PrimitiveNullHandlingTest() - { - super(); - } - - public PrimitiveNullHandlingTest(String name) - { - super(name); - } - - public PrimitiveNullHandlingTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public PrimitiveNullHandlingTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public PrimitiveNullHandlingTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/PrivateAccessorTest.java b/src/test/java/org/ognl/test/PrivateAccessorTest.java deleted file mode 100644 index 96b2d89e..00000000 --- a/src/test/java/org/ognl/test/PrivateAccessorTest.java +++ /dev/null @@ -1,125 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.DefaultMemberAccess; -import ognl.OgnlContext; -import org.ognl.test.objects.Root; - -public class PrivateAccessorTest extends OgnlTestCase -{ - - private static Root ROOT = new Root(); - - private static Object[][] TESTS = { - // Using private get/set methods - { ROOT, "getPrivateAccessorIntValue()", new Integer(67) }, - { ROOT, "privateAccessorIntValue", new Integer(67) }, - { ROOT, "privateAccessorIntValue", new Integer(67), new Integer(100) }, - { ROOT, "privateAccessorIntValue2", new Integer(67) }, - { ROOT, "privateAccessorIntValue2", new Integer(67), new Integer(100) }, - { ROOT, "privateAccessorIntValue3", new Integer(67) }, - { ROOT, "privateAccessorIntValue3", new Integer(67), new Integer(100) }, - { ROOT, "privateAccessorBooleanValue", Boolean.TRUE }, - { ROOT, "privateAccessorBooleanValue", Boolean.TRUE, Boolean.FALSE }, - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new PrivateAccessorTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new PrivateAccessorTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new PrivateAccessorTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public PrivateAccessorTest() - { - super(); - } - - public PrivateAccessorTest(String name) - { - super(name); - } - - public PrivateAccessorTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public PrivateAccessorTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public PrivateAccessorTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } - - /* - * =================================================================== Overridden methods - * =================================================================== - */ - public void setUp() - { - super.setUp(); - _context = new OgnlContext(null, null, new DefaultMemberAccess(true)); - _compileExpressions = false; - } -} diff --git a/src/test/java/org/ognl/test/ProjectionSelectionTest.java b/src/test/java/org/ognl/test/ProjectionSelectionTest.java deleted file mode 100644 index c1e31cb7..00000000 --- a/src/test/java/org/ognl/test/ProjectionSelectionTest.java +++ /dev/null @@ -1,100 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Root; - -import java.math.BigInteger; -import java.util.Arrays; - -public class ProjectionSelectionTest extends OgnlTestCase -{ - private static Root ROOT = new Root(); - - private static Object[][] TESTS = { - // Projection, selection - { ROOT, "array.{class}", - Arrays.asList(new Class[] { Integer.class, Integer.class, Integer.class, Integer.class }) }, - { ROOT, "map.array.{? #this > 2 }", Arrays.asList(new Integer[] { new Integer(3), new Integer(4) }) }, - { ROOT, "map.array.{^ #this > 2 }", Arrays.asList(new Integer[] { new Integer(3) }) }, - { ROOT, "map.array.{$ #this > 2 }", Arrays.asList(new Integer[] { new Integer(4) }) }, - { ROOT, "map.array[*].{?true} instanceof java.util.Collection", Boolean.TRUE }, - { null, "#fact=1, 30H.{? #fact = #fact * (#this+1), false }, #fact", - new BigInteger("265252859812191058636308480000000") }, - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - result.addTest(new ProjectionSelectionTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public ProjectionSelectionTest() - { - super(); - } - - public ProjectionSelectionTest(String name) - { - super(name); - } - - public ProjectionSelectionTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public ProjectionSelectionTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public ProjectionSelectionTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/PropertyArithmeticAndLogicalOperatorsTest.java b/src/test/java/org/ognl/test/PropertyArithmeticAndLogicalOperatorsTest.java deleted file mode 100644 index 4a0430fd..00000000 --- a/src/test/java/org/ognl/test/PropertyArithmeticAndLogicalOperatorsTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Root; -import org.ognl.test.objects.SimpleNumeric; -import org.ognl.test.objects.TestModel; - -import java.util.Arrays; - -/** - * - */ -public class PropertyArithmeticAndLogicalOperatorsTest extends OgnlTestCase { - - private static Root ROOT = new Root(); - private static TestModel MODEL = new TestModel(); - private static SimpleNumeric NUMERIC = new SimpleNumeric(); - - private static Object[][] TESTS = { - { ROOT, "objectIndex > 0", Boolean.TRUE}, - { ROOT, "false", Boolean.FALSE}, - { ROOT, "!false || true", Boolean.TRUE}, - { ROOT, "property.bean3.value >= 24", Boolean.TRUE}, - { ROOT, "genericIndex-1", new Integer(1)}, - { ROOT, "((renderNavigation ? 0 : 1) + map.size) * theInt", new Integer(((ROOT.getRenderNavigation() ? 0 : 1 ) + ROOT.getMap().size()) * ROOT.getTheInt())}, - { ROOT, "{theInt + 1}", Arrays.asList(new Integer(ROOT.getTheInt() + 1)) }, - { MODEL, "(unassignedCopyModel.optionCount > 0 && canApproveCopy) || entry.copy.size() > 0", Boolean.TRUE }, - { ROOT, " !(printDelivery || @Boolean@FALSE)", Boolean.FALSE}, - { ROOT, "(getIndexedProperty('nested').size - 1) > genericIndex", Boolean.FALSE}, - { ROOT, "(getIndexedProperty('nested').size + 1) >= genericIndex", Boolean.TRUE}, - { ROOT, "(getIndexedProperty('nested').size + 1) == genericIndex", Boolean.TRUE}, - { ROOT, "(getIndexedProperty('nested').size + 1) < genericIndex", Boolean.FALSE}, - { ROOT, "map.size * genericIndex", new Integer(ROOT.getMap().size() * ((Integer)ROOT.getGenericIndex()).intValue())}, - { ROOT, "property == property", Boolean.TRUE}, - { ROOT, "property.bean3.value % 2 == 0", Boolean.TRUE}, - { ROOT, "genericIndex % 3 == 0", Boolean.FALSE}, - { ROOT, "genericIndex % theInt == property.bean3.value", Boolean.FALSE}, - { ROOT, "theInt / 100.0", ROOT.getTheInt() / 100.0}, - { ROOT, "@java.lang.Long@valueOf('100') == @java.lang.Long@valueOf('100')", Boolean.TRUE}, - { NUMERIC, "budget - timeBilled", new Double(NUMERIC.getBudget() - NUMERIC.getTimeBilled())}, - { NUMERIC, "(budget % tableSize) == 0", Boolean.TRUE} - }; - - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) - { - if (TESTS[i].length == 5) - { - result.addTest(new PropertyArithmeticAndLogicalOperatorsTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else - result.addTest(new PropertyArithmeticAndLogicalOperatorsTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2])); - } - - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public PropertyArithmeticAndLogicalOperatorsTest() - { - super(); - } - - public PropertyArithmeticAndLogicalOperatorsTest(String name) - { - super(name); - } - - public PropertyArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, - Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public PropertyArithmeticAndLogicalOperatorsTest(String name, Object root, String expressionString, - Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public PropertyArithmeticAndLogicalOperatorsTest(String name, Object root, - String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/PropertyTest.java b/src/test/java/org/ognl/test/PropertyTest.java deleted file mode 100644 index 610df1ac..00000000 --- a/src/test/java/org/ognl/test/PropertyTest.java +++ /dev/null @@ -1,173 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.*; - -import java.text.SimpleDateFormat; -import java.util.Arrays; - -public class PropertyTest extends OgnlTestCase -{ - - public static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm a 'CST'"); - public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy"); - public static final String VALUE = "foo"; - - private static Root ROOT = new Root(); - private static BaseBean BEAN = new FirstBean(); - private static PropertyHolder PROPERTY = new PropertyHolder(); - - private static Object[][] TESTS = { - { ROOT, "testString != null && !false", Boolean.TRUE}, - { ROOT, "!getRenderNavigation() and !getReadonly()", Boolean.TRUE }, - { ROOT, "!bean2.pageBreakAfter", Boolean.TRUE}, - { ROOT, "map", ROOT.getMap() }, - { ROOT, "map.test", ROOT }, - { ROOT, "map[\"test\"]", ROOT }, - { ROOT, "map[\"te\" + \"st\"]", ROOT }, - { ROOT, "map[(\"s\" + \"i\") + \"ze\"]", ROOT.getMap().get(Root.SIZE_STRING) }, - { ROOT, "map[\"size\"]", ROOT.getMap().get(Root.SIZE_STRING) }, - { ROOT, "map[@org.ognl.test.objects.Root@SIZE_STRING]", ROOT.getMap().get(Root.SIZE_STRING) }, - { ROOT, "stringValue != null && stringValue.length() > 0", Boolean.FALSE}, - { ROOT, "indexedStringValue != null && indexedStringValue.length() > 0", Boolean.TRUE}, - { ROOT.getMap(), "list", ROOT.getList() }, - { ROOT, "map.array[0]", new Integer(ROOT.getArray()[0]) }, - { ROOT, "map.list[1]", ROOT.getList().get(1) }, - { ROOT, "map[^]", new Integer(99) }, - { ROOT, "map[$]", null }, - { ROOT.getMap(), "array[$]", new Integer(ROOT.getArray()[ROOT.getArray().length-1]) }, - { ROOT, "[\"map\"]", ROOT.getMap() }, - { ROOT.getArray(), "length", new Integer(ROOT.getArray().length) }, - { ROOT, "getMap().list[|]", ROOT.getList().get(ROOT.getList().size()/2) }, - { ROOT, "map.(array[2] + size())", new Integer(ROOT.getArray()[2] + ROOT.getMap().size()) }, - { ROOT, "map.(#this)", ROOT.getMap() }, - { ROOT, "map.(#this != null ? #this['size'] : null)", ROOT.getMap().get(Root.SIZE_STRING) }, - { ROOT, "map[^].(#this == null ? 'empty' : #this)", new Integer(99) }, - { ROOT, "map[$].(#this == null ? 'empty' : #this)", "empty" }, - { ROOT, "map[$].(#root == null ? 'empty' : #root)", ROOT }, - { ROOT, "((selected != null) && (currLocale.toString() == selected.toString())) ? 'first' : 'second'", "first" }, - { ROOT, "{stringValue, getMap()}", Arrays.asList(new Object[]{ROOT.getStringValue(), ROOT.getMap()})}, - { ROOT, "{'stringValue', map[\"test\"].map[\"size\"]}", Arrays.asList(new Object[]{"stringValue", ROOT.getMap().get("size")}) }, - { ROOT, "property.bean3.value + '(this.checked)'", "100(this.checked)"}, - { ROOT, "getIndexedProperty(property.bean3.map[\"bar\"])", ROOT.getArray()}, - { ROOT, "getProperty().getBean3()", ((Bean2)ROOT.getProperty()).getBean3()}, - { ROOT, "intValue", new Integer(0), new Integer(2), new Integer(2) }, - { ROOT, "! booleanValue", Boolean.TRUE}, - { ROOT, "booleanValue", Boolean.FALSE, Boolean.TRUE, Boolean.TRUE}, - { ROOT, "! disabled", new Boolean(false)}, - { ROOT, "disabled || readonly", Boolean.TRUE}, - { ROOT, "property.bean3.value != null", Boolean.TRUE}, - { ROOT, "\"background-color:blue; width:\" + (currentLocaleVerbosity / 2) + \"px\"", "background-color:blue; width:43px"}, - { ROOT, "renderNavigation ? '' : 'noborder'", "noborder" }, - { ROOT, "format('key', array)", ROOT.format("key", ROOT.getArray()) }, - { ROOT, "format('key', intValue)", ROOT.format("key", /*ROOT.getIntValue()*/ 2) }, // getIntValue() is 0 during startup, but set to 2 during tests! - { ROOT, "format('key', map.size)", ROOT.format("key", ROOT.getMap().size()) }, - { ROOT, "'disableButton(this,\"' + map.get('button-testing') + '\");clearElement("testFtpMessage")'", - "disableButton(this,'null');clearElement('testFtpMessage')" }, - { ROOT.getMap(), "!disableWarning", Boolean.TRUE}, - { ROOT.getMap(), "get('value').bean3.value", new Integer(((Bean2)ROOT.getMap().get("value")).getBean3().getValue())}, - { ROOT.getMap(), "\"Tapestry\".toCharArray()[2]", new Character('p')}, - { ROOT.getMap(), "nested.deep.last", Boolean.TRUE}, - { ROOT, "'last ' + getCurrentClass(@org.ognl.test.PropertyTest@VALUE)", "last foo stop"}, - { ROOT, "@org.ognl.test.PropertyTest@formatValue(property.millis, true, true)", formatValue((int)((Bean2)ROOT.getProperty()).getMillis(), true, true) }, - { ROOT, "nullObject || !readonly", Boolean.TRUE }, - { ROOT, "testDate == null ? '-' : @org.ognl.test.PropertyTest@DATETIME_FORMAT.format(testDate)", DATETIME_FORMAT.format(ROOT.getTestDate()) }, - { ROOT, "disabled ? 'disabled' : 'othernot'", "disabled" }, - { BEAN, "two.getMessage(active ? 'ACT' : 'INA')", "[ACT]"}, - { BEAN, "hasChildren('aaa')", Boolean.TRUE}, - { BEAN, "two.hasChildren('aa')", Boolean.FALSE}, - { BEAN, "two.hasChildren('a')", Boolean.FALSE}, - { ROOT, "sorted ? (readonly ? 'currentSortDesc' : 'currentSortAsc') : 'currentSortNone'", "currentSortAsc"}, - { ROOT, "getAsset( (width?'Yes':'No')+'Icon' )", "NoIcon"}, - { ROOT, "flyingMonkey", Boolean.TRUE}, - { ROOT, "expiration == null ? '' : @org.ognl.test.PropertyTest@DATE_FORMAT.format(expiration)", ""}, - { ROOT, "printDelivery ? 'javascript:toggle(' + bean2.id + ');' : ''", "javascript:toggle(1);"}, - { ROOT, "openTransitionWin", Boolean.FALSE}, - { ROOT, "b.methodOfB(a.methodOfA(b)-1)", new Integer(0)}, - { ROOT, "disabled", Boolean.TRUE}, - { PROPERTY, "value", ""}, - { PROPERTY, "search", "foo" } - }; - - public static String formatValue(int millis, boolean b1, boolean b2) - { - return millis + "-formatted"; - } - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - - if (TESTS[i].length == 5) { - - result.addTest(new PropertyTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else - result.addTest(new PropertyTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2])); - } - - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public PropertyTest() - { - super(); - } - - public PropertyTest(String name) - { - super(name); - } - - public PropertyTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public PropertyTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public PropertyTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/ProtectedInnerClassTest.java b/src/test/java/org/ognl/test/ProtectedInnerClassTest.java deleted file mode 100644 index 8949283c..00000000 --- a/src/test/java/org/ognl/test/ProtectedInnerClassTest.java +++ /dev/null @@ -1,92 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Root; - -public class ProtectedInnerClassTest extends OgnlTestCase -{ - - private static Root ROOT = new Root(); - - private static Object[][] TESTS = { - // member access of inner class (Arrays.asList() returned protected inner class) - { ROOT, "list.size()", new Integer(ROOT.getList().size()) }, - { ROOT, "list[0]", ROOT.getList().get(0) }, - }; - - /* - * =================================================================== Public static methods - * =================================================================== - */ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for(int i = 0; i < TESTS.length; i++) { - result.addTest(new ProtectedInnerClassTest((String) TESTS[i][1], TESTS[i][0], (String) TESTS[i][1], - TESTS[i][2])); - } - return result; - } - - /* - * =================================================================== Constructors - * =================================================================== - */ - public ProtectedInnerClassTest() - { - super(); - } - - public ProtectedInnerClassTest(String name) - { - super(name); - } - - public ProtectedInnerClassTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public ProtectedInnerClassTest(String name, Object root, String expressionString, Object expectedResult, - Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public ProtectedInnerClassTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/QuotingTest.java b/src/test/java/org/ognl/test/QuotingTest.java deleted file mode 100644 index b8f7f463..00000000 --- a/src/test/java/org/ognl/test/QuotingTest.java +++ /dev/null @@ -1,99 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; - -public class QuotingTest extends OgnlTestCase -{ - private static Object[][] TESTS = { - // Quoting - { null, "`c`", new Character('c') }, - { null, "'s'", new Character('s') }, - { null, "'string'", "string" }, - { null, "\"string\"", "string" }, - { null, "'' + 'bar'", "bar"}, - { null, "'yyyy年MM月dd日'", "yyyy年MM月dd日"} - }; - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new QuotingTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new QuotingTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new QuotingTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public QuotingTest() - { - super(); - } - - public QuotingTest(String name) - { - super(name); - } - - public QuotingTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public QuotingTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public QuotingTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/SetterTest.java b/src/test/java/org/ognl/test/SetterTest.java deleted file mode 100644 index 99af8716..00000000 --- a/src/test/java/org/ognl/test/SetterTest.java +++ /dev/null @@ -1,129 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.InappropriateExpressionException; -import ognl.NoSuchPropertyException; -import org.ognl.test.objects.Root; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - -public class SetterTest extends OgnlTestCase -{ - private static Root ROOT = new Root(); - - static Set _list = new HashSet(); - static { - _list.add("Test1"); - } - - private static Object[][] TESTS = { - // Setting values - { ROOT.getMap(), "newValue", null, new Integer(101) }, - { ROOT, "settableList[0]", "foo", "quux" }, // absolute indexes - { ROOT, "settableList[0]", "quux" }, - { ROOT, "settableList[2]", "baz", "quux" }, - { ROOT, "settableList[2]", "quux" }, - { ROOT, "settableList[$]", "quux", "oompa" }, // special indexes - { ROOT, "settableList[$]", "oompa" }, - { ROOT, "settableList[^]", "quux", "oompa" }, - { ROOT, "settableList[^]", "oompa" }, - { ROOT, "settableList[|]", "bar", "oompa" }, - { ROOT, "settableList[|]", "oompa" }, - { ROOT, "map.newValue", new Integer(101), new Integer(555) }, - { ROOT, "map", ROOT.getMap(), new HashMap(), NoSuchPropertyException.class }, - { ROOT.getMap(), "newValue2 || put(\"newValue2\",987), newValue2", new Integer(987), new Integer(1002) }, - { ROOT, "map.(someMissingKey || newValue)", new Integer(555), new Integer(666) }, - { ROOT.getMap(), "newValue || someMissingKey", new Integer(666), new Integer(666) }, // no setting happens! - { ROOT, "map.(newValue && aKey)", null, new Integer(54321)}, - { ROOT, "map.(someMissingKey && newValue)", null, null }, // again, no setting - { null, "0", new Integer(0), null, InappropriateExpressionException.class }, // illegal for setting, no property - { ROOT, "map[0]=\"map.newValue\", map[0](#this)", new Integer(666), new Integer(888) }, - { ROOT, "selectedList", null, _list, IllegalArgumentException.class}, - { ROOT, "openTransitionWin", Boolean.FALSE, Boolean.TRUE} - }; - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new SetterTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new SetterTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new SetterTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public SetterTest() - { - super(); - } - - public SetterTest(String name) - { - super(name); - } - - public SetterTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public SetterTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public SetterTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/SetterWithConversionTest.java b/src/test/java/org/ognl/test/SetterWithConversionTest.java deleted file mode 100644 index 008eaea7..00000000 --- a/src/test/java/org/ognl/test/SetterWithConversionTest.java +++ /dev/null @@ -1,108 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Root; - -public class SetterWithConversionTest extends OgnlTestCase -{ - private static Root ROOT = new Root(); - - private static Object[][] TESTS = { - // Property set with conversion - { ROOT, "intValue", new Integer(0), new Double(6.5), new Integer(6) }, - { ROOT, "intValue", new Integer(6), new Double(1025.87645), new Integer(1025) }, - { ROOT, "intValue", new Integer(1025), "654", new Integer(654) }, - { ROOT, "stringValue", null, new Integer(25), "25" }, - { ROOT, "stringValue", "25", new Float(100.25), "100.25" }, - { ROOT, "anotherStringValue", "foo", new Integer(0), "0" }, - { ROOT, "anotherStringValue", "0", new Double(0.5), "0.5" }, - { ROOT, "anotherIntValue", new Integer(123), "5", new Integer(5) }, - { ROOT, "anotherIntValue", new Integer(5), new Double(100.25), new Integer(100) }, - // { ROOT, "anotherIntValue", new Integer(100), new String[] { "55" }, new Integer(55)}, - // { ROOT, "yetAnotherIntValue", new Integer(46), new String[] { "55" }, new Integer(55)}, - - }; - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - if (TESTS[i].length == 3) { - result.addTest(new SetterWithConversionTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2])); - } else { - if (TESTS[i].length == 4) { - result.addTest(new SetterWithConversionTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3])); - } else { - if (TESTS[i].length == 5) { - result.addTest(new SetterWithConversionTest((String)TESTS[i][1], TESTS[i][0], (String)TESTS[i][1], TESTS[i][2], TESTS[i][3], TESTS[i][4])); - } else { - throw new RuntimeException("don't understand TEST format"); - } - } - } - } - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public SetterWithConversionTest() - { - super(); - } - - public SetterWithConversionTest(String name) - { - super(name); - } - - public SetterWithConversionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public SetterWithConversionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public SetterWithConversionTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/ShortCircuitingExpressionTest.java b/src/test/java/org/ognl/test/ShortCircuitingExpressionTest.java deleted file mode 100644 index f232d1aa..00000000 --- a/src/test/java/org/ognl/test/ShortCircuitingExpressionTest.java +++ /dev/null @@ -1,90 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.NoSuchPropertyException; -import ognl.OgnlException; - -public class ShortCircuitingExpressionTest extends OgnlTestCase -{ - private static Object[][] TESTS = { - { "#root ? someProperty : 99", new Integer(99) }, - { "#root ? 99 : someProperty", OgnlException.class }, - { "(#x=99)? #x.someProperty : #x", NoSuchPropertyException.class }, - { "#xyzzy.doubleValue()", NullPointerException.class }, - { "#xyzzy && #xyzzy.doubleValue()", null }, - { "(#x=99) && #x.doubleValue()", new Double(99) }, - { "#xyzzy || 101", new Integer(101) }, - { "99 || 101", new Integer(99) }, - }; - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - result.addTest(new ShortCircuitingExpressionTest((String)TESTS[i][0] + " (" + TESTS[i][1] + ")", null, (String)TESTS[i][0], TESTS[i][1])); - } - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public ShortCircuitingExpressionTest() - { - super(); - } - - public ShortCircuitingExpressionTest(String name) - { - super(name); - } - - public ShortCircuitingExpressionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public ShortCircuitingExpressionTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public ShortCircuitingExpressionTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/SimpleNavigationChainTreeTest.java b/src/test/java/org/ognl/test/SimpleNavigationChainTreeTest.java deleted file mode 100644 index bcbc1c3d..00000000 --- a/src/test/java/org/ognl/test/SimpleNavigationChainTreeTest.java +++ /dev/null @@ -1,93 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.Ognl; - -public class SimpleNavigationChainTreeTest extends OgnlTestCase { - - private static Object[][] TESTS = { - {"name", Boolean.TRUE}, - {"name[i]", Boolean.FALSE}, - {"name + foo", Boolean.FALSE}, - {"name.foo", Boolean.TRUE} - }; - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - result.addTest(new SimpleNavigationChainTreeTest((String) TESTS[i][0] + " (" + TESTS[i][1] + ")", null, (String) TESTS[i][0], TESTS[i][1])); - } - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public SimpleNavigationChainTreeTest() - { - super(); - } - - public SimpleNavigationChainTreeTest(String name) - { - super(name); - } - - public SimpleNavigationChainTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public SimpleNavigationChainTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public SimpleNavigationChainTreeTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } - - /*=================================================================== - Overridden methods - ===================================================================*/ - protected void runTest() throws Exception - { - assertTrue(Ognl.isSimpleNavigationChain(getExpression(), _context) == ((Boolean) getExpectedResult()).booleanValue()); - } -} diff --git a/src/test/java/org/ognl/test/SimplePropertyTreeTest.java b/src/test/java/org/ognl/test/SimplePropertyTreeTest.java deleted file mode 100644 index 24dc7824..00000000 --- a/src/test/java/org/ognl/test/SimplePropertyTreeTest.java +++ /dev/null @@ -1,97 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import ognl.Ognl; - -public class SimplePropertyTreeTest extends OgnlTestCase -{ - private static Object[][] TESTS = { - { "name", Boolean.TRUE }, - { "foo", Boolean.TRUE }, - { "name[i]", Boolean.FALSE }, - { "name + foo", Boolean.FALSE }, - { "name.foo", Boolean.FALSE }, - { "name.foo.bar", Boolean.FALSE }, - { "name.{? foo }", Boolean.FALSE }, - { "name.( foo )", Boolean.FALSE } - }; - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - result.addTest(new SimplePropertyTreeTest((String)TESTS[i][0] + " (" + TESTS[i][1] + ")", null, (String)TESTS[i][0], TESTS[i][1])); - } - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public SimplePropertyTreeTest() - { - super(); - } - - public SimplePropertyTreeTest(String name) - { - super(name); - } - - public SimplePropertyTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public SimplePropertyTreeTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public SimplePropertyTreeTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } - - /*=================================================================== - Overridden methods - ===================================================================*/ - protected void runTest() throws Exception - { - assertTrue(Ognl.isSimpleProperty(getExpression(), _context) == ((Boolean)getExpectedResult()).booleanValue()); - } -} diff --git a/src/test/java/org/ognl/test/StaticsAndConstructorsTest.java b/src/test/java/org/ognl/test/StaticsAndConstructorsTest.java deleted file mode 100644 index 22a8d35c..00000000 --- a/src/test/java/org/ognl/test/StaticsAndConstructorsTest.java +++ /dev/null @@ -1,188 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test; - -import junit.framework.TestSuite; -import org.ognl.test.objects.Root; -import org.ognl.test.objects.Simple; - -public class StaticsAndConstructorsTest extends OgnlTestCase -{ - private static Root ROOT = new Root(); - - private static Object[][] TESTS = { - { "@java.lang.Class@forName(\"java.lang.Object\")", Object.class }, - { "@java.lang.Integer@MAX_VALUE", new Integer(Integer.MAX_VALUE) }, - { "@@max(3,4)", new Integer(4) }, - { "new java.lang.StringBuffer().append(55).toString()", "55" }, - { "class", ROOT.getClass() }, - { "@org.ognl.test.objects.Root@class", ROOT.getClass() }, - { "class.getName()", ROOT.getClass().getName() }, - { "@org.ognl.test.objects.Root@class.getName()", ROOT.getClass().getName() }, - { "@org.ognl.test.objects.Root@class.name", ROOT.getClass().getName() }, - { "class.getSuperclass()", ROOT.getClass().getSuperclass() }, - { "class.superclass", ROOT.getClass().getSuperclass() }, - { "class.name", ROOT.getClass().getName() }, - { "getStaticInt()", new Integer(Root.getStaticInt()) }, - { "@org.ognl.test.objects.Root@getStaticInt()", new Integer(Root.getStaticInt()) }, - { "new org.ognl.test.objects.Simple(property).getStringValue()", new Simple().getStringValue() }, - { "new org.ognl.test.objects.Simple(map['test'].property).getStringValue()", new Simple().getStringValue() }, - { "map.test.getCurrentClass(@org.ognl.test.StaticsAndConstructorsTest@KEY.toString())", "size stop"}, - { "new org.ognl.test.StaticsAndConstructorsTest$IntWrapper(index)", new IntWrapper(ROOT.getIndex()) }, - { "new org.ognl.test.StaticsAndConstructorsTest$IntObjectWrapper(index)", new IntObjectWrapper(ROOT.getIndex()) }, - { "new org.ognl.test.StaticsAndConstructorsTest$A(#root)", new A(ROOT)}, - {"@org.ognl.test.StaticsAndConstructorsTest$Animals@values().length != 2", Boolean.TRUE}, - {"isOk(@org.ognl.test.objects.SimpleEnum@ONE, null)", Boolean.TRUE}, - }; - - public static final String KEY = "size"; - - public static class IntWrapper { - public IntWrapper(int value) - { - this.value = value; - } - - private final int value; - - public String toString() - { - return Integer.toString(value); - } - - public boolean equals(Object o) - { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - - IntWrapper that = (IntWrapper) o; - - return value == that.value; - } - } - - public static class IntObjectWrapper { - - public IntObjectWrapper(Integer value) - { - this.value = value; - } - - private final Integer value; - - public String toString() - { - return value.toString(); - } - - public boolean equals(Object o) - { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - - IntObjectWrapper that = (IntObjectWrapper) o; - - return value.equals(that.value); - } - } - - public static class A - { - String key = "A"; - - public A(Root root) - { - - } - - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - A a = (A) o; - - if (key != null ? !key.equals(a.key) : a.key != null) return false; - - return true; - } - } - - public enum Animals { - - Dog, Cat, Wallabee, Bear - } - - /*=================================================================== - Public static methods - ===================================================================*/ - public static TestSuite suite() - { - TestSuite result = new TestSuite(); - - for (int i = 0; i < TESTS.length; i++) { - result.addTest(new StaticsAndConstructorsTest((String)TESTS[i][0] + " (" + TESTS[i][1] + ")", ROOT, (String)TESTS[i][0], TESTS[i][1])); - } - return result; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public StaticsAndConstructorsTest() - { - super(); - } - - public StaticsAndConstructorsTest(String name) - { - super(name); - } - - public StaticsAndConstructorsTest(String name, Object root, String expressionString, Object expectedResult, Object setValue, Object expectedAfterSetResult) - { - super(name, root, expressionString, expectedResult, setValue, expectedAfterSetResult); - } - - public StaticsAndConstructorsTest(String name, Object root, String expressionString, Object expectedResult, Object setValue) - { - super(name, root, expressionString, expectedResult, setValue); - } - - public StaticsAndConstructorsTest(String name, Object root, String expressionString, Object expectedResult) - { - super(name, root, expressionString, expectedResult); - } -} diff --git a/src/test/java/org/ognl/test/objects/BaseObjectIndexed.java b/src/test/java/org/ognl/test/objects/BaseObjectIndexed.java deleted file mode 100644 index ee6536f7..00000000 --- a/src/test/java/org/ognl/test/objects/BaseObjectIndexed.java +++ /dev/null @@ -1,76 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -import java.util.*; - -public class BaseObjectIndexed extends Object -{ - private Map attributes = new HashMap(); - - public BaseObjectIndexed() - { - super(); - } - - public Map getAttributes() - { - return attributes; - } - - public Object getAttribute(String name) - { - return attributes.get(name); - } - - public void setAttribute(String name, Object value) - { - attributes.put(name, value); - } - - /* allow testing property name where types do not match */ - public Object getOtherAttribute(String name) - { - return null; - } - - public void setOtherAttribute(Object someObject, Object foo) - { - /* do nothing */ - } - - - /* test whether get only is found */ - public Object getSecondaryAttribute(Object name) - { - return attributes.get(name); - } -} diff --git a/src/test/java/org/ognl/test/objects/Bean1.java b/src/test/java/org/ognl/test/objects/Bean1.java deleted file mode 100644 index 4661b7ac..00000000 --- a/src/test/java/org/ognl/test/objects/Bean1.java +++ /dev/null @@ -1,41 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -public class Bean1 extends Object -{ - private Bean2 bean2 = new Bean2(); - - public Bean2 getBean2() - { - return bean2; - } -} diff --git a/src/test/java/org/ognl/test/objects/Bean2.java b/src/test/java/org/ognl/test/objects/Bean2.java deleted file mode 100644 index 0f7f2790..00000000 --- a/src/test/java/org/ognl/test/objects/Bean2.java +++ /dev/null @@ -1,92 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -public class Bean2 extends Object -{ - private Bean3 bean3 = new Bean3(); - - private boolean _pageBreakAfter = false; - - public String code = "code"; - - public Long getId() - { - return 1l; - } - - public Bean3 getBean3() - { - return bean3; - } - - public long getMillis() - { - return 1000 * 60 * 2; - } - - public boolean isCarrier() - { - return false; - } - - public boolean isPageBreakAfter() - { - return _pageBreakAfter; - } - - public void setPageBreakAfter(boolean value) - { - _pageBreakAfter = value; - } - - public void togglePageBreakAfter() - { - _pageBreakAfter ^= true; - } - - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Bean2 bean2 = (Bean2) o; - - if (_pageBreakAfter != bean2._pageBreakAfter) return false; - - return true; - } - - public int hashCode() - { - return (_pageBreakAfter ? 1 : 0); - } -} diff --git a/src/test/java/org/ognl/test/objects/Bean3.java b/src/test/java/org/ognl/test/objects/Bean3.java deleted file mode 100644 index 05ad187e..00000000 --- a/src/test/java/org/ognl/test/objects/Bean3.java +++ /dev/null @@ -1,110 +0,0 @@ -// -------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -// -------------------------------------------------------------------------- -package org.ognl.test.objects; - -import java.util.HashMap; -import java.util.Map; - -public class Bean3 extends Object -{ - private int value = 100; - - private Map map; - { - map = new HashMap(); - map.put("foo", "bar"); - map.put("bar", "baz"); - } - - private String _nullValue; - private Object _indexValue; - - public int getValue() - { - return value; - } - - public void setValue(int value) - { - this.value = value; - } - - public Object getIndexedValue(int index) - { - return _indexValue; - } - - public void setIndexedValue(int index, Object value) - { - _indexValue = value; - } - - public Map getMap() - { - return map; - } - - public void setNullValue(String value) - { - _nullValue = value; - } - - public String getNullValue() - { - return _nullValue; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((_indexValue == null) ? 0 : _indexValue.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) - { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - final Bean3 other = (Bean3) obj; - if (_indexValue == null) { - if (other._indexValue != null) return false; - } else if (!_indexValue.equals(other._indexValue)) return false; - return true; - } -} diff --git a/src/test/java/org/ognl/test/objects/BeanProvider.java b/src/test/java/org/ognl/test/objects/BeanProvider.java deleted file mode 100644 index fdfb9a9b..00000000 --- a/src/test/java/org/ognl/test/objects/BeanProvider.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * - */ -package org.ognl.test.objects; - - -/** - * Test interface to be used with a custom propery accessor. - */ -public interface BeanProvider -{ - - /** - * Gets a bean by name. - * @param name - * @return - */ - Object getBean(String name); - - /** - * Sets a new bean mapping. - * @param name - * @param bean - */ - void setBean(String name, Object bean); -} diff --git a/src/test/java/org/ognl/test/objects/Component.java b/src/test/java/org/ognl/test/objects/Component.java deleted file mode 100644 index b35cbdb8..00000000 --- a/src/test/java/org/ognl/test/objects/Component.java +++ /dev/null @@ -1,85 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -public class Component extends Object -{ - private URLStorage toDisplay = new URLStorage(); - private Page page = new Page(); - - public static class URLStorage extends Object - { - private String pictureUrl = "http://www.picturespace.com/pictures/100"; - - public String getPictureUrl() - { - return pictureUrl; - } - - public void setPictureUrl(String value) - { - pictureUrl = value; - } - } - - public static class Page extends Object - { - public Object createRelativeAsset(String value) - { - return "/toplevel/" + value; - } - } - - public Component() - { - super(); - } - - public Page getPage() - { - return page; - } - - public void setPage(Page value) - { - page = value; - } - - public URLStorage getToDisplay() - { - return toDisplay; - } - - public void setToDisplay(URLStorage value) - { - toDisplay = value; - } -} diff --git a/src/test/java/org/ognl/test/objects/ComponentImpl.java b/src/test/java/org/ognl/test/objects/ComponentImpl.java deleted file mode 100644 index 85bbb871..00000000 --- a/src/test/java/org/ognl/test/objects/ComponentImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.ognl.test.objects; - -/** - * - */ -public class ComponentImpl implements IComponent { - - String _clientId; - int _count = 0; - - public String getClientId() - { - return _clientId; - } - - public void setClientId(String id) - { - _clientId = id; - } - - public int getCount(String index) - { - return _count; - } - - public void setCount(String index, int count) - { - _count = count; - } -} diff --git a/src/test/java/org/ognl/test/objects/CorrectedObject.java b/src/test/java/org/ognl/test/objects/CorrectedObject.java deleted file mode 100644 index a5f92b0d..00000000 --- a/src/test/java/org/ognl/test/objects/CorrectedObject.java +++ /dev/null @@ -1,56 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -public class CorrectedObject -{ - public CorrectedObject() - { - } - - public void setStringValue(String value) - { - } - - public String getStringValue() - { - return null; - } - - public String getIndexedStringValue(String key) - { - return null; - } - - public void setIndexedStringValue(String key, String value) - { - } -} diff --git a/src/test/java/org/ognl/test/objects/EvenOdd.java b/src/test/java/org/ognl/test/objects/EvenOdd.java deleted file mode 100644 index fc9afe93..00000000 --- a/src/test/java/org/ognl/test/objects/EvenOdd.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.ognl.test.objects; - -/** - * - */ -public class EvenOdd { - - private boolean even = true; - - /** - * Returns "even" or "odd". Whatever it returns on one invocation, it will - * return the opposite on the next. By default, the first value returned is - * "even". - */ - public String getNext() - { - String result = even ? "even" : "odd"; - - even = !even; - - return result; - } - - public boolean isEven() - { - return even; - } - - /** - * Overrides the even flag. - */ - - public void setEven(boolean value) - { - even = value; - } -} diff --git a/src/test/java/org/ognl/test/objects/FirstBean.java b/src/test/java/org/ognl/test/objects/FirstBean.java deleted file mode 100644 index bbaeebca..00000000 --- a/src/test/java/org/ognl/test/objects/FirstBean.java +++ /dev/null @@ -1,17 +0,0 @@ -/** - * - */ -package org.ognl.test.objects; - - -/** - */ -public class FirstBean extends BaseBean -{ - - public String getName() - { - return "FirstBean"; - } - -} diff --git a/src/test/java/org/ognl/test/objects/GetterMethods.java b/src/test/java/org/ognl/test/objects/GetterMethods.java deleted file mode 100644 index 04285852..00000000 --- a/src/test/java/org/ognl/test/objects/GetterMethods.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.ognl.test.objects; - -/** - * - */ -public class GetterMethods { - - private int theInt = 1; - - public boolean isAllowDisplay(Object something) - { - return true; - } - - public int getAllowDisplay() - { - return theInt; - } - - public void setAllowDisplay(int val) - { - theInt = val; - } -} diff --git a/src/test/java/org/ognl/test/objects/Indexed.java b/src/test/java/org/ognl/test/objects/Indexed.java deleted file mode 100644 index dacf42e6..00000000 --- a/src/test/java/org/ognl/test/objects/Indexed.java +++ /dev/null @@ -1,111 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -import java.util.*; - -public class Indexed extends BaseIndexed -{ - private String[] _values = new String[] { "foo", "bar", "baz" }; - - private List _list = new ArrayList(); - private ListSource _source = new ListSourceImpl(); - - private Map _props = new HashMap(); - - public Indexed() - { - _list.add(new Integer(1)); - _list.add(new Integer(2)); - _list.add(new Integer(3)); - - _source.addValue(new Bean2()); - } - - public Indexed(String[] values) - { - _values = values; - } - - /* Indexed property "_values" */ - public String[] getValues() - { - return _values; - } - - public void setValues(String[] value) - { - _values = value; - } - - /** - This method returns the string from the array and appends "xxx" to - distinguish the "get" method from the direct array access. - */ - public String getValues(int index) - { - return _values[index] + "xxx"; - } - - public void setValues(int index, String value) - { - if (value.endsWith("xxx")) { - _values[index] = value.substring(0, value.length() - 3); - } else { - _values[index] = value; - } - } - - public Collection getList() - { - return _list; - } - - public String getTitle(int count) - { - return "Title count " + count; - } - - public ListSource getSource() - { - return _source; - } - - public void setProperty(String property, Object value) - { - _props.put(property, value); - } - - public Object getProperty(String property) - { - return _props.get(property); - } -} diff --git a/src/test/java/org/ognl/test/objects/MenuItem.java b/src/test/java/org/ognl/test/objects/MenuItem.java deleted file mode 100644 index dd83c32f..00000000 --- a/src/test/java/org/ognl/test/objects/MenuItem.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.ognl.test.objects; - -import java.util.ArrayList; -import java.util.List; - -/** - * - */ -public class MenuItem { - - private String page; - private String label; - private List children = new ArrayList(); - - public MenuItem(String page, String label){ - this(page, label, new ArrayList()); - } - - public MenuItem(String page, String label, List children){ - this.page = page; - this.label = label; - this.children = children; - } - - public List getChildren() { - return children; - } - - public String getLabel() { - return label; - } - - public String getPage() { - return page; - } - - public String toString(){ - StringBuffer sb = new StringBuffer("MenuItem["); - sb.append("page="+getPage()); - sb.append(",label="+getLabel()); - sb.append(",children="+getChildren().size()); - sb.append("]"); - return sb.toString(); - } -} diff --git a/src/test/java/org/ognl/test/objects/Model.java b/src/test/java/org/ognl/test/objects/Model.java deleted file mode 100644 index d007207d..00000000 --- a/src/test/java/org/ognl/test/objects/Model.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.ognl.test.objects; - -/** - * - */ -public class Model { - - public int getOptionCount() - { - return 1; - } -} diff --git a/src/test/java/org/ognl/test/objects/MyMap.java b/src/test/java/org/ognl/test/objects/MyMap.java deleted file mode 100644 index 7b8bf6b8..00000000 --- a/src/test/java/org/ognl/test/objects/MyMap.java +++ /dev/null @@ -1,42 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -import java.util.*; - -/** - This tests the interface inheritence test. This is a subinterface - of Map and therefore should inherit the Map property accessor. - */ -public interface MyMap extends Map -{ - public String getDescription(); -} diff --git a/src/test/java/org/ognl/test/objects/MyMapImpl.java b/src/test/java/org/ognl/test/objects/MyMapImpl.java deleted file mode 100644 index 3cf777ab..00000000 --- a/src/test/java/org/ognl/test/objects/MyMapImpl.java +++ /dev/null @@ -1,118 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -import java.util.*; - -/** - This tests the interface inheritence test. This test implements - MyMap->Map but extends Object, therefore should be coded using - MapPropertyAccessor instead of ObjectPropertyAccessor. - */ -public class MyMapImpl extends Object implements MyMap -{ - private Map map = new HashMap(); - - public void clear() - { - map.clear(); - } - - public boolean containsKey(Object key) - { - return map.containsKey(key); - } - - public boolean containsValue(Object value) - { - return map.containsValue(value); - } - - public Set entrySet() - { - return map.entrySet(); - } - - public boolean equals(Object o) - { - return map.equals(o); - } - - public Object get(Object key) - { - return map.get(key); - } - - public int hashCode() - { - return map.hashCode(); - } - - public boolean isEmpty() - { - return map.isEmpty(); - } - - public Set keySet() - { - return map.keySet(); - } - - public Object put(Object key, Object value) - { - return map.put(key, value); - } - - public void putAll(Map t) - { - map.putAll(t); - } - - public Object remove(Object key) - { - return map.remove(key); - } - - public int size() - { - return map.size(); - } - - public Collection values() - { - return map.values(); - } - - public String getDescription() - { - return "MyMap implementation"; - } -} diff --git a/src/test/java/org/ognl/test/objects/ObjectIndexed.java b/src/test/java/org/ognl/test/objects/ObjectIndexed.java deleted file mode 100644 index f6921e51..00000000 --- a/src/test/java/org/ognl/test/objects/ObjectIndexed.java +++ /dev/null @@ -1,42 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -public class ObjectIndexed extends BaseObjectIndexed -{ - public ObjectIndexed() - { - super(); - setAttribute("foo", "bar"); - setAttribute("bar", "baz"); - setAttribute("other", new OtherObjectIndexed()); - } -} diff --git a/src/test/java/org/ognl/test/objects/OtherObjectIndexed.java b/src/test/java/org/ognl/test/objects/OtherObjectIndexed.java deleted file mode 100644 index af112f6a..00000000 --- a/src/test/java/org/ognl/test/objects/OtherObjectIndexed.java +++ /dev/null @@ -1,41 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -public class OtherObjectIndexed extends BaseObjectIndexed -{ - public OtherObjectIndexed() - { - super(); - setAttribute("foo", "bar"); - setAttribute("bar", "baz"); - } -} diff --git a/src/test/java/org/ognl/test/objects/Root.java b/src/test/java/org/ognl/test/objects/Root.java deleted file mode 100644 index d63c8576..00000000 --- a/src/test/java/org/ognl/test/objects/Root.java +++ /dev/null @@ -1,561 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -import ognl.DynamicSubscript; - -import java.util.*; - -public class Root extends Object -{ - public static final String SIZE_STRING = "size"; - public static final int STATIC_INT = 23; - - private int[] array = { 1, 2, 3, 4 }; - private Map map = new HashMap(23); - private MyMap myMap = new MyMapImpl(); - private List list = Arrays.asList(new Object[] { null, this, array }); - private List settableList = new ArrayList(Arrays.asList(new Object[] { "foo", "bar", "baz" })); - private int index = 1; - private int intValue = 0; - private String stringValue; - private int yetAnotherIntValue = 46; - private boolean privateAccessorBooleanValue = true; - private int privateAccessorIntValue = 67; - private int privateAccessorIntValue2 = 67; - private int privateAccessorIntValue3 = 67; - public String anotherStringValue = "foo"; - public int anotherIntValue = 123; - public int six = 6; - private boolean _disabled; - private Locale _selected = Locale.getDefault(); - private List> _booleanValues = new ArrayList>(); - - private boolean[] _booleanArray = {true, false, true, true}; - private List _list; - private int verbosity = 87; - private BeanProvider _beanProvider = new BeanProviderImpl(); - private boolean _render; - private Boolean _readOnly = Boolean.FALSE; - private Integer _objIndex = new Integer(1); - private Object _genericObjIndex = new Integer(2); - private Date _date = new Date(); - private boolean _openWindow = false; - - private ITreeContentProvider _contentProvider = new TreeContentProvider(); - private Indexed _indexed = new Indexed(); - private SearchTab _tab = new SearchTab(); - - /*=================================================================== - Public static methods - ===================================================================*/ - public static int getStaticInt() - { - return STATIC_INT; - } - - /*=================================================================== - Constructors - ===================================================================*/ - public Root() - { - super(); - } - - /*=================================================================== - Private methods - ===================================================================*/ - { - map.put( "test", this ); - map.put( "array", array ); - map.put( "list", list ); - map.put( "size", new Integer(5000) ); - map.put( DynamicSubscript.first, new Integer(99) ); - map.put( "baz", array); - map.put("value", new Bean2()); - map.put("bar", new Bean3()); - map.put(new Long(82), "StringStuff=someValue"); - - IFormComponent comp = new FormComponentImpl(); - comp.setClientId("formComponent"); - - IForm form = new FormImpl(); - form.setClientId("form1"); - comp.setForm(form); - - map.put("comp", comp); - - Map newMap = new HashMap(); - Map chain = new HashMap(); - newMap.put("deep", chain); - - chain.put("last", Boolean.TRUE); - - map.put("nested", newMap); - - /* make myMap identical */ - myMap.putAll( map ); - - List bool1 = new ArrayList(); - bool1.add(Boolean.TRUE); - bool1.add(Boolean.FALSE); - bool1.add(Boolean.TRUE); - - _booleanValues.add(bool1); - - List bool2 = new ArrayList(); - bool2.add(Boolean.TRUE); - bool2.add(Boolean.FALSE); - bool2.add(Boolean.TRUE); - - _booleanValues.add(bool2); - } - - private boolean isPrivateAccessorBooleanValue() - { - return privateAccessorBooleanValue; - } - - private void setPrivateAccessorBooleanValue(boolean value) - { - privateAccessorBooleanValue = value; - } - - private int getPrivateAccessorIntValue() - { - return privateAccessorIntValue; - } - - private void setPrivateAccessorIntValue(int value) - { - privateAccessorIntValue = value; - } - - /*=================================================================== - Protected methods - ===================================================================*/ - protected int getPrivateAccessorIntValue2() - { - return privateAccessorIntValue2; - } - - protected void setPrivateAccessorIntValue2(int value) - { - privateAccessorIntValue2 = value; - } - - /*=================================================================== - Package protected methods - ===================================================================*/ - int getPrivateAccessorIntValue3() - { - return privateAccessorIntValue3; - } - - void setPrivateAccessorIntValue3(int value) - { - privateAccessorIntValue3 = value; - } - - /*=================================================================== - Public methods - ===================================================================*/ - public int[] getArray() - { - return array; - } - - public boolean[] getBooleanArray() - { - return _booleanArray; - } - - public void setArray(int[] value) - { - array = value; - } - - public String format(String key, Object value) - { - return format(key, new Object[] { value }); - } - - public String format(String key, Object[] value) - { - return "formatted: "+key+" "+Arrays.toString(value); - } - - public String getCurrentClass(String value) - { - return value + " stop"; - } - - public Messages getMessages() - { - return new Messages(map); - } - - public Map getMap() - { - return map; - } - - public MyMap getMyMap() - { - return myMap; - } - - public List getList() - { - return list; - } - - public Object getAsset(String key) - { - return key; - } - - public List getSettableList() - { - return settableList; - } - - public int getIndex() - { - return index; - } - - public Integer getObjectIndex() - { - return _objIndex; - } - - public Integer getNullIndex() - { - return null; - } - - public Object getGenericIndex() - { - return _genericObjIndex; - } - - public int getIntValue() - { - return intValue; - } - - public void setIntValue(int value) - { - intValue = value; - } - - public int getTheInt() - { - return six; - } - - public String getStringValue() - { - return stringValue; - } - - public void setStringValue(String value) - { - stringValue = value; - } - - public String getIndexedStringValue() - { - return "array"; - } - - public Object getNullObject() - { - return null; - } - - public String getTestString() - { - return "wiggle"; - } - - public Object getProperty() - { - return new Bean2(); - } - - public Bean2 getBean2() - { - return new Bean2(); - } - - public Object getIndexedProperty(String name) - { - return myMap.get(name); - } - - public Indexed getIndexer() - { - return _indexed; - } - - public BeanProvider getBeans() - { - return _beanProvider; - } - - public boolean getBooleanValue() - { - return _disabled; - } - - public void setBooleanValue(boolean value) - { - _disabled = value; - } - - public boolean getDisabled() - { - return _disabled; - } - - public void setDisabled(boolean disabled) - { - _disabled = disabled; - } - - public Locale getSelected() - { - return _selected; - } - - public void setSelected(Locale locale) - { - _selected = locale; - } - - public Locale getCurrLocale() - { - return Locale.getDefault(); - } - - public int getCurrentLocaleVerbosity() - { - return verbosity; - } - - public boolean getRenderNavigation() - { - return _render; - } - - public void setSelectedList(List selected) - { - _list = selected; - } - - public List getSelectedList() - { - return _list; - } - - public Boolean getReadonly() - { - return _readOnly; - } - - public void setReadonly(Boolean value) - { - _readOnly = value; - } - - public Object getSelf() - { - return this; - } - - public Date getTestDate() - { - return _date; - } - - public String getWidth() - { - return "238px"; - } - - public Long getTheLong() - { - return new Long(4); - } - - public boolean isSorted() - { - return true; - } - - public TestClass getMyTest() - { - return new TestImpl(); - } - - public ITreeContentProvider getContentProvider() - { - return _contentProvider; - } - - public boolean isPrintDelivery() - { - return true; - } - - public Long getCurrentDeliveryId() - { - return 1l; - } - - public Boolean isFlyingMonkey() - { - return Boolean.TRUE; - } - - public Boolean isDumb() - { - return Boolean.FALSE; - } - - public Date getExpiration() - { - return null; - } - - public Long getMapKey() - { - return new Long(82); - } - - public Object getArrayValue() - { - return new Object[] {new Integer("2"), new Integer("2")}; - } - - public List getResult() - { - List list = new ArrayList(); - list.add(new Object[]{new Integer("2"), new Integer("2")}); - list.add(new Object[]{new Integer("2"), new Integer("2")}); - list.add(new Object[]{new Integer("2"), new Integer("2")}); - - return list; - } - - public boolean isEditorDisabled() - { - return false; - } - - public boolean isDisabled() - { - return true; - } - - public boolean isOpenTransitionWin() - { - return _openWindow; - } - - public void setOpenTransitionWin(boolean value) - { - _openWindow = value; - } - - public boolean isOk(SimpleEnum value, String otherValue) - { - return true; - } - - public List> getBooleanValues() - { - return _booleanValues; - } - - public int getIndex1() - { - return 1; - } - - public int getIndex2() - { - return 1; - } - - public SearchTab getTab() - { - return _tab; - } - - public void setTab(SearchTab tab) - { - _tab = tab; - } - - public static class A - { - public int methodOfA(B b) - { - return 0; - } - - public int getIntValue() - { - return 1; - } - } - - public static class B - { - public int methodOfB(int i) - { - return 0; - } - } - - public A getA() - { - return new A(); - } - - public B getB() - { - return new B(); - } -} diff --git a/src/test/java/org/ognl/test/objects/SecondBean.java b/src/test/java/org/ognl/test/objects/SecondBean.java deleted file mode 100644 index 895399f8..00000000 --- a/src/test/java/org/ognl/test/objects/SecondBean.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * - */ -package org.ognl.test.objects; - - -/** - */ -public class SecondBean extends BaseBean -{ - public String getName() - { - return "SecondBean"; - } - -} diff --git a/src/test/java/org/ognl/test/objects/Simple.java b/src/test/java/org/ognl/test/objects/Simple.java deleted file mode 100644 index 23147ae3..00000000 --- a/src/test/java/org/ognl/test/objects/Simple.java +++ /dev/null @@ -1,276 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.objects; - -import org.ognl.test.OgnlTestCase; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; - -public class Simple extends Object -{ - private String stringValue = "test"; - private float floatValue; - private int intValue; - private boolean booleanValue; - private BigInteger bigIntValue = BigInteger.valueOf(0); - private BigDecimal bigDecValue = new BigDecimal(0.0); - - private Root root = new Root(); - - private Bean3 _bean; - private Bean2 _bean2; - - private Object[] _array; - - private Messages _messages; - - public Simple() - { - Map src = new HashMap(); - src.put("test", "This is a test"); - - _messages = new Messages(src); - } - - public Simple(Bean3 bean) - { - _bean = bean; - } - - public Simple(Bean2 bean) - { - _bean2 = bean; - } - - public Simple(Object[] values) - { - super(); - } - - public Simple(String stringValue, float floatValue, int intValue) - { - super(); - this.stringValue = stringValue; - this.floatValue = floatValue; - this.intValue = intValue; - } - - public void setValues(String stringValue, float floatValue, int intValue) - { - this.stringValue = stringValue; - this.floatValue = floatValue; - this.intValue = intValue; - } - - public String getStringValue() - { - return stringValue; - } - - public void setStringValue(String value) - { - stringValue = value; - } - - public float getFloatValue() - { - return floatValue; - } - - public void setFloatValue(float value) - { - floatValue = value; - } - - public int getIntValue() - { - return intValue; - } - - public void setIntValue(int value) - { - intValue = value; - } - - public boolean getValueIsTrue(Object currValue) - { - return true; - } - - public boolean getBooleanValue() - { - return booleanValue; - } - - public void setBooleanValue(boolean value) - { - booleanValue = value; - } - - public BigInteger getBigIntValue() - { - return bigIntValue; - } - - public void setArray(Object[] values) - { - _array = values; - } - - public Object[] getArray() - { - return _array; - } - - public void setBigIntValue(BigInteger value) - { - bigIntValue = value; - } - - public BigDecimal getBigDecValue() - { - return bigDecValue; - } - - public void setBigDecValue(BigDecimal value) - { - bigDecValue = value; - } - - public Root getRootValue() - { - return root; - } - - public MethodTestMethods getTestMethods() - { - return new MethodTestMethods(); - } - - public Messages getMessages() - { - return _messages; - } - - public int getOne() - { - return 1; - } - - public int getTwo() - { - return 2; - } - - public int getThree() - { - return 3; - } - - public int getTestValue(int val) - { - return val + 1; - } - - public boolean isEditorDisabled() - { - return false; - } - - public boolean isDisabled() - { - return true; - } - - public boolean getIsTruck() { - return true; - } - - public GetterMethods getMethodsTest() - { - return new GetterMethods(); - } - - public String getDisplayValue(int val) - { - return "test"; - } - - public boolean equals(Object other) - { - boolean result = false; - - if (other instanceof Simple) { - Simple os = (Simple)other; - - result = OgnlTestCase.isEqual(os.getStringValue(), getStringValue()) && (os.getIntValue() == getIntValue()); - } - return result; - } - - public boolean isThisVarArgsWorking(Object...arguments) - { - return true; - } - - public String isNullVarArgs() { - return "null"; - } - - public String isStringVarArgs(String... arguments) - { - return "args"; - } - - public TestInterface get() { - return new TestInterface() { - @Override - public String request() { - return "null"; - } - @Override - public String request(Object... args) { - return "args"; - } - }; - } - - interface TestInterface { - - String request(); - String request(Object... args); - - } - -} diff --git a/src/test/java/org/ognl/test/objects/SimpleNumeric.java b/src/test/java/org/ognl/test/objects/SimpleNumeric.java deleted file mode 100644 index 1182dbde..00000000 --- a/src/test/java/org/ognl/test/objects/SimpleNumeric.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.ognl.test.objects; - -/** - * Used for {@link org.ognl.test.PropertyArithmeticAndLogicalOperatorsTest}. - */ -public class SimpleNumeric { - - public double getBudget() - { - return 140; - } - - public double getTimeBilled() - { - return 24.12; - } - - public String getTableSize() - { - return "10"; - } -} diff --git a/src/test/java/org/ognl/test/objects/TestModel.java b/src/test/java/org/ognl/test/objects/TestModel.java deleted file mode 100644 index 31a269be..00000000 --- a/src/test/java/org/ognl/test/objects/TestModel.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.ognl.test.objects; - -/** - * - */ -public class TestModel { - - public Copy getCopy() - { - return new Copy(); - } - - public Model getUnassignedCopyModel() - { - return new Model(); - } - - public boolean isCanApproveCopy() - { - return true; - } - - public Entry getEntry() - { - return new Entry(); - } -} diff --git a/src/test/java/org/ognl/test/objects/Two.java b/src/test/java/org/ognl/test/objects/Two.java deleted file mode 100644 index f71e1844..00000000 --- a/src/test/java/org/ognl/test/objects/Two.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.ognl.test.objects; - -/** - * - */ -public class Two { - - public String getMessage(String mes) - { - return "[" + mes + "]"; - } - - public boolean hasChildren(String name) - { - return name.length() > 2; - } -} diff --git a/src/test/java/org/ognl/test/util/ContextClassLoader.java b/src/test/java/org/ognl/test/util/ContextClassLoader.java deleted file mode 100644 index e9045164..00000000 --- a/src/test/java/org/ognl/test/util/ContextClassLoader.java +++ /dev/null @@ -1,59 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.util; - -import ognl.OgnlContext; - -public class ContextClassLoader extends ClassLoader -{ - private OgnlContext context; - - /*=================================================================== - Constructors - ===================================================================*/ - public ContextClassLoader(ClassLoader parentClassLoader, OgnlContext context) - { - super(parentClassLoader); - this.context = context; - } - - /*=================================================================== - Overridden methods - ===================================================================*/ - protected Class findClass(String name) throws ClassNotFoundException - { - if ((context != null) && (context.getClassResolver() != null)) { - return context.getClassResolver().classForName(name, context); - } - return super.findClass(name); - } - -} diff --git a/src/test/java/org/ognl/test/util/EnhancedClassLoader.java b/src/test/java/org/ognl/test/util/EnhancedClassLoader.java deleted file mode 100644 index eaef451f..00000000 --- a/src/test/java/org/ognl/test/util/EnhancedClassLoader.java +++ /dev/null @@ -1,50 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.util; - -public class EnhancedClassLoader extends ClassLoader -{ - /*=================================================================== - Constructors - ===================================================================*/ - public EnhancedClassLoader(ClassLoader parentClassLoader) - { - super(parentClassLoader); - } - - /*=================================================================== - Overridden methods - ===================================================================*/ - public Class defineClass(String enhancedClassName, byte[] byteCode) - { - return defineClass(enhancedClassName, byteCode, 0, byteCode.length); - } -} diff --git a/src/test/java/org/ognl/test/util/NameFactory.java b/src/test/java/org/ognl/test/util/NameFactory.java deleted file mode 100644 index 2f1bd5ba..00000000 --- a/src/test/java/org/ognl/test/util/NameFactory.java +++ /dev/null @@ -1,62 +0,0 @@ -//-------------------------------------------------------------------------- -// Copyright (c) 2004, Drew Davidson and Luke Blanshard -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// 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. -// Neither the name of the Drew Davidson nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS 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 -// COPYRIGHT OWNER OR 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. -//-------------------------------------------------------------------------- -package org.ognl.test.util; - -public class NameFactory extends Object -{ - private String classBaseName; - private int classNameCounter = 0; - private String variableBaseName; - private int variableNameCounter = 0; - - /*=================================================================== - Constructors - ===================================================================*/ - public NameFactory(String classBaseName, String variableBaseName) - { - super(); - this.classBaseName = classBaseName; - this.variableBaseName = variableBaseName; - } - - /*=================================================================== - Public methods - ===================================================================*/ - public String getNewClassName() - { - return classBaseName + classNameCounter++; - } - - public String getNewVariableName() - { - return variableBaseName + variableNameCounter++; - } -}