first commit

This commit is contained in:
MaddoScientisto 2026-03-14 20:04:39 +01:00
commit 4d332ef662
27586 changed files with 3281783 additions and 0 deletions

View file

@ -0,0 +1,17 @@
package com.ablia.db;
public interface AddImgInterface {
String getPathAttach();
String getImgFileName(int paramInt);
String getImgFileName(int paramInt, String paramString);
String getImgTmst();
void setImgTmst(String paramString);
ResParm save();
void findByPrimaryKey(long paramLong);
}

View file

@ -0,0 +1,957 @@
package com.ablia.db;
import com.ablia.common.Parm;
import com.ablia.common.TtFont;
import com.ablia.util.Debug;
import com.ablia.util.FileWr;
import com.ablia.util.SimpleDateFormat;
import com.ablia.util.StringTokenizer;
import com.ablia.util.Vectumerator;
import java.io.FileInputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
public class ApplParm extends Debug implements Serializable {
private static final long serialVersionUID = 1L;
private static HashMap<Locale, NumberFormat> hmNf0 = new HashMap<>();
private static HashMap<Locale, NumberFormat> hmNf1 = new HashMap<>();
private static HashMap<Locale, NumberFormat> hmNf2 = new HashMap<>();
private static HashMap<Locale, NumberFormat> hmNf3 = new HashMap<>();
private static HashMap<Locale, NumberFormat> hmNf4 = new HashMap<>();
private static HashMap<String, Locale> hmLocale = new HashMap<>();
public static final String DB_VALIDATION_QUERY = "SELECT 1";
private String apCode;
private boolean block = true;
public static final int CONNECTION_LIFE_TIME_DEFAULT_MIN = 0;
private int connectionLifeTime = 0;
private String database;
public static final String DB_PROPERTIES_FILE = "ablia";
public static final String PROP_DB_DRIVER = "dbDriver";
public static final String PROP_DB_DATABASE = "database";
public static final String PROP_DB_PASSWORD = "password";
public static final String PROP_DB_ATINAV_PASSWORD = "atinavPassword";
public static final String PROP_DB_INITIAL_CONS = "initialCons";
public static final String PROP_DB_REUSE_CONS = "reuseCons";
public static final String PROP_DB_TIMEOUT = "timeout";
public static final String PROP_DB_USER = "user";
public static final String PROP_DB_PROPERTY_FILE = "dbPropertyFile";
public static final String PROP_DB_PROPERTY_DEFAULT_FILE = "ablia";
public static final String PROP_DB_MAX_CONS = "maxCons";
public static final String PROP_DB_MAX_CONNECTION_HITS = "maxConnectionHits";
private Properties dbEnvironProperty;
private String dbAtinavpasswd;
private int dbType = 0;
private SimpleDateFormat tsf;
private SimpleDateFormat tsfForFile;
private int initialCons = 1;
private String langCode;
private int maxConnectionHits = 0;
private int maxCons = 10;
private String mdwpath;
private String password;
public static final String PASSWORD = "Password";
public static final String PROP_FALSE = "FALSE";
public static final String PROP_TRUE = "true";
private String propertyFileName;
private ResourceBundle propertyResource;
private boolean reuseCons = true;
private SimpleDateFormat tf;
private int timeout = 300;
private String user;
private SimpleDateFormat df;
private String apCodeParms;
private static Hashtable<String, Hashtable<String, Parm>> allWebAppParms;
private static Hashtable<String, ResourceBundle> dictionarys;
private static Hashtable<String, String> missedDictionaryKey = new Hashtable<>();
private static Hashtable<String, Hashtable<String, RewriteRule>> allRewriteRules;
public static final String PROP_DB_CONN_LIFE_TIME = "connectionLifeTime";
public static final String USER = "User";
private boolean isLogParm = false;
public ApplParm() {}
public ApplParm(int theDbType, String theDatabase) {
this.dbType = theDbType;
this.database = theDatabase;
}
public ApplParm(int theDbType, String theDatabase, String theUser, String thePassword) {
this.dbType = theDbType;
this.database = theDatabase;
this.user = theUser;
this.password = thePassword;
}
public ApplParm(int theDbType, String theDatabase, String theUser, String thePassword, int initial_Cons, int max_Cons, int time_Out) {
this.dbType = theDbType;
this.database = theDatabase;
this.user = theUser;
this.password = thePassword;
this.initialCons = initial_Cons;
this.maxCons = max_Cons;
this.timeout = time_Out;
}
public String getApCode() {
if (this.apCode == null || this.apCode.isEmpty())
this.apCode = String.valueOf(this.dbType) + this.database + this.user + this.password;
return this.apCode;
}
private String getApCodeParms() {
if (this.apCodeParms == null || this.apCodeParms.isEmpty()) {
String tempDB = this.database;
if (this.database.indexOf("_log") > 0)
tempDB = this.database.replace("_log", "");
this.apCodeParms = String.valueOf(this.dbType) + tempDB + this.user + this.password;
}
return this.apCodeParms;
}
public String getApCode(DBAdapter obj) {
StringBuilder sb = new StringBuilder(obj.getClass().getName());
sb.append(getApCode());
return sb.toString();
}
public static final void resetHashtable() {
if (dictionarys != null) {
dictionarys.clear();
dictionarys = null;
}
if (allWebAppParms != null) {
allWebAppParms.clear();
allWebAppParms = null;
}
if (allRewriteRules != null) {
allRewriteRules.clear();
allRewriteRules = null;
}
}
public String getApDescription() {
StringBuffer temp = new StringBuffer();
temp.append("PropFile: " + getPropertyFileName());
temp.append("\nSOURCE DB ");
temp.append("\ndriver: " + getDbType());
temp.append("\ndb name: " + getDatabase());
temp.append("\nuser: " + getUser());
temp.append("\npassword: " + getPassword());
temp.append("\nConnection String: " + getConnectionString());
temp.append("\ntimeout: " + getTimeout());
temp.append("\ninitial cons: " + getInitialCons());
temp.append("\nmax cons: " + getMaxCons());
temp.append("\nAP CODE: " + getApCode());
return temp.toString();
}
public int getConnectionLifeTime() {
return this.connectionLifeTime;
}
public String getConnectionString() {
return DriversJdbc.getConnectionString(getDbType());
}
public String getDatabase() {
if (this.database == null)
this.database = "test";
return this.database;
}
public SimpleDateFormat getDataFormat() {
if (this.df == null)
if (getResource("DATA_FORMAT").isEmpty()) {
this.df = new SimpleDateFormat("dd/MM/yyyy");
} else {
this.df = new SimpleDateFormat(getResource("DATA_FORMAT"));
}
return this.df;
}
public Properties getDbEnvironProperty() {
if (this.dbEnvironProperty == null)
if (getDbType() == 13 || getDbType() == 14) {
this.dbEnvironProperty = new Properties();
if (!getUser().isEmpty())
this.dbEnvironProperty.put("user", getUser());
if (!getPassword().isEmpty())
this.dbEnvironProperty.put("password", getPassword());
} else if (getDbType() == 11 && (!getDbAtinavpasswd().isEmpty() || !getMdwpath().isEmpty())) {
this.dbEnvironProperty = new Properties();
if (!getMdwpath().isEmpty())
this.dbEnvironProperty.put("mdwpath", getMdwpath());
if (!getUser().isEmpty())
this.dbEnvironProperty.put("user", getUser());
if (!getPassword().isEmpty())
this.dbEnvironProperty.put("password", getPassword());
if (!getDbAtinavpasswd().isEmpty())
this.dbEnvironProperty.put("dbpasswd", getDbAtinavpasswd());
} else if (getDbType() == 12) {
this.dbEnvironProperty = new Properties();
this.dbEnvironProperty.put("logonuser", getUser());
this.dbEnvironProperty.put("logonpassword", getPassword());
}
return this.dbEnvironProperty;
}
public String getDbAtinavpasswd() {
if (this.dbAtinavpasswd == null)
this.dbAtinavpasswd = "";
return this.dbAtinavpasswd;
}
public int getDbType() {
if (this.dbType == 0) {
Properties prop = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(getPropertyFileName());
prop.load(in);
this.dbType = Integer.valueOf(prop.getProperty("dbDriver"));
} catch (Exception e) {}
}
return this.dbType;
}
public boolean getDebug() {
if (getResource("DEBUG").equals("true"))
return true;
return false;
}
public String getDebugFile() {
if (getResource("LOG_FILE").isEmpty())
return super.getDebugFile();
return getResource("LOG_FILE");
}
public int getDebugLevel() {
return getParm("DEBUG_LEVEL").getNumeroInt();
}
public String getDefaultLangCode() {
if (!getResource("LOCALE").isEmpty())
return getResource("LOCALE").toLowerCase();
return Locale.ITALIAN.getLanguage();
}
public String getDriverManager() {
return DriversJdbc.getDriverManager(getDbType());
}
public int getInitialCons() {
return this.initialCons;
}
public String getLangCode() {
if (this.langCode == null || this.langCode.isEmpty())
this.langCode = getDefaultLangCode();
return this.langCode;
}
public Locale getLocale() {
if (!hmLocale.containsKey(getLangCode())) {
Locale locale = new Locale(getLangCode(), getLangCode());
System.out.println("applparm getlocale lang:" + getLangCode());
hmLocale.put(getLangCode(), locale);
}
return hmLocale.get(getLangCode());
}
public int getMaxConnectionHits() {
return this.maxConnectionHits;
}
public int getMaxCons() {
return this.maxCons;
}
public String getMdwpath() {
if (this.mdwpath == null)
this.mdwpath = "";
return this.mdwpath;
}
public NumberFormat getNf() {
return getNf2();
}
public String getPassword() {
if (this.password == null) {
Properties prop = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream("ablia");
prop.load(in);
this.password = prop.getProperty("password");
} catch (Exception e) {}
if (this.password == null)
this.password = "";
}
return this.password;
}
public String getPropertyFileName() {
return (this.propertyFileName == null) ? "ablia" : this.propertyFileName;
}
private ResourceBundle getPropertyResource() {
try {
if (this.propertyResource == null)
this.propertyResource = ResourceBundle.getBundle(getPropertyFileName());
} catch (Exception e) {
System.out.println("ERROR!! ApplParm.getPropertyResource() property file: " + getPropertyFileName() + "\n" + e.getMessage());
}
return this.propertyResource;
}
public String getResource(String key) {
try {
String temp = getParm(key).getTesto();
if (temp.isEmpty())
return getResourceFromPropertyFile(key);
return temp;
} catch (Exception e) {
if (key.equals("DEBUG") || key.equals("LOG_FILE")) {
System.out.println("SEVERE ERROR!! DEBUG or LOG_FILE not set. ApplParm: " + e.getMessage() + " . Property file:" +
getPropertyFileName());
} else {
handleDebug("ApplParm: " + e.getMessage() + " . Property file:" + getPropertyFileName(), 5);
}
return "";
}
}
public String getResourceFromPropertyFile(String key) {
try {
return getPropertyResource().getString(key);
} catch (Exception e) {
if (key.equals("DEBUG")) {
System.out.println("WARNING!!! ApplParm: " + e.getMessage() + " . Property file:" + getPropertyFileName());
} else {
handleDebug("ApplParm: " + e.getMessage() + " . Property file:" + getPropertyFileName(), 5);
}
return "";
}
}
public SimpleDateFormat getTimeFormat() {
if (this.tf == null)
if (getResource("TIME_FORMAT").isEmpty()) {
this.tf = new SimpleDateFormat("hh:mm");
} else {
this.tf = new SimpleDateFormat(getResource("TIME_FORMAT"));
}
return this.tf;
}
public int getTimeout() {
return this.timeout;
}
public String getUrl() {
return String.valueOf(getConnectionString()) + ":" + getDatabase();
}
public String getUser() {
if (this.user == null)
this.user = "";
return this.user;
}
public boolean isBlock() {
return this.block;
}
public boolean isReuseCons() {
return this.reuseCons;
}
public void setApCode(String newApCode) {
this.apCode = newApCode;
}
public void setBlock(boolean block) {
this.block = block;
}
public void setConnectionLifeTime(int l_connectionLifeTime) {
this.connectionLifeTime = l_connectionLifeTime;
}
public void setDatabase(String s) {
this.database = s;
setApCode(null);
}
public void setDbEnvironProperty(Properties newDbEnvironProperty) {
this.dbEnvironProperty = newDbEnvironProperty;
}
public void setDbAtinavpasswd(String dbpasswd) {
this.dbAtinavpasswd = dbpasswd;
}
public void setDbType(int newDbType) {
this.dbType = newDbType;
setApCode(null);
}
public void setDebugFile(String string) {
super.setDebugFile(string);
}
public void setInitialCons(int i) {
this.initialCons = i;
}
public void setLangCode(String newLangCode) {
if (!newLangCode.isEmpty() && this.langCode != newLangCode)
this.langCode = newLangCode;
}
public void setMaxConnectionHits(int maxConnectionHits) {
this.maxConnectionHits = maxConnectionHits;
}
public void setMaxCons(int i) {
this.maxCons = i;
}
public void setMdwpath(String mdwpath) {
this.mdwpath = mdwpath;
}
public void setPassword(String s) {
if (this.password == null)
this.password = "db2admin";
this.password = s;
setApCode(null);
}
public void setPropertyFileName(String newPropertyFileName) {
this.propertyFileName = newPropertyFileName;
}
public void setReuseCons(boolean reuseCons) {
this.reuseCons = reuseCons;
}
public void setTimeout(int i) {
this.timeout = i;
}
public void setUser(String s) {
this.user = s;
setApCode(null);
}
public RewriteRule getRewriteRule(String theCode) {
if (allRewriteRules == null)
allRewriteRules = new Hashtable<>();
synchronized (allRewriteRules) {
if (!allRewriteRules.containsKey(getApCode())) {
Hashtable<String, RewriteRule> theApRules = new Hashtable<>();
StringTokenizer rules = new StringTokenizer(getParm("REWRITE_URL_RULES").getTesto(), "\n");
while (rules.hasMoreTokens()) {
String currentRule = rules.nextToken();
if (!currentRule.startsWith("#")) {
if (currentRule.endsWith("\r"))
currentRule = currentRule.substring(0, currentRule.length() - 1);
StringTokenizer ruleValues = new StringTokenizer(currentRule, ",");
if (ruleValues.countToken() >= 2) {
RewriteRule aRule = new RewriteRule();
aRule.setCode(ruleValues.getToken(0));
if (ruleValues.getToken(1).startsWith("/")) {
aRule.setServlet(ruleValues.getToken(1));
} else {
aRule.setServlet("/" + ruleValues.getToken(1));
}
aRule.setCmd(ruleValues.getToken(2));
aRule.setAct(ruleValues.getToken(3));
if (ruleValues.getToken(4) != null) {
StringTokenizer ruleParms = new StringTokenizer(ruleValues.getToken(4), "@");
if (ruleParms.hasMoreTokens()) {
Vectumerator<String> vecParms = new Vectumerator<>();
Vectumerator<String> vecConstParms = new Vectumerator<>();
Vectumerator<String> vecConstValues = new Vectumerator<>();
ruleParms.nextToken();
while (ruleParms.hasMoreTokens()) {
String aParm = ruleParms.nextToken();
int idx;
if ((idx = aParm.indexOf('=')) > 0) {
String theParm = aParm.substring(0, idx);
String theValue = aParm.substring(idx + 1);
vecConstParms.add(theParm);
vecConstValues.add(theValue);
continue;
}
vecParms.add(aParm);
}
aRule.setParms(vecParms);
aRule.setConstParms(vecConstParms);
aRule.setConstValues(vecConstValues);
}
}
theApRules.put(aRule.getCode(), aRule);
}
}
}
allRewriteRules.put(getApCode(), theApRules);
}
}
Hashtable<String, RewriteRule> apRules = allRewriteRules.get(getApCode());
if (apRules.containsKey(theCode))
return apRules.get(theCode);
handleDebug("WARNING: AP: " + getDatabase() + " rewrite rule non presente: " + theCode, 3);
return null;
}
public void resetCurrentApParms() {
if (allWebAppParms != null && allWebAppParms.containsKey(getApCode()))
allWebAppParms.remove(getApCode());
if (allRewriteRules != null && allRewriteRules.containsKey(getApCode()))
allRewriteRules.remove(getApCode());
this.df = null;
this.tf = null;
dictionarys = null;
reloadAllResourceBundles();
TtFont.reset();
}
private static synchronized void appendNewLangKey(String theContentKey, String l_lang, String missedFileName) {
try {
if (!missedDictionaryKey.containsKey(String.valueOf(theContentKey) + "_" + l_lang)) {
missedFileName = String.valueOf(missedFileName) + "_missed";
try {
ResourceBundle rb = ResourceBundle.getBundle(missedFileName, new Locale(l_lang, l_lang));
rb.getString(theContentKey);
} catch (Exception e) {
FileWr fw = new FileWr(String.valueOf(missedFileName) + "_" + l_lang + ".properties", true);
fw.writeLine(String.valueOf(theContentKey) + "=");
fw.closeFile();
}
missedDictionaryKey.put(String.valueOf(theContentKey) + "_" + l_lang, theContentKey);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String getMissDictionaryPropertyPath() {
String temp = getResource("DICT_MISS_PROP_PTH");
return temp.isEmpty() ? "/" : temp;
}
private String getDictionaryPropertyFile() {
String temp = getResource("DICT_PROP_FILE");
return temp.isEmpty() ? "dict" : temp;
}
public String translate(String sentence, String l_lang) {
String sentenceKey = sentence;
l_lang = l_lang.toLowerCase();
if (l_lang.isEmpty() || l_lang.equals(getDefaultLangCode()))
return sentence;
try {
ResourceBundle rb;
sentenceKey = sentence.replace('\n', ' ');
sentenceKey = sentenceKey.replace('\r', ' ');
sentenceKey = sentenceKey.trim().replaceAll(" +", "_");
String translation = null;
if (!getDictionarys().containsKey(String.valueOf(l_lang) + getApCode())) {
rb = ResourceBundle.getBundle(getDictionaryPropertyFile(), new Locale(l_lang, l_lang));
dictionarys.put(String.valueOf(l_lang) + getApCode(), rb);
} else {
rb = dictionarys.get(String.valueOf(l_lang) + getApCode());
}
translation = rb.getString(sentenceKey);
if (translation == null || translation.isEmpty()) {
if (translation != null)
appendNewLangKey(sentenceKey, l_lang, String.valueOf(getMissDictionaryPropertyPath()) + getDictionaryPropertyFile());
return "." + sentence + ".";
}
return new String(translation.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
} catch (MissingResourceException mre) {
String temp = "Translate key for " + getDictionaryPropertyFile() + "_" + l_lang + " missed: " + sentenceKey;
appendNewLangKey(sentenceKey, l_lang, String.valueOf(getMissDictionaryPropertyPath()) + getDictionaryPropertyFile());
handleDebug(temp, 2);
return "." + sentence + ".";
} catch (Exception e) {
handleDebug(e, 2);
return "Translate failed";
}
}
public NumberFormat getNf0() {
if (!hmNf0.containsKey(getLocale())) {
getLocale();
NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);
nf.setMaximumFractionDigits(0);
nf.setMinimumFractionDigits(0);
hmNf0.put(getLocale(), nf);
}
return hmNf0.get(getLocale());
}
public NumberFormat getNf2() {
if (!hmNf2.containsKey(getLocale())) {
getLocale();
NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
hmNf2.put(getLocale(), nf);
}
return hmNf2.get(getLocale());
}
public NumberFormat getNf3() {
if (!hmNf3.containsKey(getLocale())) {
getLocale();
NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);
nf.setMaximumFractionDigits(3);
nf.setMinimumFractionDigits(3);
hmNf3.put(getLocale(), nf);
}
return hmNf3.get(getLocale());
}
public String getConnectionsCreateTs() {
ConnectionPool cp = ConnectionPool.getInstance(this);
Enumeration<CPConnection> enuF = cp.getFree().elements();
Enumeration<CPConnection> enuU = cp.getUsed().elements();
StringBuffer res = new StringBuffer();
int i = 0;
while (enuF.hasMoreElements()) {
i++;
CPConnection row = enuF.nextElement();
res.append("F");
res.append(" #");
res.append(i);
res.append(" ");
res.append(row.getLifeTime());
res.append("-->");
res.append(row.getHits());
res.append(" hits");
if (enuF.hasMoreElements())
res.append("<br>");
}
i = 0;
if (enuU.hasMoreElements()) {
res.append("<br><span style=\"color:#FF0000\">");
while (enuU.hasMoreElements()) {
i++;
CPConnection row = enuU.nextElement();
res.append("U");
res.append(" #");
res.append(i);
res.append(" ");
res.append(row.getLifeTime());
res.append(" (");
res.append(row.getCallTime());
res.append(")");
res.append("-->");
res.append(row.getHits());
res.append(" hits");
if (!row.getReqIpAddress().isEmpty()) {
res.append("<br><b>ip</b>: ");
res.append(row.getReqIpAddress());
}
if (!row.getReqUrl().isEmpty()) {
res.append("<br><b>Url</b>: ");
res.append(row.getReqUrl());
}
if (row.getLastUpdId_user() != 0L) {
res.append("<br><b>User id</b>: ");
res.append(row.getLastUpdId_user());
}
res.append("<br>");
res.append(DBAdapter.convertStringToHtml(row.getLastCallingStackTrace()));
if (enuU.hasMoreElements())
res.append("<br>");
}
res.append("</span>");
}
return res.toString();
}
public NumberFormat getNf4() {
if (!hmNf4.containsKey(getLocale())) {
getLocale();
NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);
nf.setMaximumFractionDigits(4);
nf.setMinimumFractionDigits(4);
hmNf4.put(getLocale(), nf);
}
return hmNf4.get(getLocale());
}
public NumberFormat getNf1() {
if (!hmNf1.containsKey(getLocale())) {
getLocale();
NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);
nf.setMaximumFractionDigits(1);
nf.setMinimumFractionDigits(1);
hmNf1.put(getLocale(), nf);
}
return hmNf1.get(getLocale());
}
public Parm getParmXXXXXX(String theKey) {
int logLevel = 2;
if (allWebAppParms == null)
allWebAppParms = new Hashtable<>();
if (!allWebAppParms.containsKey(getApCodeParms()))
synchronized (allWebAppParms) {
if (!allWebAppParms.containsKey(getApCodeParms())) {
Hashtable<String, Parm> theParms = new Hashtable<>();
Parm parm = new Parm(new ApplParmFull(this));
Vectumerator<? extends DBAdapter> vec = parm.findAll();
while (vec.hasMoreElements()) {
Parm row = (Parm)vec.nextElement();
theParms.put(row.getCodice(), row);
}
allWebAppParms.put(getApCodeParms(), theParms);
}
}
theKey = theKey.trim().toUpperCase();
Hashtable<String, Parm> parms = allWebAppParms.get(getApCodeParms());
if (parms.containsKey(theKey))
return parms.get(theKey);
Parm bean = new Parm();
if (theKey.equals("DEBUG")) {
bean.setCodice("DEBUG");
bean.setTesto("false");
bean.setNumero(1.0D);
} else if (theKey.equals("LOCALE")) {
bean.setCodice("LOCALE");
bean.setTesto("it");
} else if (theKey.equals("LOG_USERS_UPDATES")) {
bean.setCodice("LOG_USERS_UPDATES");
bean.setNumero(0.0D);
} else {
if (theKey.equals("FROM") || theKey.equals("TO_DEBUG") ||
theKey.equals("SMTP"))
logLevel = 2;
handleDebug("Parm.getParm(theKey): codice NON PRESENTE: " + theKey, logLevel);
}
System.out.println("WARNING: AP: " + getDatabase() + " codice non presente: " + theKey);
return bean;
}
public SimpleDateFormat getTimestampFormat() {
if (this.tsf == null)
this.tsf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
return this.tsf;
}
public SimpleDateFormat getTimestampFormatForFiles() {
if (this.tsfForFile == null)
this.tsfForFile = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SSS");
return this.tsfForFile;
}
public static final void resetHashtable(String apCode) {
if (dictionarys != null) {
dictionarys.clear();
dictionarys = null;
}
if (allWebAppParms != null && allWebAppParms.containsKey(apCode))
allWebAppParms.remove(apCode);
if (allRewriteRules != null && allRewriteRules.containsKey(apCode))
allRewriteRules.remove(apCode);
}
public static final void resetAll() {
resetHashtable();
reloadAllResourceBundles();
}
public static void reloadAllResourceBundles() {
try {
Field cacheList = ResourceBundle.class.getDeclaredField("cacheList");
cacheList.setAccessible(true);
((Map<?, ?>)cacheList.get(ResourceBundle.class)).clear();
} catch (Exception e) {
System.err.println("ApplPrm.reloadAllResourceBundles : " + e.getMessage());
}
}
private static Hashtable<String, ResourceBundle> getDictionarys() {
if (dictionarys == null)
dictionarys = new Hashtable<>();
return dictionarys;
}
public Parm getParmNoHt(String theKey) {
if (theKey.equals("DEBUG")) {
Parm bean = new Parm();
bean.setCodice("DEBUG");
bean.setTesto(getResourceFromPropertyFile(theKey));
if (bean.getTesto().equals("true"))
bean.setNumero(1.0D);
return bean;
}
if (theKey.equals("LOCALE")) {
Parm bean = new Parm();
bean.setCodice("LOCALE");
bean.setTesto(getResourceFromPropertyFile(theKey));
return bean;
}
Parm parm = new Parm(new ApplParmFull(this));
try {
parm.findByCodice(theKey);
return parm;
} catch (Exception e) {
handleDebug(e, 3);
return parm;
}
}
public Parm getParm(String theKey) {
if (allWebAppParms == null)
allWebAppParms = new Hashtable<>();
int logLevel = 2;
if (!allWebAppParms.containsKey(getApCodeParms())) {
if (theKey.equals("DEBUG")) {
Parm parm = new Parm();
parm.setCodice("DEBUG");
parm.setTesto("false");
parm.setNumero(0.0D);
return parm;
}
if (theKey.equals("LOCALE")) {
Parm parm = new Parm();
parm.setCodice("LOCALE");
parm.setTesto("it");
return parm;
}
if (theKey.equals("LOG_USERS_UPDATES")) {
Parm parm = new Parm();
parm.setCodice("LOG_USERS_UPDATES");
parm.setNumero(0.0D);
return parm;
}
}
if (!allWebAppParms.containsKey(getApCodeParms()))
synchronized (allWebAppParms) {
if (!allWebAppParms.containsKey(getApCodeParms())) {
Hashtable<String, Parm> theParms = new Hashtable<>();
Parm parm = new Parm(new ApplParmFull(this));
Vectumerator<? extends DBAdapter> vec = parm.findAll();
while (vec.hasMoreElements()) {
Parm row = (Parm)vec.nextElement();
theParms.put(row.getCodice(), row);
}
if (theParms.containsKey("LANG_AVAILABLE")) {
Parm pLangAvail = theParms.get("LANG_AVAILABLE");
StringTokenizer st = new StringTokenizer(pLangAvail.getTesto(), ",");
if (st.hasMoreTokens()) {
Parm p = new Parm(new ApplParmFull(this));
p.setCodice("LANG_PRIMARY");
p.setTesto(st.nextToken());
theParms.put(p.getCodice(), p);
}
if (st.hasMoreTokens()) {
Parm p = new Parm(new ApplParmFull(this));
p.setCodice("LANG_SECONARY");
p.setTesto(st.nextToken());
theParms.put(p.getCodice(), p);
}
}
allWebAppParms.put(getApCodeParms(), theParms);
}
}
theKey = theKey.trim().toUpperCase();
Hashtable<String, Parm> parms = allWebAppParms.get(getApCodeParms());
if (parms.containsKey(theKey))
return parms.get(theKey);
Parm bean = new Parm();
if (theKey.equals("DEBUG")) {
bean.setCodice("DEBUG");
bean.setTesto("false");
bean.setNumero(1.0D);
} else if (theKey.equals("LOCALE")) {
bean.setCodice("LOCALE");
bean.setTesto("it");
} else {
if (theKey.equals("FROM") || theKey.equals("TO_DEBUG") ||
theKey.equals("SMTP"))
logLevel = 2;
handleDebug("Parm.getParm(theKey): codice NON PRESENTE: " + theKey, logLevel);
}
System.out.println("WARNING: AP: " + getDatabase() + " codice non presente: " + theKey);
return bean;
}
public boolean isParmsHtReadyxxx() {
if (allWebAppParms != null && allWebAppParms.containsKey(getApCodeParms()))
return true;
return false;
}
}

View file

@ -0,0 +1,404 @@
package com.ablia.db;
import com.ablia.common.Parm;
import com.ablia.common.Users;
import com.ablia.reg.EcDc;
import com.ablia.util.SimpleDateFormat;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Properties;
public class ApplParmFull implements Serializable {
private static final long serialVersionUID = 5716730193350553875L;
private ApplParm ap;
private long lastUpdId_user;
private String reqIpAddress;
private Users lastUpdUser;
private String reqUrl;
public ApplParmFull(ApplParm applParm, long lastUpdId_user, String reqIpAddress, String reqUrl) {
this.ap = applParm;
this.lastUpdId_user = lastUpdId_user;
this.reqIpAddress = reqIpAddress;
this.reqUrl = reqUrl;
}
public long getLastUpdId_user() {
return this.lastUpdId_user;
}
public void setLastUpdId_user(long lastUpdId_user) {
this.lastUpdId_user = lastUpdId_user;
setLastUpdUser(null);
}
public String getReqIpAddress() {
return (this.reqIpAddress == null) ? "" : this.reqIpAddress.trim();
}
public void setReqIpAddress(String reqIpAddress) {
this.reqIpAddress = reqIpAddress;
}
public ApplParmFull() {}
public ApplParmFull(ApplParm applParm) {
this.ap = applParm;
}
public ApplParm getAp() {
return this.ap;
}
public void setAp(ApplParm applParm) {
this.ap = applParm;
}
public Parm getParm(String theKey) {
return getAp().getParm(theKey);
}
public String getApCode() {
return getAp().getApCode();
}
public int hashCode() {
return this.ap.hashCode();
}
public void handleDebug(Exception exception) {
this.ap.handleDebug(exception);
}
public void handleDebug(Exception exception, int logLevel) {
this.ap.handleDebug(exception, logLevel);
}
public void handleDebug(PreparedStatement ps) {
this.ap.handleDebug(ps);
}
public void handleDebug(PreparedStatement ps, int logLevel) {
this.ap.handleDebug(ps, logLevel);
}
public void handleDebug(String s) {
this.ap.handleDebug(s);
}
public void handleDebug(String s, int logLevel) {
this.ap.handleDebug(s, logLevel);
}
public String getApCode(DBAdapter obj) {
return this.ap.getApCode(obj);
}
public void setDebug(boolean flag) {
this.ap.setDebug(flag);
}
public void setDebugLevel(int i) {
this.ap.setDebugLevel(i);
}
public void writeLog(String msg) {
this.ap.writeLog(msg);
}
public String getApDescription() {
return this.ap.getApDescription();
}
public int getConnectionLifeTime() {
return this.ap.getConnectionLifeTime();
}
public String getConnectionString() {
return this.ap.getConnectionString();
}
public String getDatabase() {
return this.ap.getDatabase();
}
public SimpleDateFormat getDataFormat() {
return this.ap.getDataFormat();
}
public String toString() {
return this.ap.toString();
}
public Properties getDbEnvironProperty() {
return this.ap.getDbEnvironProperty();
}
public String getDbAtinavpasswd() {
return this.ap.getDbAtinavpasswd();
}
public int getDbType() {
return this.ap.getDbType();
}
public boolean getDebug() {
return this.ap.getDebug();
}
public String getDebugFile() {
return this.ap.getDebugFile();
}
public int getDebugLevel() {
return this.ap.getDebugLevel();
}
public String getDefaultLangCode() {
return this.ap.getDefaultLangCode();
}
public String getDriverManager() {
return this.ap.getDriverManager();
}
public int getInitialCons() {
return this.ap.getInitialCons();
}
public String getLangCode() {
return this.ap.getLangCode();
}
public Locale getLocale() {
return this.ap.getLocale();
}
public int getMaxConnectionHits() {
return this.ap.getMaxConnectionHits();
}
public int getMaxCons() {
return this.ap.getMaxCons();
}
public String getMdwpath() {
return this.ap.getMdwpath();
}
public NumberFormat getNf() {
return this.ap.getNf();
}
public String getPassword() {
return this.ap.getPassword();
}
public String getPropertyFileName() {
return this.ap.getPropertyFileName();
}
public String getResource(String key) {
return this.ap.getResource(key);
}
public String getPropertyFile() {
return this.ap.getPropertyFile();
}
public void setPropertyFile(String propertyFile) {
this.ap.setPropertyFile(propertyFile);
}
public final String getSoftwareVersion() {
return this.ap.getSoftwareVersion();
}
public String getResourceFromPropertyFile(String key) {
return this.ap.getResourceFromPropertyFile(key);
}
public final String getSoftwareVersionLog() {
return this.ap.getSoftwareVersionLog();
}
public SimpleDateFormat getTimeFormat() {
return this.ap.getTimeFormat();
}
public int getTimeout() {
return this.ap.getTimeout();
}
public String getUrl() {
return this.ap.getUrl();
}
public String getUser() {
return this.ap.getUser();
}
public boolean isBlock() {
return this.ap.isBlock();
}
public boolean isReuseCons() {
return this.ap.isReuseCons();
}
public void setApCode(String newApCode) {
this.ap.setApCode(newApCode);
}
public void setBlock(boolean block) {
this.ap.setBlock(block);
}
public void setConnectionLifeTime(int l_connectionLifeTime) {
this.ap.setConnectionLifeTime(l_connectionLifeTime);
}
public void setDatabase(String s) {
this.ap.setDatabase(s);
}
public void setDbEnvironProperty(Properties newDbEnvironProperty) {
this.ap.setDbEnvironProperty(newDbEnvironProperty);
}
public void setDbAtinavpasswd(String dbpasswd) {
this.ap.setDbAtinavpasswd(dbpasswd);
}
public void setDbType(int newDbType) {
this.ap.setDbType(newDbType);
}
public void setDebugFile(String string) {
this.ap.setDebugFile(string);
}
public void setInitialCons(int i) {
this.ap.setInitialCons(i);
}
public void setLangCode(String newLangCode) {
this.ap.setLangCode(newLangCode);
}
public void setMaxConnectionHits(int maxConnectionHits) {
this.ap.setMaxConnectionHits(maxConnectionHits);
}
public void setMaxCons(int i) {
this.ap.setMaxCons(i);
}
public void setMdwpath(String mdwpath) {
this.ap.setMdwpath(mdwpath);
}
public void setPassword(String s) {
this.ap.setPassword(s);
}
public void setPropertyFileName(String newPropertyFileName) {
this.ap.setPropertyFileName(newPropertyFileName);
}
public void setReuseCons(boolean reuseCons) {
this.ap.setReuseCons(reuseCons);
}
public void setTimeout(int i) {
this.ap.setTimeout(i);
}
public void setUser(String s) {
this.ap.setUser(s);
}
public RewriteRule getRewriteRule(String theCode) {
return this.ap.getRewriteRule(theCode);
}
public void resetCurrentApParms() {
this.ap.resetCurrentApParms();
}
public String translate(String sentence, String l_lang) {
return this.ap.translate(sentence, l_lang);
}
public NumberFormat getNf0() {
return this.ap.getNf0();
}
public NumberFormat getNf2() {
return this.ap.getNf2();
}
public NumberFormat getNf3() {
return this.ap.getNf3();
}
public String getConnectionsCreateTs() {
return this.ap.getConnectionsCreateTs();
}
public NumberFormat getNf4() {
return this.ap.getNf4();
}
public NumberFormat getNf1() {
return this.ap.getNf1();
}
public SimpleDateFormat getTimestampFormat() {
return this.ap.getTimestampFormat();
}
public Parm getParmNoHt(String theKey) {
return this.ap.getParmNoHt(theKey);
}
public Users getLastUpdUser() {
if (this.lastUpdUser == null && getLastUpdId_user() > 0L) {
this.lastUpdUser = new Users(this);
this.lastUpdUser.findByPrimaryKey(getLastUpdId_user());
}
return (this.lastUpdUser == null) ? new Users(this) : this.lastUpdUser;
}
public void setLastUpdUser(Users lastUpdUser) {
this.lastUpdUser = lastUpdUser;
}
public String getReqUrl() {
return (this.reqUrl == null) ? "" : this.reqUrl.trim();
}
public void setReqUrl(String reqUrl) {
this.reqUrl = reqUrl;
}
public String getEncryptedPassword(String plainPassword) {
long flgCrypt = getParm("PWD_CRYPT").getNumeroLong();
String cryptedPwd = plainPassword;
if (flgCrypt == 1L) {
cryptedPwd = EcDc.encodeDizionario(plainPassword, "Xg3Z5sFQ");
} else if (flgCrypt == 2L) {
cryptedPwd = EcDc.cryptMD5(plainPassword);
} else if (flgCrypt == 3L) {
cryptedPwd = EcDc.cryptSHA(plainPassword, "SHA-256");
}
return cryptedPwd;
}
}

View file

@ -0,0 +1,209 @@
package com.ablia.db;
import com.ablia.util.Debug;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
public class CPConnection extends Debug {
private ApplParm ap;
private Connection conn;
private Timestamp createTs;
private int hits;
private String lastCallingStackTrace;
private Timestamp callTs;
private String reqUrl;
private long lastUpdId_user;
private String reqIpAddress;
private ResParm rp;
public static CPConnection getInstance(ApplParm ap) {
CPConnection cpC = null;
synchronized (ap) {
cpC = new CPConnection(ap);
cpC.setRp(cpC.initConn());
}
return cpC;
}
private CPConnection(ApplParm newAp) {
this.ap = newAp;
}
public void addHit() {
this.hits++;
}
public void close() {
if (this.conn != null)
try {
this.conn.close();
} catch (SQLException e) {
handleDebug(e, 0);
}
}
protected void finalize() throws Throwable {
close();
this.conn = null;
}
public ApplParm getApFull() {
return this.ap;
}
public Connection getConn() {
return this.conn;
}
public Timestamp getCreateTs() {
return this.createTs;
}
public boolean getDebug() {
if (getApFull() != null)
return getApFull().getDebug();
return super.getDebug();
}
public String getDebugFile() {
if (getApFull() != null)
return getApFull().getDebugFile();
return getDebugFile();
}
public int getDebugLevel() {
if (getApFull() != null)
return getApFull().getDebugLevel();
return getDebugLevel();
}
public int getHits() {
return this.hits;
}
public String getLastCallingStackTrace() {
return this.lastCallingStackTrace;
}
public Timestamp getCallTs() {
return this.callTs;
}
private ResParm initConn() {
ResParm rp = new ResParm(true);
if (this.conn == null) {
try {
if (this.ap.getDbEnvironProperty() != null) {
this.conn = DriverManager.getConnection(String.valueOf(this.ap.getConnectionString()) + ":" + this.ap.getDatabase(), this.ap.getDbEnvironProperty());
} else {
this.conn = DriverManager.getConnection(String.valueOf(this.ap.getConnectionString()) + ":" + this.ap.getDatabase(), this.ap.getUser(), this.ap.getPassword());
}
this.createTs = new Timestamp(Calendar.getInstance().getTime().getTime());
this.hits = 0;
rp.setStatus(true);
} catch (Exception e) {
rp.setStatus(false);
rp.setMsg("CPConnection.initConn: Error during connection.....: " + e.getMessage() + "\nDatabase resource: " +
this.ap.getDatabase() + "\nDatabase type: " + this.ap.getDbType() + "\nDatabase url: " + this.ap.getUrl() + "\nUser: " +
this.ap.getUser() + "\nPassword: " + this.ap.getPassword() + "\nDbpasswd: " + this.ap.getDbAtinavpasswd() + "\n" +
e.getMessage());
}
} else {
rp.setStatus(false);
rp.setMsg("CPConnection.initConn: connessione nulla!!");
}
return rp;
}
public boolean isValid() {
if (getConn() == null)
return false;
try {
return getConn().isValid(0);
} catch (Exception e) {
handleDebug(e, 0);
return false;
}
}
public void setLastCallingStackTrace(String lastCallingStackTrace) {
this.lastCallingStackTrace = lastCallingStackTrace;
}
public void setCallTs(Timestamp lastFreeTs) {
this.callTs = lastFreeTs;
}
public long getLifeTimeSeconds() {
long mt1 = getCreateTs().getTime();
long mt2 = Calendar.getInstance().getTimeInMillis();
return (mt2 - mt1) / 1000L;
}
public String getLifeTime() {
return DBAdapter.secToHourMinSec(getLifeTimeSeconds());
}
public String getCallTime() {
long ctm = getCallTimeMilliSeconds();
if (ctm < 10000L) {
int sec = (int)ctm / 1000;
int ms = (int)(ctm - (long)(sec * 1000));
return String.valueOf(sec) + "," + ms + " ms";
}
return DBAdapter.secToHourMinSec(ctm / 1000L);
}
public long getCallTimeMilliSeconds() {
if (getCallTs() != null) {
long mt1 = getCallTs().getTime();
long mt2 = Calendar.getInstance().getTimeInMillis();
return mt2 - mt1;
}
return 0L;
}
public String getReqIpAddress() {
return (this.reqIpAddress == null) ? "" : this.reqIpAddress;
}
public void setReqIpAddress(String reqIpAddress) {
this.reqIpAddress = reqIpAddress;
}
public String getReqUrl() {
return (this.reqUrl == null) ? "" : this.reqUrl;
}
public void setReqUrl(String reqUrl) {
this.reqUrl = reqUrl;
}
public long getLastUpdId_user() {
return this.lastUpdId_user;
}
public void setLastUpdId_user(long lastUpdId_user) {
this.lastUpdId_user = lastUpdId_user;
}
public ResParm getRp() {
return this.rp;
}
public void setRp(ResParm rp) {
this.rp = rp;
}
}

View file

@ -0,0 +1,472 @@
package com.ablia.db;
import com.ablia.annotation.CRDescriptor;
import com.ablia.common.Parm;
import com.ablia.util.Debug;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public abstract class CRAdapter extends Debug {
public static final String AB_EMPTY_STRING = "";
protected HashMap<String, FieldsDescriptor> crFieldDescriptor;
private ApplParmFull apFull;
private Timestamp createTmst;
private String searchTxt;
protected DBAdapter getSecondaryObject(DBAdapter obj, Class<?> objClass, long pkLongValue) {
return getSecondaryObject(obj, objClass, new Long(pkLongValue));
}
protected DBAdapter getSecondaryObject(DBAdapter obj, Class<?> objClass, Object pkValue) {
try {
return DBAdapter.getSecondaryObject(getApFull(), obj, objClass, pkValue);
} catch (Exception e) {
handleDebug(e);
return obj;
}
}
private boolean searchRequest = false;
private long flgOrderBy;
private long flgTipoReport;
private int pageRow;
private int pageNumber;
private int searchPageNumber;
private String currentTab;
private String cmd;
private String flgReport;
private long id_users;
private String act;
private String lang;
private long flgShowDeleteLogic = 0L;
private String currentFocus;
private String _id;
private String filePdf;
private String fileName;
private Timestamp lastUpdTmst;
private String searchRighe;
private String searchRighe2;
public CRAdapter() {}
public CRAdapter(ApplParmFull newAp) {
setApFull(newAp);
}
public ApplParmFull getApFull() {
return this.apFull;
}
public String getFlgReport() {
return (this.flgReport == null) ? "" : this.flgReport.trim();
}
public String getLang() {
return (this.lang == null) ? "it" : this.lang.trim().toLowerCase();
}
public int getSearchPageNumber() {
return (this.searchPageNumber == 0) ? 1 : this.searchPageNumber;
}
public boolean isSearchRequest() {
return this.searchRequest;
}
public void setApFull(ApplParmFull newAp) {
this.apFull = newAp;
}
public void setFlgReport(String newFlgReport) {
this.flgReport = newFlgReport;
}
public void setLang(String newLang) {
this.lang = newLang;
}
public void setSearchPageNumber(int newSearchPageNumber) {
this.searchPageNumber = newSearchPageNumber;
}
public void setSearchRequest(boolean newSearchRequest) {
this.searchRequest = newSearchRequest;
}
public long getFlgTipoReport() {
return this.flgTipoReport;
}
public void setFlgTipoReport(long flgTipoReport) {
this.flgTipoReport = flgTipoReport;
}
public int getPageNumber() {
return this.pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public int getPageRow() {
return this.pageRow;
}
public void setPageRow(int pageRow) {
this.pageRow = pageRow;
}
public String getSearchTxt() {
return (this.searchTxt == null) ? "" : this.searchTxt.trim();
}
public void setSearchTxt(String searchTxt) {
this.searchTxt = searchTxt;
}
public String getCurrentTab() {
return (this.currentTab == null) ? "" : this.currentTab.trim();
}
public void setCurrentTab(String currentTab) {
this.currentTab = currentTab;
}
public long getFlgOrderBy() {
return this.flgOrderBy;
}
public void setFlgOrderBy(long flgOrderBy) {
this.flgOrderBy = flgOrderBy;
}
public long getId_users() {
return this.id_users;
}
public void setId_users(long newId_users) {
this.id_users = newId_users;
}
public String getCmd() {
return (this.cmd == null) ? "" : this.cmd.trim();
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getAct() {
return (this.act == null) ? "" : this.act.trim();
}
public void setAct(String act) {
this.act = act;
}
public long getFlgShowDeleteLogic() {
return this.flgShowDeleteLogic;
}
public void setFlgShowDeleteLogic(long flgShowDeleteLogic) {
this.flgShowDeleteLogic = flgShowDeleteLogic;
}
public String getCurrentFocus() {
return (this.currentFocus == null) ? "" : this.currentFocus.trim();
}
public void setCurrentFocus(String currentFocus) {
this.currentFocus = currentFocus;
}
public String get_id() {
return (this._id == null) ? "" : this._id.trim();
}
public void set_id(String anchor) {
this._id = anchor;
}
public String getFilePdf() {
return this.filePdf;
}
public void setFilePdf(String filePdf) {
this.filePdf = filePdf;
}
private void buildDescrizioneCRMap() {
boolean debug = true;
StringBuilder sb = new StringBuilder();
initCrFieldDescriptor();
Class<?> currentclClass = getClass();
while (!currentclClass.getName().equals("com.ablia.db.CRAdapter")) {
Field[] ff1 = currentclClass.getDeclaredFields();
int order = 1000;
for (int i = 0; i < ff1.length; i++) {
String name = ff1[i].getName();
String desc = name;
CRDescriptor annotation = ff1[i].<CRDescriptor>getAnnotation(CRDescriptor.class);
if (annotation == null || annotation.abilita()) {
if (annotation != null)
desc = annotation.descrizione();
Object valueUpd = getCRValueByFieldname(name, ff1[i].getType(), this);
String valueS = convertCRValueToString(valueUpd, ff1[i].getType());
DBAdapter.logDebug(debug, "buildDescrizioneCRMap: " + desc + " (" + name + ")" + ": " + valueS);
DBAdapter.logDebug(debug, String.valueOf(name) + ": " + valueUpd);
if (!valueS.isEmpty())
if (getCrFieldDescriptor().containsKey(desc)) {
FieldsDescriptor currentCRFD = getCrFieldDescriptor().get(desc);
currentCRFD.setVal(valueS);
getCrFieldDescriptor().put(desc, currentCRFD);
} else {
getCrFieldDescriptor().put(desc,
new FieldsDescriptor(desc, (long)order, desc, convertCRValueToString(valueUpd, ff1[i].getType())));
order++;
}
}
}
currentclClass = currentclClass.getSuperclass();
}
}
private static Object getCRValueByFieldname(String filedName, Class<?> tipo, CRAdapter thiss) {
String functionName = "get" + filedName.substring(0, 1).toUpperCase() + filedName.substring(1);
Object value = null;
try {
Method method = thiss.getClass().getMethod(functionName);
value = method.invoke(thiss);
if (filedName.startsWith("flg") && value instanceof Long) {
String descColumn = filedName.substring(3);
functionName = "get" + descColumn.substring(0, 1).toUpperCase() + descColumn.substring(1);
Class[] parm = new Class<?>[1];
parm[0] = long.class;
Long[] parmValue = { (Long)value };
method = thiss.getClass().getMethod(functionName);
value = method.invoke(thiss);
} else if (filedName.startsWith("id_")) {
functionName = "get" + filedName.substring(3, 4).toUpperCase() + filedName.substring(4);
method = thiss.getClass().getMethod(functionName);
Object currentObj = method.invoke(thiss);
Method descMethod = currentObj.getClass().getMethod("getDescrizione");
value = descMethod.invoke(currentObj);
}
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {}
return value;
}
private static boolean isNotEmpty(Object valueUpd, Class<?> tipo) {
boolean ret = false;
if (valueUpd != null) {
String sclass = valueUpd.getClass().getName();
if (sclass.indexOf("Long") > 0 || sclass.indexOf("Double") > 0 || sclass.indexOf("String") > 0 || sclass.indexOf("Date") > 0 ||
sclass.indexOf("Time") > 0)
if (tipo.getName() == "long") {
if ((Long)valueUpd == 0L || (Long)valueUpd == -1L) {
ret = false;
} else {
ret = true;
}
} else if (tipo.getName() == "double") {
if ((Double)valueUpd == 0.0D) {
ret = false;
} else {
ret = true;
}
} else if (tipo.getName().indexOf("String") > 0) {
if (((String)valueUpd).equals("") || ((String)valueUpd).isEmpty()) {
ret = false;
} else {
ret = true;
}
} else if (tipo.getName().indexOf("Date") > 0) {
Date data = (Date)valueUpd;
if (data == null) {
ret = false;
} else {
ret = true;
}
} else if (tipo.getName().indexOf("Time") > 0) {
if ((Time)valueUpd == null) {
ret = false;
} else {
ret = true;
}
}
}
return ret;
}
private final String convertCRValueToString(Object valueUpd, Class<?> tipo) {
String ret = "";
if (valueUpd != null) {
String sclass = valueUpd.getClass().getName();
if (sclass.indexOf("String") > 0) {
ret = (String)valueUpd;
} else if (sclass.indexOf("Long") > 0 || sclass.indexOf("Double") > 0 || sclass.indexOf("String") > 0 || sclass.indexOf("Date") > 0 ||
sclass.indexOf("Time") > 0) {
if (tipo.getName() == "long") {
if ((Long)valueUpd > 0L)
ret = valueUpd.toString();
} else if (tipo.getName() == "double" || tipo.getName() == "float") {
if ((Double)valueUpd > 0.0D)
ret = getApFull().getNf().format(valueUpd);
} else if (tipo.getName().indexOf("String") > 0) {
ret = (String)valueUpd;
} else if (tipo.getName().indexOf("Date") > 0) {
Date data = (Date)valueUpd;
if (data != null)
ret = getApFull().getDataFormat().format(data);
} else if (tipo.getName().indexOf("Time") > 0 &&
(Time)valueUpd != null) {
ret = getApFull().getTimeFormat().format((Time)valueUpd);
}
}
}
return ret.trim();
}
public String getFileName() {
return (this.fileName == null) ? "" : this.fileName.trim();
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public Parm getParm(String theKey) {
if (getApFull() != null)
return getApFull().getAp().getParm(theKey);
return new Parm();
}
public final boolean checkVersion(String theKey) {
String temp = "," + getParm("VERSION").getTesto();
if (temp.indexOf("," + theKey) >= 0)
return true;
return false;
}
public Timestamp getCreateTmst() {
return this.createTmst;
}
public void setCreateTmst(Timestamp createTmst) {
this.createTmst = createTmst;
}
public final HashMap<String, FieldsDescriptor> getCrFieldDescriptor() {
return this.crFieldDescriptor;
}
public void setCrFieldDescriptor(HashMap<String, FieldsDescriptor> crFieldDescriptor) {
this.crFieldDescriptor = crFieldDescriptor;
}
protected void initCrFieldDescriptor() {
if (this.crFieldDescriptor == null)
this.crFieldDescriptor = new HashMap<>();
}
public String getDescrizioneCR() {
StringBuilder sb = new StringBuilder();
buildDescrizioneCRMap();
FieldsComparator comparator = new FieldsComparator(getCrFieldDescriptor());
Map<String, FieldsDescriptor> orderMap = new TreeMap<>(comparator);
orderMap.putAll(getCrFieldDescriptor());
for (Map.Entry<String, FieldsDescriptor> entry : orderMap.entrySet()) {
if (!entry.getValue().getVal().isEmpty()) {
if (sb.length() > 0)
sb.append(" - ");
sb.append(String.valueOf(entry.getValue().getDesc()) + ": ");
sb.append(entry.getValue().getVal());
}
}
return sb.toString();
}
public String getDescrizioneHtmlCR() {
StringBuilder sb = new StringBuilder();
buildDescrizioneCRMap();
FieldsComparator comparator = new FieldsComparator(getCrFieldDescriptor());
Map<String, FieldsDescriptor> orderMap = new TreeMap<>(comparator);
orderMap.putAll(getCrFieldDescriptor());
for (Map.Entry<String, FieldsDescriptor> entry : orderMap.entrySet()) {
if (!entry.getValue().getVal().isEmpty()) {
if (sb.length() > 0)
sb.append("<br />");
sb.append(String.valueOf(entry.getValue().getDesc()) + ": ");
sb.append(entry.getValue().getVal());
}
}
return sb.toString();
}
public Timestamp getLastUpdTmst() {
return this.lastUpdTmst;
}
public void setLastUpdTmst(Timestamp lastUpdTmst) {
this.lastUpdTmst = lastUpdTmst;
}
public String getSearchRighe() {
return (this.searchRighe == null) ? "" : this.searchRighe.trim();
}
public void setSearchRighe(String searchRighe) {
this.searchRighe = searchRighe;
}
public String getSearchRighe2() {
return (this.searchRighe2 == null) ? "" : this.searchRighe2.trim();
}
public void setSearchRighe2(String searchRighe2) {
this.searchRighe2 = searchRighe2;
}
public boolean isGoogleTranslatorEnable() {
return getParm("USE_GOOGLE_TRANSLATOR").isTrue();
}
}

View file

@ -0,0 +1,145 @@
package com.ablia.db;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ColumnDescriptor {
private boolean autoIncrement = false;
private String columnName;
private short dataType;
private int columnSize;
private Field field;
private int stringCaseValue = 0;
private EncodedField encodedField;
private boolean fk;
public int getStringCaseValue() {
return this.stringCaseValue;
}
public void setStringCaseValue(int stringCaseValue) {
this.stringCaseValue = stringCaseValue;
}
public Field getField() {
return this.field;
}
public void setField(Field field) {
this.field = field;
}
public int getColumnSize() {
return this.columnSize;
}
public void setColumnSize(int columnSize) {
this.columnSize = columnSize;
}
private boolean fkNum = false;
private boolean pk;
private Method getMethod;
private Method setMethod;
public ColumnDescriptor(String theColumnName, short theDataType, int theColumnSize, boolean isPk) {
setColumnName(theColumnName);
setDataType(theDataType);
setPk(isPk);
setColumnSize(theColumnSize);
}
public ColumnDescriptor(String theColumnName, short theDataType, int theColumnSize, boolean isPk, Field theField, int l_strigCase, EncodedField l_econdedField) {
setColumnName(theColumnName);
setDataType(theDataType);
setPk(isPk);
setColumnSize(theColumnSize);
setField(theField);
setStringCaseValue(l_strigCase);
setEncodedField(l_econdedField);
}
public String getColumnName() {
return this.columnName;
}
public short getDataType() {
return this.dataType;
}
public boolean isAutoIncrement() {
return this.autoIncrement;
}
public boolean isFk() {
return this.fk;
}
public boolean isFkNum() {
return this.fkNum;
}
public boolean isPk() {
return this.pk;
}
public void setAutoIncrement(boolean newAutoIncrement) {
this.autoIncrement = newAutoIncrement;
}
public void setColumnName(String newColumnName) {
this.columnName = newColumnName;
}
public void setDataType(short newDataType) {
this.dataType = newDataType;
}
public void setFk(boolean newFk) {
this.fk = newFk;
}
public void setFkNum(boolean newFkNum) {
this.fkNum = newFkNum;
}
public void setPk(boolean newPk) {
this.pk = newPk;
}
public Method getGetMethod() {
return this.getMethod;
}
public Method getSetMethod() {
return this.setMethod;
}
public void setGetMethod(Method method) {
this.getMethod = method;
}
public void setSetMethod(Method method) {
this.setMethod = method;
}
public EncodedField getEncodedField() {
if (this.encodedField == null)
this.encodedField = new EncodedField();
return this.encodedField;
}
public void setEncodedField(EncodedField encodedField) {
this.encodedField = encodedField;
}
}

View file

@ -0,0 +1,507 @@
package com.ablia.db;
import com.ablia.util.Debug;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
public class ConnectionPool extends Debug {
private static Hashtable<String, ConnectionPool> ht_connectionPools;
private static final String NO_CALLING_STACK_TRACE_MSG = "<b>For full stack trace pls. set debug level to DEBUG (5) or INFO1 (1)</b>";
private ApplParm ap;
private Vector<CPConnection> free;
private int freeCons;
private Vector<CPConnection> used;
private int usedCons;
private ApplParmFull apFull;
private static Hashtable<String, ConnectionPool> getHt_connectionPools() {
if (ht_connectionPools == null)
ht_connectionPools = new Hashtable<>();
return ht_connectionPools;
}
public static Enumeration<ConnectionPool> getCpools() {
return getHt_connectionPools().elements();
}
public static synchronized ConnectionPool getInstance(ApplParm ap) {
String cpKey = String.valueOf(ap.getDatabase()) + "_" + ap.getUser() + "_" + ap.getPassword();
if (getHt_connectionPools().containsKey(cpKey))
return getHt_connectionPools().get(cpKey);
ConnectionPool cp = new ConnectionPool(ap);
cp.initCPConnection();
getHt_connectionPools().put(cpKey, cp);
return cp;
}
public static void resetAll() {
Enumeration<ConnectionPool> enu = getCpools();
while (enu.hasMoreElements()) {
ConnectionPool l_cp = enu.nextElement();
l_cp.resetAllConnection();
}
ht_connectionPools = null;
}
private ConnectionPool(ApplParm newAp) {
this.ap = newAp;
try {
Class.forName(this.ap.getDriverManager()).newInstance();
} catch (ClassNotFoundException cnf) {
System.err.println("Connection Pool: " + cnf.getMessage());
} catch (Exception e) {
System.err.println("Connection Pool: " + e.getMessage());
}
}
private ConnectionPool(ApplParmFull newAp) {
this.apFull = newAp;
this.ap = this.apFull.getAp();
try {
Class.forName(this.ap.getDriverManager()).newInstance();
} catch (ClassNotFoundException cnf) {
System.err.println("Connection Pool: " + cnf.getMessage());
} catch (Exception e) {
System.err.println("Connection Pool: " + e.getMessage());
}
}
private ResParm addCPConnection() {
CPConnection cpConn = CPConnection.getInstance(getAp());
ResParm rp = new ResParm();
if (cpConn == null) {
rp.setStatus(false);
rp.setMsg("Errore! addCPConnection.getInstance() CPConnection null!");
} else if (cpConn.getConn() == null) {
rp.setStatus(false);
rp.setMsg("Errore! addCPConnection.getInstance() Connection null! " + cpConn.getRp().getMsg());
} else {
rp = cpConn.getRp();
}
if (rp.getStatus()) {
getFree().addElement(cpConn);
this.freeCons++;
printDebugMsg("Add new connection...");
}
return rp;
}
private synchronized boolean checkFreeConnection() {
boolean test = true;
Enumeration<CPConnection> enu = ((Vector<CPConnection>)getFree().clone()).elements();
while (enu.hasMoreElements()) {
CPConnection con = enu.nextElement();
if (!con.isValid()) {
removeFreeConnection(con);
test = false;
}
}
return test;
}
private synchronized boolean checkUsedConnection() {
boolean test = true;
Enumeration<CPConnection> enu = ((Vector<CPConnection>)getUsed().clone()).elements();
while (enu.hasMoreElements()) {
CPConnection con = enu.nextElement();
if (!con.isValid()) {
removeCPConnection(con);
test = false;
}
}
return test;
}
private synchronized boolean resetAllConnection() {
boolean test = false;
Enumeration<CPConnection> enu = ((Vector<CPConnection>)getUsed().clone()).elements();
while (enu.hasMoreElements()) {
CPConnection con = enu.nextElement();
removeCPConnection(con);
test = true;
}
this.used = null;
enu = ((Vector<CPConnection>)getFree().clone()).elements();
while (enu.hasMoreElements()) {
CPConnection con = enu.nextElement();
con.close();
getFree().removeElement(con);
con = null;
this.freeCons--;
test = true;
}
this.free = null;
return test;
}
protected void finalize() throws Throwable {
resetAllConnection();
}
public final synchronized String garbageCollection(int l_logLevel) {
String msg = "\nConnection Pool Garbage Collection for:" + getAp().getUrl();
try {
int uc = getUsedCons();
int fc = getFreeCons();
checkUsedConnection();
checkFreeConnection();
msg = String.valueOf(msg) + "\nUsed connections before gc: " + uc;
msg = String.valueOf(msg) + "\nUsed connections after gc: " + getUsedCons();
msg = String.valueOf(msg) + "\nReleased connections: " + (uc - getUsedCons());
msg = String.valueOf(msg) + "\nFree connections before gc: " + fc;
msg = String.valueOf(msg) + "\nFree connections after gc: " + getFreeCons();
msg = String.valueOf(msg) + "\nDeleted connections: " + (fc - getFreeCons());
msg = String.valueOf(msg) + "\n--------------------------------------------\n";
handleDebug(msg, l_logLevel);
Class.forName(this.ap.getDriverManager()).newInstance();
} catch (Exception e) {
handleDebug(e, 0);
}
return msg;
}
public synchronized CPConnection getCPConnection() throws SQLException {
if (this.freeCons < 0)
this.freeCons = 0;
ResParm rp = new ResParm(true);
if (this.freeCons == 0)
if (this.ap.getMaxCons() == 0 || this.usedCons < this.ap.getMaxCons()) {
rp = addCPConnection();
if (!rp.getStatus())
throw new SQLException("cp.getCPConnection() addCPConnection(): cannot get a new connection ...db:" + getAp().getUrl() +
"\nusername:" + getAp().getUser() + "\npassword:" + getAp().getPassword() + "\nfree:" + this.freeCons + " used:" +
getUsedCons() + "\naddCPConnection Exception:\n" + rp.getMsg() + "\n***************************\n");
} else if (this.ap.isBlock()) {
try {
wait((long)this.ap.getTimeout());
} catch (InterruptedException ie) {
System.err.println("Interrupted Exception: " + ie.getMessage());
}
if (this.freeCons == 0)
if (this.ap.getMaxCons() == 0 || this.usedCons < this.ap.getMaxCons()) {
rp = addCPConnection();
} else if (checkUsedConnection()) {
if (resetAllConnection()) {
rp = addCPConnection();
handleDebug(
"WARNING! CONNECTION POOL RESET. CHANGE TIMEOUT OR MAXCON PARMS OR CHECK FOR ERRORS ON YOU CODE db:" +
getAp().getUrl(),
0);
} else {
throw new SQLException("After timeout error resetting all connection...db:" + getAp().getUrl() +
" free:" + this.freeCons + " used:" + getUsedCons() + "\n***************************\n");
}
} else if (this.ap.getMaxCons() == 0 || this.usedCons < this.ap.getMaxCons()) {
rp = addCPConnection();
} else {
throw new SQLException("After timeout still connection non available. IT SHOULD BE NEVER HAPPEN!!..db:" +
getAp().getUrl() + " free:" + this.freeCons + " used:" + getUsedCons() +
"\n***************************\n");
}
} else {
throw new SQLException("Max number of connections reached!\n***************************\n");
}
if (!rp.getStatus())
throw new SQLException("cp.getCPConnection() after retries: cannot get a new connection ...db:" + getAp().getUrl() +
"\nusername:" + getAp().getUser() + "\npassword:" + getAp().getPassword() + "\nfree:" + this.freeCons + " used:" +
getUsedCons() + "\naddCPConnection Exception:\n" + rp.getMsg() + "\n***************************\n");
CPConnection cpCon = getFree().lastElement();
getFree().removeElement(cpCon);
this.freeCons--;
if (getAp().getConnectionLifeTime() > 0) {
Calendar cts = Calendar.getInstance();
cts.setTime(cpCon.getCreateTs());
cts.add(12, getAp().getConnectionLifeTime());
if (Calendar.getInstance().after(cts)) {
handleDebug("getCPConnection: too old connection. I'll get a new one. db:" + getAp().getUrl() + " free:" + this.freeCons +
" used:" + getUsedCons() + " connection timestamp: " + cpCon.getLifeTime() + " Connection life time: " +
getAp().getConnectionLifeTime() + " min.", 5);
cpCon.close();
cpCon = null;
return getCPConnection();
}
}
if (!cpCon.isValid()) {
handleDebug("getCPConnection: connection no more valid. db:" + getAp().getUrl() + " free:" + this.freeCons + " used:" + getUsedCons() +
" connection timestamp: " + cpCon.getLifeTime(), 5);
cpCon = CPConnection.getInstance(getAp());
rp = cpCon.getRp();
}
if (cpCon == null || cpCon.getConn() == null || !rp.getStatus())
throw new SQLException("cp.getCPConnection(): cannot get a new connection ...db:" + getAp().getUrl() + "\nusername:" +
getAp().getUser() + "\npassword:" + getAp().getPassword() + "\nfree:" + this.freeCons + " used:" + getUsedCons() + "\n" +
"\naddCPConnection new connection after invalid connection. Exception:\n" + rp.getMsg() +
"\n***************************\n");
getUsed().addElement(cpCon);
this.usedCons++;
cpCon.addHit();
cpCon.setCallTs(new Timestamp(System.currentTimeMillis()));
if (getDebug() && getDebugLevel() >= 1) {
StringBuffer msg = new StringBuffer("Connection Calling Stack Trace:\n");
StringBuffer msgAll = new StringBuffer("Connection Calling Stack Trace (NO DBAdapter class found!):\n");
StackTraceElement[] callingFrame = Thread.currentThread().getStackTrace();
boolean dbAdapterTrovato = false;
boolean dbAdapterSparito = false;
if (callingFrame.length > 0) {
int numRigheDBAdapter = 0;
for (int i = 1; i < callingFrame.length; i++) {
String temp = String.valueOf(callingFrame[i].getClassName()) + "." + callingFrame[i].getMethodName();
msgAll.append(temp);
msgAll.append("\n");
if (temp.indexOf("DBAdapter") > 1)
dbAdapterTrovato = true;
if (dbAdapterTrovato && temp.indexOf("DBAdapter") < 0)
dbAdapterSparito = true;
if (dbAdapterSparito) {
msg.append(temp);
msg.append("\n");
numRigheDBAdapter++;
if (numRigheDBAdapter >= 4)
break;
}
}
}
if (dbAdapterSparito) {
cpCon.setLastCallingStackTrace(msg.toString());
} else {
cpCon.setLastCallingStackTrace(msgAll.toString());
}
} else {
cpCon.setLastCallingStackTrace("<b>For full stack trace pls. set debug level to DEBUG (5) or INFO1 (1)</b>");
}
handleDebug("getCPConnection: db:" + getAp().getUrl() + " free:" + this.freeCons + " used:" + getUsedCons(), 5);
return cpCon;
}
public String getCpParms() {
String temp = "Initial Connections: " + this.ap.getInitialCons() + "\n" + "Max Connections: " + this.ap.getMaxCons() + "\n" + "Timeout: " +
this.ap.getTimeout() + "\n" + "Free Connections: " + this.freeCons + "\n" + "Used Connections: " + this.usedCons;
return temp;
}
public boolean getDebug() {
if (getAp() != null)
return super.getDebug();
return super.getDebug();
}
public int getFreeCons() {
return this.freeCons;
}
public int getUsedCons() {
return this.usedCons;
}
private void initCPConnection() {
int i = 0;
while (this.freeCons < this.ap.getInitialCons() && i < this.ap.getMaxCons()) {
ResParm rp = addCPConnection();
if (rp.getStatus()) {
i++;
continue;
}
break;
}
this.usedCons = 0;
}
public void releaseCPConnection(CPConnection con) {
releaseCPConnection(con, this.ap.isReuseCons());
}
private synchronized void releaseCPConnection(CPConnection con, boolean reuseThisCon) {
if (con != null) {
con.setReqIpAddress("");
if (getUsed().contains(con)) {
getUsed().removeElement(con);
this.usedCons--;
if (reuseThisCon) {
if (this.ap.getMaxConnectionHits() > 0) {
if (con.getHits() > this.ap.getMaxConnectionHits()) {
con.close();
con = null;
} else {
getFree().addElement(con);
this.freeCons++;
}
} else {
getFree().addElement(con);
this.freeCons++;
}
} else {
con.close();
con = null;
printDebugMsg("Removed connection...");
}
notify();
} else {
handleDebug(
"releaseCPConnection: used Connection " + con +
" not from this Connection Pool or connection already removed! Processing Garbage Collection...db:" +
getAp().getUrl() + " free:" + this.freeCons + " used:" + getUsedCons() + "\n" + con.getLastCallingStackTrace(),
0);
garbageCollection(0);
}
} else {
handleDebug("releaseCPConnection: trying to release a null connection!! Processing Garbage Collection db:" + getAp().getUrl() +
" free:" + this.freeCons + " used:" + getUsedCons(), 0);
garbageCollection(0);
}
handleDebug("releaseCPConnection: well done ...db:" + getAp().getUrl() + " free:" + this.freeCons + " used:" + getUsedCons(),
5);
}
private synchronized void removeFreeConnection(CPConnection con) {
if (con != null) {
con.setReqIpAddress("");
if (getFree().contains(con)) {
getFree().removeElement(con);
con.close();
con = null;
this.freeCons--;
} else {
handleDebug("removeFreeConnection: Free Connection " + con +
" not from this Connection Pool or connection already removed!...db:" + getAp().getUrl() + " free:" + this.freeCons +
" used:" + getUsedCons(), 0);
garbageCollection(0);
}
notify();
} else {
handleDebug("removeFreeConnection: trying to release a null connection!! Processing Garbage Collection db:" + getAp().getUrl() +
" free:" + this.freeCons + " used:" + getUsedCons(), 0);
garbageCollection(0);
}
handleDebug("removeFreeConnection: well done ...db:" + getAp().getUrl() + " free:" + this.freeCons + " used:" + getUsedCons(),
5);
}
public void removeCPConnection(CPConnection con) {
releaseCPConnection(con, false);
}
public void setFreeCons(int newFreeCons) {
this.freeCons = newFreeCons;
}
public void setUsedCons(int newUsedCons) {
this.usedCons = newUsedCons;
}
public String getDebugFile() {
if (getAp() != null)
return getAp().getDebugFile();
return getDebugFile();
}
public int getDebugLevel() {
if (getAp() != null)
return getAp().getDebugLevel();
return getDebugLevel();
}
public Vector<CPConnection> getFree() {
if (this.free == null)
this.free = new Vector<>(this.ap.getInitialCons());
return this.free;
}
public void setFree(Vector<CPConnection> free) {
this.free = free;
}
public Vector<CPConnection> getUsed() {
if (this.used == null)
this.used = new Vector<>(this.ap.getInitialCons());
return this.used;
}
public void setUsed(Vector<CPConnection> used) {
this.used = used;
}
private void resetOldUsedConnection(long min) {
System.out.println("Resetting used connection for " + getAp().getApCode());
Enumeration<CPConnection> enu = ((Vector<CPConnection>)getUsed().clone()).elements();
int i = 0;
while (enu.hasMoreElements()) {
i++;
CPConnection con = enu.nextElement();
if (con.getCallTimeMilliSeconds() > min * 60000L) {
System.out.println("Force closing used connection " + i + " ....");
con.close();
getUsed().removeElement(con);
con = null;
this.usedCons--;
}
}
}
public ApplParm getAp() {
return this.ap;
}
private final void printDebugMsg(String msg) {
String methodName = Thread.currentThread().getStackTrace()[10].getMethodName();
String className = Thread.currentThread().getStackTrace()[10].getClassName();
if (methodName.indexOf("findRows") >= 0) {
methodName = Thread.currentThread().getStackTrace()[9].getMethodName();
className = Thread.currentThread().getStackTrace()[9].getClassName();
}
StringBuilder sb = new StringBuilder(">>>>>>>> Connection Pool:\n");
Date d = new Date(System.currentTimeMillis());
sb.append(d.toString());
sb.append("\n");
sb.append(msg);
sb.append("\n");
sb.append(className);
sb.append(".");
sb.append(methodName);
sb.append("\n");
if (this.apFull != null) {
sb.append(this.apFull.getReqUrl());
sb.append("\n");
}
sb.append(this.ap.getDatabase());
sb.append("\nTot connections= ");
sb.append(this.freeCons + this.usedCons);
sb.append("\nMax connections= ");
sb.append(this.ap.getMaxCons());
sb.append("\n<<<<<<<<<");
System.out.println(sb.toString());
}
public static synchronized ConnectionPool getInstance(ApplParmFull apFull) {
String cpKey = String.valueOf(apFull.getAp().getDatabase()) + "_" + apFull.getAp().getUser() + "_" + apFull.getAp().getPassword();
if (getHt_connectionPools().containsKey(cpKey))
return getHt_connectionPools().get(cpKey);
ConnectionPool cp = new ConnectionPool(apFull.getAp());
cp.initCPConnection();
getHt_connectionPools().put(cpKey, cp);
return cp;
}
public static void resetOldUsed(final long min) {
new Thread() {
public void run() {
Enumeration<ConnectionPool> enu = ConnectionPool.getCpools();
while (enu.hasMoreElements()) {
ConnectionPool l_cp = enu.nextElement();
l_cp.resetOldUsedConnection(min);
}
}
}.start();
}
}

View file

@ -0,0 +1,102 @@
package com.ablia.db;
import com.ablia.common.CrontabInterface;
import com.ablia.common.Users;
import com.ablia.mail.MailProperties;
import com.ablia.util.Timer;
import java.sql.Timestamp;
import java.util.Hashtable;
public class CrontabJobThread extends Thread {
public boolean isRunning = false;
private ApplParmFull apFull;
private CrontabInterface crontabInterface;
private String jobName;
private String eMail;
private static Hashtable<String, CrontabJobThread> runningInstaces = new Hashtable<>();
private CrontabJobThread(CrontabInterface crontabInterface, ApplParmFull ap, String jobName, String eMail) {
this.crontabInterface = crontabInterface;
setApFull(ap);
this.eMail = eMail;
this.jobName = jobName;
start();
}
public synchronized void run() {
this.isRunning = true;
Timer timer = new Timer();
timer.start();
String corpoMessaggio = String.valueOf(timer.getTStart().toString()) + " " + getApFull().getDatabase() + " CrontabJobThread: " + this.jobName + " started!!";
System.out.println(corpoMessaggio);
CrontabThread.appendLog(this.apFull, corpoMessaggio);
ResParm rp = new ResParm();
try {
rp = this.crontabInterface.crontabJob(getApFull());
} catch (Exception e) {
e.printStackTrace();
rp.setException(e);
}
Timestamp tEnd = new Timestamp(System.currentTimeMillis());
timer.stop();
String endMsg = String.valueOf(timer.getTStop().toString()) + " " + getApFull().getDatabase() + " CrontabJobThread: " + this.jobName + " (" +
timer.getDurataHourMin() + ") FINISHED";
if (!rp.getStatus() || !rp.getMsg().isEmpty())
endMsg = String.valueOf(endMsg) + "\n---- start crontabjob message -----\n" + rp.getMsg() + (
(rp.getException() != null) ? ("\n" + rp.getExceptionStackTrace()) : "") + "\n----- end crontabjob message ------";
CrontabThread.appendLog(this.apFull, endMsg);
corpoMessaggio = String.valueOf(corpoMessaggio) + "\n" + endMsg;
this.isRunning = false;
if (this.eMail != null && !this.eMail.isEmpty()) {
Users bean = new Users(this.apFull);
MailProperties mp = new MailProperties();
mp.put("TO", this.eMail);
mp.setProperty("FROM", this.apFull.getParm("FROM").getTesto());
mp.put("SUBJECT", "Crontab Job " + this.jobName + " " + this.apFull.getDatabase() + " del " + tEnd);
mp.setProperty("BCC", "");
mp.setProperty("CC", "");
mp.put("MSG", corpoMessaggio);
try {
bean.sendMailMessage(mp);
} catch (Exception e) {
e.printStackTrace();
CrontabThread.appendLog(this.apFull, String.valueOf(new Timestamp(System.currentTimeMillis()).toString()) + " " + getApFull().getDatabase() +
" CrontabJobThread: " + this.jobName + " SEND MAIL ERROR TO " + this.eMail + "\n" + e.getMessage());
}
}
runningInstaces.remove(this.jobName);
}
public ApplParmFull getApFull() {
return this.apFull;
}
private void setApFull(ApplParmFull ap) {
this.apFull = ap;
}
public static String minToTempoHourMin(long min) {
return String.valueOf(String.valueOf((int)(min / 60L))) + " h " + String.valueOf(min - (long)((int)(min / 60L) * 60)) + " min";
}
public static String secToTempoHourMin(long sec) {
long h = sec / 3600L;
long min = (sec - h * 60L) / 60L;
long secF = sec - h * 3660L - min * 60L;
return String.valueOf(h) + " h " + min + " min " + secF + " sec";
}
public static CrontabJobThread getInstance(CrontabInterface crontabInterface, ApplParmFull ap, String jobName, String eMail) {
if (!runningInstaces.containsKey(jobName)) {
CrontabJobThread currentThread = new CrontabJobThread(crontabInterface, ap, jobName, eMail);
runningInstaces.put(jobName, currentThread);
return currentThread;
}
return runningInstaces.get(jobName);
}
}

View file

@ -0,0 +1,200 @@
package com.ablia.db;
import com.ablia.common.CrontabInterface;
import com.ablia.log.Log;
import com.ablia.util.FileLogger;
import com.ablia.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
public class CrontabThread extends Thread {
private static Hashtable<String, CrontabThread> instance = new Hashtable<>();
public boolean isRunning = false;
private ApplParmFull apFull;
public static void getInstance(ApplParmFull theApplParmFull) {
boolean debug = true;
if (!instance.containsKey(theApplParmFull.getApCode())) {
DBAdapter.logDebug(debug, "\n****** Init Crontab Servlet started!! " + theApplParmFull.getApCode() + " ******");
CrontabThread currentThread = new CrontabThread(theApplParmFull);
instance.put(theApplParmFull.getApCode(), currentThread);
}
}
private CrontabThread(ApplParmFull l_ap) {
setApFull(l_ap);
start();
}
public synchronized void run() {
this.isRunning = true;
String dashLine = "******************************************************\n";
String endDashLine = "######################################################\n";
Date d = new Date(System.currentTimeMillis());
System.out.println("\n" + d.toString() + " " + getApFull().getDatabase() + " ****** CrontabThread started!! ******");
appendLog(this.apFull, String.valueOf(dashLine) + d.toString() + " " + getApFull().getDatabase() + " CrontabThread started!!\n" + dashLine);
if ((long)getApFull().getParm("DAILY_CRONTAB_ENABLE").getNumeroInt() == 1L)
while (this.isRunning) {
if ((long)getApFull().getParm("DAILY_CRONTAB_ENABLE").getNumeroInt() == 1L) {
try {
String crontabs = getApFull().getParm("DAILY_CRONTAB").getTesto().trim();
String job = "NO JOB SELECTED!";
if (!crontabs.isEmpty())
try {
String crontabsOk = crontabs;
String delimeter = "\n";
if (crontabs.indexOf('\r') > 1) {
crontabsOk = crontabs.replaceAll("\n", "");
delimeter = "\r";
} else if (crontabs.indexOf('\n') > 1) {
crontabsOk = crontabs.replaceAll("\r", "");
delimeter = "\n";
}
StringTokenizer st = new StringTokenizer(crontabsOk, delimeter);
while (st.hasMoreTokens()) {
job = st.nextToken();
String eMail = null;
if (eseguoJob(job)) {
StringTokenizer stJob = new StringTokenizer(job, " ");
if (stJob.countToken() == 7) {
eMail = stJob.getToken(6);
} else if (stJob.countToken() == 2) {
eMail = st.getToken(1);
}
String realJob = job.substring(0, job.indexOf(' '));
Class<?> jobClass = Class.forName(realJob);
Object jobInst = jobClass.newInstance();
CrontabJobThread.getInstance((CrontabInterface)jobInst, this.apFull, realJob, eMail);
}
}
} catch (Exception e) {
d = new Date(System.currentTimeMillis());
appendLog(this.apFull, String.valueOf(d.toString()) + " Exception CRONTAB JOB: " + job + "\n" + e.getMessage());
}
if (getApFull().getParm("USE_LOG").getNumero() == 1.0D && (getApFull().getParm("LOG_GG").getNumero() > 0.0D ||
getApFull().getParm("LOG_MAIL_GG").getNumero() > 0.0D)) {
job = "com.ablia.common.Log 0 0 * * * ";
if (eseguoJob(job))
try {
CrontabJobThread.getInstance(new Log(), this.apFull, "Pulizia Log giornaliera",
getApFull().getParm("LOG_CRONTAB_MAIL").getTesto());
} catch (Exception e) {
d = new Date(System.currentTimeMillis());
appendLog(this.apFull, String.valueOf(d.toString()) + " Exception CRONTAB JOB: " + job + "\n" + e.getMessage());
}
}
Calendar calNow = Calendar.getInstance();
long milsNow = calNow.getTimeInMillis();
calNow.set(14, 0);
calNow.set(13, 0);
sleep(60000L - milsNow + calNow.getTimeInMillis());
} catch (Exception e) {
e.printStackTrace();
}
continue;
}
this.isRunning = false;
}
instance.remove(getApFull().getApCode());
d = new Date(System.currentTimeMillis());
appendLog(this.apFull, String.valueOf(endDashLine) + d.toString() + " CrontabThread STOPPED!!\n" + endDashLine);
System.out.println("\n" + d.toString() + " CrontabThread STOPPED!!");
setApFull(null);
}
public ApplParmFull getApFull() {
return this.apFull;
}
private void setApFull(ApplParmFull ap) {
this.apFull = ap;
}
private boolean eseguoJob(String currentJob) {
java.util.StringTokenizer orari = new java.util.StringTokenizer(currentJob, " ");
if (orari.countTokens() >= 1 && orari.countTokens() <= 7) {
int minute = 0, hour = 0, mday = -1, month = -1, wday = -1;
if (orari.countTokens() >= 6) {
orari.nextToken();
String temp = orari.nextToken();
minute = temp.equals("*") ? -1 : Integer.parseInt(temp);
temp = orari.nextToken();
hour = temp.equals("*") ? -1 : Integer.parseInt(temp);
temp = orari.nextToken();
mday = temp.equals("*") ? -1 : Integer.parseInt(temp);
temp = orari.nextToken();
month = temp.equals("*") ? -1 : Integer.parseInt(temp);
temp = orari.nextToken();
wday = temp.equals("*") ? -1 : Integer.parseInt(temp);
}
Calendar cal = Calendar.getInstance();
int currentMese = cal.get(2);
int currentWday = cal.get(7);
int currentMday = cal.get(5);
int currentHour = cal.get(11);
int currentMin = cal.get(12);
if ((month < 0 || currentMese == month) && (mday < 0 || currentMday == mday) && (wday < 0 || currentWday == wday) && (
hour < 0 || currentHour == hour) && (minute < 0 || currentMin == minute))
return true;
return false;
}
String nomeJob = orari.nextToken();
Date d = new Date(System.currentTimeMillis());
appendLog(this.apFull, String.valueOf(d.toString()) + " CRONTAB JOB: " + nomeJob + "\nERRORE! riga crontab errata: " + currentJob);
return false;
}
public static final ResParm appendLog(ApplParmFull ap, String msg) {
ResParm rp = new ResParm();
synchronized (ap) {
FileLogger.getInstance(ap.getParm("DAILY_CRONTAB_MAIN_LOG_FILE").getTesto().trim()).writeMessage(msg);
}
return rp;
}
public static final ResParm clearLog(ApplParmFull ap) {
ResParm rp = new ResParm(true);
synchronized (ap) {
try {
File clog = new File(ap.getParm("DAILY_CRONTAB_MAIN_LOG_FILE").getTesto().trim());
if (clog.exists())
clog.delete();
clog.createNewFile();
} catch (Exception e) {
e.printStackTrace();
rp.setStatus(false);
rp.setMsg(e.getMessage());
}
}
return rp;
}
public static final String getLog(ApplParmFull ap) {
String logMsg = "";
File clog = new File(ap.getParm("DAILY_CRONTAB_MAIN_LOG_FILE").getTesto().trim());
if (clog.exists()) {
String NL = "\n";
try {
StringBuilder sb = new StringBuilder();
BufferedReader bufferedreader = new BufferedReader(
new FileReader(ap.getParm("DAILY_CRONTAB_MAIN_LOG_FILE").getTesto().trim()));
String s1;
while ((s1 = bufferedreader.readLine()) != null) {
sb.append(s1);
sb.append("\n");
}
bufferedreader.close();
logMsg = sb.toString();
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
}
return logMsg;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,68 @@
package com.ablia.db;
import java.sql.SQLException;
public class DBAdapterException extends SQLException {
private static final long serialVersionUID = -8013752768366984642L;
private ResParm rp = null;
private boolean duplicateKeyError = false;
private String mySQLState;
public DBAdapterException() {}
public DBAdapterException(Exception e) {
super(e.toString());
}
public DBAdapterException(String s) {
super(s);
}
public DBAdapterException(String s, ResParm rp) {
super(s);
setRp(rp);
}
public DBAdapterException(SQLException sqle) {
super(sqle.getMessage());
setSQLState(sqle.getSQLState());
if (sqle.getSQLState() != null)
if (sqle.getSQLState().equals("S1000") ||
sqle.getSQLState().equals("S1009")) {
this.duplicateKeyError = true;
} else {
this.duplicateKeyError = false;
}
}
public String getMessage() {
if (isDuplicateKeyError())
return "Duplicated Key error!!!";
return super.getMessage();
}
public ResParm getRp() {
return this.rp;
}
public String getSQLState() {
if (this.mySQLState == null)
return super.getSQLState();
return this.mySQLState;
}
public boolean isDuplicateKeyError() {
return this.duplicateKeyError;
}
private void setRp(ResParm newRp) {
this.rp = newRp;
}
private void setSQLState(String newSQLState) {
this.mySQLState = newSQLState;
}
}

View file

@ -0,0 +1,61 @@
package com.ablia.db;
public class DBAdapterSaveResponse {
private String _id;
private String lastUpdTmst;
private String lastUpdInfo;
private String msg;
private boolean status;
public DBAdapterSaveResponse(String _id, String lastUpdTmst, String lastUpdInfo, String msg, boolean status) {
this._id = _id;
this.lastUpdInfo = lastUpdInfo;
this.lastUpdTmst = lastUpdTmst;
this.msg = msg;
this.status = status;
}
public String get_id() {
return this._id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getMsg() {
return "xxx" + this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getLastUpdTmst() {
return this.lastUpdTmst;
}
public void setLastUpdTmst(String lastUpdTmst) {
this.lastUpdTmst = lastUpdTmst;
}
public String getLastUpdInfo() {
return this.lastUpdInfo;
}
public void setLastUpdInfo(String lastUpdInfo) {
this.lastUpdInfo = lastUpdInfo;
}
public boolean isStatus() {
return this.status;
}
public void setStatus(boolean dbStatus) {
this.status = dbStatus;
}
}

View file

@ -0,0 +1,46 @@
package com.ablia.db;
import com.ablia.util.Debug;
import com.ablia.util.SimpleDateFormat;
import java.sql.Date;
import java.text.ParseException;
public abstract class DBReflectAdapter extends Debug implements DBReflectInterface {
private ApplParm fieldAp;
public ApplParm getApFull() {
return this.fieldAp;
}
public Object[] getFieldSetArg(String parmValue, Class type) throws ParseException {
Object[] retParm = new Object[1];
if (type.equals(String.class)) {
retParm[0] = parmValue;
} else if (type.equals(Long.class) ||
type.getName().equals("long")) {
retParm[0] = new Long(parmValue);
} else if (type.equals(Integer.class) ||
type.getName().equals("int")) {
retParm[0] = new Integer(parmValue);
} else if (type.equals(Double.class) ||
type.getName().equals("double")) {
retParm[0] = Double.valueOf(parmValue.replace(',', '.'));
} else if (type.equals(Float.class) ||
type.getName().equals("float")) {
retParm[0] = Float.valueOf(parmValue.replace(',', '.'));
} else if (type.equals(Date.class)) {
try {
retParm[0] = new Date(getApFull().getDataFormat().parse(
parmValue).getTime());
} catch (ParseException e) {}
retParm[0] = new Date(
new SimpleDateFormat("dd/MM/yy")
.parse(parmValue).getTime());
}
return retParm;
}
public void setAp(ApplParm newFieldAp) {
this.fieldAp = newFieldAp;
}
}

View file

@ -0,0 +1,7 @@
package com.ablia.db;
import java.text.ParseException;
public interface DBReflectInterface {
Object[] getFieldSetArg(String paramString, Class paramClass) throws ParseException;
}

View file

@ -0,0 +1,47 @@
package com.ablia.db;
import com.ablia.common.DescLangItem;
import com.ablia.util.Vectumerator;
import java.util.Vector;
public interface DbInterface {
ResParm delete();
Vectumerator<? extends DBAdapter> findAll();
void findByPrimaryKey(Object paramObject);
int getDBState();
ResParm save();
ResParm translateAllDbDesc(String paramString);
String getReqIpAddress();
void setReqIpAddress(String paramString);
boolean useDescLangTables();
boolean isGoogleTranslatorEnable();
void setDescTxtLangValues(Vector<DescLangItem> paramVector);
String getCurrentFocus();
String getCurrentLang();
String getCurrentTab();
String getLastUpdTmstString();
String getLastUpdTmstForFiles();
String get_Id();
String get_IdName();
String getReqUrl();
String getSqlQuery();
}

View file

@ -0,0 +1,135 @@
package com.ablia.db;
public class DriversJdbc {
public static final String SLQSTATE_COMMUNICATION_ERROR = "08S01";
public static final String SLQSTATE_SQLSERVER_LOCK_REQUEST_TIME_EXEDEED = "S0003";
public static final String SLQSTATE_INTEGRITY_CONSTRAINT_VIOLATION = "23000";
public static final String MYSQL_UTF8_CONNECTION_STRING = "?useUnicode=true&characterEncoding=UTF-8";
private static final int TOT_NUMBER_OF_DRIVERS = 17;
public static final int JDBC_ODBC = 0;
public static final int ORACLE = 1;
public static final int HSQLDB = 2;
public static final int MYSQL_CONNECTORJ = 3;
public static final int POSTGRES = 4;
public static final int MARIA_DB = 5;
public static final int SYBASE = 6;
public static final int INTERBASE = 7;
public static final int DB2 = 8;
public static final int INFORMIX = 9;
public static final int ZYH_DBF = 10;
public static final int ATINAV_ACCESS = 11;
public static final int EASY_JDBC = 12;
public static final int MS_SQL_SERVER_2000 = 13;
public static final int MS_SQL_SERVER_2005_2008 = 14;
public static final int PERVASIVE_PSQL_JDBC = 15;
public static final int UCANACCESS = 16;
private static String[] driverDescription;
private static String[] driverManager;
private static String[] connectionString;
public static final String LAST_INSERT_ID_MYSQL = "Select LAST_INSERT_ID() as id ";
public static final String LAST_INSERT_ID_MS_SQL_SERVER = "SELECT @@IDENTITY AS id ";
public static final String LAST_INSERT_ID_INFORMIX = "Select dbinfo('sqlca.sqlerrd1') as id from ";
public static String getConnectionString(int i) {
if (connectionString == null) {
connectionString = new String[17];
connectionString[0] = "jdbc:odbc";
connectionString[1] = "jdbc:oracle";
connectionString[2] = "jdbc:hsqldb";
connectionString[3] = "jdbc:mysql";
connectionString[4] = "jdbc:postgresql";
connectionString[5] = "jdbc:mariadb";
connectionString[6] = "jdbc:sybase:Tds";
connectionString[7] = "jdbc:interbase";
connectionString[8] = "jdbc:db2";
connectionString[9] = "jdbc:informix-sqli";
connectionString[10] = "jdbc:DBF";
connectionString[11] = "jdbc:atinav";
connectionString[12] = "jdbc:easysoft";
connectionString[13] = "jdbc:microsoft:sqlserver";
connectionString[14] = "jdbc:sqlserver";
connectionString[15] = "jdbc:pervasive";
connectionString[16] = "jdbc:ucanaccess";
}
return connectionString[i];
}
public static String getDriverDescription(int i) {
if (driverDescription == null) {
driverDescription = new String[17];
driverDescription[0] = "JDBC-ODBC:\t<data-source-name>[;<attribute-name>=<attribute-value>] (es:UID=me;PWD=secret)";
driverDescription[1] = "ORACLE THIN: ";
driverDescription[2] = "HSQLDB DRIVER:\thsql://[hostname] (Server Mode)\n\t\t[DatabasePath] (Stand alone)";
driverDescription[3] = "jdbc:mysql://[hostname][,failoverhost...][:port]/[dbname][?param1=value1][&param2=value2]";
driverDescription[4] = "POSTGRES:\t[//[hostname]/][dbname]:";
driverDescription[5] = "MARIA DB:\t//[hostname][:port]/[DB?user=[dbuser]&password=[dbpassword]]: ";
driverDescription[6] = "SYBASE: ";
driverDescription[7] = "INTERBASE: ";
driverDescription[8] = "DB2: ";
driverDescription[9] = "INFORMIX IFX:\t[//][host]:[port]/[dbname]:INFORMIXSERVER=[dbservername]: ";
driverDescription[10] = "ZYH DBF-FOXPRO:\t/[path to dbf files] or [//][host][:port]/[DatabasePath]: ";
driverDescription[11] = "ATINAV-ACCESS:\t[hostname]:[serverportno]:[databasepath] (port usually is 7227): ";
driverDescription[12] = "EasySoft JDBC-ODBC:\t//[hostname]/[DSN]: ";
driverDescription[13] = "MS Sql Server 2000 JDBC driver:\t//[hostname]:1433;databaseName=[dbname];user=[dbuser];password=[dbpassword];: ";
driverDescription[14] = "MS Sql Server 2005/2008 JDBC driver:\t//[hostname]:1433;databaseName=[dbname];user=[dbuser];password=[dbpassword];: ";
driverDescription[15] = "Pervasive PSQL 10 JDBC driver:\t//[hostname]:1583/[DATABASE][;encoding=;encrypt=;encryption=] ";
driverDescription[16] = "UCanAccess JDBC driver:\t//db_or_accdb_file_path";
}
return driverDescription[i];
}
public static String getDriverManager(int i) {
if (driverManager == null) {
driverManager = new String[17];
driverManager[0] = "sun.jdbc.odbc.JdbcOdbcDriver";
driverManager[1] = "oracle.jdbc.ddndlthin";
driverManager[2] = "org.hsqldb.jdbcDriver";
driverManager[3] = "com.mysql.jdbc.Driver";
driverManager[4] = "org.postgresql.Driver";
driverManager[5] = "org.mariadb.jdbc.Driver";
driverManager[6] = "com.sybase.jdbc.SybDriver";
driverManager[7] = "interbase.interclient.Driver";
driverManager[8] = "COM.ibm.db2.jdbc.app.DB2Driver";
driverManager[9] = "com.informix.jdbc.IfxDriver";
driverManager[10] = "zyh.sql.dbf.DBFDriver";
driverManager[11] = "acs.jdbc.Driver";
driverManager[12] = "easysoft.sql.jobDriver";
driverManager[13] = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
driverManager[14] = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
driverManager[15] = "com.pervasive.jdbc.v2.Driver";
driverManager[16] = "net.ucanaccess.jdbc.UcanaccessDriver";
}
return driverManager[i];
}
public static int getTotNumberOfDrivers() {
return 17;
}
}

View file

@ -0,0 +1,57 @@
package com.ablia.db;
public class EncodedField {
public static final long MODALITA_MASTER = 0L;
public static final long MODALITA_USER = 1L;
public EncodedField(boolean codifica, long flgAlgoritmo, long modalita) {
this.flgAlgoritmo = flgAlgoritmo;
this.codifica = codifica;
this.flgModalita = modalita;
}
private long flgAlgoritmo = 1L;
private boolean codifica = false;
private long flgModalita;
public EncodedField() {}
public long getFlgAlgoritmo() {
return this.flgAlgoritmo;
}
public void setFlgAlgoritmo(long flgAlgoritmo) {
this.flgAlgoritmo = flgAlgoritmo;
}
public boolean isCodifica() {
return this.codifica;
}
public void setCodifica(boolean codifica) {
this.codifica = codifica;
}
public long getFlgModalita() {
return this.flgModalita;
}
public void setFlgModalita(long modalita) {
this.flgModalita = modalita;
}
public String getEncodedFieldsPrefix() {
return String.valueOf(getFlgModalita()) + "," + getFlgAlgoritmo() + ",0";
}
public static final String getModalita(long l_flgModalita) {
if (l_flgModalita == 0L)
return "Master Key";
if (l_flgModalita == 1L)
return "User";
return "";
}
}

View file

@ -0,0 +1,18 @@
package com.ablia.db;
import java.util.Comparator;
import java.util.Map;
public class FieldsComparator implements Comparator<Object> {
Map<String, FieldsDescriptor> map;
public FieldsComparator(Map<String, FieldsDescriptor> map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
if (this.map.get(o1).getOrder() == this.map.get(o2).getOrder())
return 1;
return Long.valueOf(this.map.get(o1).getOrder()).compareTo(Long.valueOf(this.map.get(o2).getOrder()));
}
}

View file

@ -0,0 +1,50 @@
package com.ablia.db;
public class FieldsDescriptor {
private String fieldName;
private long order;
private String desc;
private String val;
public FieldsDescriptor(String fieldName, long order, String desc, String val) {
this.fieldName = fieldName;
this.order = order;
this.desc = desc;
this.val = val;
}
public String getFieldName() {
return (this.fieldName == null) ? "" : this.fieldName.trim();
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public long getOrder() {
return this.order;
}
public void setOrder(long order) {
this.order = order;
}
public String getDesc() {
return (this.desc == null) ? "" : this.desc.trim();
}
public void setDesc(String desc) {
this.desc = (desc == null) ? "" : desc.trim();
}
public String getVal() {
return (this.val == null) ? "" : this.val.trim();
}
public void setVal(String val) {
this.val = val;
}
}

View file

@ -0,0 +1,88 @@
package com.ablia.db;
import com.ablia.util.Debug;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcStub extends Debug {
private boolean isRegistered;
private Statement stmt;
private ResultSet rst;
private Connection conn;
private ApplParm ap;
public JdbcStub(ApplParm applparm) throws SQLException {
this.isRegistered = false;
this.ap = applparm;
if (!this.isRegistered)
synchronized (this) {
try {
Class.forName(this.ap.getDriverManager()).newInstance();
} catch (Exception exception) {
System.err.println("Errore: " + exception.getMessage());
}
this.isRegistered = true;
}
String s = String.valueOf(this.ap.getConnectionString()) + ":" + this.ap.getDatabase();
handleDebug("Connecting... with " + s + " user:" + this.ap.getUser() + " Pwd:" + this.ap.getPassword());
if (this.ap.getUser().isEmpty()) {
setConn(DriverManager.getConnection(s));
} else {
setConn(DriverManager.getConnection(s, this.ap.getUser(), this.ap.getPassword()));
}
handleDebug("Connessione ok");
}
public JdbcStub(Connection connection) {
this.isRegistered = false;
this.conn = connection;
}
public void Close() throws SQLException {
if (this.stmt != null)
this.stmt.close();
}
public ResultSet ExecuteQuery(String s) throws SQLException {
try {
this.stmt = this.conn.createStatement();
this.rst = this.stmt.executeQuery(s);
return this.rst;
} catch (SQLException _ex) {
throw _ex;
}
}
public int ExecuteUpdate(String s) throws SQLException {
Close();
try {
this.stmt = this.conn.createStatement();
int i = this.stmt.executeUpdate(s);
return i;
} catch (SQLException sqlexception) {
sqlexception.printStackTrace(System.out);
throw new SQLException();
} finally {
this.stmt.close();
}
}
protected void finalize() throws SQLException {
Close();
}
public Connection getConn() {
return this.conn;
}
public void setConn(Connection connection) {
this.conn = connection;
}
}

View file

@ -0,0 +1,44 @@
package com.ablia.db;
public class OrString {
private static final String OR = " OR ";
private static final String SPACE = " ";
private StringBuffer theString;
private static final String START = " (";
private static final String STOP = ") ";
public String toString() {
return String.valueOf(getTheString().toString()) + ") ";
}
public void addOr(String l_or) {
if (!l_or.trim().isEmpty()) {
if (getTheString().length() == 0) {
getTheString().append(" (");
} else {
getTheString().append(" OR ");
}
getTheString().append(" ");
getTheString().append(l_or);
}
}
private StringBuffer getTheString() {
if (this.theString == null)
this.theString = new StringBuffer();
return this.theString;
}
public static final String prepareSqlStatement(String sqlString) {
int idx = sqlString.indexOf('\'');
while (idx != -1) {
sqlString = String.valueOf(sqlString.substring(0, idx)) + "'" + sqlString.substring(idx, sqlString.length());
idx = sqlString.indexOf('\'', idx + 2);
}
return sqlString;
}
}

View file

@ -0,0 +1,140 @@
package com.ablia.db;
import com.ablia.util.Out;
import java.util.Vector;
public class ResParm {
private String msg;
private Vector vec;
private long errorCode = 0L;
private Exception exception;
private boolean status;
private String infoMsg;
private Object returnObj;
public ResParm() {}
public ResParm(boolean l_status, String l_msg) {
setStatus(l_status);
setMsg(l_msg);
}
public ResParm(boolean l_status) {
setStatus(l_status);
setMsg("");
}
public ResParm(boolean l_status, Exception e) {
setStatus(l_status);
setException(e);
setMsg(e.getMessage());
}
public String getMsg() {
return (this.msg == null) ? "" : this.msg;
}
public boolean getStatus() {
return this.status;
}
public Vector getVec() {
return this.vec;
}
public void appendMsg(String s) {
setMsg(String.valueOf(getMsg()) + s);
}
public void append(ResParm rp2) {
setStatus((getStatus() && rp2.getStatus()));
if (getMsg().isEmpty()) {
if (!rp2.getMsg().isEmpty())
setMsg(rp2.getMsg());
} else if (!rp2.getMsg().isEmpty()) {
setMsg(String.valueOf(getMsg()) + "->" + rp2.getMsg());
}
if (getInfoMsg().isEmpty()) {
if (!rp2.getInfoMsg().isEmpty())
setInfoMsg(rp2.getInfoMsg());
} else if (!rp2.getInfoMsg().isEmpty()) {
setInfoMsg(String.valueOf(getInfoMsg()) + "->" + rp2.getInfoMsg());
}
setReturnObj(rp2.getReturnObj());
setVec(rp2.getVec());
}
public void setStatus(boolean flag) {
this.status = flag;
}
public void setVec(Vector vector) {
this.vec = vector;
}
public Exception getException() {
return this.exception;
}
public String getExceptionStackTrace() {
if (getException() != null) {
Out o = new Out(System.out);
getException().printStackTrace(o);
return String.valueOf(getException().toString()) + "\n" + o.getMsg();
}
return "";
}
public void setException(Exception exception) {
this.exception = exception;
}
public void setMsg(String s) {
this.msg = s;
}
public void setMsg(Exception e) {
setException(e);
this.msg = String.valueOf(e.toString()) + ": " + e.getMessage();
}
public long getErrorCode() {
return this.errorCode;
}
public void setErrorCode(long errorCode) {
this.errorCode = errorCode;
}
public String getErrMsg() {
if (!getStatus() && getMsg().toLowerCase().indexOf("erro") < 0)
return "Error! " + getMsg();
return getMsg();
}
public String getInfoMsg() {
return (this.infoMsg == null) ? "" : this.infoMsg;
}
public void setInfoMsg(String infoMsg) {
this.infoMsg = infoMsg;
}
public void appendInfoMsg(String s) {
setInfoMsg(String.valueOf(getInfoMsg()) + s);
}
public Object getReturnObj() {
return this.returnObj;
}
public void setReturnObj(Object returnObj) {
this.returnObj = returnObj;
}
}

View file

@ -0,0 +1,84 @@
package com.ablia.db;
import com.ablia.util.Vectumerator;
public class RewriteRule {
private String cmd;
private String servlet;
private String code;
private Vectumerator parms;
private String act;
private Vectumerator constValues;
private Vectumerator constParms;
public String getCmd() {
return this.cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getAct() {
return this.act;
}
public void setAct(String act) {
this.act = act;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public Vectumerator getParms() {
return this.parms;
}
public void setParms(Vectumerator parms) {
this.parms = parms;
}
public String getServlet() {
return this.servlet;
}
public void setServlet(String servlet) {
this.servlet = servlet;
}
public String getParm(int idx) {
if (getParms() != null) {
if (idx < getParms().getTotNumberOfRecords())
return getParms().get(idx);
return null;
}
return null;
}
public Vectumerator getConstValues() {
return this.constValues;
}
public void setConstValues(Vectumerator values) {
this.constValues = values;
}
public Vectumerator getConstParms() {
return this.constParms;
}
public void setConstParms(Vectumerator constParms) {
this.constParms = constParms;
}
}

View file

@ -0,0 +1,88 @@
package com.ablia.db;
public class WcString {
private static final String GROUP_BY = " GROUP BY";
private static final String WHERE = " WHERE";
private static final String SPACE = " ";
private StringBuffer theString;
private StringBuffer theGroupBy;
private static final String AND = " AND ";
private static final String HAVING = " HAVING";
public String toString() {
return String.valueOf(getTheGroupBy().toString()) + " " + getTheString().toString();
}
public void addWc(String l_wc) {
if (!l_wc.trim().isEmpty()) {
if (getTheString().length() == 0) {
getTheString().append(" WHERE");
} else {
getTheString().append(" AND ");
}
getTheString().append(" ");
getTheString().append(l_wc);
}
}
public void addHavingWc(String l_wc) {
if (getTheString().length() == 0) {
getTheString().append(" HAVING");
} else {
getTheString().append(" AND ");
}
getTheString().append(" ");
getTheString().append(l_wc);
}
private StringBuffer getTheString() {
if (this.theString == null)
this.theString = new StringBuffer();
return this.theString;
}
public void addGroupBy(String l_column) {
if (!l_column.trim().isEmpty()) {
if (getTheGroupBy().length() == 0) {
getTheGroupBy().append(" GROUP BY");
} else {
getTheGroupBy().append(",");
}
getTheGroupBy().append(" ");
getTheGroupBy().append(l_column);
}
}
private StringBuffer getTheGroupBy() {
if (this.theGroupBy == null)
this.theGroupBy = new StringBuffer();
return this.theGroupBy;
}
public String toStringWOWhere() {
if (getTheString().length() == 0)
return getTheString().toString();
return getTheString().toString().substring(
" WHERE".length() + " ".length());
}
public void setWhere(String l_whereCondition) {
this.theString = new StringBuffer(l_whereCondition);
}
public static final String prepareSqlStatement(String sqlString) {
int idx = sqlString.indexOf('\'');
while (idx != -1) {
sqlString = String.valueOf(sqlString.substring(0, idx)) + "'" +
sqlString.substring(idx, sqlString.length());
idx = sqlString.indexOf('\'', idx + 2);
}
return sqlString;
}
}

View file

@ -0,0 +1,87 @@
package com.ablia.db;
import com.ablia.util.FileWr;
import java.io.IOException;
public class XmlTableExporter {
private static final String START_DB = "<export-database name='";
private static final String END_DB = "</export-database>";
private static final String START_FILE = "<dbadapter>";
private static final String START_TABLE = "<table name='";
private static final String END_TABLE = "</table>";
private static final String END_FILE = "</dbadapter>";
private static final String START_ROW = "<row>";
private static final String END_ROW = "</row>";
private static final String START_COL = "<col name='";
private static final String END_COL = "</col>";
private static final String START_CDATA = "<![CDATA[";
private static final String END_CDATA = "]]>";
private static final String CLOSING_WITH_TICK = "'>";
private FileWr _fw;
public XmlTableExporter(FileWr fw) {
this._fw = fw;
}
public void close() throws IOException {
if (this._fw != null)
this._fw.closeFile();
}
public void startDbExport(String dbName) throws IOException {
String stg = "<export-database name='" + dbName + "'>";
this._fw.writeLine(stg);
}
public void endDbExport() throws IOException {
this._fw.writeLine("</export-database>");
}
public void startTable(String tableName) throws IOException {
String stg = "<table name='" + tableName + "'>";
this._fw.writeLine(stg);
}
public void endTable() throws IOException {
this._fw.writeLine("</table>");
}
public void endFile() throws IOException {
this._fw.writeLine("</dbadapter>");
}
public void startRow() throws IOException {
this._fw.writeLine("<row>");
}
public void endRow() throws IOException {
this._fw.writeLine("</row>");
}
public void addColumn(String name, String val) throws IOException {
String stg;
if (val != null && (val.indexOf("<") > 0 || val.indexOf(">") > 0)) {
stg = "<col name='" + name + "'>" + "<![CDATA[" + val + "]]>" + "</col>";
} else {
stg = "<col name='" + name + "'>" + val + "</col>";
}
this._fw.writeLine(stg);
}
public void startFile() throws IOException {
this._fw.writeLine("<dbadapter>");
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

View file

@ -0,0 +1,170 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<!-- #BeginTemplate "/Templates/packageSpec.dwt" -->
<head>
<!--
@(#)package.html 1.60 98/01/27
Copyright 1998 Sun Microsystems, Inc. 901 San Antonio Road,
Palo Alto, California, 94303, U.S.A. All Rights Reserved.
This software is the confidential and proprietary information of Sun
Microsystems, Inc. ("Confidential Information"). You shall not
disclose such Confidential Information and shall use it only in
accordance with the terms of the license agreement you entered into
with Sun.
CopyrightVersion 1.2
-->
</head>
<body bgcolor="white">
<h2>Package <!-- #BeginEditable "nomePackage" -->com.ablia.db<!-- #EndEditable -->
description </h2>
<!-- #BeginEditable "packageSpec" -->
<p>Provide an architecture for database access.<br>
Here is an example about the use of the classes under this package. We start
with a simple database like this:</p>
<p><img src="demo.gif" width="597" height="357"></p>
<p>Here we have:</p>
<ul>
<li>2 kernel entity (SUPPLIER and ITEM)</li>
<li>1 association entity (ITEM_SUPPLIER) with 2primary/foreign key</li>
<li>1 attribute entity (SUPPLIER_TYPE)</li>
</ul>
<p>You should name your entity like this:</p>
<ul>
<li>all the entity (tables) singolar and capitalized;</li>
<li>the primary key like &quot;id_[name_of_the_entity_lowercased]&quot;. If
an entity has a two-part name (like SUPPLIER_TYPE), the primary key should
be &quot;id_[first_part_lowercased][second_part_with_first_letter_capitalized][<i>and
so on</i>]&quot;. </li>
</ul>
<p>If you use these rules, you can use com.ablia.tools.Db2Bean class to automatically
create your beans from a created database. Otherwhise you should create your
bean manually inheriting the class com.ablia.DBAdapter and writing by hands
all the abstract method.<br>
The create statements for the database we use as example are (for a mysql database):<code><br>
CREATE TABLE ITEM(<br>
id_item VARCHAR(30) NOT NULL,<br>
price DECIMAL(18,4),<br>
description VARCHAR(30),<br>
nota TEXT,<br>
PRIMARY KEY (id_item),<br>
UNIQUE UC_id_item (id_item));</code></p>
<p><code><br>
CREATE TABLE SUPPLIER_TYPE(<br>
id_supplierType VARCHAR(4) NOT NULL,<br>
description VARCHAR(60),<br>
PRIMARY KEY (id_supplierType),<br>
UNIQUE UC_id_supplierType (id_supplierType));</code></p>
<p><code><br>
CREATE TABLE SUPPLIER(<br>
id_supplier INT NOT NULL AUTO_INCREMENT,<br>
name VARCHAR(60),<br>
address VARCHAR(60),<br>
tel VARCHAR(30),<br>
fax VARCHAR(30),<br>
eMail VARCHAR(30),<br>
city VARCHAR(30),<br>
state VARCHAR(30),<br>
nota TEXT,<br>
id_supplierType VARCHAR(4) NOT NULL,<br>
FOREIGN KEY (id_supplierType) REFERENCES SUPPLIER_TYPE (id_supplierType),<br>
PRIMARY KEY (id_supplier));</code></p>
<p><code><br>
CREATE TABLE ITEM_SUPPLIER(<br>
price DECIMAL(18,4),<br>
id_item VARCHAR(30) NOT NULL,<br>
id_supplier INT NOT NULL,<br>
FOREIGN KEY (id_item) REFERENCES ITEM (id_item),<br>
FOREIGN KEY (id_supplier) REFERENCES SUPPLIER (id_supplier),<br>
PRIMARY KEY (id_item,id_supplier));</code></p>
<p>Just cut and paste on the mysql client console to create it (You have to create
a demo database with a statement like this</p>
<p><code>mysqladmin -uroot -proot create demo</code></p>
<p>Once you have created the database, lets use Db2Bean class to create the access
bean. Here is the console on a Feebsd:</p>
<p><code>test# /usr/local/linux-jdk1.2.2/bin/java -cp /usr/local/linux-jdk1.2.2/jre/lib/rt.jar:/usr/local/ablia/java/lib/ablia.jar:/usr/local/ablia/java/lib/mysql.jar:/usr/local/ablia/java/classes/
com.ablia.tools.Db2Bean<br>
Jdbc connection.....<br>
Choose the Jdbc driver (it must be in your classpath):<br>
(0) JDBC-ODBC:<br>
(1) ORACLE THIN:<br>
(2) IDB DRIVER:<br>
(3) TWZ MYSQL:<br>
(4) POSTGRES:<br>
(5) MM MYSQL: //[hostname]/[dbname]:<br>
(6) SYBASE:<br>
(7) INTERBASE:<br>
(8) DB2:<br>
(9) INFORMIX IFX: [//][host]:[port]/[dbname]:INFORMIXSERVER=[dbservername]:<br>
(10) ZYH DBF-FOXPRO: /[path to dbf files] or [//][host][:port]/[DatabasePath]:<br>
Driver=5<br>
jdbc resource: MM MYSQL: //[hostname]/[dbname]: //localhost/demo<br>
Login: root<br>
Password: root<br>
Output path:(c:/000) /tmp<br>
Package: com.demo<br>
creating table bean ITEM.....Done<br>
creating table bean ITEM_SUPPLIER.....Done<br>
creating table bean SUPPLIER.....Done<br>
creating table bean SUPPLIER_TYPE.....Done<br>
Creating key classes ITEM_SUPPLIER ........Done<br>
bye</code><br>
</p>
<p>In /tmp we should have these classes:</p>
<p><code>Item.java<br>
ItemSupplier.java<br>
ItemSupplierKey.java<br>
Supplier.java<br>
SupplierType.java</code><br>
</p>
<p>These classes ar just a start point. You should develop your own method just
like a find method with a corresponding [bean]CR class (CR stands for search
criteria) like this:</p>
<p><code>public com.ablia.util.Vectumerator findItemsByCR(<br>
com.demo.ItemCR CR,<br>
int pageNumber,<br>
int pageRows)<br>
throws com.ablia.db.DBAdapterException, java.sql.SQLException<br>
{<br>
//////////////////////////////////////////////////<br>
// serach statement<br>
//////////////////////////////////////////////////<br>
String s_Sql_Find = &quot;select DISTINCT A.* from ITEM AS A&quot;;<br>
//////////////////////////////////////////////////<br>
String s_Sql_Order = &quot; order by A.description&quot;;</code></p>
<p><code> // search condition<br>
String wc = &quot;&quot;; // where dataFineVld is null&quot;;<br>
if (!CR.getDescription().equals(&quot;&quot;))<br>
&nbsp;&nbsp;&nbsp;&nbsp;wc = buildWc(wc, &quot;A.description like'&quot; + CR.getDescription()+&quot;%'&quot;);<br>
//other search criteria</code></p>
<p><code><br>
java.sql.PreparedStatement stmt =<br>
getConn().prepareStatement(s_Sql_Find + wc + s_Sql_Order);</code></p>
<p><code> </code><code>return findRows(stmt, pageNumber, pageRows);</code></p>
<p><code>}</code></p>
<p>The <code>findRows(stmt, pageNumber, pageRows);</code> return a Vectumerator
(something like a Vector and an enumeration) with information about the tot
number of records, the page we ar fetching and how many rows contain a page.
This is usefull for page next / page previous command with jsp. You can use
for this the nextVec, prevVec and pageList tag in com.ablia.taglib package.</p>
<p>To use the bean you just create you should:</p>
<ul>
<li>crate an com.ablia.db.ApplParm object with all necessary parameters to connect
to a database (see the ApplParm constructor);</li>
<li>Create the bean (com.demo.Item item = new com.demo.Item(ap);)</li>
<li>Just use the bean: set some properties, save it, find all the objects/rows
of the table, find by primary key, delete an object/row, and so on</li>
</ul>
<p>Today, on march 2002, there are about 10/15 applications that use this architecture,
for web site or for intranet application.</p>
<!-- #EndEditable -->
<h2>&nbsp;</h2>
<!-- Put @see and @since tags down here. -->
</body>
<!-- #EndTemplate -->
</html>

File diff suppressed because it is too large Load diff