Configure Tomcat 8 with Postgres - postgresql

I want to configure Tomcat 8 with PostgreSQL
I added this in context.xml
<Resource name="jdbc/DefaultDB" auth="Container" type="javax.sql.DataSource"
username="postgres" password="qwerty"
url="jdbc:postgresql://localhost:5432/crm"
driverClassName="org.postgresql.Driver"
initialSize="5" maxWait="5000"
maxActive="120" maxIdle="5"
validationQuery="select 1"
poolPreparedStatements="true"/>
And I tried to run this Java code:
public String init()
{
String user_name = null;
try
{
Context ctx = new InitialContext();
if (ctx == null)
throw new Exception("Boom - No Context");
DataSource ds = (DataSource) ctx.lookup("jdbc/DefaultDB");
if (ds != null)
{
Connection conn = ds.getConnection();
if (conn != null)
{
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select id, user_name from user where username = " + user);
if (rst.next())
{
user_name = rst.getString("user_name");
}
conn.close();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return user_name;
}
But for some reason after I added this code Tomcat is not starting. Do you have any idea where I'm wrong?
I get this in Tomcat log file:
28-Mar-2016 10:37:07.955 WARNING [localhost-startStop-1] org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory.getObjectInstance Name = DefaultDB Property maxActive is not used in DBCP2, use maxTotal instead. maxTotal default value is 8. You have set value of "120" for "maxActive" property, which is being ignored.
28-Mar-2016 10:37:07.956 WARNING [localhost-startStop-1] org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory.getObjectInstance Name = DefaultDB Property maxWait is not used in DBCP2 , use maxWaitMillis instead. maxWaitMillis default value is -1. You have set value of "5000" for "maxWait" property, which is being ignored.
javax.naming.NameNotFoundException: Name [jdbc/DefaultDB] is not bound in this Context. Unable to find [jdbc].

as #a_horse_with_no_name says, your lookup is wrong. your code must be like this:
public String init()
{
String user_name = null;
try
{
Context ctx = new InitialContext();
if (ctx == null)
throw new Exception("Boom - No Context");
Context envCtx = (Context) ctx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/DefaultDB");
if (ds != null)
{
Connection conn = ds.getConnection();
if (conn != null)
{
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select id, user_name from user where username = " + user);
if (rst.next())
{
user_name = rst.getString("user_name");
}
conn.close();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return user_name;
}

Related

Column <<column_name>> not found when using ADO-NET connection for Postgresql in insert query

I have problem when using ADO.NET connection for PostgreSQL. I have tried this query using PSQLODBC driver 12.000.000 both ANSI and Unicode. I use PostgreSQL v.9.5. I notice the column name has "_" in its name.
When I use the Select query, the connection successfully execute it. The query return variables as I want.
using (OdbcConnection conn = (OdbcConnection)Dts.Connections["XXX"].AcquireConnection(Dts.Transaction))
{
try
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
}
catch (Exception e)
{
String err = e.Message.ToString();
Console.WriteLine(err);
}
try
{
OdbcCommand cmd = new OdbcCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT XX FROM <<table>> where <<params>>";
...
OdbcDataReader rdd = cmd.ExecuteReader();
while (rdd.Read())
{
<<read operation here>>;
}
conn.Close();
}
catch (Exception ers)
{
<<catch operation here>>;
}
}
But when I use Insert query, it failed to check the column name, even the column are exist in my PostgreSQL tables:
using (OdbcConnection conn2 = (OdbcConnection)Dts.Connections["OJK_REPORTING_DEV"].AcquireConnection(Dts.Transaction))
{
try
{
if (conn2.State != ConnectionState.Open)
{
conn2.Open();
}
}
catch (Exception e)
{
string x = e.Message.ToString();
}
try
{
OdbcCommand cmd = new OdbcCommand();
cmd.Connection = conn2;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO <<table>>(<<column>>)VALUES(<<params>>)";
<<cmd.Parameters.AddWithValue here>>;
cmd.ExecuteNonQuery();
conn2.Close();
}
catch (Exception e)
{
<<exception catch here>>;
}
}
When I debug this line, I get this error:
ERROR[42703] ERROR: column <> not found, error while executing the query
Right, after several research, I've got an answer. Since i use PostgreSQL ODBC, the query parameters are not using #<name> inside the query, but using ?, so you need to formulate the query like
INSERT INTO <TABLE_NAME> (<COLUMNS>) VALUE ?
and call the parameters
cmd.AddWithValue("#<name>",<value>)

Master -Slave Database Configuration With Hikari Pool

I have two DataSource Beans one with #Primary annotation.
Individual Hikari pools are created for every DataSource.
I am trying to change the HikariDataSource from Pool 1(if connection is not available) to Pool 2 .
#Primary
#Bean(destroyMethod = "close", name = "dataSource")
public CustomHikariDataSource dataSource() throws SQLException {
try {
primaryDataSource = mainDataSource();
} catch (Exception e) {
primaryDataSource = secondaryDataSource();
}
HikariConfig config = new HikariConfig();
config.setDataSource(primaryDataSource);
config.setPoolName("POOL_PRIMARY");
config.setAllowPoolSuspension(true);
config.setIdleTimeout(10000);
config.setMaxLifetime(30000);
return new CustomHikariDataSource(config);
}
#Bean(destroyMethod = "close", name = "failoverDataSource")
public CustomHikariDataSource failoverDataSource() throws SQLException {
secondaryDataSource = secondaryDataSource();
HikariConfig config = new HikariConfig();
config.setDataSource(secondaryDataSource);
config.setPoolName("POOL_SECONDARY");
config.setAllowPoolSuspension(true);
return new CustomHikariDataSource(config);
}
private DataSource mainDataSource() {
return dataSourceProperties().initializeDataSourceBuilder().build();
}
private DataSource secondaryDataSource() {
return failoverDataSourceProperties().initializeDataSourceBuilder().build();
}
Where is the actual Problem?
Finally i am able to achieve it by Overriding getConnection() method from HikariDataSource.class
#Override
public Connection getConnection() throws SQLException {
if (isClosed()) {
throw new SQLException("HikariDataSource " + this + " has been closed.");
}
if (fastPathPool != null && (fastPathPool.poolState == 0 || fastPathPool.poolState == 1)) {
try {
fastPathPool.resumePool();
con = fastPathPool.getConnection();
} catch (Exception e) {
}
if (con.isClosed()) {
config = pool.config;
fastPathPool.suspendPool();
} else
return con;
}
config.setDataSource(dataSource);
config.setAllowPoolSuspension(true);
config.setMinimumIdle(minIdle);
pool = new HikariPool(config);
HikariPool result = pool;
if (result == null) {
synchronized (this) {
result = pool;
if (result == null) {
validate();
System.out.println("{} - Starting..." + getPoolName());
try {
pool = result = new HikariPool(this);
this.seal();
} catch (PoolInitializationException pie) {
if (pie.getCause() instanceof SQLException) {
throw (SQLException) pie.getCause();
} else {
throw pie;
}
}
System.out.println("{} - Start completed." + getPoolName());
}
}
}
return result.getConnection();
}
For complete class ,feel free to ping me.
Happy Coding ! :)

Junit testing for database conection

Is there a way to test below code.Here I am connecting to database with JNDI.I am new to mockito and not getting a way to test the same.
#SuppressWarnings("unused")
public Connection getJNDIConnection() {
Connection result = null;
try {
InitialContext initialContext = new InitialContext();
if (initialContext == null) {
LOGGER.info("JNDI problem. Cannot get InitialContext.");
}
DataSource datasource = (DataSource) initialContext.lookup(jndiName);
if (datasource != null) {
result = datasource.getConnection();
} else {
LOGGER.info("Failed to lookup datasource.");
}
} catch (NamingException ex) {
LOGGER.error("Cannot get connection: " + ex);
} catch (SQLException ex) {
LOGGER.error("Cannot get connection: " + ex);
}
return result;
}
Of course, you can to do it, but I think you should read the documentation yourself. The main points here is:
InitialContext initialContext = mock(InitialContext.class);
DataSource dataSource = mock(DataSource.class);
Connection expected = mock(Connection.class);
whenNew(InitialContext.class).withNoArguments().thenReturn(initialContext);
when(initialContext.lookup(jndiName)).thenReturn(dataSource);
when(initialContext.getConnection()).thenReturn(connection);
Connection result = intatnceOfCalss.getJNDIConnection();
assertSame("Should be equals", expected, result);
Also you should use PowerMock to mock constructors and static methods. To have deal with Logger, just add this code:
#BeforeClass
public static void setUpClass() {
mockStatic(LoggerFactory.class);
Logger logger = mock(Logger.class);
when(LoggerFactory.getLogger(ApplySqlFileIfExistsChange.class)).thenReturn(logger);
}
Don't forget about annotations:
#RunWith(PowerMockRunner.class)
#PrepareForTest({LoggerFactory.class})
Try to read this doc http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html

Login error when input wrong credentials " An unhandled exception occurred during the execution of the current web request

These in ASP.NET application of which I am starting to learn. There is an error stating System.IndexOutOfRangeException: UserId.
Here is the code:
protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string roles = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Username", Login1.UserName);
cmd.Parameters.AddWithValue("#Password", Login1.Password);
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
userId = Convert.ToInt32(reader["UserId"]);
roles = reader["Roles"].ToString();
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
case -2:
Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, roles, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet));
break;
}
}
}
}
}
Here is the Image to the error
Error message

How update DB table with DataSet

I am begginer with ADO.NET , I try update table with DataSet.
O client side I have dataset with one table. I send this dataset on service side (it is ASP.NET Web Service).
On Service side I try update table in database, but it dont 't work.
public bool Update(DataSet ds)
{
SqlConnection conn = null;
SqlDataAdapter da = null;
SqlCommand cmd = null;
try
{
string sql = "UPDATE * FROM Tab1";
string connStr = WebConfigurationManager.ConnectionStrings["Employees"].ConnectionString;
conn = new SqlConnection(connStr);
conn.Open();
cmd=new SqlCommand(sql,conn);
da = new SqlDataAdapter(sql, conn);
da.UpdateCommand = cmd;
da.Update(ds.Tables[0]);
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn != null)
conn.Close();
if (da != null)
da.Dispose();
}
}
Where can be problem?
It is better to look how really ADO.Net dataset works.
http://support.microsoft.com/kb/308507