package hirondelle.fish.test.doubles;
import java.sql.SQLException;
import hirondelle.web4j.database.DAOException;
import hirondelle.web4j.database.DuplicateException;
import hirondelle.web4j.util.Util;
public final class FakeDAOBehavior {
public static final String USE_FAKE_DAOS = "useFakeDAOs";
public static enum DbOperation {
Add("FakeDAOAdd"),
Change("FakeDAOChange"),
Delete("FakeDAODelete"),
FetchForChange("FakeDAOFetchForChange"),
List("FakeDAOList");
public String toString(){
return fName;
}
private DbOperation(String aName){
fName = aName;
}
private String fName;
}
public static enum DbOperationResult {Succeed, ThrowDAOException, ThrowDuplicateException}
public static void possiblyThrowExceptionFor(DbOperation aOperation) throws DAOException, DuplicateException {
DbOperationResult opResult = getOperationResult(aOperation);
if (FakeDAOBehavior.DbOperationResult.Succeed == opResult) return;
if (FakeDAOBehavior.DbOperationResult.ThrowDAOException == opResult) throw new DAOException(FORCED_FAILURE, FORCED_EXCEPTION);
if (FakeDAOBehavior.DbOperationResult.ThrowDuplicateException == opResult) throw new DuplicateException(FORCED_FAILURE, FORCED_EXCEPTION);
}
public static void setBehavior(DbOperation aDbOperation, DbOperationResult aDbOperationResult){
System.setProperty(aDbOperation.toString(), aDbOperationResult.toString() );
}
private static final String FORCED_FAILURE = "Forced failure in fake DAO.";
private static final Throwable FORCED_EXCEPTION = new SQLException(FORCED_FAILURE);
private static DbOperationResult getOperationResult(DbOperation aOperation){
DbOperationResult result = DbOperationResult.Succeed; String property = System.getProperty(aOperation.toString());
if ( Util.textHasContent(property)) {
result = DbOperationResult.valueOf(property);
}
return result;
}
}