package net.raymanoz.config;
import net.raymanoz.migrate.SchemaVersionRepository;
import net.raymanoz.migrate.SchemaVersionRepositoryImpl;
public class ConditionHandlerScriptApplied implements ConditionHandler {
SchemaVersionRepository repos;
public ConditionHandlerScriptApplied(Configuration config){
repos = new SchemaVersionRepositoryImpl(config);
}
public ConditionHandlerScriptApplied(SchemaVersionRepository repos){
this.repos = repos;
}
private int dbVersion;
private int patchNo;
private int strToIntDef(String valStr, int defValue){
int result = defValue;
try {
result = Integer.parseInt(valStr);
}
catch (NumberFormatException e){
result = -1;
}
return result;
}
private String errorMsg(int value, String valstr, String name){
String result = "";
if (value < 0){
result = String.format("Cannot convert '%s' to positive integer for %s", valstr, name);
}
return result;
}
public boolean checkParams(Condition condtion){
if (condtion == null) return false;
int noParams = condtion.paramters().size();
if (noParams != 2){
condtion.setErrored(String.format("Expecting 2 parameters (dbVersion, patchNo) - found %d", noParams));
return false;
}
dbVersion = strToIntDef(condtion.paramters().get(0), -1);
patchNo = strToIntDef(condtion.paramters().get(1), -1);
if (dbVersion < 0 || patchNo < 0) {
String errorMsg = errorMsg(dbVersion, condtion.paramters().get(0), "DB Version");
if (patchNo < 0 && errorMsg != null && errorMsg.length() > 0){
errorMsg += " and ";
}
errorMsg += errorMsg(patchNo, condtion.paramters().get(1), "Patch No");
condtion.setErrored(errorMsg);
return false;
}
return true;
}
public boolean checkCondition(Condition condtion) {
if (checkParams(condtion)) {
boolean result = repos.hasScriptBeenApplied(dbVersion, patchNo);
condtion.setResult(result);
return true;
}
else {
return false;
}
}
public String name() {
return "patchapplied";
}
public String expectedParams() {
return "db version, patch no";
}
public String description() {
return "Checks for Patch recorded complete in script history";
}
}