index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/DefaultMemberAccess.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.util.Map;
/**
* This class provides methods for setting up and restoring access in a Field. Java 2 provides access utilities for
* setting and getting fields that are non-public. This object provides coarse-grained access controls to allow access
* to private, protected and package protected members. This will apply to all classes and members.
*/
public class DefaultMemberAccess
implements MemberAccess
{
private boolean allowPrivateAccess;
private boolean allowProtectedAccess;
private boolean allowPackageProtectedAccess;
/*
* =================================================================== Constructors
* ===================================================================
*/
public DefaultMemberAccess( boolean allowAllAccess )
{
this( allowAllAccess, allowAllAccess, allowAllAccess );
}
public DefaultMemberAccess( boolean allowPrivateAccess, boolean allowProtectedAccess,
boolean allowPackageProtectedAccess )
{
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<String, Object> context, Object target, Member member, String propertyName )
{
Object result = null;
if ( isAccessible( context, target, member, propertyName ) )
{
AccessibleObject accessible = (AccessibleObject) member;
if ( !accessible.isAccessible() )
{
result = Boolean.TRUE;
accessible.setAccessible( true );
}
}
return result;
}
public void restore( Map<String, Object> context, Object target, Member member, String propertyName, Object state )
{
if ( state != null )
{
( (AccessibleObject) member ).setAccessible( (Boolean) state );
}
}
/**
* Returns true if the given member is accessible or can be made accessible by this object.
*/
public boolean isAccessible( Map<String, Object> 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;
}
}
| 4,600 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ListPropertyAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.*;
/**
* Implementation of PropertyAccessor that uses numbers and dynamic subscripts as properties to index into Lists.
*/
public class ListPropertyAccessor
extends ObjectPropertyAccessor
implements PropertyAccessor
{
@Override
public Object getProperty( Map<String, Object> context, Object target, Object name )
throws OgnlException
{
List<?> list = (List<?>) target;
if ( name instanceof String )
{
Object result;
if ( "size".equals( name ) )
{
result = list.size();
}
else
{
if ( "iterator".equals( name ) )
{
result = list.iterator();
}
else
{
if ( "isEmpty".equals( name ) || "empty".equals( name ) )
{
result = list.isEmpty() ? Boolean.TRUE : Boolean.FALSE;
}
else
{
result = super.getProperty( context, target, name );
}
}
}
return result;
}
if ( name instanceof Number )
{
return list.get( ( (Number) name ).intValue() );
}
if ( name instanceof DynamicSubscript )
{
int len = list.size();
switch ( ( (DynamicSubscript) name ).getFlag() )
{
case DynamicSubscript.FIRST:
return len > 0 ? list.get( 0 ) : null;
case DynamicSubscript.MID:
return len > 0 ? list.get( len / 2 ) : null;
case DynamicSubscript.LAST:
return len > 0 ? list.get( len - 1 ) : null;
case DynamicSubscript.ALL:
return new ArrayList<Object>( list );
default:
break;
}
}
throw new NoSuchPropertyException( target, name );
}
@Override
public void setProperty( Map<String, Object> context, Object target, Object name, Object value )
throws OgnlException
{
if ( name instanceof String && !( (String) name ).contains( "$" ) )
{
super.setProperty( context, target, name, value );
return;
}
@SuppressWarnings( "unchecked" ) // check performed by the invoker
List<Object> list = (List<Object>) target;
if ( name instanceof Number )
{
list.set( ( (Number) name ).intValue(), value );
return;
}
if ( name instanceof DynamicSubscript )
{
int len = list.size();
switch ( ( (DynamicSubscript) name ).getFlag() )
{
case DynamicSubscript.FIRST:
if ( len > 0 )
{
list.set( 0, value );
}
return;
case DynamicSubscript.MID:
if ( len > 0 )
{
list.set( len / 2, value );
}
return;
case DynamicSubscript.LAST:
if ( len > 0 )
{
list.set( len - 1, value );
}
return;
case DynamicSubscript.ALL:
if ( !( value instanceof Collection ) )
{
throw new OgnlException( "Value must be a collection" );
}
list.clear();
list.addAll( (Collection<?>) value );
return;
default:
return;
}
}
throw new NoSuchPropertyException( target, name );
}
@Override
public Class<?> getPropertyClass( OgnlContext context, Object target, Object index )
{
if ( index instanceof String )
{
String key = ( (String) index ).replace( "\"", "" );
if ( "size".equals( key ) )
{
return int.class;
}
if ( "iterator".equals( key ) )
{
return Iterator.class;
}
if ( "isEmpty".equals( key ) || "empty".equals( key ) )
{
return boolean.class;
}
return super.getPropertyClass( context, target, index );
}
if ( index instanceof Number )
{
return Object.class;
}
return null;
}
@Override
public String getSourceAccessor( OgnlContext context, Object target, Object index )
{
String indexStr = index.toString().replace( "\"", "" );
if (index instanceof String)
{
if ( "size".equals( indexStr ) )
{
context.setCurrentAccessor( List.class );
context.setCurrentType( int.class );
return ".size()";
}
if ( "iterator".equals( indexStr ) )
{
context.setCurrentAccessor( List.class );
context.setCurrentType( Iterator.class );
return ".iterator()";
}
if ( "isEmpty".equals( indexStr ) || "empty".equals( indexStr ) )
{
context.setCurrentAccessor( List.class );
context.setCurrentType( boolean.class );
return ".isEmpty()";
}
}
// 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..
return getSourceBeanMethod( context, target, index, indexStr, false );
}
@Override
public String getSourceSetter( OgnlContext context, Object target, Object index )
{
String indexStr = index.toString().replace( "\"", "" );
// 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..
/*
* System.out.println("Listpropertyaccessor setter using index: " + index + " and current object: " +
* context.getCurrentObject() + " number is current object? " +
* Number.class.isInstance(context.getCurrentObject()));
*/
return getSourceBeanMethod( context, target, index, indexStr, true );
}
private String getSourceBeanMethod( OgnlContext context, Object target, Object index, String indexStr,
boolean isSetter )
{
Object currentObject = context.getCurrentObject();
Class<?> currentType = context.getCurrentType();
if ( currentObject != null && !(currentObject instanceof Number))
{
try
{
if ( isSetter )
{
if ( OgnlRuntime.getWriteMethod( target.getClass(), indexStr ) != null
|| !currentType.isPrimitive() )
{
return super.getSourceSetter( context, target, index );
}
}
else
{
if ( OgnlRuntime.getReadMethod( target.getClass(), indexStr ) != null )
{
return super.getSourceAccessor( context, target, index );
}
}
}
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 ( !currentType.isPrimitive() && Number.class.isAssignableFrom( currentType ) )
{
indexStr += "." + OgnlRuntime.getNumericValueGetter( currentType );
}
else if ( currentObject != null && Number.class.isAssignableFrom( currentObject.getClass() )
&& !currentType.isPrimitive() )
{
// means it needs to be cast first as well
String toString = index instanceof String && currentType != Object.class ? "" : ".toString()";
indexStr = "org.apache.commons.ognl.OgnlOps#getIntValue(" + indexStr + toString + ")";
}
context.setCurrentType( Object.class );
return isSetter ? ".set(" + indexStr + ", $3)" : ".get(" + indexStr + ")";
}
}
| 4,601 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTAnd.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
import static java.lang.String.format;
/**
*/
public class ASTAnd
extends BooleanExpression
{
/** Serial */
private static final long serialVersionUID = -4585941425250141812L;
/**
* TODO: javadoc
* @param id the id
*/
public ASTAnd( int id )
{
super( id );
}
/**
* TODO: javadoc
* @param p the parser
* @param id the id
*/
public ASTAnd( OgnlParser p, int id )
{
super( p, id );
}
/* (non-Javadoc)
* @see org.apache.commons.ognl.SimpleNode#jjtClose()
*/
public void jjtClose()
{
flattenTree();
}
/* (non-Javadoc)
* @see org.apache.commons.ognl.SimpleNode#getValueBody(org.apache.commons.ognl.OgnlContext, Object)
*/
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 );
if ( i != last && !OgnlOps.booleanValue( result ) )
{
break;
}
}
return result;
}
/* (non-Javadoc)
* @see org.apache.commons.ognl.SimpleNode#setValueBody(org.apache.commons.ognl.OgnlContext, Object, Object)
*/
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 );
}
/* (non-Javadoc)
* @see org.apache.commons.ognl.ExpressionNode#getExpressionOperator(int)
*/
public String getExpressionOperator( int index )
{
return "&&";
}
/* (non-Javadoc)
* @see org.apache.commons.ognl.BooleanExpression#getGetterClass()
*/
public Class getGetterClass()
{
return null;
}
/* (non-Javadoc)
* @see org.apache.commons.ognl.BooleanExpression#toGetSourceString(org.apache.commons.ognl.OgnlContext, Object)
*/
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() ) )
{
throw new UnsupportedCompilationException(
"And expression can't be compiled until all conditions are true." );
}
if ( !OgnlRuntime.isBoolean( first ) && !context.getCurrentType().isPrimitive() )
{
first = OgnlRuntime.getCompiler( context ).createLocalReference( context, first, context.getCurrentType() );
}
String second = OgnlRuntime.getChildSource( context, target, children[1] );
if ( !OgnlRuntime.isBoolean( second ) && !context.getCurrentType().isPrimitive() )
{
second = OgnlRuntime.getCompiler( context ).createLocalReference( context, second, context.getCurrentType() );
}
result += format( "(org.apache.commons.ognl.OgnlOps.booleanValue(%s) ? ($w) (%s) : ($w) (%s))", first, second, first );
context.setCurrentObject( target );
context.setCurrentType( Object.class );
}
catch ( NullPointerException e )
{
throw new UnsupportedCompilationException( "evaluation resulted in null expression." );
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return result;
}
/* (non-Javadoc)
* @see org.apache.commons.ognl.ExpressionNode#toSetSourceString(org.apache.commons.ognl.OgnlContext, Object)
*/
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" );
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." );
}
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(org.apache.commons.ognl.OgnlOps.booleanValue(" + first + ")){";
}
else
{
result += "if(" + first + "){";
}
result += second;
result += "; } ";
context.setCurrentObject( target );
context.setCurrentType( Object.class );
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return result;
}
/* (non-Javadoc)
* @see org.apache.commons.ognl.Node#accept(org.apache.commons.ognl.NodeVisitor, Object)
*/
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,602 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/JavaSource.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
* 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.
*/
public interface JavaSource
{
/**
* 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 org.apache.commons.ognl.enhance.ExpressionAccessor#get(OgnlContext, Object)} calls.
*
* @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 it could be turned into a literal java
* expression to be compiled and executed for
* {@link org.apache.commons.ognl.enhance.ExpressionAccessor#get(OgnlContext, Object)} calls.
*
* @return Literal java string representation of an object get.
*/
String toSetSourceString( OgnlContext context, Object target );
}
| 4,603 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/OgnlParserTreeConstants.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
* Generated By:JavaCC: Do not edit this line. OgnlParserTreeConstants.java Version 4.1d1
*/
public interface OgnlParserTreeConstants
{
int JJTVOID = 0;
int JJTSEQUENCE = 1;
int JJTASSIGN = 2;
int JJTTEST = 3;
int JJTOR = 4;
int JJTAND = 5;
int JJTBITOR = 6;
int JJTXOR = 7;
int JJTBITAND = 8;
int JJTEQ = 9;
int JJTNOTEQ = 10;
int JJTLESS = 11;
int JJTGREATER = 12;
int JJTLESSEQ = 13;
int JJTGREATEREQ = 14;
int JJTIN = 15;
int JJTNOTIN = 16;
int JJTSHIFTLEFT = 17;
int JJTSHIFTRIGHT = 18;
int JJTUNSIGNEDSHIFTRIGHT = 19;
int JJTADD = 20;
int JJTSUBTRACT = 21;
int JJTMULTIPLY = 22;
int JJTDIVIDE = 23;
int JJTREMAINDER = 24;
int JJTNEGATE = 25;
int JJTBITNEGATE = 26;
int JJTNOT = 27;
int JJTINSTANCEOF = 28;
int JJTCHAIN = 29;
int JJTEVAL = 30;
int JJTCONST = 31;
int JJTTHISVARREF = 32;
int JJTROOTVARREF = 33;
int JJTVARREF = 34;
int JJTLIST = 35;
int JJTMAP = 36;
int JJTKEYVALUE = 37;
int JJTSTATICFIELD = 38;
int JJTCTOR = 39;
int JJTPROPERTY = 40;
int JJTSTATICMETHOD = 41;
int JJTMETHOD = 42;
int JJTPROJECT = 43;
int JJTSELECT = 44;
int JJTSELECTFIRST = 45;
int JJTSELECTLAST = 46;
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) */
| 4,604 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/JJTOgnlParserState.java | package org.apache.commons.ognl;
/*
* 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.
*/
/* Generated By:JavaCC: Do not edit this line. JJTOgnlParserState.java Version 4.1d1 */
import java.util.ArrayList;
import java.util.List;
/**
*/
public class JJTOgnlParserState
{
private final List<Node> nodes;
private final List<Integer> marks;
private int numNodesOnStack;
private int currentMark;
private boolean nodeCreated;
public JJTOgnlParserState()
{
nodes = new ArrayList<Node>();
marks = new ArrayList<Integer>();
numNodesOnStack = 0;
currentMark = 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 nodeCreated;
}
/*
* Call this to reinitialize the node stack. It is called automatically by the parser's ReInit() method.
*/
public void reset()
{
nodes.clear();
marks.clear();
numNodesOnStack = 0;
currentMark = 0;
}
/*
* Returns the root node of the AST. It only makes sense to call this after a successful parse.
*/
public Node rootNode()
{
return nodes.get( 0 );
}
/* Pushes a node on to the stack. */
public void pushNode( Node node )
{
nodes.add( node );
++numNodesOnStack;
}
/*
* Returns the node on the top of the stack, and remove it from the stack.
*/
public Node popNode()
{
if ( --numNodesOnStack < currentMark )
{
currentMark = marks.remove( marks.size() - 1 );
}
return nodes.remove( nodes.size() - 1 );
}
/* Returns the node currently on the top of the stack. */
public Node peekNode()
{
return nodes.get( nodes.size() - 1 );
}
/*
* Returns the number of children on the stack in the current node scope.
*/
public int nodeArity()
{
return numNodesOnStack - currentMark;
}
public void clearNodeScope( Node unused )
{
while ( numNodesOnStack > currentMark )
{
popNode();
}
currentMark = marks.remove( marks.size() - 1 );
}
public void openNodeScope( Node node )
{
marks.add( currentMark );
currentMark = numNodesOnStack;
node.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 node, int num )
{
currentMark = marks.remove( marks.size() - 1 );
while ( num-- > 0 )
{
Node poppedNode = popNode();
poppedNode.jjtSetParent( node );
node.jjtAddChild( poppedNode, num );
}
node.jjtClose();
pushNode( node );
nodeCreated = 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 node, boolean condition )
{
if ( condition )
{
int arity = nodeArity();
currentMark = marks.remove( marks.size() - 1 );
while ( arity-- > 0 )
{
Node poppedNode = popNode();
poppedNode.jjtSetParent( node );
node.jjtAddChild( poppedNode, arity );
}
node.jjtClose();
pushNode( node );
nodeCreated = true;
}
else
{
currentMark = marks.remove( marks.size() - 1 );
nodeCreated = false;
}
}
}
/* JavaCC - OriginalChecksum=61071c68a05e7c9104307c34a2e37165 (do not edit this line) */
| 4,605 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTSelectFirst.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
*/
class ASTSelectFirst
extends SimpleNode
{
public ASTSelectFirst( int id )
{
super( id );
}
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();
if ( OgnlOps.booleanValue( expr.getValue( context, next ) ) )
{
answer.add( next );
break;
}
}
return answer;
}
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 )
{
throw new UnsupportedCompilationException( "Eval expressions not supported as native java yet." );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,606 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTOr.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
*/
public class ASTOr
extends BooleanExpression
{
public ASTOr( int id )
{
super( id );
}
public ASTOr( OgnlParser p, int id )
{
super( p, id );
}
public void jjtClose()
{
flattenTree();
}
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 );
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 ) )
{
return;
}
}
children[last].setValue( context, target, value );
}
public String getExpressionOperator( int index )
{
return "||";
}
public Class getGetterClass()
{
return null;
}
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 ( !OgnlRuntime.isBoolean( first ) )
{
first = OgnlRuntime.getCompiler( context ).createLocalReference( context, first, context.getCurrentType() );
}
Class firstType = context.getCurrentType();
String second = OgnlRuntime.getChildSource( context, target, children[1] );
if ( !OgnlRuntime.isBoolean( second ) )
{
second = OgnlRuntime.getCompiler( context ).createLocalReference( context, second, context.getCurrentType() );
}
Class secondType = context.getCurrentType();
boolean mismatched =
( firstType.isPrimitive( ) && !secondType.isPrimitive( ) ) || ( !firstType.isPrimitive( )
&& secondType.isPrimitive( ) );
result += "org.apache.commons.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 )
{
throw OgnlOps.castToRuntime( t );
}
return result;
}
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" );
if ( pre == null )
{
pre = "";
}
String result = "";
try
{
children[0].getValue( context, target );
String first =
ExpressionCompiler.getRootExpression( children[0], context.getRoot(), context ) + pre
+ children[0].toGetSourceString( context, target );
if ( !OgnlRuntime.isBoolean( first ) )
{
first = OgnlRuntime.getCompiler( context ).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 );
if ( !OgnlRuntime.isBoolean( second ) )
{
second = OgnlRuntime.getCompiler( context ).createLocalReference( context, second, context.getCurrentType() );
}
result += "org.apache.commons.ognl.OgnlOps.booleanValue(" + first + ")";
result += " ? ";
result += first;
result += " : ";
result += second;
context.setCurrentObject( target );
context.setCurrentType( Boolean.TYPE );
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return result;
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,607 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/OgnlInvokePermission.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.security.BasicPermission;
/**
* BasicPermission subclass that defines a permission token for invoking methods within OGNL. This does not override any
* methods (except 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.
*/
public class OgnlInvokePermission
extends BasicPermission
{
private static final long serialVersionUID = 1L;
public OgnlInvokePermission( String name )
{
super( name );
}
public OgnlInvokePermission( String name, String actions )
{
super( name, actions );
}
}
| 4,608 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTMethodUtil.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import org.apache.commons.ognl.enhance.OgnlExpressionCompiler;
/**
*/
class ASTMethodUtil
{
private ASTMethodUtil()
{
}
static String getParmString( OgnlContext context, Object root, Node child, Class prevType )
throws OgnlException
{
String parmString = child.toGetSourceString( context, root );
if ( parmString == null || parmString.trim().length() < 1 )
{
parmString = "null";
}
// to undo type setting of constants when used as method parameters
if (child instanceof ASTConst)
{
context.setCurrentType( prevType );
}
parmString = ExpressionCompiler.getRootExpression( child, root, context ) + parmString;
String cast = "";
if ( ExpressionCompiler.shouldCast( child ) )
{
cast = (String) context.remove( ExpressionCompiler.PRE_CAST );
}
if ( cast == null )
{
cast = "";
}
if ( !(child instanceof ASTConst))
{
parmString = cast + parmString;
}
return parmString;
}
static Class getValueClass( OgnlContext context, Object root, Node child )
throws OgnlException
{
Object value = child.getValue( context, root );
Class valueClass = value != null ? value.getClass() : null;
if ( NodeType.class.isAssignableFrom( child.getClass() ) )
{
valueClass = ( (NodeType) child ).getGetterClass();
}
return valueClass;
}
static String getParmString( OgnlContext context, Class parm, String parmString, Node child, Class valueClass,
String endParam )
{
OgnlExpressionCompiler compiler = OgnlRuntime.getCompiler( context );
if ( parm.isArray() )
{
parmString = compiler.createLocalReference( context, "(" + ExpressionCompiler.getCastString( parm )
+ ")org.apache.commons.ognl.OgnlOps#toArray(" + parmString + ", " + parm.getComponentType().getName()
+ endParam, parm );
}
else if ( parm.isPrimitive() )
{
Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass( parm );
parmString = compiler.createLocalReference( context, "((" + wrapClass.getName()
+ ")org.apache.commons.ognl.OgnlOps#convertValue(" + parmString + "," + wrapClass.getName()
+ ".class, true))." + OgnlRuntime.getNumericValueGetter( wrapClass ), parm );
}
else if ( parm != Object.class )
{
parmString = compiler.createLocalReference( context, "(" + parm.getName()
+ ")org.apache.commons.ognl.OgnlOps#convertValue(" + parmString + "," + parm.getName() + ".class)",
parm );
}
else if ( ( child instanceof NodeType && ( (NodeType) child ).getGetterClass() != null
&& Number.class.isAssignableFrom( ( (NodeType) child ).getGetterClass() ) ) || ( valueClass != null
&& valueClass.isPrimitive() ) )
{
parmString = " ($w) " + parmString;
}
else if ( valueClass != null && valueClass.isPrimitive() )
{
parmString = "($w) " + parmString;
}
return parmString;
}
}
| 4,609 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/EnumerationPropertyAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Enumeration;
import java.util.Map;
/**
* Implementation of PropertyAccessor that provides "property" reference to "nextElement" (aliases to "next" also) and
* "hasMoreElements" (also aliased to "hasNext").
*/
public class EnumerationPropertyAccessor
extends ObjectPropertyAccessor
implements PropertyAccessor // This is here to make javadoc show this class as an implementor
{
@Override
public Object getProperty( Map<String, Object> context, Object target, Object name )
throws OgnlException
{
Object result;
Enumeration<?> e = (Enumeration<?>) target; // check performed by the invoker
if ( name instanceof String )
{
if ( "next".equals( name ) || "nextElement".equals( name ) )
{
result = e.nextElement();
}
else
{
if ( "hasNext".equals( name ) || "hasMoreElements".equals( name ) )
{
result = e.hasMoreElements() ? Boolean.TRUE : Boolean.FALSE;
}
else
{
result = super.getProperty( context, target, name );
}
}
}
else
{
result = super.getProperty( context, target, name );
}
return result;
}
@Override
public void setProperty( Map<String, Object> context, Object target, Object name, Object value )
throws OgnlException
{
throw new IllegalArgumentException( "can't set property " + name + " on Enumeration" );
}
}
| 4,610 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/NumericLiterals.java | package org.apache.commons.ognl;
/*
* 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.
*/
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<Class<? extends Number>, String> map = new HashMap<Class<? extends Number>, String>();
NumericLiterals() {
map.put( Integer.class, "" );
map.put( Integer.TYPE, "" );
map.put( Long.class, "l" );
map.put( Long.TYPE, "l" );
map.put( BigInteger.class, "d" );
map.put( Float.class, "f" );
map.put( Float.TYPE, "f" );
map.put( Double.class, "d" );
map.put( Double.TYPE, "d" );
map.put( BigInteger.class, "d" );
map.put( BigDecimal.class, "d" );
}
String get( Class<? extends Number> clazz ) {
return map.get( clazz );
}
}
| 4,611 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ClassResolver.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Map;
/**
* This interface defines an object that will resolve a class from a string and an ognl context table.
*/
public interface ClassResolver
{
Class<?> classForName( String className, Map<String, Object> context )
throws ClassNotFoundException;
}
| 4,612 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ElementsAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Enumeration;
/**
* This interface defines a method for getting the "elements" of an object, which means any objects that naturally would
* be considered to be contained by the object. So for a collection, you would expect this method to return all the
* objects in that collection; while for an ordinary object you would expect this method to return just that object.
* <p>
* 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.
*/
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;
}
| 4,613 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTRootVarRef.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
/**
*/
public class ASTRootVarRef
extends ASTVarRef
{
public ASTRootVarRef( int id )
{
super( id );
}
public ASTRootVarRef( OgnlParser p, int id )
{
super( p, id );
}
protected Object getValueBody( OgnlContext context, Object source )
throws OgnlException
{
return context.getRoot();
}
protected void setValueBody( OgnlContext context, Object target, Object value )
throws OgnlException
{
context.setRoot( value );
}
public String toGetSourceString( OgnlContext context, Object target )
{
if ( target != null )
{
getterClass = target.getClass();
}
if ( getterClass != null )
{
context.setCurrentType( getterClass );
}
if ( parent == null || ( getterClass != null && getterClass.isArray() ) )
{
return "";
}
return ExpressionCompiler.getRootExpression( this, target, context );
}
public String toSetSourceString( OgnlContext context, Object target )
{
if ( parent == null || ( getterClass != null && getterClass.isArray() ) )
{
return "";
}
return "$3";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,614 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTEq.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTEq
extends ComparisonExpression
{
public ASTEq( int id )
{
super( id );
}
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;
}
public String getExpressionOperator( int index )
{
return "==";
}
public String getComparisonFunction()
{
return "org.apache.commons.ognl.OgnlOps.equal";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,615 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/PropertyAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
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 definition as is used by beans. But the
* operational semantics of the term will vary by implementation of this interface: a bean-style implementation will get
* and set properties as beans do, by reflection on the target object's class, but other implementations are possible,
* such as one that uses the property name as a key into a map.
* <p>
* An implementation of this interface will often require that its target objects all be of some particular type. For
* example, the MapPropertyAccessor class requires that its targets all implement the java.util.Map interface.
* <p>
* Note that the "name" of a property is represented by a generic Object. Some implementations may 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.
*/
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.
* @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
*/
Object getProperty( Map<String, Object> 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.
* @throws OgnlException if there is an error setting the property in the given object
*/
void setProperty( Map<String, Object> 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.
* @return The source accessor method to call.
*/
String getSourceAccessor( OgnlContext context, Object target, Object index );
/**
* 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.
* @return The source setter method to call.
*/
String getSourceSetter( OgnlContext context, Object target, Object index );
}
| 4,616 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTLess.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTLess
extends ComparisonExpression
{
public ASTLess( int id )
{
super( id );
}
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;
}
public String getExpressionOperator( int index )
{
return "<";
}
public String getComparisonFunction()
{
return "org.apache.commons.ognl.OgnlOps.less";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,617 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTEval.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
*/
class ASTEval
extends SimpleNode
{
public ASTEval( int id )
{
super( 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();
Node node;
source = children[1].getValue( context, source );
node = ( expr instanceof Node ) ? (Node) expr : (Node) Ognl.parseExpression( expr.toString() );
try
{
context.setRoot( source );
result = node.getValue( context, source );
}
finally
{
context.setRoot( previousRoot );
}
return result;
}
protected void setValueBody( OgnlContext context, Object target, Object value )
throws OgnlException
{
Object expr = children[0].getValue( context, target ), previousRoot = context.getRoot();
Node node;
target = children[1].getValue( context, target );
node = ( expr instanceof Node ) ? (Node) expr : (Node) Ognl.parseExpression( expr.toString() );
try
{
context.setRoot( target );
node.setValue( context, target, value );
}
finally
{
context.setRoot( previousRoot );
}
}
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 )
{
throw new UnsupportedCompilationException( "Map expressions not supported as native java yet." );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
@Override
public boolean isEvalChain( OgnlContext context )
throws OgnlException
{
return true;
}
}
| 4,618 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTXor.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTXor
extends NumericExpression
{
public ASTXor( int id )
{
super( id );
}
public ASTXor( OgnlParser p, int id )
{
super( p, id );
}
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 ) );
}
return result;
}
public String getExpressionOperator( int index )
{
return "^";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,619 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTNotIn.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
*/
class ASTNotIn
extends SimpleNode
implements NodeType
{
public ASTNotIn( int id )
{
super( id );
}
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;
}
public Class getGetterClass()
{
return Boolean.TYPE;
}
public Class getSetterClass()
{
return null;
}
public String toGetSourceString( OgnlContext context, Object target )
{
try
{
String result = "(! org.apache.commons.ognl.OgnlOps.in( ($w) ";
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 )
{
throw OgnlOps.castToRuntime( t );
}
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,620 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTGreater.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTGreater
extends ComparisonExpression
{
public ASTGreater( int id )
{
super( id );
}
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 );
return OgnlOps.greater( v1, v2 ) ? Boolean.TRUE : Boolean.FALSE;
}
public String getExpressionOperator( int index )
{
return ">";
}
public String getComparisonFunction()
{
return "org.apache.commons.ognl.OgnlOps.greater";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,621 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTCtor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.util.List;
/**
*/
public class ASTCtor
extends SimpleNode
{
private String className;
private boolean isArray;
public ASTCtor( int id )
{
super( id );
}
public ASTCtor( OgnlParser p, int id )
{
super( p, id );
}
/** Called from parser action. */
void setClassName( String className )
{
this.className = className;
}
/**
* Gets the class name for this constructor.
*
* @return the class name.
* @since 4.0
*/
String getClassName()
{
return className;
}
void setArray( boolean value )
{
isArray = value;
}
public boolean isArray()
{
return isArray;
}
protected Object getValueBody( OgnlContext context, Object source )
throws OgnlException
{
Object result, root = context.getRoot();
int count = jjtGetNumChildren();
Object[] args = new Object[count];
for ( int i = 0; i < count; ++i )
{
args[i] = children[i].getValue( context, root );
}
if ( isArray )
{
if ( args.length != 1 ) {
throw new OgnlException( "only expect array size or fixed initializer list" );
}
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
{
result = OgnlRuntime.callConstructor( context, className, args );
}
return result;
}
public String toGetSourceString( OgnlContext context, Object target )
{
StringBuilder result = new StringBuilder("new " + className);
Class clazz = null;
Object ctorValue = null;
try
{
clazz = OgnlRuntime.classForName( context, className );
ctorValue = this.getValueBody( context, target );
context.setCurrentObject( ctorValue );
if ( ctorValue != null )
{
context.setCurrentType( ctorValue.getClass() );
context.setCurrentAccessor( ctorValue.getClass() );
}
if ( isArray )
{
context.put( "_ctorClass", clazz );
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
try
{
if ( isArray )
{
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.append("[] ").append(children[0].toGetSourceString(context, target));
}
}
else
{
result.append("(");
if ( ( children != null ) && ( children.length > 0 ) )
{
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 ( !(children[i] instanceof ASTRootVarRef))
{
value = ExpressionCompiler.getRootExpression( children[i], target, context ) + value;
}
String cast = "";
if ( ExpressionCompiler.shouldCast( children[i] ) )
{
cast = (String) context.remove( ExpressionCompiler.PRE_CAST );
}
if ( cast == null )
{
cast = "";
}
if ( !(children[i] instanceof ASTConst))
{
value = cast + value;
}
values[i] = objValue;
expressions[i] = value;
types[i] = context.getCurrentType();
}
// now try and find a matching constructor
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 = con;
ctorParamTypes = ctorTypes;
}
}
if ( ctor == null )
{
ctor =
OgnlRuntime.getConvertedConstructorAndArgs( context, clazz,
OgnlRuntime.getConstructors( clazz ), values,
new Object[values.length] );
}
if ( ctor == null )
{
throw new NoSuchMethodException(
"Unable to find constructor appropriate for arguments in class: " + clazz );
}
ctorParamTypes = ctor.getParameterTypes();
// now loop over child values again and build up the actual source string
for ( int i = 0; i < children.length; i++ )
{
if ( i > 0 )
{
result.append(", ");
}
String value = expressions[i];
if ( types[i].isPrimitive() )
{
String literal = OgnlRuntime.getNumericLiteral( types[i] );
if ( literal != null )
{
value += literal;
}
}
if ( ctorParamTypes[i] != types[i] )
{
if ( values[i] != null && !types[i].isPrimitive() && !values[i].getClass().isArray()
&& !(children[i] instanceof ASTConst))
{
value =
"(" + OgnlRuntime.getCompiler( context ).getInterfaceClass( values[i].getClass() ).getName()
+ ")" + value;
}
else if ( !(children[i] instanceof ASTConst)
|| ( children[i] instanceof ASTConst && !types[i].isPrimitive() ) )
{
if ( !types[i].isArray() && types[i].isPrimitive() && !ctorParamTypes[i].isPrimitive() )
{
value =
"new "
+ ExpressionCompiler.getCastString(
OgnlRuntime.getPrimitiveWrapperClass( types[i] ) )
+ "(" + value + ")";
}
else
{
value = " ($w) " + value;
}
}
}
result.append(value);
}
}
result.append(")");
}
context.setCurrentType( ctorValue != null ? ctorValue.getClass() : clazz );
context.setCurrentAccessor( clazz );
context.setCurrentObject( ctorValue );
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
context.remove( "_ctorClass" );
return result.toString();
}
public String toSetSourceString( OgnlContext context, Object target )
{
return "";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,622 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTShiftRight.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTShiftRight
extends NumericExpression
{
public ASTShiftRight( int id )
{
super( id );
}
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 );
}
public String getExpressionOperator( int index )
{
return ">>";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,623 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/InappropriateExpressionException.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
* 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 <code>setValue</code>.
*/
public class InappropriateExpressionException
extends OgnlException
{
private static final long serialVersionUID = -101395753764475977L;
public InappropriateExpressionException( Node tree )
{
super( "Inappropriate OGNL expression: " + tree );
}
}
| 4,624 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTConst.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
*/
public class ASTConst
extends SimpleNode
implements NodeType
{
private Object value;
private Class getterClass;
public ASTConst( int id )
{
super( id );
}
public ASTConst( OgnlParser p, int id )
{
super( p, id );
}
/**
* Called from parser actions.
* @param value the value to set
*/
public void setValue( Object value )
{
this.value = value;
}
public Object getValue()
{
return value;
}
protected Object getValueBody( OgnlContext context, Object source )
throws OgnlException
{
return this.value;
}
public boolean isNodeConstant( OgnlContext context )
throws OgnlException
{
return true;
}
public Class getGetterClass()
{
return getterClass;
}
public Class getSetterClass()
{
return null;
}
public String toGetSourceString( OgnlContext context, Object target )
{
if ( value == null && parent != null && parent instanceof ExpressionNode)
{
context.setCurrentType( null );
return "null";
}
if ( value == null )
{
context.setCurrentType( null );
return "";
}
getterClass = value.getClass();
Object retval = value;
if ( parent != null && parent instanceof ASTProperty)
{
context.setCurrentObject( value );
return value.toString();
}
if ( value != null && Number.class.isAssignableFrom( value.getClass() ) )
{
context.setCurrentType( OgnlRuntime.getPrimitiveWrapperClass( value.getClass() ) );
context.setCurrentObject( value );
return value.toString();
}
if ( !( parent != null
&& value != null
&& NumericExpression.class.isAssignableFrom( parent.getClass() ) )
&& String.class.isAssignableFrom( value.getClass() ) )
{
context.setCurrentType( String.class );
retval = '\"' + OgnlOps.getEscapeString( value.toString() ) + '\"';
context.setCurrentObject( retval.toString() );
return retval.toString();
}
if (value instanceof Character)
{
Character val = (Character) value;
context.setCurrentType( Character.class );
if ( Character.isLetterOrDigit( val.charValue() ) )
{
retval = "'" + ( (Character) value ).charValue() + "'";
}
else
{
retval = "'" + OgnlOps.getEscapedChar( ( (Character) value ).charValue() ) + "'";
}
context.setCurrentObject( retval );
return retval.toString();
}
if ( Boolean.class.isAssignableFrom( value.getClass() ) )
{
getterClass = Boolean.TYPE;
context.setCurrentType( Boolean.TYPE );
context.setCurrentObject( value );
return value.toString();
}
return value.toString();
}
public String toSetSourceString( OgnlContext context, Object target )
{
if ( parent == null )
{
throw new UnsupportedCompilationException( "Can't modify constant values." );
}
return toGetSourceString( context, target );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,625 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/PrimitiveTypes.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.HashMap;
import java.util.Map;
/**
*/
class PrimitiveTypes {
private final Map<String, Class<?>> map = new HashMap<String, Class<?>>( 101 );
PrimitiveTypes() {
map.put( "boolean", Boolean.TYPE );
map.put( "byte", Byte.TYPE );
map.put( "short", Short.TYPE );
map.put( "char", Character.TYPE );
map.put( "int", Integer.TYPE );
map.put( "long", Long.TYPE );
map.put( "float", Float.TYPE );
map.put( "double", Double.TYPE );
}
Class<?> get(String className) {
return map.get(className);
}
}
| 4,626 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTSelect.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
*/
class ASTSelect
extends SimpleNode
{
public ASTSelect( int id )
{
super( 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();
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 );
}
}
return answer;
}
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 )
{
throw new UnsupportedCompilationException( "Eval expressions not supported as native java yet." );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,627 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/NumericDefaults.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
/**
*/
class NumericDefaults {
private final Map<Class<?>, Object> NUMERIC_DEFAULTS = new HashMap<Class<?>, Object>();
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 );
}
}
| 4,628 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ComparisonExpression.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
* Base class for types that compare values.
*/
public abstract class ComparisonExpression
extends BooleanExpression
{
private static final long serialVersionUID = -5945855000509930682L;
public ComparisonExpression( int id )
{
super( id );
}
public ComparisonExpression( OgnlParser p, int id )
{
super( p, id );
}
public abstract String getComparisonFunction();
/**
* {@inheritDoc}
*/
@Override
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;
}
else if ( value != null )
{
getterClass = value.getClass();
}
else
{
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] );
// System.out.println("comparison expression currentType: " + context.getCurrentType() + " previousType: " +
// context.getPreviousType());
boolean conversion = OgnlRuntime.shouldConvertNumericTypes( context );
StringBuilder result = new StringBuilder( "(" );
if ( conversion )
{
result.append( getComparisonFunction() ).append( "( ($w) (" );
}
result.append( OgnlRuntime.getChildSource( context, target, children[0], conversion ) )
.append( " " );
if ( conversion )
{
result.append( "), ($w) " );
}
else
{
result.append( getExpressionOperator( 0 ) );
}
result.append( "" ).append( OgnlRuntime.getChildSource( context, target, children[1], conversion ) );
if ( conversion )
{
result.append( ")" );
}
context.setCurrentType( Boolean.TYPE );
result.append( ")" );
return result.toString();
}
catch ( NullPointerException e )
{
// expected to happen in some instances
throw new UnsupportedCompilationException( "evaluation resulted in null expression." );
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
}
}
| 4,629 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ObjectPropertyAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import org.apache.commons.ognl.enhance.OgnlExpressionCompiler;
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
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.
*/
public class ObjectPropertyAccessor
implements PropertyAccessor
{
/**
* Returns OgnlRuntime.NotFound if the property does not exist.
*/
public Object getPossibleProperty( Map<String, Object> context, Object target, String name )
throws OgnlException
{
Object result;
OgnlContext ognlContext = (OgnlContext) context;
try
{
result = OgnlRuntime.getMethodValue( ognlContext, target, name, true );
if ( result == OgnlRuntime.NotFound )
{
result = OgnlRuntime.getFieldValue( ognlContext, target, name, true );
}
} catch ( OgnlException ex )
{
throw ex;
} catch ( Exception ex )
{
throw new OgnlException( name, ex );
}
return result;
}
/**
* Returns OgnlRuntime.NotFound if the property does not exist.
*/
public Object setPossibleProperty( Map<String, Object> 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 ( result == OgnlRuntime.NotFound )
{
Method m = OgnlRuntime.getWriteMethod( target.getClass(), name );
if ( m != null )
{
result = m.invoke( target, value );
}
}
} catch ( OgnlException ex )
{
throw ex;
} catch ( Exception ex )
{
throw new OgnlException( name, ex );
}
return result;
}
public boolean hasGetProperty( OgnlContext context, Object target, Object oname )
throws OgnlException
{
try
{
return OgnlRuntime.hasGetProperty( context, target, oname );
}
catch ( IntrospectionException ex )
{
throw new OgnlException( "checking if " + target + " has gettable property " + oname, ex );
}
}
public boolean hasGetProperty( Map<String, Object> context, Object target, Object oname )
throws OgnlException
{
return hasGetProperty( (OgnlContext) context, target, oname );
}
public boolean hasSetProperty( OgnlContext context, Object target, Object oname )
throws OgnlException
{
try
{
return OgnlRuntime.hasSetProperty( context, target, oname );
}
catch ( IntrospectionException ex )
{
throw new OgnlException( "checking if " + target + " has settable property " + oname, ex );
}
}
public boolean hasSetProperty( Map<String, Object> context, Object target, Object oname )
throws OgnlException
{
return hasSetProperty( (OgnlContext) context, target, oname );
}
public Object getProperty( Map<String, Object> context, Object target, Object oname )
throws OgnlException
{
String name = oname.toString();
Object result = getPossibleProperty( context, target, name );
if ( result == OgnlRuntime.NotFound )
{
throw new NoSuchPropertyException( target, name );
}
return result;
}
public void setProperty( Map<String, Object> context, Object target, Object oname, Object value )
throws OgnlException
{
String name = oname.toString();
Object result = setPossibleProperty( context, target, name, value );
if ( result == OgnlRuntime.NotFound )
{
throw new NoSuchPropertyException( target, name );
}
}
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 key = ( (String) index ).replace( "\"", "" );
try
{
Field f = target.getClass().getField( key );
if ( f != null )
{
return f.getType();
}
}
catch ( NoSuchFieldException e )
{
return null;
}
}
return null;
}
return m.getReturnType();
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
}
public String getSourceAccessor( OgnlContext context, Object target, Object index )
{
try
{
String methodName = index.toString().replace( "\"", "" );
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 )
{
m =
OgnlRuntime.getReadMethod( target.getClass(),
context.getCurrentObject().toString().replace( "\"", "" ) );
}
// 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() )
{
Field f = target.getClass().getField( methodName );
if ( f != null )
{
context.setCurrentType( f.getType() );
context.setCurrentAccessor( f.getDeclaringClass() );
return "." + f.getName();
}
}
}
catch ( NoSuchFieldException e )
{
// ignore
}
return "";
}
context.setCurrentType( m.getReturnType() );
final OgnlExpressionCompiler compiler = OgnlRuntime.getCompiler( context );
context.setCurrentAccessor( compiler.getSuperOrInterfaceClass( m, m.getDeclaringClass() ) );
return "." + m.getName() + "()";
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
}
public String getSourceSetter( OgnlContext context, Object target, Object index )
{
try
{
String methodName = index.toString().replace( "\"", "" );
Method m = OgnlRuntime.getWriteMethod( target.getClass(), methodName );
if ( m == null && context.getCurrentObject() != null && context.getCurrentObject().toString() != null )
{
m =
OgnlRuntime.getWriteMethod( target.getClass(),
context.getCurrentObject().toString().replace( "\"", "" ) );
}
if ( m == null || m.getParameterTypes() == null || m.getParameterTypes().length <= 0 )
{
throw new UnsupportedCompilationException( "Unable to determine setting expression on "
+ context.getCurrentObject() + " with index of " + index );
}
Class<?> parm = m.getParameterTypes()[0];
String conversion;
if ( m.getParameterTypes().length > 1 )
{
throw new UnsupportedCompilationException(
"Object property accessors can only support single parameter setters." );
}
final OgnlExpressionCompiler compiler = OgnlRuntime.getCompiler( context );
if ( parm.isPrimitive() )
{
Class<?> wrapClass = OgnlRuntime.getPrimitiveWrapperClass( parm );
conversion = compiler.createLocalReference( context, "((" + wrapClass.getName()
+ ")org.apache.commons.ognl.OgnlOps#convertValue($3," + wrapClass.getName() + ".class, true))."
+ OgnlRuntime.getNumericValueGetter( wrapClass ), parm );
}
else if ( parm.isArray() )
{
conversion = compiler.createLocalReference( context, "(" + ExpressionCompiler.getCastString( parm )
+ ")org.apache.commons.ognl.OgnlOps#toArray($3," + parm.getComponentType().getName() + ".class)",
parm );
}
else
{
conversion = compiler.createLocalReference( context, "(" + parm.getName()
+ ")org.apache.commons.ognl.OgnlOps#convertValue($3," + parm.getName() + ".class)", parm );
}
context.setCurrentType( m.getReturnType() );
context.setCurrentAccessor(
compiler.getSuperOrInterfaceClass( m, m.getDeclaringClass() ) );
return "." + m.getName() + "(" + conversion + ")";
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
}
}
| 4,630 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/NullHandler.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Map;
/**
* Interface for handling null results from Chains. Object has the opportunity to substitute an object for the null and
* continue.
*/
public interface NullHandler
{
/**
* Method called on target returned null.
*/
Object nullMethodResult( Map<String, Object> context, Object target, String methodName, Object[] args );
/**
* Property in target evaluated to null. Property can be a constant String property name or a DynamicSubscript.
*/
Object nullPropertyValue( Map<String, Object> context, Object target, Object property );
}
| 4,631 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTThisVarRef.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
*/
public class ASTThisVarRef
extends ASTVarRef
{
public ASTThisVarRef( int id )
{
super( id );
}
public ASTThisVarRef( OgnlParser p, int id )
{
super( p, id );
}
protected Object getValueBody( OgnlContext context, Object source )
throws OgnlException
{
return context.getCurrentObject();
}
protected void setValueBody( OgnlContext context, Object target, Object value )
throws OgnlException
{
context.setCurrentObject( value );
}
public String toGetSourceString( OgnlContext context, Object target )
{
throw new UnsupportedCompilationException( "Unable to compile this references." );
}
public String toSetSourceString( OgnlContext context, Object target )
{
throw new UnsupportedCompilationException( "Unable to compile this references." );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,632 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ObjectElementsAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Enumeration;
/**
* Implementation of ElementsAccessor that returns a single-element iterator, containing the original target object.
*/
public class ObjectElementsAccessor
implements ElementsAccessor
{
/**
* {@inheritDoc}
*/
public Enumeration<?> getElements( Object target )
{
final Object object = target;
return new Enumeration<Object>()
{
private boolean seen;
public boolean hasMoreElements()
{
return !seen;
}
public Object nextElement()
{
Object result = null;
if ( !seen )
{
result = object;
seen = true;
}
return result;
}
};
}
}
| 4,633 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTAdd.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.String.format;
/**
*/
class ASTAdd
extends NumericExpression
{
public ASTAdd( int id )
{
super( id );
}
public ASTAdd( OgnlParser p, int id )
{
super( p, id );
}
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.add( result, children[i].getValue( context, source ) );
}
return result;
}
public String getExpressionOperator( int index )
{
return "+";
}
boolean isWider( NodeType type, NodeType lastType )
{
if ( lastType == null )
{
return true;
}
// System.out.println("checking isWider(" + type.getGetterClass() + " , " + lastType.getGetterClass() + ")");
if ( String.class.isAssignableFrom( lastType.getGetterClass() ) )
{
return false;
}
if ( String.class.isAssignableFrom( type.getGetterClass() ) )
{
return true;
}
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() ) )
{
return false;
}
if ( parent == null && String.class.isAssignableFrom( lastType.getGetterClass() ) )
{
return true;
}
if ( parent == null && String.class.isAssignableFrom( type.getGetterClass() ) )
{
return false;
}
if ( BigDecimal.class.isAssignableFrom( type.getGetterClass() )
|| BigInteger.class.isAssignableFrom( type.getGetterClass() ) )
{
return true;
}
if ( BigDecimal.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() ) )
{
return false;
}
if ( Float.class.isAssignableFrom( type.getGetterClass() )
&& Integer.class.isAssignableFrom( lastType.getGetterClass() ) )
{
return true;
}
return true;
}
public String toGetSourceString( OgnlContext context, Object target )
{
try
{
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();
Object cast = context.get( ExpressionCompiler.PRE_CAST );
for ( Node aChildren : children )
{
aChildren.toGetSourceString( context, target );
if ( aChildren instanceof NodeType && ( (NodeType) aChildren ).getGetterClass() != null
&& isWider( (NodeType) aChildren, lastType ) )
{
lastType = (NodeType) aChildren;
}
}
context.put( ExpressionCompiler.PRE_CAST, cast );
context.setCurrentType( currType );
context.setCurrentAccessor( currAccessor );
}
// reset context since previous children loop would have changed it
context.setCurrentObject( target );
if ( ( children != null ) && ( children.length > 0 ) )
{
for ( int i = 0; i < children.length; ++i )
{
if ( i > 0 )
{
result.append(" ").append(getExpressionOperator(i)).append(" ");
}
String expr = children[i].toGetSourceString( context, target );
if ( ( "null".equals( expr ) )
|| ( !(children[i] instanceof ASTConst)
&& ( expr == null || expr.trim().isEmpty() ) ) )
{
expr = "null";
}
// System.out.println("astadd child class: " + _children[i].getClass().getName() +
// " and return expr: " + expr);
if (children[i] instanceof ASTProperty)
{
expr = ExpressionCompiler.getRootExpression( children[i], context.getRoot(), context ) + expr;
context.setCurrentAccessor( context.getRoot().getClass() );
}
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 );
}
expr = rootExpr + ( chain != null ? chain + "." : "" ) + expr;
context.setCurrentAccessor( context.getRoot().getClass() );
}
else if (children[i] instanceof ExpressionNode)
{
expr = "(" + expr + ")";
}
else if ( ( parent == null || !(parent instanceof ASTChain))
&& children[i] instanceof ASTChain)
{
String rootExpr =
ExpressionCompiler.getRootExpression( children[i], context.getRoot(), context );
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 );
if ( cast == null )
{
cast = "";
}
expr = cast + expr;
}
// turn quoted characters into quoted strings
if ( context.getCurrentType() != null && context.getCurrentType() == Character.class
&& children[i] instanceof ASTConst)
{
expr = expr.replace( "'", "\"" );
context.setCurrentType( String.class );
}
else
{
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 + "<<");
expr = expr.replace( """, "\"" );
expr = expr.replace( "\"", "'" );
expr = format( "\"%s\"", expr );
// System.out.println("Expr now >>" + 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 ( context.getCurrentType() != null
&& Number.class.isAssignableFrom( 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() ) );
}
}
if ( lastType != null )
{
context.setCurrentAccessor( lastType.getGetterClass() );
}
}
}
if ( parent == null || ASTSequence.class.isAssignableFrom( parent.getClass() ) )
{
if ( getterClass != null && String.class.isAssignableFrom( getterClass ) )
{
getterClass = Object.class;
}
}
else
{
context.setCurrentType( getterClass );
}
try
{
Object contextObj = getValueBody( context, target );
context.setCurrentObject( contextObj );
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return result.toString();
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,634 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ToStringVisitor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* A NodeVisitor implementation which will build a String representation of the AST tree.
* <p/>
* This class is meant to be used by SimpleNode.toString(), but you may use it to
*
* @since 4.0
*/
public class ToStringVisitor
implements NodeVisitor<StringBuilder, StringBuilder>
{
static final ToStringVisitor INSTANCE = new ToStringVisitor();
public StringBuilder visit( ASTSequence node, StringBuilder data )
{
return commaSeparatedChildren( node, data );
}
private StringBuilder commaSeparatedChildren( SimpleNode node, StringBuilder data )
{
if ( ( node.children != null ) )
{
for ( int i = 0; i < node.children.length; ++i )
{
if ( i > 0 )
{
data.append( ", " );
}
recurse( node.children[i], data );
}
}
return data;
}
public StringBuilder visit( ASTAssign node, StringBuilder data )
{
return concatInfix( node, " = ", data );
}
public StringBuilder visit( ASTTest node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
private StringBuilder visitExpressionNode( ExpressionNode node, StringBuilder data )
{
if ( node.parent != null )
{
data.append( "(" );
}
if ( ( node.children != null ) && ( node.children.length > 0 ) )
{
for ( int i = 0; i < node.children.length; ++i )
{
if ( i > 0 )
{
data.append( " " ).append( node.getExpressionOperator( i ) ).append( " " );
}
recurse( node.children[i], data );
}
}
if ( node.parent != null )
{
data.append( ')' );
}
return data;
}
public StringBuilder visit( ASTOr node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTAnd node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTBitOr node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTXor node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTBitAnd node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTEq node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTNotEq node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTLess node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTGreater node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTLessEq node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTGreaterEq node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTIn node, StringBuilder data )
{
final String infix = " in ";
return concatInfix( node, infix, data );
}
private StringBuilder concatInfix( SimpleNode node, String infix, StringBuilder data )
{
return concatInfix( node.children[0], infix, node.children[1], data );
}
private StringBuilder concatInfix( Node left, String infix, Node right, StringBuilder data )
{
recurse( left, data ).append( infix );
return recurse( right, data );
}
public StringBuilder visit( ASTNotIn node, StringBuilder data )
{
return concatInfix( node, " not in ", data );
}
public StringBuilder visit( ASTShiftLeft node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTShiftRight node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTUnsignedShiftRight node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTAdd node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTSubtract node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTMultiply node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTDivide node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTRemainder node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTNegate node, StringBuilder data )
{
return appendPrefixed( "-", node, data );
}
public StringBuilder visit( ASTBitNegate node, StringBuilder data )
{
return appendPrefixed( "~", node, data );
}
private StringBuilder appendPrefixed( String prefix, SimpleNode node, StringBuilder data )
{
data.append( prefix );
return recurse( node.children[0], data );
}
public StringBuilder visit( ASTNot node, StringBuilder data )
{
return visitExpressionNode( node, data );
}
public StringBuilder visit( ASTInstanceof node, StringBuilder data )
{
return recurse( node.children[0], data ).append( " instanceof " ).append( node.getTargetType() );
}
public StringBuilder visit( ASTChain node, StringBuilder data )
{
if ( ( node.children != null ) && ( node.children.length > 0 ) )
{
for ( int i = 0; i < node.children.length; i++ )
{
if ( i > 0 && !( node.children[i] instanceof ASTProperty )
|| !( (ASTProperty) node.children[i] ).isIndexedAccess() )
{
data.append( "." );
}
recurse( node.children[i], data );
}
}
return data;
}
public StringBuilder visit( ASTEval node, StringBuilder data )
{
data.append( "(" );
concatInfix( node, ")(", data );
return data.append( ")" );
}
public StringBuilder visit( ASTConst node, StringBuilder data )
{
final Object value = node.getValue();
if ( value == null )
{
data.append( "null" );
}
else
{
if ( value instanceof String )
{
data.append( '\"' ).append( OgnlOps.getEscapeString( value.toString() ) ).append( '\"' );
}
else
{
if ( value instanceof Character )
{
data.append( '\'' ).append( OgnlOps.getEscapedChar( (Character) value ) ).append( '\'' );
}
else
{
if ( value instanceof Node )
{
data.append( ":[ " );
recurse( (Node) value, data );
data.append( " ]" );
}
else
{
data.append( value );
if ( value instanceof Long )
{
data.append( 'L' );
}
else if ( value instanceof BigDecimal )
{
data.append( 'B' );
}
else if ( value instanceof BigInteger )
{
data.append( 'H' );
}
}
}
}
}
return data;
}
public StringBuilder visit( ASTThisVarRef node, StringBuilder data )
{
return data.append( "#this" );
}
public StringBuilder visit( ASTRootVarRef node, StringBuilder data )
{
return data.append( "#root" );
}
public StringBuilder visit( ASTVarRef node, StringBuilder data )
{
return data.append( "#" ).append( node.getName() );
}
public StringBuilder visit( ASTList node, StringBuilder data )
{
return wrappedCommaSeparatedChildren( "{ ", node, " }", data );
}
public StringBuilder visit( ASTMap node, StringBuilder data )
{
data.append( "#" );
if ( node.getClassName() != null )
{
data.append( "@" ).append( node.getClassName() ).append( "@" );
}
data.append( "{ " );
for ( int i = 0; i < node.jjtGetNumChildren(); ++i )
{
ASTKeyValue kv = (ASTKeyValue) node.children[i];
if ( i > 0 )
{
data.append( ", " );
}
concatInfix( kv.getKey(), " : ", kv.getValue(), data );
}
return data.append( " }" );
}
public StringBuilder visit( ASTKeyValue node, StringBuilder data )
{
return concatInfix( node.getKey(), " -> ", node.getValue(), data );
}
public StringBuilder visit( ASTStaticField node, StringBuilder data )
{
return data.append( "@" ).append( node.getClassName() ).append( "@" ).append( node.getFieldName() );
}
public StringBuilder visit( ASTCtor node, StringBuilder data )
{
data.append( "new " ).append( node.getClassName() );
if ( node.isArray() )
{
if ( node.children[0] instanceof ASTConst )
{
indexedChild( node, data );
}
else
{
appendPrefixed( "[] ", node, data );
}
}
else
{
wrappedCommaSeparatedChildren( "(", node, ")", data );
}
return data;
}
private StringBuilder wrappedCommaSeparatedChildren( String prefix, SimpleNode node, String suffix,
StringBuilder data )
{
data.append( prefix );
return commaSeparatedChildren( node, data ).append( suffix );
}
public StringBuilder visit( ASTProperty node, StringBuilder data )
{
if ( node.isIndexedAccess() )
{
indexedChild( node, data );
}
else
{
data.append( ( (ASTConst) node.children[0] ).getValue() );
}
return data;
}
private StringBuilder indexedChild( SimpleNode node, StringBuilder data )
{
return surroundedNode( "[", node.children[0], "]", data );
}
public StringBuilder visit( ASTStaticMethod node, StringBuilder data )
{
data.append( "@" ).append( node.getClassName() ).append( "@" ).append( node.getMethodName() );
return wrappedCommaSeparatedChildren( "(", node, ")", data );
}
public StringBuilder visit( ASTMethod node, StringBuilder data )
{
data.append( node.getMethodName() );
return wrappedCommaSeparatedChildren( "(", node, ")", data );
}
public StringBuilder visit( ASTProject node, StringBuilder data )
{
return surroundedNode( "{ ", node.children[0], " }", data );
}
private StringBuilder surroundedNode( String open, Node inner, String close, StringBuilder data )
{
data.append( open );
return recurse( inner, data ).append( close );
}
public StringBuilder visit( ASTSelect node, StringBuilder data )
{
return surroundedNode( "{? ", node.children[0], " }", data );
}
public StringBuilder visit( ASTSelectFirst node, StringBuilder data )
{
return surroundedNode( "{^ ", node.children[0], " }", data );
}
public StringBuilder visit( ASTSelectLast node, StringBuilder data )
{
return surroundedNode( "{$ ", node.children[0], " }", data );
}
private StringBuilder recurse( Node child, StringBuilder data )
{
try
{
return child == null ? data.append( "null" ) : child.accept( this, data );
}
catch ( OgnlException e )
{
// This should never happen, but delegate it on just in case.
throw new IllegalArgumentException( e );
}
}
}
| 4,635 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/MemberAccess.java | package org.apache.commons.ognl;
/*
* 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.
*/
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 inaccessible members, such as private fields.
*/
public interface MemberAccess
{
/**
* Sets the member up for accessibility
*/
Object setup( Map<String, Object> context, Object target, Member member, String propertyName );
/**
* Restores the member from the previous setup call.
*/
void restore( Map<String, Object> 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.
*/
boolean isAccessible( Map<String, Object> context, Object target, Member member, String propertyName );
}
| 4,636 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/SetPropertyAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Map;
import java.util.Set;
/**
* Implementation of PropertyAccessor that uses numbers and dynamic subscripts as properties to index into Lists.
*/
public class SetPropertyAccessor
extends ObjectPropertyAccessor
implements PropertyAccessor // This is here to make javadoc show this class as an implementor
{
@Override
public Object getProperty( Map<String, Object> context, Object target, Object name )
throws OgnlException
{
Set<?> set = (Set<?>) target; // check performed by the invoker
if ( name instanceof String )
{
Object result;
if ( "size".equals( name ) )
{
result = set.size();
}
else if ( "iterator".equals( name ) )
{
result = set.iterator();
}
else if ( "isEmpty".equals( name ) )
{
result = set.isEmpty() ? Boolean.TRUE : Boolean.FALSE;
}
else
{
result = super.getProperty( context, target, name );
}
return result;
}
throw new NoSuchPropertyException( target, name );
}
}
| 4,637 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTUnsignedShiftRight.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTUnsignedShiftRight
extends NumericExpression
{
public ASTUnsignedShiftRight( int id )
{
super( id );
}
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 );
}
public String getExpressionOperator( int index )
{
return ">>>";
}
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 child2 = OgnlRuntime.getChildSource( context, target, children[1] );
child2 = coerceToNumeric( child2, context, children[1] );
Object v1 = children[0].getValue( context, target );
int type = OgnlOps.getNumericType( v1 );
if ( type <= OgnlOps.INT )
{
child1 = "(int)" + child1;
child2 = "(int)" + child2;
}
result = child1 + " >>> " + child2;
context.setCurrentType( Integer.TYPE );
context.setCurrentObject( getValueBody( context, target ) );
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return result;
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,638 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTSelectLast.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
*/
class ASTSelectLast
extends SimpleNode
{
public ASTSelectLast( int id )
{
super( id );
}
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 ) );
for ( Enumeration e = elementsAccessor.getElements( source ); e.hasMoreElements(); )
{
Object next = e.nextElement();
if ( OgnlOps.booleanValue( expr.getValue( context, next ) ) )
{
answer.clear();
answer.add( next );
}
}
return answer;
}
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 )
{
throw new UnsupportedCompilationException( "Eval expressions not supported as native java yet." );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,639 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/MethodAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
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.
*/
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
* @throws OgnlException if there is an error calling the method
*/
Object callStaticMethod( Map<String, Object> context, Class<?> targetClass, String methodName, Object[] args )
throws OgnlException;
/**
* 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
* @throws OgnlException if there is an error calling the method
*/
Object callMethod( Map<String, Object> context, Object target, String methodName, Object[] args )
throws OgnlException;
}
| 4,640 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTProperty.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
import java.beans.IndexedPropertyDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Iterator;
/**
*/
public class ASTProperty
extends SimpleNode
implements NodeType
{
private boolean indexedAccess;
private Class getterClass;
private Class setterClass;
public ASTProperty( int id )
{
super( id );
}
public void setIndexedAccess( boolean value )
{
indexedAccess = value;
}
/**
* Returns true if this property is itself an index reference.
*
* @return Returns true if this property is itself an index reference.
*/
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 context
* @param source The object source
* @return true, if this property is described by an IndexedPropertyDescriptor
* @throws OgnlException if an error occurs
*/
public int getIndexedPropertyType( OgnlContext context, Object source )
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 )
? null
: OgnlRuntime.getCompiler( context ).getInterfaceClass( source.getClass() ),
(String) property );
}
}
return OgnlRuntime.INDEXED_PROPERTY_NONE;
}
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() );
}
protected Object getValueBody( OgnlContext context, Object source )
throws OgnlException
{
Object property = getProperty( context, source );
Object result = OgnlRuntime.getProperty( context, source, property );
if ( result == null )
{
result =
OgnlRuntime.getNullHandler( OgnlRuntime.getTargetClass( source ) ).nullPropertyValue( context, source,
property );
}
return result;
}
protected void setValueBody( OgnlContext context, Object target, Object value )
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 );
}
public Class getGetterClass()
{
return getterClass;
}
public Class getSetterClass()
{
return setterClass;
}
public String toGetSourceString( OgnlContext context, Object target )
{
if ( context.getCurrentObject() == null )
{
throw new UnsupportedCompilationException( "Current target is null." );
}
String result = "";
Method m = null;
try
{
/*
* System.out.println("astproperty is indexed? : " + isIndexedAccess() + " child: " +
* _children[0].getClass().getName() + " target: " + target.getClass().getName() + " current object: " +
* context.getCurrentObject().getClass().getName());
*/
Node child = children[0];
if ( isIndexedAccess() )
{
Object value = child.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 = getSourceString( context, child );
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.setCurrentObject( indexedValue );
context.setCurrentAccessor(
OgnlRuntime.getCompiler( context ).getSuperOrInterfaceClass( m, m.getDeclaringClass() ) );
return "." + m.getName() + "(" + srcString + ")";
}
PropertyAccessor propertyAccessor = 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 currentObject = context.getCurrentObject();
if ( child instanceof ASTConst && currentObject instanceof Number)
{
context.setCurrentType( OgnlRuntime.getPrimitiveWrapperClass( currentObject.getClass() ) );
}
Object indexValue = propertyAccessor.getProperty( context, target, value );
result = propertyAccessor.getSourceAccessor( context, target, srcString );
getterClass = context.getCurrentType();
context.setCurrentObject( indexValue );
return result;
}
String name = ( (ASTConst) child ).getValue().toString();
target = getTarget( context, target, name );
PropertyDescriptor pd = OgnlRuntime.getPropertyDescriptor( context.getCurrentObject().getClass(), name );
if ( pd != null && pd.getReadMethod() != null && !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 an indexed method accessor need to use special property descriptors to find methods
if ( pd instanceof IndexedPropertyDescriptor )
{
m = ( (IndexedPropertyDescriptor) pd ).getIndexedReadMethod();
}
else
{
if ( !(pd instanceof ObjectIndexedPropertyDescriptor) ) {
throw new OgnlException( "property '" + name + "' is not an indexed property" );
}
m = ( (ObjectIndexedPropertyDescriptor) pd ).getIndexedReadMethod();
}
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
{
context.put( "_indexedMethod", m );
}
}
else
{
/*
* System.out.println("astproperty trying to get " + name + " on object target: " +
* context.getCurrentObject().getClass().getName() + " current type " + context.getCurrentType() +
* " current accessor " + context.getCurrentAccessor() + " prev type " + context.getPreviousType() +
* " prev accessor " + context.getPreviousAccessor());
*/
PropertyAccessor pa = OgnlRuntime.getPropertyAccessor( context.getCurrentObject().getClass() );
if ( context.getCurrentObject().getClass().isArray() )
{
if ( pd == null )
{
pd = OgnlRuntime.getProperty( context.getCurrentObject().getClass(), name );
if ( pd != null && pd.getReadMethod() != null )
{
m = pd.getReadMethod();
result = pd.getName();
}
else
{
getterClass = int.class;
context.setCurrentAccessor( context.getCurrentObject().getClass() );
context.setCurrentType( int.class );
result = "." + name;
}
}
}
else
{
if ( pd != null && pd.getReadMethod() != null )
{
m = pd.getReadMethod();
result = "." + m.getName() + "()";
}
else if ( pa != null )
{
Object currObj = context.getCurrentObject();
Class currType = context.getCurrentType();
Class prevType = context.getPreviousType();
String srcString = child.toGetSourceString( context, context.getRoot() );
if ( child instanceof ASTConst && context.getCurrentObject() instanceof String)
{
srcString = "\"" + srcString + "\"";
}
context.setCurrentObject( currObj );
context.setCurrentType( currType );
context.setPreviousType( prevType );
result = pa.getSourceAccessor( context, context.getCurrentObject(), srcString );
getterClass = context.getCurrentType();
}
}
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
// set known property types for NodeType interface when possible
if ( m != null )
{
getterClass = m.getReturnType();
context.setCurrentType( m.getReturnType() );
context.setCurrentAccessor(
OgnlRuntime.getCompiler( context ).getSuperOrInterfaceClass( m, m.getDeclaringClass() ) );
}
context.setCurrentObject( target );
return result;
}
Object getTarget( OgnlContext context, Object target, String name )
throws OgnlException
{
Class<?> clazz = context.getCurrentObject().getClass();
if ( !Iterator.class.isAssignableFrom( clazz ) || ( Iterator.class.isAssignableFrom( clazz ) && !name.contains(
"next" ) ) )
{
Object currObj = target;
try
{
target = getValue( context, context.getCurrentObject() );
}
catch ( NoSuchPropertyException e )
{
try
{
target = getValue( context, context.getRoot() );
}
catch ( NoSuchPropertyException ex )
{
// ignore
}
}
finally
{
context.setCurrentObject( currObj );
}
}
return target;
}
Method getIndexedWriteMethod( PropertyDescriptor pd )
{
if (pd instanceof IndexedPropertyDescriptor)
{
return ( (IndexedPropertyDescriptor) pd ).getIndexedWriteMethod();
}
if (pd instanceof ObjectIndexedPropertyDescriptor)
{
return ( (ObjectIndexedPropertyDescriptor) pd ).getIndexedWriteMethod();
}
return null;
}
public String toSetSourceString( OgnlContext context, Object target )
{
String result = "";
Method m = null;
if ( context.getCurrentObject() == null )
{
throw new UnsupportedCompilationException( "Current target is null." );
}
/*
* System.out.println("astproperty(setter) is indexed? : " + isIndexedAccess() + " child: " +
* _children[0].getClass().getName() + " target: " + target.getClass().getName() + " children length: " +
* _children.length);
*/
try
{
Node child = children[0];
if ( isIndexedAccess() )
{
Object value = child.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 = getSourceString( context, child );
// System.out.println("astproperty setter using indexed value " + value + " and srcString: " +
// srcString);
if ( context.get( "_indexedMethod" ) == null ) {
PropertyAccessor propertyAccessor = OgnlRuntime.getPropertyAccessor( target.getClass() );
Object currentObject = context.getCurrentObject();
if ( child instanceof ASTConst && currentObject instanceof Number)
{
context.setCurrentType( OgnlRuntime.getPrimitiveWrapperClass( currentObject.getClass() ) );
}
Object indexValue = propertyAccessor.getProperty( context, target, value );
result = lastChild( context )
? propertyAccessor.getSourceSetter( context, target, srcString )
: propertyAccessor.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();
context.setCurrentObject( indexValue );
/*
* 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;
}
m = (Method) context.remove( "_indexedMethod" );
PropertyDescriptor pd = (PropertyDescriptor) context.remove( "_indexedDescriptor" );
boolean lastChild = lastChild( context );
if ( lastChild )
{
m = getIndexedWriteMethod( pd );
if ( m == null )
{
throw new UnsupportedCompilationException(
"Indexed property has no corresponding write method." );
}
}
setterClass = m.getParameterTypes()[0];
Object indexedValue = null;
if ( !lastChild )
{
indexedValue = OgnlRuntime.callMethod( context, target, m.getName(), new Object[]{ value } );
}
context.setCurrentType( setterClass );
context.setCurrentAccessor(
OgnlRuntime.getCompiler( context ).getSuperOrInterfaceClass( m, m.getDeclaringClass() ) );
if ( !lastChild )
{
context.setCurrentObject( indexedValue );
return "." + m.getName() + "(" + srcString + ")";
}
return "." + m.getName() + "(" + srcString + ", $3)";
}
String name = ( (ASTConst) child ).getValue().toString();
// System.out.println(" astprop(setter) : trying to set " + name + " on object target " +
// context.getCurrentObject().getClass().getName());
target = getTarget( context, target, name );
PropertyDescriptor pd = OgnlRuntime.getPropertyDescriptor(
OgnlRuntime.getCompiler( context ).getInterfaceClass( context.getCurrentObject().getClass() ), name );
if ( pd != null )
{
Method pdMethod = lastChild( context ) ? pd.getWriteMethod() : pd.getReadMethod();
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 an indexed method accessor need to use special property descriptors to find methods
if ( pd instanceof IndexedPropertyDescriptor )
{
IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
m = lastChild( context ) ? ipd.getIndexedWriteMethod() : ipd.getIndexedReadMethod();
}
else
{
if ( !(pd instanceof ObjectIndexedPropertyDescriptor) ) {
throw new OgnlException( "property '" + name + "' is not an indexed property" );
}
ObjectIndexedPropertyDescriptor opd = (ObjectIndexedPropertyDescriptor) pd;
m = lastChild( context ) ? opd.getIndexedWriteMethod() : opd.getIndexedReadMethod();
}
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];
String cast = parm.isArray() ? ExpressionCompiler.getCastString( parm ) : parm.getName();
result = m.getName() + "((" + cast + ")$3)";
setterClass = parm;
}
else
{
context.put( "_indexedMethod", m );
context.put( "_indexedDescriptor", pd );
}
}
else
{
PropertyAccessor pa = OgnlRuntime.getPropertyAccessor( context.getCurrentObject().getClass() );
/*
* System.out.println("astproperty trying to set " + name + " on object target: " +
* context.getCurrentObject().getClass().getName() + " using propertyaccessor type: " + pa);
*/
if ( target != null )
{
setterClass = target.getClass();
}
if ( parent != null && pd != null && pa == null )
{
m = pd.getReadMethod();
result = m.getName() + "()";
}
else
{
if ( context.getCurrentObject().getClass().isArray() )
{
result = "";
}
else if ( pa != null )
{
Object currObj = context.getCurrentObject();
// Class currType = context.getCurrentType();
// Class prevType = context.getPreviousType();
String srcString = child.toGetSourceString( context, context.getRoot() );
if ( child instanceof ASTConst && context.getCurrentObject() instanceof String)
{
srcString = "\"" + srcString + "\"";
}
context.setCurrentObject( currObj );
// context.setCurrentType(currType);
// context.setPreviousType(prevType);
if ( !lastChild( context ) )
{
result = pa.getSourceAccessor( context, context.getCurrentObject(), srcString );
}
else
{
result = pa.getSourceSetter( context, context.getCurrentObject(), srcString );
}
getterClass = context.getCurrentType();
}
}
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
context.setCurrentObject( target );
if ( m != null )
{
context.setCurrentType( m.getReturnType() );
context.setCurrentAccessor(
OgnlRuntime.getCompiler( context ).getSuperOrInterfaceClass( m, m.getDeclaringClass() ) );
}
return result;
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
private static String getSourceString( OgnlContext context, Node child )
{
String srcString = child.toGetSourceString( context, context.getRoot() );
srcString = ExpressionCompiler.getRootExpression( child, context.getRoot(), context ) + srcString;
if (child instanceof ASTChain)
{
String cast = (String) context.remove( ExpressionCompiler.PRE_CAST );
if ( cast != null )
{
srcString = cast + srcString;
}
}
if ( child 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());
return srcString;
}
}
| 4,641 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/NumericTypes.java | package org.apache.commons.ognl;
/*
* 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 interface defines some useful constants for describing the various possible numeric types of OGNL.
*/
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. */
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.
*/
int MIN_REAL_TYPE = FLOAT;
}
| 4,642 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/PrimitiveDefaults.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
/**
*/
class PrimitiveDefaults {
private final Map<Class<?>, Object> map = new HashMap<Class<?>, Object>( 20 );
PrimitiveDefaults() {
map.put( Boolean.TYPE, Boolean.FALSE );
map.put( Boolean.class, Boolean.FALSE );
map.put( Byte.TYPE, (byte) 0 );
map.put( Byte.class, (byte) 0 );
map.put( Short.TYPE, (short) 0 );
map.put( Short.class, (short) 0 );
map.put( Character.TYPE, (char) 0 );
map.put( Integer.TYPE, 0 );
map.put( Long.TYPE, 0L );
map.put( Float.TYPE, 0.0f );
map.put( Double.TYPE, 0.0 );
map.put( BigInteger.class, BigInteger.ZERO );
map.put( BigDecimal.class, BigDecimal.ZERO );
}
Object get( Class<?> cls ) {
return map.get( cls );
}
}
| 4,643 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/DynamicSubscript.java | package org.apache.commons.ognl;
/*
* 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 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.
*/
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 );
private final int flag;
private DynamicSubscript( int flag )
{
this.flag = flag;
}
public int getFlag()
{
return flag;
}
@Override
public String toString()
{
switch ( flag )
{
case FIRST:
return "^";
case MID:
return "|";
case LAST:
return "$";
case ALL:
return "*";
default:
return "?"; // Won't happen
}
}
}
| 4,644 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/EnumerationIterator.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Enumeration;
import java.util.Iterator;
/**
* Object that implements Iterator from an Enumeration
*/
public class EnumerationIterator<E>
implements Iterator<E>
{
public static <T> Iterator<T> newIterator( Enumeration<T> e )
{
return new EnumerationIterator<T>( e );
}
private final Enumeration<E> e;
public EnumerationIterator( Enumeration<E> e )
{
this.e = e;
}
public boolean hasNext()
{
return e.hasMoreElements();
}
public E next()
{
return e.nextElement();
}
public void remove()
{
throw new UnsupportedOperationException( "remove() not supported by Enumeration" );
}
}
| 4,645 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTMethod.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import org.apache.commons.ognl.enhance.OgnlExpressionCompiler;
import org.apache.commons.ognl.enhance.OrderedReturn;
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
import java.lang.reflect.Method;
/**
*/
public class ASTMethod
extends SimpleNode
implements OrderedReturn, NodeType
{
private String methodName;
private String lastExpression;
private String coreExpression;
private Class getterClass;
public ASTMethod( int id )
{
super( id );
}
public ASTMethod( OgnlParser p, int id )
{
super( p, id );
}
/**
* Called from parser action.
*
* @param methodName sets the name of the method
*/
public void setMethodName( String methodName )
{
this.methodName = methodName;
}
/**
* Returns the method name that this node will call.
*
* @return the method name
*/
public String getMethodName()
{
return methodName;
}
protected Object getValueBody( OgnlContext context, Object source )
throws OgnlException
{
Object[] args = new Object[jjtGetNumChildren()];
Object result, root = context.getRoot();
for ( int i = 0; i < args.length; ++i )
{
args[i] = children[i].getValue( context, root );
}
result = OgnlRuntime.callMethod( context, source, methodName, args );
if ( result == null )
{
NullHandler nullHandler = OgnlRuntime.getNullHandler( OgnlRuntime.getTargetClass( source ) );
result = nullHandler.nullMethodResult( context, source, methodName, args );
}
return result;
}
public String getLastExpression()
{
return lastExpression;
}
public String getCoreExpression()
{
return coreExpression;
}
public Class getGetterClass()
{
return getterClass;
}
public Class getSetterClass()
{
return getterClass;
}
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 = "";
StringBuilder sourceStringBuilder;
Method method;
OgnlExpressionCompiler compiler = OgnlRuntime.getCompiler( context );
try
{
method = OgnlRuntime.getMethod( context, context.getCurrentType() != null
? context.getCurrentType()
: target.getClass(), methodName, children, false );
if ( method == null )
{
method = OgnlRuntime.getReadMethod( target.getClass(), methodName,
children != null ? children.length : -1 );
}
if ( method == null )
{
method = OgnlRuntime.getWriteMethod( target.getClass(), methodName,
children != null ? children.length : -1 );
if ( method != null )
{
context.setCurrentType( method.getReturnType() );
context.setCurrentAccessor(
compiler.getSuperOrInterfaceClass( method, method.getDeclaringClass() ) );
coreExpression = toSetSourceString( context, target );
if ( coreExpression == null || coreExpression.length() < 1 )
{
throw new UnsupportedCompilationException( "can't find suitable getter method" );
}
coreExpression += ";";
lastExpression = "null";
return coreExpression;
}
return "";
}
getterClass = method.getReturnType();
// TODO: This is a hacky workaround until javassist supports varargs method invocations
boolean varArgs = method.isVarArgs();
if ( varArgs )
{
throw new UnsupportedCompilationException(
"Javassist does not currently support varargs method calls" );
}
sourceStringBuilder = new StringBuilder().append( "." ).append( method.getName() ).append( "(" );
if ( ( children != null ) && ( children.length > 0 ) )
{
Class[] parms = method.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 )
{
sourceStringBuilder.append( ", " );
}
Class prevType = context.getCurrentType();
Object root = context.getRoot();
context.setCurrentObject( root );
context.setCurrentType( root != null ? root.getClass() : null );
context.setCurrentAccessor( null );
context.setPreviousType( null );
Node child = children[i];
String parmString = ASTMethodUtil.getParmString( context, root, child, prevType );
Class valueClass = ASTMethodUtil.getValueClass( context, root, child );
if ( ( !varArgs || varArgs && ( i + 1 ) < parms.length ) && valueClass != parms[i] )
{
parmString = ASTMethodUtil.getParmString( context, parms[i], parmString, child, valueClass,
".class, true)" );
}
sourceStringBuilder.append( parmString );
}
if ( prevCast != null )
{
context.put( ExpressionCompiler.PRE_CAST, prevCast );
}
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
try
{
Object contextObj = getValueBody( context, target );
context.setCurrentObject( contextObj );
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
sourceStringBuilder.append( ")" ).append( post );
if ( method.getReturnType() == void.class )
{
coreExpression = sourceStringBuilder.toString() + ";";
lastExpression = "null";
}
context.setCurrentType( method.getReturnType() );
context.setCurrentAccessor( compiler.getSuperOrInterfaceClass( method, method.getDeclaringClass() ) );
return sourceStringBuilder.toString();
}
public String toSetSourceString( OgnlContext context, Object target )
{
/*
* System.out.println("current type: " + context.getCurrentType() + " target:" + target + " " +
* context.getCurrentObject() + " last child? " + lastChild(context));
*/
Method method =
OgnlRuntime.getWriteMethod( context.getCurrentType() != null ? context.getCurrentType() : target.getClass(),
methodName, children != null ? children.length : -1 );
if ( method == null )
{
throw new UnsupportedCompilationException(
"Unable to determine setter method generation for " + methodName );
}
String post = "";
StringBuilder result = new StringBuilder("." + method.getName() + "(");
if ( method.getReturnType() != void.class && method.getReturnType().isPrimitive() && ( parent == null
|| !(parent instanceof ASTTest)) )
{
Class wrapper = OgnlRuntime.getPrimitiveWrapperClass( method.getReturnType() );
ExpressionCompiler.addCastString( context, "new " + wrapper.getName() + "(" );
post = ")";
getterClass = wrapper;
}
boolean varArgs = method.isVarArgs();
if ( varArgs )
{
throw new UnsupportedCompilationException( "Javassist does not currently support varargs method calls" );
}
OgnlExpressionCompiler compiler = OgnlRuntime.getCompiler( context );
try
{
/*
* if (lastChild(context) && method.getParameterTypes().length > 0 && _children.length <= 0) throw new
* UnsupportedCompilationException("Unable to determine setter method generation for " + method);
*/
if ( ( children != null ) && ( children.length > 0 ) )
{
Class[] parms = method.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();
context.setCurrentObject( context.getRoot() );
context.setCurrentType( context.getRoot() != null ? context.getRoot().getClass() : null );
context.setCurrentAccessor( null );
context.setPreviousType( null );
Node child = children[i];
Object value = child.getValue( context, context.getRoot() );
String parmString = child.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 ( child instanceof ASTProperty || child instanceof ASTMethod
|| child instanceof ASTStaticMethod || child 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 (child instanceof ASTConst)
{
context.setCurrentType( prevType );
}
parmString = ExpressionCompiler.getRootExpression( child, context.getRoot(), context ) + parmString;
String cast = "";
if ( ExpressionCompiler.shouldCast( child ) )
{
cast = (String) context.remove( ExpressionCompiler.PRE_CAST );
}
if ( cast == null )
{
cast = "";
}
parmString = cast + parmString;
Class valueClass = value != null ? value.getClass() : null;
if ( NodeType.class.isAssignableFrom( child.getClass() ) )
{
valueClass = ( (NodeType) child ).getGetterClass();
}
if ( valueClass != parms[i] )
{
parmString =
ASTMethodUtil.getParmString( context, parms[i], parmString, child, valueClass, ".class)" );
}
result.append(parmString);
}
if ( prevCast != null )
{
context.put( ExpressionCompiler.PRE_CAST, prevCast );
}
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
try
{
Object contextObj = getValueBody( context, target );
context.setCurrentObject( contextObj );
}
catch ( Throwable t )
{
// ignore
}
context.setCurrentType( method.getReturnType() );
context.setCurrentAccessor( compiler.getSuperOrInterfaceClass( method, method.getDeclaringClass() ) );
return result + ")" + post;
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,646 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTMultiply.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTMultiply
extends NumericExpression
{
public ASTMultiply( int id )
{
super( id );
}
public ASTMultiply( OgnlParser p, int id )
{
super( p, id );
}
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 ) );
}
return result;
}
public String getExpressionOperator( int index )
{
return "*";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,647 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/IteratorPropertyAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Iterator;
import java.util.Map;
/**
* Implementation of PropertyAccessor that provides "property" reference to "next" and "hasNext".
*/
public class IteratorPropertyAccessor
extends ObjectPropertyAccessor
implements PropertyAccessor // This is here to make javadoc show this class as an implementor
{
@Override
public Object getProperty( Map<String, Object> context, Object target, Object name )
throws OgnlException
{
Object result;
Iterator<?> iterator = (Iterator<?>) target; // check performed by the invoker
if ( name instanceof String )
{
if ( "next".equals( name ) )
{
result = iterator.next();
}
else
{
if ( "hasNext".equals( name ) )
{
result = iterator.hasNext() ? Boolean.TRUE : Boolean.FALSE;
}
else
{
result = super.getProperty( context, target, name );
}
}
}
else
{
result = super.getProperty( context, target, name );
}
return result;
}
@Override
public void setProperty( Map<String, Object> context, Object target, Object name, Object value )
throws OgnlException
{
throw new IllegalArgumentException( "can't set property " + name + " on Iterator" );
}
}
| 4,648 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/DefaultClassResolver.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.HashMap;
import java.util.Map;
/**
* Default class resolution. Uses ClassLoader.loadClass() 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.
*/
public class DefaultClassResolver
implements ClassResolver
{
private final Map<String, Class<?>> classes = new HashMap<String, Class<?>>( 101 );
/**
* Resolves a class for a given className
*
* @param className The name of the Class
* @return The resulting Class object
* @throws ClassNotFoundException If the class could not be found
*/
public Class<?> classForName( String className )
throws ClassNotFoundException
{
return classForName( className, null );
}
/**
* {@inheritDoc}
*/
public Class<?> classForName( String className, Map<String, Object> unused )
throws ClassNotFoundException
{
Class<?> result = classes.get( className );
if ( result == null )
{
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
try
{
result = classLoader.loadClass( className );
}
catch ( ClassNotFoundException ex )
{
if ( className.indexOf( '.' ) == -1 )
{
result = classLoader.loadClass( "java.lang." + className );
classes.put( "java.lang." + className, result );
}
}
classes.put( className, result );
}
return result;
}
}
| 4,649 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTSequence.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import org.apache.commons.ognl.enhance.OrderedReturn;
/**
*/
public class ASTSequence
extends SimpleNode
implements NodeType, OrderedReturn
{
private Class getterClass;
private String lastExpression;
private String coreExpression;
public ASTSequence( int id )
{
super( id );
}
public ASTSequence( OgnlParser p, int id )
{
super( p, id );
}
public void jjtClose()
{
flattenTree();
}
protected Object getValueBody( OgnlContext context, Object source )
throws OgnlException
{
Object result = null;
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 );
}
children[last].setValue( context, target, value );
}
public Class getGetterClass()
{
return getterClass;
}
public Class getSetterClass()
{
return null;
}
public String getLastExpression()
{
return lastExpression;
}
public String getCoreExpression()
{
return coreExpression;
}
public String toSetSourceString( OgnlContext context, Object target )
{
return "";
}
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 );
if ( ( i + 1 ) < children.length && children[i] instanceof ASTOr)
{
seqValue = "(" + seqValue + ")";
}
if ( i > 0 && children[i] instanceof ASTProperty && seqValue != null
&& !seqValue.trim().isEmpty() )
{
String pre = (String) context.get( "_currentChain" );
if ( pre == null )
{
pre = "";
}
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 ( seqValue != null && !seqValue.trim().isEmpty() && ( i + 1 ) < children.length )
{
result += seqValue + ";";
}
else if ( seqValue != null && !seqValue.trim().isEmpty() )
{
result += seqValue;
}
// set last known type from last child with a type
if ( children[i] instanceof NodeType && ( (NodeType) children[i] ).getGetterClass() != null )
{
lastType = (NodeType) children[i];
}
}
if ( lastType != null )
{
getterClass = lastType.getGetterClass();
}
return result;
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,650 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/OgnlRuntime.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
import org.apache.commons.ognl.enhance.OgnlExpressionCompiler;
import org.apache.commons.ognl.internal.CacheException;
import org.apache.commons.ognl.internal.entry.DeclaredMethodCacheEntry;
import org.apache.commons.ognl.internal.entry.GenericMethodParameterTypeCacheEntry;
import org.apache.commons.ognl.internal.entry.MethodAccessEntryValue;
import org.apache.commons.ognl.internal.entry.PermissionCacheEntry;
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.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.Permission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utility class used by internal OGNL API to do various things like:
* <ul>
* <li>Handles majority of reflection logic / caching.</li>
* <li>Utility methods for casting strings / various numeric types used by {@link OgnlExpressionCompiler}.</li.
* <li>Core runtime configuration point for setting/using global {@link TypeConverter} / {@link OgnlExpressionCompiler}
* / {@link NullHandler} instances / etc..</li>
* </ul>
*/
public class OgnlRuntime
{
/**
* Constant expression used to indicate that a given method / property couldn't be found during reflection
* operations.
*/
public static final Object NotFound = new Object();
public static final Object[] NoArguments = new Object[]{ };
/**
* Token returned by TypeConverter for no conversion possible
*/
public static final Object NoConversionPossible = "ognl.NoConversionPossible";
/**
* Not an indexed property
*/
public static final int INDEXED_PROPERTY_NONE = 0;
/**
* JavaBeans IndexedProperty
*/
public static final int INDEXED_PROPERTY_INT = 1;
/**
* OGNL ObjectIndexedProperty
*/
public static final int INDEXED_PROPERTY_OBJECT = 2;
/**
* Constant string representation of null string.
*/
public static final String NULL_STRING = "" + null;
/**
* Java beans standard set method prefix.
*/
public static final String SET_PREFIX = "set";
/**
* Java beans standard get method prefix.
*/
public static final String GET_PREFIX = "get";
/**
* Java beans standard is<Foo> boolean getter prefix.
*/
public static final String IS_PREFIX = "is";
/**
* Prefix padding for hexadecimal numbers to HEX_LENGTH.
*/
private static final Map<Integer, String> HEX_PADDING = new HashMap<Integer, String>();
private static final int HEX_LENGTH = 8;
/**
* Returned by <CODE>getUniqueDescriptor()</CODE> when the object is <CODE>null</CODE>.
*/
private static final String NULL_OBJECT_STRING = "<null>";
static final OgnlCache cache = new OgnlCache();
private static final PrimitiveTypes primitiveTypes = new PrimitiveTypes();
private static final PrimitiveDefaults primitiveDefaults = new PrimitiveDefaults();
private static SecurityManager securityManager = System.getSecurityManager();
/**
* Expression compiler used by {@link Ognl#compileExpression(OgnlContext, Object, String)} calls.
*/
private static OgnlExpressionCompiler compiler;
/**
* Used to provide primitive type equivalent conversions into and out of native / object types.
*/
private static final PrimitiveWrapperClasses primitiveWrapperClasses = new PrimitiveWrapperClasses();
/**
* Constant strings for casting different primitive types.
*/
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)
*/
private static final NumericValues numericValues = new NumericValues();
/**
* Numeric primitive literal string expressions.
*/
private static final NumericLiterals numericLiterals = new NumericLiterals();
private static final NumericDefaults numericDefaults = new NumericDefaults();
/**
* Clears all of the cached reflection information normally used to improve the speed of expressions that operate on
* the same classes or are executed multiple times.
* <p>
* <strong>Warning:</strong> Calling this too often can be a huge performance drain on your expressions - use with
* care.
* </p>
*/
public static void clearCache()
{
cache.clear();
}
public static String getNumericValueGetter( Class<?> type )
{
return numericValues.get( type );
}
public static Class<?> getPrimitiveWrapperClass( Class<?> primitiveClass )
{
return primitiveWrapperClasses.get( primitiveClass );
}
public static String getNumericCast( Class<? extends Number> type )
{
return numericCasts.get( type );
}
public static String getNumericLiteral( Class<? extends Number> type )
{
return numericLiterals.get( type );
}
public static void setCompiler( OgnlExpressionCompiler compiler )
{
OgnlRuntime.compiler = compiler;
}
public static OgnlExpressionCompiler getCompiler( OgnlContext ognlContext )
{
if ( compiler == null )
{
try
{
OgnlRuntime.classForName( ognlContext, "javassist.ClassPool" );
compiler = new ExpressionCompiler();
}
catch ( ClassNotFoundException e )
{
throw new IllegalArgumentException(
"Javassist library is missing in classpath! Please add missed dependency!", e );
}
}
return compiler;
}
public static void compileExpression( OgnlContext context, Node expression, Object root )
throws Exception
{
getCompiler( context ).compileExpression( context, expression, root );
}
/**
* Gets the "target" class of an object for looking up accessors that are registered on the target. If the object is
* a Class object this will return the Class itself, else it will return object's getClass() result.
*/
public static Class<?> getTargetClass( Object o )
{
return ( o == null ) ? null : ( ( o instanceof Class ) ? (Class<?>) o : o.getClass() );
}
/**
* Returns the base name (the class name without the package name prepended) of the object given.
*/
public static String getBaseName( Object o )
{
return ( o == null ) ? null : getClassBaseName( o.getClass() );
}
/**
* Returns the base name (the class name without the package name prepended) of the class given.
*/
public static String getClassBaseName( Class<?> clazz )
{
String className = clazz.getName();
return className.substring( className.lastIndexOf( '.' ) + 1 );
}
public static String getClassName( Object object, boolean fullyQualified )
{
if ( !( object instanceof Class ) )
{
object = object.getClass();
}
return getClassName( (Class<?>) object, fullyQualified );
}
public static String getClassName( Class<?> clazz, boolean fullyQualified )
{
return fullyQualified ? clazz.getName() : getClassBaseName( clazz );
}
/**
* Returns the package name of the object's class.
*/
public static String getPackageName( Object object )
{
return ( object == null ) ? null : getClassPackageName( object.getClass() );
}
/**
* Returns the package name of the class given.
*/
public static String getClassPackageName( Class<?> clazz )
{
String className = clazz.getName();
int index = className.lastIndexOf( '.' );
return ( index < 0 ) ? null : className.substring( 0, index );
}
/**
* Returns a "pointer" string in the usual format for these things - 0x<hex digits>.
*/
public static String getPointerString( int num )
{
String hex = Integer.toHexString( num ), pad;
Integer l = hex.length();
// stringBuilder.append(HEX_PREFIX);
if ( ( pad = HEX_PADDING.get( l ) ) == null )
{
StringBuilder paddingStringBuilder = new StringBuilder();
for ( int i = hex.length(); i < HEX_LENGTH; i++ )
{
paddingStringBuilder.append( '0' );
}
pad = paddingStringBuilder.toString();
HEX_PADDING.put( l, pad );
}
return new StringBuilder().append( pad ).append( hex ).toString();
}
/**
* Returns a "pointer" string in the usual format for these things - 0x<hex digits> for the object given. This will
* always return a unique value for each object.
*/
public static String getPointerString( Object object )
{
return getPointerString( ( object == null ) ? 0 : System.identityHashCode( object ) );
}
/**
* Returns a unique descriptor string that includes the object's class and a unique integer 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.
*/
public static String getUniqueDescriptor( Object object, boolean fullyQualified )
{
StringBuilder stringBuilder = new StringBuilder();
if ( object != null )
{
if ( object instanceof Proxy )
{
Class<?> interfaceClass = object.getClass().getInterfaces()[0];
String className = getClassName( interfaceClass, fullyQualified );
stringBuilder.append( className ).append( '^' );
object = Proxy.getInvocationHandler( object );
}
String className = getClassName( object, fullyQualified );
String pointerString = getPointerString( object );
stringBuilder.append( className ).append( '@' ).append( pointerString );
}
else
{
stringBuilder.append( NULL_OBJECT_STRING );
}
return stringBuilder.toString();
}
/**
* Returns a unique descriptor string that includes the object's class' base name and a unique integer identifier.
*/
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.
*/
public static <T> Object[] toArray( List<T> list )
{
Object[] array;
int size = list.size();
if ( size == 0 )
{
array = NoArguments;
}
else
{
array = new Object[size];
for ( int i = 0; i < size; i++ )
{
array[i] = list.get( i );
}
}
return array;
}
/**
* Returns the parameter types of the given method.
*/
public static Class<?>[] getParameterTypes( Method method )
throws CacheException
{
return cache.getMethodParameterTypes( method );
}
/**
* Finds the appropriate parameter types for the given {@link Method} and {@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 method The method to find types for.
* @return Array of parameter types for the given method.
* @throws org.apache.commons.ognl.internal.CacheException
*/
public static Class<?>[] findParameterTypes( Class<?> type, Method method )
throws CacheException
{
if ( type == null || type.getGenericSuperclass() == null || !(type.getGenericSuperclass() instanceof ParameterizedType) || method.getDeclaringClass().getTypeParameters() == null )
{
return getParameterTypes( method );
}
GenericMethodParameterTypeCacheEntry key = new GenericMethodParameterTypeCacheEntry( method, type );
return cache.getGenericMethodParameterTypes( key );
}
/**
* Returns the parameter types of the given method.
* @param constructor
* @return
* @throws org.apache.commons.ognl.internal.CacheException
*/
public static Class<?>[] getParameterTypes( Constructor<?> constructor )
throws CacheException
{
return cache.getParameterTypes( constructor );
}
/**
* Gets the SecurityManager that OGNL uses to determine permissions for invoking methods.
*
* @return SecurityManager for OGNL
*/
public static SecurityManager getSecurityManager()
{
return securityManager;
}
/**
* Sets the SecurityManager that OGNL uses to determine permissions for invoking methods.
*
* @param securityManager SecurityManager to set
*/
public static void setSecurityManager( SecurityManager securityManager )
{
OgnlRuntime.securityManager = securityManager;
cache.setSecurityManager(securityManager);
}
/**
* Permission will be named "invoke.<declaring-class>.<method-name>".
* @param method
* @return
* @throws org.apache.commons.ognl.internal.CacheException
*/
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, CacheException
{
Object result;
if ( securityManager != null && !cache.getMethodPerm( method ) )
{
throw new IllegalAccessException( "Method [" + method + "] cannot be accessed." );
}
MethodAccessEntryValue entry = cache.getMethodAccess( method );
if ( !entry.isAccessible() )
{
// only synchronize method invocation if it actually requires it
synchronized ( method )
{
if ( entry.isNotPublic() && !entry.isAccessible() )
{
method.setAccessible( true );
}
result = method.invoke( target, argsArray );
if ( !entry.isAccessible() )
{
method.setAccessible( false );
}
}
}
else
{
result = method.invoke( target, argsArray );
}
return result;
}
/**
* Gets the class for a method argument that is appropriate for looking up methods by reflection, by looking for the
* standard primitive wrapper classes and exchanging for them their underlying primitive class objects. Other
* classes are passed through unchanged.
*
* @param arg an object that is being passed to a method
* @return the class to use to look up the method
*/
public static Class<?> getArgClass( Object arg )
{
if ( arg == null )
{
return null;
}
Class<?> clazz = arg.getClass();
if ( clazz == Boolean.class )
{
return Boolean.TYPE;
}
if ( clazz.getSuperclass() == Number.class )
{
if ( clazz == Integer.class )
{
return Integer.TYPE;
}
if ( clazz == Double.class )
{
return Double.TYPE;
}
if ( clazz == Byte.class )
{
return Byte.TYPE;
}
if ( clazz == Long.class )
{
return Long.TYPE;
}
if ( clazz == Float.class )
{
return Float.TYPE;
}
if ( clazz == Short.class )
{
return Short.TYPE;
}
}
else if ( clazz == Character.class )
{
return Character.TYPE;
}
return clazz;
}
/**
* Tells whether the given object is compatible with the given class ---that is, whether the given object can be
* passed as an argument to a method or constructor whose parameter type is the given class. If object is null this
* will return true because null is compatible with any type.
*/
public static boolean isTypeCompatible( Object object, Class<?> clazz )
{
boolean result = true;
if ( object != null )
{
if ( clazz.isPrimitive() )
{
if ( getArgClass( object ) != clazz )
{
result = false;
}
}
else if ( !clazz.isInstance( object ) )
{
result = false;
}
}
return result;
}
/**
* Tells whether the given array of objects is compatible with the given array of classes---that is, whether the
* given array of objects can be passed as arguments to a method or constructor whose parameter types are the given
* array of classes.
*/
public static boolean areArgsCompatible( Object[] args, Class<?>[] classes )
{
return areArgsCompatible( args, classes, null );
}
public static boolean areArgsCompatible( Object[] args, Class<?>[] classes, Method method )
{
boolean result = true;
boolean varArgs = method != null && method.isVarArgs();
if ( args.length != classes.length && !varArgs )
{
result = false;
}
else if ( varArgs )
{
for ( int index = 0; result && ( index < args.length ); ++index )
{
if ( index >= classes.length )
{
break;
}
result = isTypeCompatible( args[index], classes[index] );
if ( !result && classes[index].isArray() )
{
result = isTypeCompatible( args[index], classes[index].getComponentType() );
}
}
}
else
{
for ( int index = 0; result && ( index < args.length ); ++index )
{
result = isTypeCompatible( args[index], classes[index] );
}
}
return result;
}
/**
* Tells whether the first array of classes is more specific than the second. Assumes that the two arrays are of the
* same length.
*/
public static boolean isMoreSpecific( Class<?>[] classes1, Class<?>[] classes2 )
{
for ( int index = 0; index < classes1.length; ++index )
{
Class<?> class1 = classes1[index], class2 = classes2[index];
if ( class1 != class2 )
{
if ( class1.isPrimitive() )
{
return true;
}
if ( class1.isAssignableFrom( class2 ) )
{
return false;
}
if ( class2.isAssignableFrom( class1 ) )
{
return true;
}
}
}
// They are the same! So the first is not more specific than the second.
return false;
}
public static Class<?> classForName( OgnlContext context, String className )
throws ClassNotFoundException
{
Class<?> result = primitiveTypes.get( className );
if ( result == null )
{
ClassResolver resolver;
if ( ( context == null ) || ( ( resolver = context.getClassResolver() ) == null ) )
{
resolver = OgnlContext.DEFAULT_CLASS_RESOLVER;
}
result = resolver.classForName( className, context );
}
if ( result == null )
{
throw new ClassNotFoundException( "Unable to resolve class: " + className );
}
return result;
}
public static boolean isInstance( OgnlContext context, Object value, String className )
throws OgnlException
{
try
{
Class<?> clazz = classForName( context, className );
return clazz.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 getNumericDefaultValue( Class<?> forClass )
{
return numericDefaults.get( forClass );
}
public static Object getConvertedType( OgnlContext context, Object target, Member member, String propertyName,
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 )
{
boolean result = false;
if ( parameterTypes.length == args.length )
{
result = true;
for ( int i = 0; result && ( i <= parameterTypes.length - 1 ); i++ )
{
Object arg = args[i];
Class<?> type = parameterTypes[i];
if ( isTypeCompatible( arg, type ) )
{
newArgs[i] = arg;
}
else
{
Object convertedType = getConvertedType( context, target, member, propertyName, arg, type );
if ( convertedType == OgnlRuntime.NoConversionPossible )
{
result = false;
}
else
{
newArgs[i] = convertedType;
}
}
}
}
return result;
}
public static Method getConvertedMethodAndArgs( OgnlContext context, Object target, String propertyName,
List<Method> methods, Object[] args, Object[] newArgs )
{
Method convertedMethod = null;
TypeConverter typeConverter = context.getTypeConverter();
if ( ( typeConverter != null ) && ( methods != null ) )
{
int methodsSize = methods.size();
for ( int i = 0; ( convertedMethod == null ) && ( i < methodsSize ); i++ )
{
Method method = methods.get( i );
Class<?>[] parameterTypes =
findParameterTypes( target != null ? target.getClass() : null, method );// getParameterTypes(method);
if ( getConvertedTypes( context, target, method, propertyName, parameterTypes, args, newArgs ) )
{
convertedMethod = method;
}
}
}
return convertedMethod;
}
public static Constructor<?> getConvertedConstructorAndArgs( OgnlContext context, Object target,
List<Constructor<?>> constructors, Object[] args,
Object[] newArgs )
{
Constructor<?> constructor = null;
TypeConverter typeConverter = context.getTypeConverter();
if ( ( typeConverter != null ) && ( constructors != null ) )
{
for ( int i = 0; ( constructor == null ) && ( i < constructors.size() ); i++ )
{
Constructor<?> ctor = constructors.get( i );
Class<?>[] parameterTypes = getParameterTypes( ctor );
if ( getConvertedTypes( context, target, ctor, null, parameterTypes, args, newArgs ) )
{
constructor = ctor;
}
}
}
return constructor;
}
/**
* Gets the appropriate method to be called for the given target, method name and arguments. If successful this
* method will return the Method within the target that can be called and the 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 propertyName Name of property to get method of.
* @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,
List<Method> methods, Object[] args, Object[] actualArgs )
{
Method appropriateMethod = null;
Class<?>[] resultParameterTypes = null;
if ( methods != null )
{
for ( Method method : methods )
{
Class<?> typeClass = target != null ? target.getClass() : null;
if ( typeClass == null && source != null && source instanceof Class)
{
typeClass = (Class<?>) source;
}
Class<?>[] mParameterTypes = findParameterTypes( typeClass, method );
if ( areArgsCompatible( args, mParameterTypes, method ) &&
( ( appropriateMethod == null ) || isMoreSpecific( mParameterTypes, resultParameterTypes ) ) )
{
appropriateMethod = method;
resultParameterTypes = mParameterTypes;
System.arraycopy( args, 0, actualArgs, 0, args.length );
for ( int i = 0; i < mParameterTypes.length; i++ )
{
Class<?> type = mParameterTypes[i];
if ( type.isPrimitive() && ( actualArgs[i] == null ) )
{
actualArgs[i] = getConvertedType( context, source, appropriateMethod, propertyName, null, type );
}
}
}
}
}
if ( appropriateMethod == null )
{
appropriateMethod = getConvertedMethodAndArgs( context, target, propertyName, methods, args, actualArgs );
}
return appropriateMethod;
}
public static Object callAppropriateMethod( OgnlContext context, Object source, Object target, String methodName,
String propertyName, List<Method> methods, Object[] args )
throws MethodFailedException
{
Throwable cause = null;
Object[] actualArgs = new Object[args.length];
try
{
Method method = getAppropriateMethod( context, source, target, propertyName, methods, args, actualArgs );
if ( ( method == null ) || !isMethodAccessible( context, source, method, propertyName ) )
{
StringBuilder buffer = new StringBuilder();
String className = "";
if ( target != null )
{
className = target.getClass().getName() + ".";
}
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 )
{
buffer.append( ", " );
}
}
throw new NoSuchMethodException( className + methodName + "(" + buffer + ")" );
}
Object[] convertedArgs = actualArgs;
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() )
{
convertedArgs = new Object[i + 1];
System.arraycopy( actualArgs, 0, convertedArgs, 0, convertedArgs.length );
Object[] varArgs;
// if they passed in varargs arguments grab them and dump in to new varargs array
if ( actualArgs.length > i )
{
List<Object> varArgsList = new ArrayList<Object>();
for ( int j = i; j < actualArgs.length; j++ )
{
if ( actualArgs[j] != null )
{
varArgsList.add( actualArgs[j] );
}
}
varArgs = varArgsList.toArray();
}
else
{
varArgs = new Object[0];
}
convertedArgs[i] = varArgs;
break;
}
}
}
return invokeMethod( target, method, convertedArgs );
}
catch ( NoSuchMethodException | IllegalAccessException e )
{
cause = e;
} catch ( InvocationTargetException e )
{
cause = e.getTargetException();
}
throw new MethodFailedException( source, methodName, cause );
}
public static Object callStaticMethod( OgnlContext context, String className, String methodName, Object[] args )
throws OgnlException
{
try
{
Class<?> targetClass = classForName( context, className );
MethodAccessor methodAccessor = getMethodAccessor( targetClass );
return methodAccessor.callStaticMethod( context, targetClass, methodName, args );
}
catch ( ClassNotFoundException ex )
{
throw new MethodFailedException( className, methodName, ex );
}
}
/**
* 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.
* @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
{
if ( target == null )
{
throw new NullPointerException( "target is null for method " + methodName );
}
return getMethodAccessor( target.getClass() ).callMethod( context, target, methodName, args );
}
public static Object callConstructor( OgnlContext context, String className, Object[] args )
throws OgnlException
{
Throwable cause = null;
Object[] actualArgs = args;
try
{
Constructor<?> ctor = null;
Class<?>[] ctorParameterTypes = null;
Class<?> target = classForName( context, className );
List<Constructor<?>> constructors = getConstructors( target );
for ( Constructor<?> constructor : constructors )
{
Class<?>[] cParameterTypes = getParameterTypes( constructor );
if ( areArgsCompatible( args, cParameterTypes ) && ( ctor == null || isMoreSpecific( cParameterTypes,
ctorParameterTypes ) ) )
{
ctor = constructor;
ctorParameterTypes = cParameterTypes;
}
}
if ( ctor == null )
{
actualArgs = new Object[args.length];
if ( ( ctor = getConvertedConstructorAndArgs( context, target, constructors, args, actualArgs ) ) == null )
{
throw new NoSuchMethodException();
}
}
if ( !context.getMemberAccess().isAccessible( context, target, ctor, null ) )
{
throw new IllegalAccessException( "access denied to " + target.getName() + "()" );
}
return ctor.newInstance( actualArgs );
}
catch ( ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException e )
{
cause = e;
} catch ( InvocationTargetException e )
{
cause = e.getTargetException();
}
throw new MethodFailedException( className, "new", cause );
}
public static Object getMethodValue( OgnlContext context, Object target, String propertyName )
throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException
{
return getMethodValue( context, target, propertyName, false );
}
/**
* If the checkAccessAndExistence flag is true this method will check to see if the method exists and if it is
* accessible according to the context's MemberAccess. If neither test passes this will return NotFound.
*/
public static Object getMethodValue( OgnlContext context, Object target, String propertyName,
boolean checkAccessAndExistence )
throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException
{
Object methodValue = null;
Class<?> targetClass = target == null ? null : target.getClass();
Method method = getGetMethod( context, targetClass, propertyName );
if ( method == null )
{
method = getReadMethod( targetClass, propertyName, 0 );
}
if ( checkAccessAndExistence && (( method == null ) || !context.getMemberAccess().isAccessible( context, target, method, propertyName )) )
{
methodValue = NotFound;
}
if ( methodValue == null )
{
if ( method == null ) {
throw new NoSuchMethodException( propertyName );
}
try
{
methodValue = invokeMethod( target, method, NoArguments );
}
catch ( InvocationTargetException ex )
{
throw new OgnlException( propertyName, ex.getTargetException() );
}
}
return methodValue;
}
public static boolean setMethodValue( OgnlContext context, Object target, String propertyName, Object value )
throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException
{
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
{
boolean result = true;
Method method = getSetMethod( context, ( target == null ) ? null : target.getClass(), propertyName );
if ( checkAccessAndExistence && (( method == null ) || !context.getMemberAccess().isAccessible( context, target, method, propertyName )) )
{
result = false;
}
if ( result )
{
if ( method != null )
{
Object[] args = new Object[]{ value };
callAppropriateMethod( context, target, target, method.getName(), propertyName,
Collections.nCopies( 1, method ), args );
}
else
{
result = false;
}
}
return result;
}
public static List<Constructor<?>> getConstructors( Class<?> targetClass )
{
return cache.getConstructor( targetClass );
}
/**
* @param targetClass
* @param staticMethods if true (false) returns only the (non-)static methods
* @return Returns the map of methods for a given class
*/
public static Map<String, List<Method>> 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 );
}
public static List<Method> getMethods( Class<?> targetClass, String name, boolean staticMethods )
{
return getMethods( targetClass, staticMethods ).get( name );
}
public static Map<String, Field> getFields( Class<?> targetClass )
{
return cache.getField( targetClass );
}
public static Field getField( Class<?> inClass, String name )
{
Field field = getFields( inClass ).get( name );
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();
}
}
return field;
}
public static Object getFieldValue( OgnlContext context, Object target, String propertyName )
throws NoSuchFieldException
{
return getFieldValue( context, target, propertyName, false );
}
public static Object getFieldValue( OgnlContext context, Object target, String propertyName,
boolean checkAccessAndExistence )
throws NoSuchFieldException
{
Object result = null;
Class<?> targetClass = target == null ? null : target.getClass();
Field field = getField( targetClass, propertyName );
if ( checkAccessAndExistence && (( field == null ) || !context.getMemberAccess().isAccessible( context, target, field, propertyName )) )
{
result = NotFound;
}
if ( result == null )
{
if ( field == null )
{
throw new NoSuchFieldException( propertyName );
}
try
{
Object state;
if ( Modifier.isStatic( field.getModifiers() ) ) {
throw new NoSuchFieldException( propertyName );
}
state = context.getMemberAccess().setup( context, target, field, propertyName );
result = field.get( target );
context.getMemberAccess().restore( context, target, field, propertyName, state );
}
catch ( IllegalAccessException ex )
{
throw new NoSuchFieldException( propertyName );
}
}
return result;
}
public static boolean setFieldValue( OgnlContext context, Object target, String propertyName, Object value )
throws OgnlException
{
boolean result = false;
try
{
Class<?> targetClass = target == null ? null : target.getClass();
Field field = getField( targetClass, propertyName );
Object state;
if ( ( field != null ) && !Modifier.isStatic( field.getModifiers() ) )
{
state = context.getMemberAccess().setup( context, target, field, propertyName );
try
{
if ( isTypeCompatible( value, field.getType() ) || (
( value = getConvertedType( context, target, field, propertyName, value, field.getType() ) ) != null ) )
{
field.set( target, value );
result = true;
}
}
finally
{
context.getMemberAccess().restore( context, target, field, propertyName, state );
}
}
}
catch ( IllegalAccessException ex )
{
throw new NoSuchPropertyException( target, propertyName, ex );
}
return result;
}
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 )
{
return context.getMemberAccess().isAccessible( context, target, field, propertyName );
}
public static boolean hasField( OgnlContext context, Object target, Class<?> inClass, String propertyName )
{
Field field = getField( inClass, propertyName );
return ( field != null ) && isFieldAccessible( context, target, field, propertyName );
}
public static Object getStaticField( OgnlContext context, String className, String fieldName )
throws OgnlException
{
Exception cause;
try
{
Class<?> clazz = classForName( context, className );
/*
* Check for virtual static field "class"; this cannot interfere with normal static fields because it is a
* reserved word.
*/
if ( "class".equals( fieldName ) )
{
return clazz;
}
if ( clazz.isEnum() )
{
return Enum.valueOf( (Class<? extends Enum>) clazz, fieldName );
}
Field field = clazz.getField( fieldName );
if ( !Modifier.isStatic(field.getModifiers()) )
{
throw new OgnlException( "Field " + fieldName + " of class " + className + " is not static" );
}
return field.get( null );
}
catch ( ClassNotFoundException | IllegalAccessException | SecurityException | NoSuchFieldException e )
{
cause = e;
}
throw new OgnlException( "Could not get static field " + fieldName + " from class " + className, cause );
}
/**
* @param targetClass
* @param propertyName
* @param findSets
* @return Returns the list of (g)setter of a class for a given property name
* @
*/
public static List<Method> getDeclaredMethods( Class<?> targetClass, String propertyName, boolean findSets )
{
String baseName = Character.toUpperCase( propertyName.charAt( 0 ) ) + propertyName.substring( 1 );
List<Method> methods = new ArrayList<Method>();
List<String> methodNames = new ArrayList<String>( 2 );
if ( findSets )
{
methodNames.add( SET_PREFIX + baseName );
}
else
{
methodNames.add( IS_PREFIX + baseName );
methodNames.add( GET_PREFIX + baseName );
}
for ( String methodName : methodNames )
{
DeclaredMethodCacheEntry key = new DeclaredMethodCacheEntry( targetClass );
List<Method> methodList = cache.getMethod( key ).get( methodName );
if ( methodList != null )
{
methods.addAll( methodList );
}
}
return methods;
}
/**
* Convenience used to check if a method is volatile or synthetic so as to avoid calling un-callable methods.
*
* @param method The method to check.
* @return True if the method should be callable, false otherwise.
*/
//TODO: the method was intended as private, so it'd need to move in a util class
public static boolean isMethodCallable( Method method )
{
return !( method.isSynthetic() || Modifier.isVolatile( method.getModifiers() ) );
}
public static Method getGetMethod( OgnlContext unused, Class<?> targetClass, String propertyName )
throws IntrospectionException, OgnlException
{
Method result = null;
List<Method> methods = getDeclaredMethods( targetClass, propertyName, false /* find 'get' methods */ );
if ( methods != null )
{
for ( Method method : methods )
{
Class<?>[] mParameterTypes = findParameterTypes( targetClass, method ); // getParameterTypes(method);
if ( mParameterTypes.length == 0 )
{
result = method;
break;
}
}
}
return result;
}
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 Method getSetMethod( OgnlContext context, Class<?> targetClass, String propertyName )
throws IntrospectionException, OgnlException
{
Method setMethod = null;
List<Method> methods = getDeclaredMethods( targetClass, propertyName, true /* find 'set' methods */ );
if ( methods != null )
{
for ( Method method : methods )
{
Class<?>[] mParameterTypes = findParameterTypes( targetClass, method ); // getParameterTypes(method);
if ( mParameterTypes.length == 1 )
{
setMethod = method;
break;
}
}
}
return setMethod;
}
public static boolean hasSetMethod( OgnlContext context, Object target, Class<?> targetClass, String propertyName )
throws IntrospectionException, OgnlException
{
return isMethodAccessible( context, target, getSetMethod( context, targetClass, propertyName ), propertyName );
}
public static boolean hasGetProperty( OgnlContext context, Object target, Object oname )
throws IntrospectionException, OgnlException
{
Class<?> targetClass = ( target == null ) ? null : target.getClass();
String name = oname.toString();
return hasGetMethod( context, target, targetClass, name ) || hasField( context, target, targetClass, name );
}
public static boolean hasSetProperty( OgnlContext context, Object target, Object oname )
throws IntrospectionException, OgnlException
{
Class<?> targetClass = ( target == null ) ? null : target.getClass();
String name = oname.toString();
return hasSetMethod( context, target, targetClass, name ) || hasField( context, target, targetClass, name );
}
/**
* 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.
*/
public static Map<String, PropertyDescriptor> getPropertyDescriptors( Class<?> targetClass )
throws IntrospectionException, OgnlException
{
return cache.getPropertyDescriptor( targetClass );
}
/**
* This method returns a PropertyDescriptor for the given class and property name using a Map lookup (using
* getPropertyDescriptorsMap()).
* @param targetClass a target class.
* @param propertyName a property name.
* @return the PropertyDescriptor for the given targetClass and propertyName.
* @throws java.beans.IntrospectionException
* @throws OgnlException
*/
public static PropertyDescriptor getPropertyDescriptor( Class<?> targetClass, String propertyName )
throws IntrospectionException, OgnlException
{
if ( targetClass == null )
{
return null;
}
return getPropertyDescriptors( targetClass ).get( propertyName );
}
public static PropertyDescriptor[] getPropertyDescriptorsArray( Class<?> targetClass )
throws IntrospectionException, OgnlException
{
Collection<PropertyDescriptor> propertyDescriptors = getPropertyDescriptors( targetClass ).values();
return propertyDescriptors.toArray( new PropertyDescriptor[propertyDescriptors.size()] );
}
/**
* Gets the property descriptor with the given name for the target class given.
*
* @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 java.beans.IntrospectionException
* @throws OgnlException
*/
public static PropertyDescriptor getPropertyDescriptorFromArray( Class<?> targetClass, String name )
throws IntrospectionException, OgnlException
{
PropertyDescriptor result = null;
PropertyDescriptor[] propertyDescriptors = getPropertyDescriptorsArray( targetClass );
for ( PropertyDescriptor propertyDescriptor : propertyDescriptors )
{
if ( result != null )
{
break;
}
if ( propertyDescriptor.getName().compareTo( name ) == 0 )
{
result = propertyDescriptor;
}
}
return result;
}
public static void setMethodAccessor( Class<?> clazz, MethodAccessor accessor )
{
cache.setMethodAccessor( clazz, accessor );
}
public static MethodAccessor getMethodAccessor( Class<?> clazz )
throws OgnlException
{
return cache.getMethodAccessor( clazz );
}
public static void setPropertyAccessor( Class<?> clazz, PropertyAccessor accessor )
{
cache.setPropertyAccessor( clazz, accessor );
}
public static PropertyAccessor getPropertyAccessor( Class<?> clazz )
throws OgnlException
{
return cache.getPropertyAccessor( clazz );
}
public static ElementsAccessor getElementsAccessor( Class<?> clazz )
throws OgnlException
{
return cache.getElementsAccessor( clazz );
}
public static void setElementsAccessor( Class<?> clazz, ElementsAccessor accessor )
{
cache.setElementsAccessor( clazz, accessor );
}
public static NullHandler getNullHandler( Class<?> clazz )
throws OgnlException
{
return cache.getNullHandler( clazz );
}
public static void setNullHandler( Class<?> clazz, NullHandler handler )
{
cache.setNullHandler( clazz, handler );
}
public static Object getProperty( OgnlContext context, Object source, Object name )
throws OgnlException
{
PropertyAccessor accessor;
if ( source == null )
{
throw new OgnlException( "source is null for getProperty(null, \"" + name + "\")" );
}
if ( ( accessor = getPropertyAccessor( getTargetClass( source ) ) ) == null )
{
throw new OgnlException( "No property accessor for " + getTargetClass( source ).getName() );
}
return accessor.getProperty( context, source, name );
}
public static void setProperty( OgnlContext context, Object target, Object name, Object value )
throws OgnlException
{
PropertyAccessor accessor;
if ( target == null )
{
throw new OgnlException( "target is null for setProperty(null, \"" + name + "\", " + value + ")" );
}
if ( ( accessor = getPropertyAccessor( getTargetClass( target ) ) ) == null )
{
throw new OgnlException( "No property accessor for " + getTargetClass( target ).getName() );
}
accessor.setProperty( context, target, name, value );
}
/**
* Determines the index property type, if any. Returns <code>INDEXED_PROPERTY_NONE</code> if the property is not
* index-accessible as determined by OGNL or JavaBeans. If it is indexable then this will return whether it is a
* JavaBeans indexed property, conforming to the indexed property patterns (returns
* <code>INDEXED_PROPERTY_INT</code>) or if it conforms to the OGNL arbitrary object indexable (returns
* <code>INDEXED_PROPERTY_OBJECT</code>).
*/
public static int getIndexedPropertyType( OgnlContext context, Class<?> sourceClass, String name )
throws OgnlException
{
int result = INDEXED_PROPERTY_NONE;
try
{
PropertyDescriptor propertyDescriptor = getPropertyDescriptor( sourceClass, name );
if ( propertyDescriptor != null )
{
if ( propertyDescriptor instanceof IndexedPropertyDescriptor )
{
result = INDEXED_PROPERTY_INT;
}
else
{
if ( propertyDescriptor instanceof ObjectIndexedPropertyDescriptor )
{
result = INDEXED_PROPERTY_OBJECT;
}
}
}
}
catch ( Exception ex )
{
throw new OgnlException( "problem determining if '" + name + "' is an indexed property", ex );
}
return result;
}
public static Object getIndexedProperty( OgnlContext context, Object source, String name, Object index )
throws OgnlException
{
Object[] args = new Object[] { index };
try
{
PropertyDescriptor propertyDescriptor = getPropertyDescriptor( ( source == null ) ? null : source.getClass(), name );
Method method;
if ( propertyDescriptor instanceof IndexedPropertyDescriptor )
{
method = ( (IndexedPropertyDescriptor) propertyDescriptor ).getIndexedReadMethod();
}
else
{
if ( !(propertyDescriptor instanceof ObjectIndexedPropertyDescriptor) ) {
throw new OgnlException( "property '" + name + "' is not an indexed property" );
}
method = ( (ObjectIndexedPropertyDescriptor) propertyDescriptor ).getIndexedReadMethod();
}
return callMethod( context, source, method.getName(), args );
}
catch ( OgnlException ex )
{
throw ex;
}
catch ( Exception ex )
{
throw new OgnlException( "getting indexed property descriptor for '" + name + "'", ex );
}
}
public static void setIndexedProperty( OgnlContext context, Object source, String name, Object index, Object value )
throws OgnlException
{
Object[] args = new Object[] { index, value };
try
{
PropertyDescriptor propertyDescriptor = getPropertyDescriptor( ( source == null ) ? null : source.getClass(), name );
Method method;
if ( propertyDescriptor instanceof IndexedPropertyDescriptor )
{
method = ( (IndexedPropertyDescriptor) propertyDescriptor ).getIndexedWriteMethod();
}
else
{
if ( !(propertyDescriptor instanceof ObjectIndexedPropertyDescriptor) ) {
throw new OgnlException( "property '" + name + "' is not an indexed property" );
}
method = ( (ObjectIndexedPropertyDescriptor) propertyDescriptor ).getIndexedWriteMethod();
}
callMethod( context, source, method.getName(), args );
}
catch ( OgnlException ex )
{
throw ex;
}
catch ( Exception ex )
{
throw new OgnlException( "getting indexed property descriptor for '" + name + "'", ex );
}
}
/**
* 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 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();
Object cast = context.get( ExpressionCompiler.PRE_CAST );
context.setCurrentObject( context.getRoot() );
context.setCurrentType( context.getRoot() != null ? context.getRoot().getClass() : null );
context.setCurrentAccessor( null );
context.setPreviousType( null );
for ( int i = 0; i < children.length; i++ )
{
children[i].toGetSourceString( context, context.getRoot() );
parms[i] = context.getCurrentType();
}
context.put( ExpressionCompiler.PRE_CAST, cast );
context.setCurrentType( currType );
context.setCurrentAccessor( currAccessor );
context.setCurrentObject( target );
}
else
{
parms = new Class[0];
}
List<Method> methods = OgnlRuntime.getMethods( target, name, includeStatic );
if ( methods == null )
{
return null;
}
for ( Method method : methods )
{
boolean varArgs = method.isVarArgs();
if ( parms.length != method.getParameterTypes().length && !varArgs )
{
continue;
}
Class<?>[] methodParameterTypes = method.getParameterTypes();
boolean matched = true;
for ( int i = 0; i < methodParameterTypes.length; i++ )
{
Class<?> methodParameterType = methodParameterTypes[i];
if ( varArgs && methodParameterType.isArray() )
{
continue;
}
Class<?> parm = parms[i];
if ( parm == null )
{
matched = false;
break;
}
if ( parm == methodParameterType || methodParameterType.isPrimitive() && Character.TYPE != methodParameterType && Byte.TYPE != methodParameterType
&& Number.class.isAssignableFrom(parm)
&& OgnlRuntime.getPrimitiveWrapperClass(parm) == methodParameterType)
{
continue;
}
matched = false;
break;
}
if ( matched )
{
return method;
}
}
return null;
}
/**
* Finds the best possible match for a method on the specified target class with a matching name.
* <p>
* The name matched will also try different combinations like <code>is + name, has + name, get + name, etc..</code>
* </p>
*
* @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 )
{
return getReadMethod( target, name, -1 );
}
public static Method getReadMethod( Class<?> target, String name, int numParms )
{
try
{
name = name.replace( "\"", "" ).toLowerCase();
BeanInfo info = Introspector.getBeanInfo( target );
MethodDescriptor[] methodDescriptors = info.getMethodDescriptors();
// exact matches first
Method method = null;
for ( MethodDescriptor methodDescriptor : methodDescriptors )
{
if ( !isMethodCallable( methodDescriptor.getMethod() ) )
{
continue;
}
String methodName = methodDescriptor.getName();
String lowerMethodName = methodName.toLowerCase();
int methodParamLen = methodDescriptor.getMethod().getParameterTypes().length;
if ( ( methodName.equalsIgnoreCase( name ) || lowerMethodName.equals( "get" + name )
|| lowerMethodName.equals( "has" + name ) || lowerMethodName.equals( "is" + name ) )
&& !methodName.startsWith( "set" ) )
{
if ( numParms > 0 && methodParamLen == numParms )
{
return methodDescriptor.getMethod();
}
if ( numParms < 0 )
{
if ( methodName.equals( name ) )
{
return methodDescriptor.getMethod();
}
if ( method == null || ( method.getParameterTypes().length > methodParamLen ) )
{
method = methodDescriptor.getMethod();
}
}
}
}
if ( method != null )
{
return method;
}
for ( MethodDescriptor methodDescriptor : methodDescriptors )
{
if ( !isMethodCallable( methodDescriptor.getMethod() ) )
{
continue;
}
if ( methodDescriptor.getName().toLowerCase().endsWith( name ) && !methodDescriptor.getName().startsWith( "set" )
&& methodDescriptor.getMethod().getReturnType() != Void.TYPE )
{
if ( numParms > 0 && methodDescriptor.getMethod().getParameterTypes().length == numParms )
{
return methodDescriptor.getMethod();
}
if ( (numParms < 0) && (method == null || ( method.getParameterTypes().length
> methodDescriptor.getMethod().getParameterTypes().length )) )
{
method = methodDescriptor.getMethod();
}
}
}
if ( method != null )
{
return method;
}
// try one last time adding a get to beginning
if ( !name.startsWith( "get" ) )
{
return OgnlRuntime.getReadMethod( target, "get" + name, numParms );
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return null;
}
public static Method getWriteMethod( Class<?> target, String name )
{
return getWriteMethod( target, name, -1 );
}
public static Method getWriteMethod( Class<?> target, String name, int numParms )
{
try
{
name = name.replace( "\"", "" );
BeanInfo info = Introspector.getBeanInfo( target );
MethodDescriptor[] methods = info.getMethodDescriptors();
for ( MethodDescriptor method : methods )
{
if ( !isMethodCallable( method.getMethod() ) )
{
continue;
}
if ( ( method.getName().equalsIgnoreCase( name ) || method.getName().toLowerCase().equals(
name.toLowerCase() ) || method.getName().toLowerCase().equals( "set" + name.toLowerCase() ) )
&& !method.getName().startsWith( "get" ) )
{
if ( numParms > 0 && method.getMethod().getParameterTypes().length == numParms )
{
return method.getMethod();
}
if ( numParms < 0 )
{
return method.getMethod();
}
}
}
// try again on pure class
Method[] cmethods = target.getClass().getMethods();
for ( Method cmethod : cmethods )
{
if ( !isMethodCallable( cmethod ) )
{
continue;
}
if ( ( cmethod.getName().equalsIgnoreCase( name ) || cmethod.getName().toLowerCase().equals(
name.toLowerCase() ) || cmethod.getName().toLowerCase().equals( "set" + name.toLowerCase() ) )
&& !cmethod.getName().startsWith( "get" ) )
{
if ( numParms > 0 && cmethod.getParameterTypes().length == numParms )
{
return cmethod;
}
if ( numParms < 0 )
{
return cmethod;
}
}
}
// try one last time adding a set to beginning
if ( !name.startsWith( "set" ) )
{
return OgnlRuntime.getReadMethod( target, "set" + name, numParms );
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return null;
}
public static PropertyDescriptor getProperty( Class<?> target, String name )
{
try
{
BeanInfo info = Introspector.getBeanInfo( target );
PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
for ( PropertyDescriptor propertyDescriptor : propertyDescriptors )
{
String propertyDescriptorName = propertyDescriptor.getName();
if ( propertyDescriptorName.equalsIgnoreCase( name ) || propertyDescriptorName.toLowerCase().equals( name.toLowerCase() )
|| propertyDescriptorName.toLowerCase().endsWith( name.toLowerCase() ) )
{
return propertyDescriptor;
}
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return null;
}
public static boolean isBoolean( String expression )
{
return expression != null && ( "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( "org.apache.commons.ognl.OgnlOps" ) );
}
/**
* Compares the {@link OgnlContext#getCurrentType()} and {@link OgnlContext#getPreviousType()} class types on the
* stack to determine if a numeric expression should force object conversion.
* <p/>
* <p/>
* Normally used in conjunction with the <code>forceConversion</code> parameter of
* {@link OgnlRuntime#getChildSource(OgnlContext, Object, Node, boolean)}.
* </p>
*
* @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
* <code>o1 >= o2</code>.
*/
public static boolean shouldConvertNumericTypes( OgnlContext context )
{
Class<?> currentType = context.getCurrentType();
Class<?> previousType = context.getPreviousType();
return currentType == null || previousType == null
|| !( currentType == previousType && currentType.isPrimitive() && previousType.isPrimitive() )
&& !currentType.isArray() && !previousType.isArray();
}
/**
* 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.
* @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)
*/
public static String getChildSource( OgnlContext context, Object target, Node child, boolean forceConversion )
throws OgnlException
{
String pre = (String) context.get( "_currentChain" );
if ( pre == null )
{
pre = "";
}
try
{
child.getValue( context, target );
}
catch ( NullPointerException e )
{
// ignore
}
catch ( ArithmeticException e )
{
context.setCurrentType( int.class );
return "0";
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
String source;
try
{
source = child.toGetSourceString( context, target );
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
// handle root / method expressions that may not have proper root java source access
if ( !(child instanceof ASTConst) && ( target == null || context.getRoot() != target ) )
{
source = pre + source;
}
if ( context.getRoot() != null )
{
source = ExpressionCompiler.getRootExpression( child, context.getRoot(), context ) + source;
context.setCurrentAccessor( context.getRoot().getClass() );
}
if (child instanceof ASTChain)
{
String cast = (String) context.remove( ExpressionCompiler.PRE_CAST );
if ( cast == null )
{
cast = "";
}
source = cast + source;
}
if ( source == null || source.trim().length() < 1 )
{
source = "null";
}
return source;
}
}
| 4,651 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/NumericCasts.java | package org.apache.commons.ognl;
/*
* 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.
*/
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<Class<? extends Number>, String> map = new HashMap<Class<? extends Number>, String>();
NumericCasts() {
map.put( Double.class, "(double)" );
map.put( Float.class, "(float)" );
map.put( Integer.class, "(int)" );
map.put( Long.class, "(long)" );
map.put( BigDecimal.class, "(double)" );
map.put( BigInteger.class, "" );
}
String get( Class<? extends Number> cls ) {
return map.get( cls );
}
}
| 4,652 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/IteratorEnumeration.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Enumeration;
import java.util.Iterator;
/**
* Maps an Iterator to an Enumeration
*/
public class IteratorEnumeration<T>
implements Enumeration<T>
{
public static <E> Enumeration<E> newEnumeration( Iterator<E> iterator )
{
return new IteratorEnumeration<E>( iterator );
}
private final Iterator<T> it;
private IteratorEnumeration( Iterator<T> it )
{
this.it = it;
}
/**
* {@inheritDoc}
*/
public boolean hasMoreElements()
{
return it.hasNext();
}
/**
* {@inheritDoc}
*/
public T nextElement()
{
return it.next();
}
}
| 4,653 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/NumericExpression.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
/**
* Base class for numeric expressions.
*/
public abstract class NumericExpression
extends ExpressionNode
implements NodeType
{
private static final long serialVersionUID = -174952564587478850L;
protected Class<?> getterClass;
public NumericExpression( int id )
{
super( id );
}
public NumericExpression( OgnlParser p, int id )
{
super( p, id );
}
/**
* {@inheritDoc}
*/
public Class<?> getGetterClass()
{
if ( getterClass != null )
{
return getterClass;
}
return Double.TYPE;
}
/**
* {@inheritDoc}
*/
public Class<?> getSetterClass()
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
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.append( " " ).append( getExpressionOperator( i ) ).append( " " );
}
String str = OgnlRuntime.getChildSource( context, target, children[i] );
result.append( coerceToNumeric( str, context, children[i] ) );
}
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
return result.toString();
}
public String coerceToNumeric( String source, OgnlContext context, Node child )
{
StringBuilder ret = new StringBuilder( source );
Object value = context.getCurrentObject();
if ( child instanceof ASTConst && value != null )
{
return value.toString();
}
if ( context.getCurrentType() != null && !context.getCurrentType().isPrimitive()
&& context.getCurrentObject() != null && context.getCurrentObject() instanceof Number)
{
ret = new StringBuilder( "((" ).append(
ExpressionCompiler.getCastString( context.getCurrentObject().getClass() ) ).append( ")" ).append(
ret ).append( ")." ).append(
OgnlRuntime.getNumericValueGetter( context.getCurrentObject().getClass() ) );
}
else if ( context.getCurrentType() != null && context.getCurrentType().isPrimitive()
&& ( child instanceof ASTConst || child instanceof NumericExpression) )
{
@SuppressWarnings( "unchecked" ) // checked by the condition in the if clause
Class<? extends Number> numberClass = (Class<? extends Number>) context.getCurrentType();
ret.append( OgnlRuntime.getNumericLiteral( numberClass ) );
}
else if ( context.getCurrentType() != null && String.class.isAssignableFrom( context.getCurrentType() ) )
{
ret = new StringBuilder( "Double.parseDouble(" )
.append( ret )
.append( ")" );
context.setCurrentType( Double.TYPE );
}
if (child instanceof NumericExpression)
{
ret = new StringBuilder( "(" ).append( ret ).append( ")" );
}
return ret.toString();
}
}
| 4,654 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTInstanceof.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
public class ASTInstanceof
extends SimpleNode
implements NodeType
{
private String targetType;
public ASTInstanceof( int id )
{
super( id );
}
public ASTInstanceof( OgnlParser p, int id )
{
super( p, id );
}
void setTargetType( String targetType )
{
this.targetType = targetType;
}
String getTargetType()
{
return targetType;
}
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 Class getGetterClass()
{
return boolean.class;
}
public Class getSetterClass()
{
return null;
}
public String toGetSourceString( OgnlContext context, Object target )
{
try
{
String ret = "";
if (children[0] instanceof ASTConst)
{
ret = ( (Boolean) getValueBody( context, target ) ).toString();
}
else
{
ret = children[0].toGetSourceString( context, target ) + " instanceof " + targetType;
}
context.setCurrentType( Boolean.TYPE );
return ret;
}
catch ( Throwable t )
{
throw OgnlOps.castToRuntime( t );
}
}
public String toSetSourceString( OgnlContext context, Object target )
{
return toGetSourceString( context, target );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,655 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/IteratorElementsAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import static org.apache.commons.ognl.IteratorEnumeration.newEnumeration;
import java.util.Enumeration;
import java.util.Iterator;
/**
* Implementation of the ElementsAccessor interface for Iterators, which simply returns the target iterator itself.
*/
public class IteratorElementsAccessor
implements ElementsAccessor
{
/**
* {@inheritDoc}
*/
public Enumeration<?> getElements( Object target )
{
return newEnumeration( (Iterator<?>) target );
}
}
| 4,656 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/BooleanExpression.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
* Base class for boolean expressions.
*/
public abstract class BooleanExpression
extends ExpressionNode
implements NodeType
{
private static final long serialVersionUID = 8630306635724834872L;
protected Class<?> getterClass;
public BooleanExpression( int id )
{
super( id );
}
public BooleanExpression( OgnlParser p, int id )
{
super( p, id );
}
/**
* {@inheritDoc}
*/
public Class<?> getGetterClass()
{
return getterClass;
}
/**
* {@inheritDoc}
*/
public Class<?> getSetterClass()
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
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;
}
String ret = super.toGetSourceString( context, target );
if ( "(false)".equals( ret ) )
{
return "false";
}
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 )
{
throw OgnlOps.castToRuntime( t );
}
}
}
| 4,657 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ObjectMethodAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
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.
*/
public class ObjectMethodAccessor
implements MethodAccessor
{
/**
* {@inheritDoc}
*/
public Object callStaticMethod( Map<String, Object> context, Class<?> targetClass, String methodName,
Object[] args )
throws MethodFailedException
{
List<Method> methods = OgnlRuntime.getMethods( targetClass, methodName, true );
return OgnlRuntime.callAppropriateMethod( (OgnlContext) context, targetClass, null, methodName, null, methods,
args );
}
/**
* {@inheritDoc}
*/
public Object callMethod( Map<String, Object> context, Object target, String methodName, Object[] args )
throws MethodFailedException
{
Class<?> targetClass = ( target == null ) ? null : target.getClass();
List<Method> methods = OgnlRuntime.getMethods( targetClass, methodName, false );
if ( ( methods == null ) || ( methods.isEmpty() ) )
{
methods = OgnlRuntime.getMethods( targetClass, methodName, true );
}
return OgnlRuntime.callAppropriateMethod( (OgnlContext) context, target, target, methodName, null, methods,
args );
}
}
| 4,658 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/PrimitiveWrapperClasses.java | package org.apache.commons.ognl;
/*
* 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.
*/
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<?>, Class<?>> map = new IdentityHashMap<Class<?>, Class<?>>();
PrimitiveWrapperClasses() {
map.put( Boolean.TYPE, Boolean.class );
map.put( Boolean.class, Boolean.TYPE );
map.put( Byte.TYPE, Byte.class );
map.put( Byte.class, Byte.TYPE );
map.put( Character.TYPE, Character.class );
map.put( Character.class, Character.TYPE );
map.put( Short.TYPE, Short.class );
map.put( Short.class, Short.TYPE );
map.put( Integer.TYPE, Integer.class );
map.put( Integer.class, Integer.TYPE );
map.put( Long.TYPE, Long.class );
map.put( Long.class, Long.TYPE );
map.put( Float.TYPE, Float.class );
map.put( Float.class, Float.TYPE );
map.put( Double.TYPE, Double.class );
map.put( Double.class, Double.TYPE );
}
Class<?> get( Class<?> cls ) {
return map.get( cls );
}
}
| 4,659 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTIn.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
*/
class ASTIn
extends SimpleNode
implements NodeType
{
public ASTIn( int id )
{
super( id );
}
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 );
return OgnlOps.in( v1, v2 ) ? Boolean.TRUE : Boolean.FALSE;
}
public Class getGetterClass()
{
return Boolean.TYPE;
}
public Class getSetterClass()
{
return null;
}
public String toGetSourceString( OgnlContext context, Object target )
{
try
{
String result = "org.apache.commons.ognl.OgnlOps.in( ($w) ";
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 )
{
throw OgnlOps.castToRuntime( t );
}
}
public String toSetSourceString( OgnlContext context, Object target )
{
throw new UnsupportedCompilationException( "Map expressions not supported as native java yet." );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,660 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTNotEq.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTNotEq
extends ComparisonExpression
{
public ASTNotEq( int id )
{
super( id );
}
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 );
return OgnlOps.equal( v1, v2 ) ? Boolean.FALSE : Boolean.TRUE;
}
public String getExpressionOperator( int index )
{
return "!=";
}
public String getComparisonFunction()
{
return "!org.apache.commons.ognl.OgnlOps.equal";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,661 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ExpressionNode.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionCompiler;
public abstract class ExpressionNode
extends SimpleNode
{
private static final long serialVersionUID = 9076228016268317598L;
public ExpressionNode( int i )
{
super( i );
}
public ExpressionNode( OgnlParser p, int i )
{
super( p, i );
}
/**
* Returns true iff this node is constant without respect to the children.
*/
@Override
public boolean isNodeConstant( OgnlContext context )
throws OgnlException
{
return false;
}
@Override
public boolean isConstant( OgnlContext context )
throws OgnlException
{
boolean result = isNodeConstant( context );
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 );
}
else
{
result = false;
}
}
}
return result;
}
public String getExpressionOperator( int index )
{
throw new UnsupportedOperationException( "unknown operator for " + OgnlParserTreeConstants.jjtNodeName[id] );
}
@Override
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.append( " " ).append( getExpressionOperator( i ) ).append( " " );
}
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().isEmpty() )
{
String pre = null;
if (children[i] instanceof ASTMethod)
{
pre = (String) context.get( "_currentChain" );
}
if ( pre == null )
{
pre = "";
}
String cast = (String) context.remove( ExpressionCompiler.PRE_CAST );
if ( cast == null )
{
cast = "";
}
value =
cast + ExpressionCompiler.getRootExpression( children[i], context.getRoot(), context ) + pre
+ value;
}
result.append( value );
}
}
if ( parent != null && !NumericExpression.class.isAssignableFrom( parent.getClass() ) )
{
result.append( ")" );
}
return result.toString();
}
@Override
public String toSetSourceString( OgnlContext context, Object target )
{
StringBuilder sourceStringBuilder = new StringBuilder( parent == null ? "" : "(" );
if ( ( children != null ) && ( children.length > 0 ) )
{
for ( int i = 0; i < children.length; ++i )
{
if ( i > 0 )
{
sourceStringBuilder.append( " " ).append( getExpressionOperator( i ) ).append( ' ' );
}
sourceStringBuilder.append( children[i].toSetSourceString( context, target ) );
}
}
if ( parent != null )
{
sourceStringBuilder.append( ")" );
}
return sourceStringBuilder.toString();
}
}
| 4,662 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTTest.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
*/
class ASTTest
extends ExpressionNode
{
public ASTTest( int id )
{
super( id );
}
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 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 )
{
return ( index == 1 ) ? "?" : ":";
}
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 );
}
String result = "";
try
{
String first = OgnlRuntime.getChildSource( context, target, children[0] );
if ( !OgnlRuntime.isBoolean( first ) && !context.getCurrentType().isPrimitive() )
{
first = OgnlRuntime.getCompiler( context ).createLocalReference( context, first, context.getCurrentType() );
}
if (children[0] instanceof ExpressionNode)
{
first = "(" + first + ")";
}
String second = OgnlRuntime.getChildSource( context, target, children[1] );
Class secondType = context.getCurrentType();
if ( !OgnlRuntime.isBoolean( second ) && !context.getCurrentType().isPrimitive() )
{
second = OgnlRuntime.getCompiler( context ).createLocalReference( context, second, context.getCurrentType() );
}
if (children[1] instanceof ExpressionNode)
{
second = "(" + second + ")";
}
String third = OgnlRuntime.getChildSource( context, target, children[2] );
Class thirdType = context.getCurrentType();
if ( !OgnlRuntime.isBoolean( third ) && !context.getCurrentType().isPrimitive() )
{
third = OgnlRuntime.getCompiler( context ).createLocalReference( context, third, context.getCurrentType() );
}
if (children[2] instanceof ExpressionNode)
{
third = "(" + third + ")";
}
boolean mismatched =
( secondType.isPrimitive( ) && !thirdType.isPrimitive( ) ) || ( !secondType.isPrimitive( )
&& thirdType.isPrimitive( ) );
result += "org.apache.commons.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 )
{
throw OgnlOps.castToRuntime( t );
}
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,663 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ExpressionSyntaxException.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
* Exception thrown if a malformed OGNL expression is encountered.
*/
public class ExpressionSyntaxException
extends OgnlException
{
private static final long serialVersionUID = 3828005676770762146L;
public ExpressionSyntaxException( String expression, Throwable reason )
{
super( "Malformed OGNL expression: " + expression, reason );
}
}
| 4,664 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTMap.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
*/
class ASTMap
extends SimpleNode
{
private String className;
private final Map<OgnlContext, Class> defaultMapClassMap = new HashMap<OgnlContext, Class>();
public ASTMap( int id )
{
super( id );
}
public ASTMap( OgnlParser p, int id )
{
super( p, id );
}
protected void setClassName( String value )
{
className = value;
}
/**
* Gets the class name for this map.
*
* @return the class name.
* @since 4.0
*/
String getClassName()
{
return className;
}
protected Object getValueBody( OgnlContext context, Object source )
throws OgnlException
{
Map answer;
if ( className == null )
{
Class defaultMapClass = getDefaultMapClass( context );
try
{
answer = (Map) defaultMapClass.newInstance();
}
catch ( Exception ex )
{
/* This should never happen */
throw new OgnlException( "Default Map class '" + defaultMapClass.getName() + "' instantiation error",
ex );
}
}
else
{
try
{
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];
Node k = kv.getKey(), v = kv.getValue();
answer.put( k.getValue( context, source ), ( v == null ) ? null : v.getValue( context, source ) );
}
return answer;
}
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 )
{
throw new UnsupportedCompilationException( "Map expressions not supported as native java yet." );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
private Class getDefaultMapClass( OgnlContext context )
{
Class defaultMapClass = defaultMapClassMap.get( context );
if ( defaultMapClass != null )
{
return defaultMapClass;
}
defaultMapClass = LinkedHashMap.class;
defaultMapClassMap.put( context, defaultMapClass );
return defaultMapClass;
}
}
| 4,665 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/NumericValues.java | package org.apache.commons.ognl;
/*
* 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.
*/
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<Class<?>, String> map = new HashMap<Class<?>, String>();
NumericValues() {
map.put( Double.class, "doubleValue()" );
map.put( Float.class, "floatValue()" );
map.put( Integer.class, "intValue()" );
map.put( Long.class, "longValue()" );
map.put( Short.class, "shortValue()" );
map.put( Byte.class, "byteValue()" );
map.put( BigDecimal.class, "doubleValue()" );
map.put( BigInteger.class, "doubleValue()" );
map.put( Boolean.class, "booleanValue()" );
}
String get( Class<?> cls ) {
return map.get( cls );
}
}
| 4,666 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/SimpleNode.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.ExpressionAccessor;
import java.io.PrintWriter;
import java.io.Serializable;
public abstract class SimpleNode
implements Node, Serializable
{
private static final long serialVersionUID = 8305393337889433901L;
protected Node parent;
protected Node[] children;
protected int id;
protected OgnlParser parser;
private boolean constantValueCalculated;
private volatile boolean hasConstantValue;
private Object constantValue;
private ExpressionAccessor accessor;
public SimpleNode( int i )
{
id = i;
}
public SimpleNode( OgnlParser p, int i )
{
this( i );
parser = p;
}
public void jjtOpen()
{
}
public void jjtClose()
{
}
public void jjtSetParent( Node n )
{
parent = n;
}
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;
}
children[i] = n;
}
public Node jjtGetChild( int i )
{
return children[i];
}
public int jjtGetNumChildren()
{
return ( children == null ) ? 0 : children.length;
}
/*
* You can override these two methods in subclasses of SimpleNode to customize the way the node appears when the
* tree is dumped. If your output uses more than one line you should override toString(String), otherwise overriding
* toString() is probably all you need to do.
*/
@Override
public String toString()
{
final StringBuilder data = new StringBuilder();
try
{
accept( ToStringVisitor.INSTANCE, data );
}
catch ( OgnlException e )
{
// ignored.
}
return data.toString();
}
// OGNL additions
public String toString( String prefix )
{
return prefix + OgnlParserTreeConstants.jjtNodeName[id] + " " + toString();
}
public String toGetSourceString( OgnlContext context, Object target )
{
return toString();
}
public String toSetSourceString( OgnlContext context, Object target )
{
return toString();
}
/*
* Override this method if you want to customize how the node dumps out its children.
*/
public void dump( PrintWriter writer, String prefix )
{
writer.println( toString( prefix ) );
if ( children != null )
{
for (Node child : children) {
SimpleNode n = (SimpleNode) child;
if ( n != null )
{
n.dump( writer, prefix + " " );
}
}
}
}
public int getIndexInParent()
{
int result = -1;
if ( parent != null )
{
int icount = parent.jjtGetNumChildren();
for ( int i = 0; i < icount; i++ )
{
if ( parent.jjtGetChild( i ) == this )
{
result = i;
break;
}
}
}
return result;
}
public Node getNextSibling()
{
Node result = null;
int i = getIndexInParent();
if ( i >= 0 )
{
int icount = parent.jjtGetNumChildren();
if ( i < icount )
{
result = parent.jjtGetChild( i + 1 );
}
}
return result;
}
protected Object evaluateGetValueBody( OgnlContext context, Object source )
throws OgnlException
{
context.setCurrentObject( source );
context.setCurrentNode( this );
if ( !constantValueCalculated )
{
constantValueCalculated = true;
boolean constant = isConstant( context );
if ( constant )
{
constantValue = getValueBody( context, source );
}
hasConstantValue = constant;
}
return hasConstantValue ? constantValue : getValueBody( context, source );
}
protected void evaluateSetValueBody( OgnlContext context, Object target, Object value )
throws OgnlException
{
context.setCurrentObject( target );
context.setCurrentNode( this );
setValueBody( context, target, value );
}
public final Object getValue( OgnlContext context, Object source )
throws OgnlException
{
Object result = null;
if ( context.getTraceEvaluations() )
{
Throwable evalException = null;
Evaluation evaluation = new Evaluation( this, source );
context.pushEvaluation( evaluation );
try
{
result = evaluateGetValueBody( context, source );
}
catch ( OgnlException | RuntimeException ex )
{
evalException = ex;
throw ex;
} finally
{
Evaluation eval = context.popEvaluation();
eval.setResult( result );
if ( evalException != null )
{
eval.setException( evalException );
}
}
}
else
{
result = evaluateGetValueBody( context, source );
}
return result;
}
/**
* Subclasses implement this method to do the actual work of extracting the appropriate value from the source
* object.
*/
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() )
{
Throwable evalException = null;
Evaluation evaluation = new Evaluation( this, target, true );
context.pushEvaluation( evaluation );
try
{
evaluateSetValueBody( context, target, value );
}
catch ( OgnlException ex )
{
evalException = ex;
ex.setEvaluation( evaluation );
throw ex;
}
catch ( RuntimeException ex )
{
evalException = ex;
throw ex;
}
finally
{
Evaluation eval = context.popEvaluation();
if ( evalException != null )
{
eval.setException( evalException );
}
}
}
else
{
evaluateSetValueBody( context, target, value );
}
}
/**
* Subclasses implement this method to do the actual work of setting the appropriate value in the target object. The
* default implementation throws an <code>InappropriateExpressionException</code>, meaning that it cannot be a set
* expression.
*/
protected void setValueBody( OgnlContext context, Object target, Object value )
throws OgnlException
{
throw new InappropriateExpressionException( this );
}
/** Returns true iff this node is constant without respect to the children. */
public boolean isNodeConstant( OgnlContext context )
throws OgnlException
{
return false;
}
public boolean isConstant( OgnlContext context )
throws OgnlException
{
return isNodeConstant( context );
}
public boolean isNodeSimpleProperty( OgnlContext context )
throws OgnlException
{
return false;
}
public boolean isSimpleProperty( OgnlContext context )
throws OgnlException
{
return isNodeSimpleProperty( context );
}
public boolean isSimpleNavigationChain( OgnlContext context )
throws OgnlException
{
return isSimpleProperty( context );
}
public boolean isEvalChain( OgnlContext context )
throws OgnlException
{
if ( children == null )
{
return false;
}
for ( Node child : children )
{
if ( child instanceof SimpleNode && ( (SimpleNode) child ).isEvalChain( context ) )
{
return true;
}
}
return false;
}
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()
{
boolean shouldFlatten = false;
int newSize = 0;
for ( Node aChildren : children )
{
if ( aChildren.getClass() == getClass() )
{
shouldFlatten = true;
newSize += aChildren.jjtGetNumChildren();
}
else
{
++newSize;
}
}
if ( shouldFlatten )
{
Node[] newChildren = new Node[newSize];
int j = 0;
for ( Node c : children )
{
if ( c.getClass() == getClass() )
{
for ( int k = 0; k < c.jjtGetNumChildren(); ++k )
{
newChildren[j++] = c.jjtGetChild( k );
}
}
else
{
newChildren[j++] = c;
}
}
if ( j != newSize )
{
throw new Error( "Assertion error: " + j + " != " + newSize );
}
children = newChildren;
}
}
public ExpressionAccessor getAccessor()
{
return accessor;
}
public void setAccessor( ExpressionAccessor accessor )
{
this.accessor = accessor;
}
}
| 4,667 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTShiftLeft.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTShiftLeft
extends NumericExpression
{
public ASTShiftLeft( int id )
{
super( id );
}
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 );
}
public String getExpressionOperator( int index )
{
return "<<";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,668 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/NodeType.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
* Used by some of the {@link ognl.enhance.OgnlExpressionCompiler} logic to determine the object type of {@link Node}s
* during expression evaluation.
*/
public interface NodeType
{
/**
* The type returned from the expression - if any.
*
* @return The type.
*/
Class<?> getGetterClass();
/**
* The type used to set the value - if any.
*
* @return The type.
*/
Class<?> getSetterClass();
}
| 4,669 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/CollectionElementsAccessor.java | package org.apache.commons.ognl;
/*
* 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.
*/
import static org.apache.commons.ognl.IteratorEnumeration.newEnumeration;
import java.util.Collection;
import java.util.Enumeration;
/**
* Implementation of ElementsAccessor that returns a collection's iterator.
*/
public class CollectionElementsAccessor
implements ElementsAccessor
{
/**
* {@inheritDoc}
*/
public Enumeration<?> getElements( Object target )
{
return newEnumeration( ( (Collection<?>) target ).iterator() );
}
}
| 4,670 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTAssign.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.enhance.OrderedReturn;
import org.apache.commons.ognl.enhance.UnsupportedCompilationException;
/**
*/
class ASTAssign
extends SimpleNode
{
public ASTAssign( int id )
{
super( id );
}
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 );
return result;
}
public String toGetSourceString( OgnlContext context, Object target )
{
String result = "";
String first = children[0].toGetSourceString( context, target );
String second = "";
if (children[1] instanceof ASTProperty)
{
second += "((" + OgnlRuntime.getCompiler( context ).getClassName( target.getClass() ) + ")$2).";
}
second += children[1].toGetSourceString( context, target );
if ( ASTSequence.class.isAssignableFrom( children[1].getClass() ) )
{
ASTSequence seq = (ASTSequence) children[1];
context.setCurrentType( Object.class );
String core = seq.getCoreExpression();
if ( core.endsWith( ";" ) )
{
core = core.substring( 0, core.lastIndexOf( ";" ) );
}
second =
OgnlRuntime.getCompiler( context ).createLocalReference( context,
"org.apache.commons.ognl.OgnlOps.returnValue(($w)"
+ core + ", ($w) " + seq.getLastExpression() + ")",
Object.class );
}
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 + ")";
}
if ( OrderedReturn.class.isAssignableFrom( children[0].getClass() )
&& ( (OrderedReturn) children[0] ).getCoreExpression() != null )
{
context.setCurrentType( Object.class );
result = first + second + ")";
// System.out.println("building ordered ret from child[0] with result of:" + result);
result =
OgnlRuntime
.getCompiler( context )
.createLocalReference( context,
"org.apache.commons.ognl.OgnlOps.returnValue(($w)" + result + ", ($w)"
+ ( (OrderedReturn) children[0] ).getLastExpression() + ")",
Object.class );
}
return result;
}
public String toSetSourceString( OgnlContext context, Object target )
{
String result = "";
result += children[0].toSetSourceString( context, target );
if (children[1] instanceof ASTProperty)
{
result += "((" + OgnlRuntime.getCompiler( context ).getClassName( target.getClass() ) + ")$2).";
}
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];
result = seq.getCoreExpression() + result;
value = seq.getLastExpression();
}
if ( children[1] instanceof NodeType && !(children[1] instanceof ASTProperty)
&& ( (NodeType) children[1] ).getGetterClass() != null )
{
value = "new " + ( (NodeType) children[1] ).getGetterClass().getName() + "(" + value + ")";
}
return result + value + ")";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,671 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTBitAnd.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTBitAnd
extends NumericExpression
{
public ASTBitAnd( int id )
{
super( id );
}
public ASTBitAnd( OgnlParser p, int id )
{
super( p, id );
}
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 ) );
}
return result;
}
public String getExpressionOperator( int index )
{
return "&";
}
public String coerceToNumeric( String source, OgnlContext context, Node child )
{
return "(long)" + super.coerceToNumeric( source, context, child );
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,672 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ObjectNullHandler.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.util.Map;
/**
* Implementation of NullHandler that returns null in all cases, so that NullPointerException will be thrown by the
* caller.
*/
public class ObjectNullHandler
implements NullHandler
{
/* NullHandler interface */
public Object nullMethodResult( Map<String, Object> context, Object target, String methodName, Object[] args )
{
return null;
}
public Object nullPropertyValue( Map<String, Object> context, Object target, Object property )
{
return null;
}
}
| 4,673 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/package-info.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
* 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
* 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
* 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
* pronunciation of "orthogonal" or like "ogg-null".
*/
| 4,674 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/ASTRemainder.java | package org.apache.commons.ognl;
/*
* 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.
*/
/**
*/
class ASTRemainder
extends NumericExpression
{
public ASTRemainder( int id )
{
super( id );
}
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 );
}
public String getExpressionOperator( int index )
{
return "%";
}
public <R, P> R accept( NodeVisitor<? extends R, ? super P> visitor, P data )
throws OgnlException
{
return visitor.visit( this, data );
}
}
| 4,675 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/DefaultTypeConverter.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.lang.reflect.Member;
import java.util.Map;
/**
* Default type conversion. Converts among numeric types and also strings.
*/
public class DefaultTypeConverter
implements TypeConverter
{
public <T> T convertValue( Map<String, Object> context, Object value, Class<T> toType )
{
@SuppressWarnings( "unchecked" ) // type checking performed in OgnlOps.convertValue( value, toType )
T ret = (T) OgnlOps.convertValue( value, toType );
return ret;
}
/**
* {@inheritDoc}
*/
public <T> T convertValue( Map<String, Object> context, Object target, Member member, String propertyName,
Object value, Class<T> toType )
{
return convertValue( context, value, toType );
}
}
| 4,676 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/OgnlException.java | package org.apache.commons.ognl;
/*
* 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.
*/
import java.lang.reflect.Method;
/**
* Superclass for OGNL exceptions, incorporating an optional encapsulated exception.
*/
public class OgnlException
extends Exception
{
// cache initCause method - if available..to be used during throwable constructor
// to properly setup superclass.
private static final long serialVersionUID = -842845048743721078L;
static Method initCause;
static
{
try
{
initCause = OgnlException.class.getMethod( "initCause", Throwable.class );
}
catch ( NoSuchMethodException e )
{
/** ignore */
}
}
/**
* The root evaluation of the expression when the exception was thrown
*/
private Evaluation evaluation;
/**
* Why this exception was thrown.
*
* @serial
*/
private final Throwable reason;
/** 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 );
}
/**
* Constructs an OgnlException with the given message and encapsulated exception.
*
* @param msg the exception's detail message
* @param reason the encapsulated exception
*/
public OgnlException( String msg, Throwable reason )
{
super( msg );
this.reason = reason;
if ( initCause != null )
{
try
{
initCause.invoke( this, reason );
}
catch ( Exception ignored )
{
/** ignore */
}
}
}
/**
* Returns the encapsulated exception, or null if there is none.
*
* @return the encapsulated exception
*/
public Throwable getReason()
{
return reason;
}
/**
* Returns the Evaluation that was the root evaluation when the exception was thrown.
*
* @return The {@link Evaluation}.
*/
public Evaluation getEvaluation()
{
return evaluation;
}
/**
* Sets the Evaluation that was current when this exception was thrown.
*
* @param value The {@link Evaluation}.
*/
public void setEvaluation( Evaluation value )
{
evaluation = value;
}
/**
* Returns a string representation of this exception.
*
* @return a string representation of this exception
*/
@Override
public String toString()
{
if ( reason == null )
{
return super.toString();
}
return super.toString() + " [" + reason + "]";
}
/**
* Prints the stack trace for this (and possibly the encapsulated) exception on System.err.
*/
@Override
public void printStackTrace()
{
printStackTrace( System.err );
}
/**
* Prints the stack trace for this (and possibly the encapsulated) exception on the given print stream.
*/
@Override
public void printStackTrace( java.io.PrintStream s )
{
synchronized ( s )
{
super.printStackTrace( s );
if ( reason != null )
{
s.println( "/-- Encapsulated exception ------------\\" );
reason.printStackTrace( s );
s.println( "\\--------------------------------------/" );
}
}
}
/**
* Prints the stack trace for this (and possibly the encapsulated) exception on the given print writer.
*/
@Override
public void printStackTrace( java.io.PrintWriter s )
{
synchronized ( s )
{
super.printStackTrace( s );
if ( reason != null )
{
s.println( "/-- Encapsulated exception ------------\\" );
reason.printStackTrace( s );
s.println( "\\--------------------------------------/" );
}
}
}
}
| 4,677 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/OgnlCache.java | package org.apache.commons.ognl;
/*
* 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.
*/
import org.apache.commons.ognl.internal.*;
import org.apache.commons.ognl.internal.entry.*;
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<MethodAccessor> 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<PropertyAccessor> 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<ElementsAccessor> 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<NullHandler> 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<Map<String, PropertyDescriptor>> propertyDescriptorCache =
cacheFactory.createClassCache( new PropertyDescriptorCacheEntryFactory() );
private final ClassCache<List<Constructor<?>>> constructorCache =
cacheFactory.createClassCache(key -> Arrays.<Constructor<?>>asList( key.getConstructors() ));
private final Cache<DeclaredMethodCacheEntry, Map<String, List<Method>>> _methodCache =
cacheFactory.createCache( new DeclaredMethodCacheEntryFactory() );
private final Cache<PermissionCacheEntry, Permission> _invokePermissionCache =
cacheFactory.createCache( new PermissionCacheEntryFactory() );
private final ClassCache<Map<String, Field>> _fieldCache =
cacheFactory.createClassCache( new FieldCacheEntryFactory() );
private final Cache<Method, Class<?>[]> _methodParameterTypesCache =
cacheFactory.createCache(Method::getParameterTypes);
private final Cache<GenericMethodParameterTypeCacheEntry, Class<?>[]> _genericMethodParameterTypesCache =
cacheFactory.createCache( new GenericMethodParameterTypeFactory() );
private final Cache<Constructor<?>, Class<?>[]> _ctorParameterTypesCache =
cacheFactory.createCache(Constructor::getParameterTypes);
private final Cache<Method, MethodAccessEntryValue> _methodAccessCache =
cacheFactory.createCache( new MethodAccessCacheEntryFactory( ) );
private final MethodPermCacheEntryFactory methodPermCacheEntryFactory =
new MethodPermCacheEntryFactory( System.getSecurityManager() );
private final Cache<Method, Boolean> _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<Constructor<?>> getConstructor( Class<?> clazz ) throws CacheException {
return constructorCache.get( clazz );
}
public Map<String, Field> getField( Class<?> clazz ) throws CacheException {
return _fieldCache.get( clazz );
}
public Map<String, List<Method>> getMethod( DeclaredMethodCacheEntry declaredMethodCacheEntry ) throws CacheException {
return _methodCache.get( declaredMethodCacheEntry );
}
public Map<String, PropertyDescriptor> 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();
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 );
}
}
| 4,678 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/NodeVisitor.java | package org.apache.commons.ognl;
/*
* 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.
*/
/*
*/
public interface NodeVisitor<R, P>
{
R visit( ASTSequence node, P data )
throws OgnlException;
R visit( ASTAssign node, P data )
throws OgnlException;
R visit( ASTTest node, P data )
throws OgnlException;
R visit( ASTOr node, P data )
throws OgnlException;
R visit( ASTAnd node, P data )
throws OgnlException;
R visit( ASTBitOr node, P data )
throws OgnlException;
R visit( ASTXor node, P data )
throws OgnlException;
R visit( ASTBitAnd node, P data )
throws OgnlException;
R visit( ASTEq node, P data )
throws OgnlException;
R visit( ASTNotEq node, P data )
throws OgnlException;
R visit( ASTLess node, P data )
throws OgnlException;
R visit( ASTGreater node, P data )
throws OgnlException;
R visit( ASTLessEq node, P data )
throws OgnlException;
R visit( ASTGreaterEq node, P data )
throws OgnlException;
R visit( ASTIn node, P data )
throws OgnlException;
R visit( ASTNotIn node, P data )
throws OgnlException;
R visit( ASTShiftLeft node, P data )
throws OgnlException;
R visit( ASTShiftRight node, P data )
throws OgnlException;
R visit( ASTUnsignedShiftRight node, P data )
throws OgnlException;
R visit( ASTAdd node, P data )
throws OgnlException;
R visit( ASTSubtract node, P data )
throws OgnlException;
R visit( ASTMultiply node, P data )
throws OgnlException;
R visit( ASTDivide node, P data )
throws OgnlException;
R visit( ASTRemainder node, P data )
throws OgnlException;
R visit( ASTNegate node, P data )
throws OgnlException;
R visit( ASTBitNegate node, P data )
throws OgnlException;
R visit( ASTNot node, P data )
throws OgnlException;
R visit( ASTInstanceof node, P data )
throws OgnlException;
R visit( ASTChain node, P data )
throws OgnlException;
R visit( ASTEval node, P data )
throws OgnlException;
R visit( ASTConst node, P data )
throws OgnlException;
R visit( ASTThisVarRef node, P data )
throws OgnlException;
R visit( ASTRootVarRef node, P data )
throws OgnlException;
R visit( ASTVarRef node, P data )
throws OgnlException;
R visit( ASTList node, P data )
throws OgnlException;
R visit( ASTMap node, P data )
throws OgnlException;
R visit( ASTKeyValue node, P data )
throws OgnlException;
R visit( ASTStaticField node, P data )
throws OgnlException;
R visit( ASTCtor node, P data )
throws OgnlException;
R visit( ASTProperty node, P data )
throws OgnlException;
R visit( ASTStaticMethod node, P data )
throws OgnlException;
R visit( ASTMethod node, P data )
throws OgnlException;
R visit( ASTProject node, P data )
throws OgnlException;
R visit( ASTSelect node, P data )
throws OgnlException;
R visit( ASTSelectFirst node, P data )
throws OgnlException;
R visit( ASTSelectLast node, P data )
throws OgnlException;
}
| 4,679 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/HashMapCache.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
import java.util.HashMap;
import java.util.Map;
public class HashMapCache<K, V>
implements Cache<K, V>
{
private final Map<K, V> cache = new HashMap<K, V>( 512 );
private final CacheEntryFactory<K, V> cacheEntryFactory;
public HashMapCache( CacheEntryFactory<K, V> 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<K, V> 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 );
}
}
| 4,680 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/HashMapCacheFactory.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
import org.apache.commons.ognl.internal.entry.ClassCacheEntryFactory;
public class HashMapCacheFactory
implements CacheFactory
{
public <K, V> Cache<K, V> createCache( CacheEntryFactory<K, V> entryFactory )
{
return new HashMapCache<K, V>( entryFactory );
}
public <V> ClassCache<V> createClassCache()
{
return createClassCache( null );
}
public <V> ClassCache<V> createClassCache( ClassCacheEntryFactory<V> entryFactory )
{
return new HashMapClassCache<V>( entryFactory );
}
}
| 4,681 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/ConcurrentHashMapCacheFactory.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
import org.apache.commons.ognl.internal.entry.ClassCacheEntryFactory;
public class ConcurrentHashMapCacheFactory
implements CacheFactory
{
public <K, V> Cache<K, V> createCache( CacheEntryFactory<K, V> entryFactory )
{
return new ConcurrentHashMapCache<K, V>( entryFactory );
}
public <V> ClassCache<V> createClassCache()
{
return createClassCache( null );
}
public <V> ClassCache<V> createClassCache( ClassCacheEntryFactory<V> entryFactory )
{
return new ConcurrentHashMapClassCache<V>( entryFactory );
}
}
| 4,682 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/ClassCache.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.ClassCacheInspector;
/**
* This is a highly specialized map for storing values keyed by Class objects.
*/
public interface ClassCache<V>
extends Cache<Class<?>, V>
{
void setClassInspector( ClassCacheInspector inspector );
}
| 4,683 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/Cache.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/**
*/
public interface Cache<K, V>
{
void clear();
int getSize();
V get( K key )
throws CacheException;
V put( K key, V value );
}
| 4,684 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/ClassCacheImpl.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.ClassCacheInspector;
import java.util.Arrays;
/**
* Implementation of {@link ClassCache}.
*/
public class ClassCacheImpl<V>
implements ClassCache<V>
{
/* 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 final Entry<Class<?>, V>[] table = new Entry[TABLE_SIZE];
private ClassCacheInspector classInspector;
private int size;
/**
* {@inheritDoc}
*/
public void setClassInspector( ClassCacheInspector inspector )
{
classInspector = inspector;
}
/**
* {@inheritDoc}
*/
public void clear()
{
Arrays.fill(table, null);
size = 0;
}
/**
* {@inheritDoc}
*/
public int getSize()
{
return size;
}
/**
* {@inheritDoc}
*/
public final V get( Class<?> key )
throws CacheException
{
int i = key.hashCode() & TABLE_SIZE_MASK;
Entry<Class<?>, V> entry = table[i];
while ( entry != null )
{
if ( key == entry.getKey() )
{
return entry.getValue();
}
entry = entry.getNext();
}
return null;
}
/**
* {@inheritDoc}
*/
public final V put( Class<?> key, V value )
{
if ( classInspector != null && !classInspector.shouldCache( key ) )
{
return value;
}
V result = null;
int i = key.hashCode() & TABLE_SIZE_MASK;
Entry<Class<?>, V> entry = table[i];
if ( entry == null )
{
table[i] = new Entry<Class<?>, V>( key, value );
size++;
}
else
{
if ( key == entry.getKey() )
{
result = entry.getValue();
entry.setValue( value );
}
else
{
while ( true )
{
if ( key == entry.getKey() )
{
/* replace value */
result = entry.getValue();
entry.setValue( value );
break;
}
if ( entry.getNext() == null )
{
/* add value */
entry.setNext( new Entry<Class<?>, V>( key, value ) );
break;
}
entry = entry.getNext();
}
}
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return "ClassCacheImpl[" + "_table=" + ( table == null ? null : Arrays.asList( table ) ) + '\n'
+ ", _classInspector=" + classInspector + '\n' + ", _size=" + size + '\n' + ']';
}
}
| 4,685 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/ReentrantReadWriteLockCacheFactory.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
import org.apache.commons.ognl.internal.entry.ClassCacheEntryFactory;
public class ReentrantReadWriteLockCacheFactory
implements CacheFactory
{
public <K, V> Cache<K, V> createCache( CacheEntryFactory<K, V> entryFactory )
{
return new ReentrantReadWriteLockCache<K, V>( entryFactory );
}
public <V> ClassCache<V> createClassCache()
{
return createClassCache( null );
}
public <V> ClassCache<V> createClassCache( ClassCacheEntryFactory<V> entryFactory )
{
return new ReentrantReadWriteLockClassCache<V>( entryFactory );
}
}
| 4,686 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/CacheException.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
public class CacheException
extends RuntimeException
{
public CacheException( Throwable e )
{
super( e.getMessage(), e );
}
}
| 4,687 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/ReentrantReadWriteLockClassCache.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.ClassCacheInspector;
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
public class ReentrantReadWriteLockClassCache<T>
extends HashMapCache<Class<?>, T>
implements ClassCache<T>
{
private ClassCacheInspector inspector;
public ReentrantReadWriteLockClassCache( CacheEntryFactory<Class<?>, 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 );
}
}
| 4,688 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/ClassCacheHandler.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
public class ClassCacheHandler
{
private ClassCacheHandler()
{
}
public static <T> T getHandler( Class<?> forClass, ClassCache<T> 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;
}
}
| 4,689 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/ConcurrentHashMapClassCache.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
import org.apache.commons.ognl.ClassCacheInspector;
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
/*
*/
public class ConcurrentHashMapClassCache<T>
extends ConcurrentHashMapCache<Class<?>, T>
implements ClassCache<T>
{
private ClassCacheInspector inspector;
public ConcurrentHashMapClassCache( CacheEntryFactory<Class<?>, T> entryFactory )
{
super( entryFactory );
}
public void setClassInspector( ClassCacheInspector inspector )
{
this.inspector = inspector;
}
@Override
public T put( Class<?> key, T value )
{
if ( inspector != null && !inspector.shouldCache( key ) )
{
return value;
}
return super.put( key, value );
}
}
| 4,690 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/ReentrantReadWriteLockCache.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReentrantReadWriteLockCache<K, V>
implements Cache<K, V>
{
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock readLock = lock.readLock();
private final Lock writeLock = lock.writeLock();
final Map<K, V> cache = new HashMap<K, V>();
private CacheEntryFactory<K, V> cacheEntryFactory;
public ReentrantReadWriteLockCache()
{
}
public ReentrantReadWriteLockCache( CacheEntryFactory<K, V> 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;
boolean shouldCreate;
readLock.lock();
try
{
v = cache.get( key );
shouldCreate = shouldCreate( cacheEntryFactory, v );
}
finally
{
readLock.unlock();
}
if ( shouldCreate )
{
try
{
writeLock.lock();
v = cache.get( key );
if ( !shouldCreate( cacheEntryFactory, v ) )
{
return v;
}
v = cacheEntryFactory.create( key );
cache.put( key, v );
return v;
}
finally
{
writeLock.unlock();
}
}
return v;
}
protected boolean shouldCreate( CacheEntryFactory<K, V> cacheEntryFactory, V v )
throws CacheException
{
return cacheEntryFactory != null && v == null;
}
public V put( K key, V value )
{
writeLock.lock();
try
{
cache.put( key, value );
return value;
}
finally
{
writeLock.unlock();
}
}
} | 4,691 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/ConcurrentHashMapCache.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapCache<K, V>
implements Cache<K, V>
{
private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<K, V>();
private CacheEntryFactory<K, V> cacheEntryFactory;
public ConcurrentHashMapCache()
{
}
public ConcurrentHashMapCache( CacheEntryFactory<K, V> cacheEntryFactory )
{
this.cacheEntryFactory = cacheEntryFactory;
}
public void clear()
{
cache.clear();
}
public int getSize()
{
return cache.size();
}
public V get( K key )
throws CacheException
{
V v = cache.get( key );
if ( shouldCreate( cacheEntryFactory, v ) )
{
return put( key, cacheEntryFactory.create( key ) );
}
return v;
}
protected boolean shouldCreate( CacheEntryFactory<K, V> cacheEntryFactory, V v )
throws CacheException
{
return cacheEntryFactory != null && v == null;
}
public V put( K key, V value )
{
V collision = cache.putIfAbsent( key, value );
if ( collision != null )
{
return collision;
}
return value;
}
public boolean contains( K key )
{
return this.cache.contains( key );
}
}
| 4,692 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/HashMapClassCache.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/*
*
*/
import org.apache.commons.ognl.ClassCacheInspector;
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
public class HashMapClassCache<T>
extends HashMapCache<Class<?>,T>
implements ClassCache<T>
{
private ClassCacheInspector inspector;
public HashMapClassCache( CacheEntryFactory<Class<?>, 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 );
}
}
| 4,693 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/Entry.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/**
* Used by {@link ClassCacheImpl} to store entries in the cache.
* <p/>
*/
class Entry<K, V>
{
private Entry<K, V> next;
private final K key;
private V value;
public Entry( K key, V value )
{
this.key = key;
this.value = value;
}
public K getKey()
{
return key;
}
public V getValue()
{
return value;
}
public void setValue( V value )
{
this.value = value;
}
public Entry<K, V> getNext()
{
return next;
}
public void setNext( Entry<K, V> next )
{
this.next = next;
}
@Override
public String toString()
{
return "Entry[" + "next=" + next + '\n' + ", key=" + key + '\n' + ", value=" + value + '\n' + ']';
}
}
| 4,694 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/CacheFactory.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
import org.apache.commons.ognl.internal.entry.CacheEntryFactory;
import org.apache.commons.ognl.internal.entry.ClassCacheEntryFactory;
/**
* User: Maurizio Cucchiara
* Date: 10/22/11
* Time: 1:35 AM
*/
public interface CacheFactory
{
<K, V> Cache<K, V> createCache( CacheEntryFactory<K, V> entryFactory );
<V> ClassCache<V> createClassCache();
<V> ClassCache<V> createClassCache( ClassCacheEntryFactory<V> entryFactory );
}
| 4,695 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/package-info.java | package org.apache.commons.ognl.internal;
/*
* 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.
*/
/**
* Internal stuff only, users don't need to take this package in consideration.
*/
| 4,696 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/entry/PropertyDescriptorCacheEntryFactory.java | package org.apache.commons.ognl.internal.entry;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.ObjectIndexedPropertyDescriptor;
import org.apache.commons.ognl.OgnlException;
import org.apache.commons.ognl.OgnlRuntime;
import org.apache.commons.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<Map<String, PropertyDescriptor>>
{
public Map<String, PropertyDescriptor> create( Class<?> targetClass )
throws CacheException
{
Map<String, PropertyDescriptor> result = new HashMap<String, PropertyDescriptor>( 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 m, String propertyName, Class<?> propertyType,
boolean isReadMethod )
throws OgnlException
{
List<Method> methods = OgnlRuntime.getDeclaredMethods( targetClass, propertyName, !isReadMethod );
for ( Method method : methods )
{
if ( method.getName().equals( m.getName() ) && m.getReturnType().isAssignableFrom( m.getReturnType() )
&& method.getReturnType() == propertyType
&& method.getParameterTypes().length == m.getParameterTypes().length )
{
return method;
}
}
return m;
}
private static void findObjectIndexedPropertyDescriptors( Class<?> targetClass,
Map<String, PropertyDescriptor> intoMap )
throws OgnlException
{
Map<String, List<Method>> allMethods = OgnlRuntime.getMethods( targetClass, false );
Map<String, List<Method>> pairs = new HashMap<String, List<Method>>( 101 );
for ( Map.Entry<String, List<Method>> entry : allMethods.entrySet() )
{
String methodName = entry.getKey();
List<Method> 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<Method> pair = pairs.computeIfAbsent(propertyName, k -> new ArrayList<Method>());
pair.add( method );
}
if ( isSet && ( parameterCount == 2 ) && ( method.getReturnType() == Void.TYPE ) )
{
List<Method> pair = pairs.computeIfAbsent(propertyName, k -> new ArrayList<Method>());
pair.add( method );
}
}
}
}
for ( Map.Entry<String, List<Method>> entry : pairs.entrySet() )
{
String propertyName = entry.getKey();
List<Method> 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<Method> 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 );
int mpc = parameterTypes.length;
if ( numParameterTypes != mpc )
{
result = false;
}
for ( int j = 0; j < numParameterTypes; j++ )
{
if ( parameterTypes[j] != mpt[j] )
{
result = false;
break;
}
}
}
lastMethodClass = clazz;
}
}
return result;
}
}
| 4,697 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/entry/ClassCacheEntryFactory.java | package org.apache.commons.ognl.internal.entry;
/*
* 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.
*/
/*
*/
public interface ClassCacheEntryFactory<T>
extends CacheEntryFactory<Class<?>, T>
{
}
| 4,698 |
0 | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal | Create_ds/commons-ognl/src/main/java/org/apache/commons/ognl/internal/entry/MethodCacheEntryFactory.java | package org.apache.commons.ognl.internal.entry;
/*
* 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.
*/
/*
*/
import org.apache.commons.ognl.OgnlRuntime;
import org.apache.commons.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<T extends MethodCacheEntry>
implements CacheEntryFactory<T, Map<String, List<Method>>>
{
public Map<String, List<Method>> create( T key )
throws CacheException
{
Map<String, List<Method>> result = new HashMap<String, List<Method>>( 23 );
Class<?> c = key.targetClass;
while ( c != null )
{
for ( Method method : c.getDeclaredMethods() )
{
// skip over synthetic methods
if ( !OgnlRuntime.isMethodCallable( method ) )
{
continue;
}
if ( shouldCache( key, method ) )
{
List<Method> ml = result.computeIfAbsent(method.getName(), k -> new ArrayList<Method>());
ml.add( method );
}
}
c = c.getSuperclass();
}
return result;
}
protected abstract boolean shouldCache( T key, Method method );
}
| 4,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.