use of org.wso2.carbon.ndatasource.rdbms.RDBMSDataSource in project jaggery by wso2.
the class DatabaseHostObject method jsConstructor.
public static Scriptable jsConstructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr) throws ScriptException {
int argsCount = args.length;
DatabaseHostObject db = new DatabaseHostObject();
// args count 1 for dataSource name
if (argsCount != 1 && argsCount != 3 && argsCount != 4) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, hostObjectName, argsCount, true);
}
if (!(args[0] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "1", "string", args[0], true);
}
if (argsCount == 1) {
String dataSourceName = (String) args[0];
DataSourceManager dataSourceManager = new DataSourceManager();
try {
CarbonDataSource carbonDataSource = dataSourceManager.getInstance().getDataSourceRepository().getDataSource(dataSourceName);
DataSource dataSource = (DataSource) carbonDataSource.getDSObject();
db.conn = dataSource.getConnection();
db.context = cx;
return db;
} catch (DataSourceException e) {
log.error("Failed to access datasource " + dataSourceName, e);
} catch (SQLException e) {
log.error("Failed to get connection", e);
}
}
if (!(args[1] instanceof String)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "2", "string", args[1], true);
}
if (!(args[2] instanceof String) && !(args[2] instanceof Integer)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "3", "string", args[2], true);
}
NativeObject configs = null;
if (argsCount == 4) {
if (!(args[3] instanceof NativeObject)) {
HostObjectUtil.invalidArgsError(hostObjectName, hostObjectName, "4", "object", args[3], true);
}
configs = (NativeObject) args[3];
}
String dbUrl = (String) args[0];
RDBMSConfiguration rdbmsConfig = new RDBMSConfiguration();
try {
if (configs != null) {
Gson gson = new Gson();
rdbmsConfig = gson.fromJson(HostObjectUtil.serializeJSON(configs), RDBMSConfiguration.class);
}
if (rdbmsConfig.getDriverClassName() == null || rdbmsConfig.getDriverClassName().equals("")) {
rdbmsConfig.setDriverClassName(getDriverClassName(dbUrl));
}
rdbmsConfig.setUsername((String) args[1]);
rdbmsConfig.setPassword((String) args[2]);
rdbmsConfig.setUrl(dbUrl);
try {
rdbmsDataSource = new RDBMSDataSource(rdbmsConfig);
} catch (DataSourceException e) {
throw new ScriptException(e);
}
db.conn = rdbmsDataSource.getDataSource().getConnection();
db.context = cx;
return db;
} catch (SQLException e) {
String msg = "Error connecting to the database : " + dbUrl;
log.warn(msg, e);
throw new ScriptException(msg, e);
}
}
Aggregations