com.mockrunner.jdbc.ParameterUtil Maven / Gradle / Ivy
package com.mockrunner.jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.util.Arrays;
import com.mockrunner.mock.jdbc.MockResultSet;
import com.mockrunner.util.common.ArrayUtil;
import com.mockrunner.util.common.MethodUtil;
import com.mockrunner.util.common.StreamUtil;
/**
* Util class for PreparedStatement
and ResultSet
* parameters.
*/
public class ParameterUtil
{
/**
* Copies a parameter of a PreparedStatement
,
* CallableStatement
or a ResultSet
value.
* InputStream
objects, Reader
objects
* and arrays are copied into new allocated streams or arrays.
* All other objects are cloned by calling the clone method.
* If the object is not cloneable, it is returned unchanged.
* @param source the parameter to copy
* @return a copy of the parameter
*/
public static Object copyParameter(Object source)
{
if(null == source) return null;
if(source.getClass().isArray())
{
return ArrayUtil.copyArray(source);
}
if(source instanceof InputStream)
{
return StreamUtil.copyStream((InputStream)source);
}
if(source instanceof Reader)
{
return StreamUtil.copyReader((Reader)source);
}
if(source instanceof Cloneable)
{
try
{
return MethodUtil.invoke(source, "clone");
}
catch(Exception exc)
{
return source;
}
}
return source;
}
/**
* Compares two parameters of a PreparedStatement
or
* CallableStatement
. Can also be used to compare
* values of a ResultSet
. It is used by
* {@link com.mockrunner.jdbc.PreparedStatementResultSetHandler}
* for comparing parameters specified in the prepare
* methods.
* Since the parameters can be of the type byte[]
,
* InputStream
and Reader
this method handles
* these types of objects. All other objects are compared using the
* equals
method. The mock versions of Ref
,
* Array
, Blob
, Clob
,
* Struct
etc. all provide a suitable equals
* implementation.
* @param source the first parameter
* @param target the second parameter
* @return true
if source is equal to target,
* false
otherwise
*/
public static boolean compareParameter(Object source, Object target)
{
if(null == source && null == target) return true;
if(null == source || null == target) return false;
if(source instanceof byte[] && target instanceof byte[])
{
return Arrays.equals((byte[])source, (byte[])target);
}
if(source instanceof InputStream && target instanceof InputStream)
{
return StreamUtil.compareStreams((InputStream)source, (InputStream)target);
}
if(source instanceof Reader && target instanceof Reader)
{
return StreamUtil.compareReaders((Reader)source, (Reader)target);
}
if(source instanceof MockResultSet && target instanceof MockResultSet)
{
return ((MockResultSet)source).isEqual((MockResultSet)target);
}
return source.equals(target);
}
}