package com.sina.util;
import java.util.Collection;
import java.util.Map;
public abstract class Assert
{
public Assert()
{
}
public static void isTrue(boolean expression, String message)
{
if(!expression)
throw new IllegalArgumentException(message);
else
return;
}
public static void isTrue(boolean expression)
{
isTrue(expression, "[Assertion failed] - this expression must be true");
}
public static void isNull(Object object, String message)
{
if(object != null)
throw new IllegalArgumentException(message);
else
return;
}
public static void isNull(Object object)
{
isNull(object, "[Assertion failed] - the object argument must be null");
}
public static void notNull(Object object, String message)
{
if(object == null)
{
if(message == null)
message = (new StringBuilder()).append("[Assertion failed] - this argument is required; it cannot be null. <").append(inferCaller()).append(">").toString();
throw new IllegalArgumentException(message);
} else
{
return;
}
}
public static void notNull(Object object)
{
notNull(object, null);
}
private static String inferCaller()
{
StackTraceElement stack[] = (new Throwable()).getStackTrace();
for(int i = 0; i < stack.length; i++)
{
StackTraceElement frame = stack[i];
String cname = frame.getClassName();
if(!cname.equals(Assert.getName()))
return (new StringBuilder()).append(cname).append(".").append(frame.getMethodName()).toString();
}
return "";
}
public static void isInstanceOf(Class clazz, Object obj)
{
isInstanceOf(clazz, obj, "");
}
public static void isInstanceOf(Class clazz, Object obj, String message)
{
notNull(clazz, "The clazz to perform the instanceof assertion cannot be null");
isTrue(clazz.isInstance(obj), (new StringBuilder()).append(message).append("Object of class '").append(obj == null ? "[null]" : obj.getClass().getName()).append("' must be an instance of '").append(clazz.getName()).append("'").toString());
}
public static void notNullOrEmpty(Object object)
{
notNullOrEmpty(object, null);
}
public static void notNullOrEmpty(Object object, String message)
{
notNull(object, null);
if((object instanceof String) && ((String)object).trim().equals(""))
{
if(message == null)
message = (new StringBuilder()).append("[Assertion failed] - this String argument is required; it cannot be empty. <").append(inferCaller()).append(">").toString();
throw new IllegalArgumentException(message);
}
if((object instanceof Collection) && ((Collection)object).isEmpty())
{
if(message == null)
message = (new StringBuilder()).append("[Assertion failed] - this Collection argument is required; it cannot be empty. <").append(inferCaller()).append(">").toString();
throw new IllegalArgumentException(message);
}
if((object instanceof Map) && ((Map)object).isEmpty())
{
if(message == null)
message = (new StringBuilder()).append("[Assertion failed] - this Map argument is required; it cannot be empty. <").append(inferCaller()).append(">").toString();
throw new IllegalArgumentException(message);
} else
{
return;
}
}
}