Tomcat and MYSQL porting to AWS - java

I have a working java 7 app that runs on tomcat 7 and MYSQL. I am trying to get it running on the basic (free tier) platform offered by Amazon AWS. I have succesfully loaded data to the RDS instance of MYSQL Community and set up an Elastic Beanstalk instance where basic JSPs are running correctly.
I am new to AWS so main problem should be my lack of knowledge.
I am not able to connect to the database from my code.
This is the code I am using to create the connection pool:
package com.authz.pap;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBConnections {
private static DataSource dataSource;
private static final DBConnections instance = new DBConnections();
static
{
try
{
Context c = new InitialContext();
dataSource = (DataSource)c.lookup("java:comp/env/jdbc/authzDB");
}
catch (Exception e)
{
dataSource = null;
}
}
private DBConnections()
{
}
public static DBConnections getInstance()
{
return instance;
}
public static DataSource getGeoServDS() {
//if(dataSource==null) instance = new DBConnections();
return dataSource;
}
}
And this:
public DbCon() {
conn=null;
ProcessStatus stat = new ProcessStatus();
stat.function="DbCon.DbCon";
stat.message = "Initializing DB";
stat.retcode=0;
stat.record();
try {
conn=DBConnections.getGeoServDS().getConnection();
conn.setAutoCommit(false);
} catch (Exception e) {
stat.message = e.toString();
stat.retcode=-1;
stat.record();
}
}
And this is the content of the context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/rest">
<Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" maxActive="8" maxIdle="4" name="jdbc/authzDB" password="xxxx" type="javax.sql.DataSource" url="jdbc:mysql://x.x.x.x:3306/authzDB?autoReconnect=true&allowMultiQueries=true" username="root"/>
<ResourceLink global="jdbc/authzDB" name="jdbc/authzDB" type="javax.sql.DataSource"/>
</Context>
What I get is a java.lang.NullPointerException on DB initialization.
What am I doing wrong?
UPDATE:
This is the content of the web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" id="WebApp_ID" version="2.5">
<display-name>paprest</display-name>
<servlet>
<servlet-name>PAP rest interface</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.authz.pap.intfc</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest interface</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

Double response:
1- I have not been able to use the data from context.xml file. I have ised a different solution:
private static Connection getRemoteConnection() {
ProcessStatus stat = new ProcessStatus();
try {
Class.forName("com.mysql.jdbc.Driver");
String dbName = "xxxxDB";
String userName = "xxxxx";
String password = "xxxxxx";
String hostname = "xxxxxxxx";
String port = "3306";
String jdbcUrl = "jdbc:mysql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password + "&autoReconnect=true&allowMultiQueries=true";
Connection con = DriverManager.getConnection(jdbcUrl);
return con;
}
catch (ClassNotFoundException e) { stat.error(e.toString());}
catch (SQLException e) { stat.error(e.toString());}
return null;
}
2- I had a different problem, as the RDS instance is not to be created independently but related to the Elastic Beanstalk. This allows the comunication betwen tomcat and Mysql.

Related

NullPointerException when initiating the connection pool

I have settings in the context.xml which contain the information for the connection of my database
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<Resource
name="jdbc/*(my username)*"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
auth="Container"
type="javax.sql.DataSource"
removeAbandoned="true"
removeAbandonedTimeout="30"
maxACtive="100"
maxIdle="30"
maxWait="10000"
username= *(my username)*
password= *(my password)*
driverClassName="com.ibm.db2.jcc.DB2Driver"
url="jdbc:db2://(my server host):50000/*(my username)*">
</Resource>
</Context>
While for the Connection Pool I created a class to initiate and to connect it to the database. The error begins in the method of getConnection(). The way the error is NullPointerException in the return of the datasource.getConnection()
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ConnectionPool {
private static ConnectionPool pool = null;
private static DataSource dataSource = null;
private ConnectionPool() {
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/COMPANY");
System.out.print(dataSource);
} catch (NamingException e) {
System.out.println(e);
}
}
public static synchronized ConnectionPool getInstance() {
if (pool == null) {
pool = new ConnectionPool();
}
return pool;
}
public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
public void freeConnection(Connection c) {
try {
c.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
I tested the database connection with Eclipse's Perspective Database Development and I was able to connect and done all the queries.
In addition, it gives me this error in output
SEVERE: Unable to create initial connections of pool.
java.sql.SQLException: No suitable driver found for jdbc:db2://db2.cecsresearch.org:50000/(my username)
Although I have the jar library files in the lib folder and in the classpath.
Please download the DB2 Java driver from https://artifacts.alfresco.com/nexus/content/repositories/public/com/ibm/db2/jcc/db2jcc4/10.1/db2jcc4-10.1.jar and add it to your tomcat/lib directory. Then restart Tomcat and you should be good to go !!
The nullpointer is simply caused by the following problem:
java.sql.SQLException: No suitable driver found for jdbc:db2://db2.cecsresearch.org:50000/(my username)
Putting your database driver in $CATALINA_HOME/lib should fix the problem.
For more info, check the docs.
driverClassName (String) The fully qualified Java class name of the
JDBC driver to be used. The driver has to be accessible from the same
classloader as tomcat-jdbc.jar
You can also check the official jndi-datasource examples.

Why Wildfly does not find the postgresql driver

I am developping a multi-tier software using java. The middle tier is a java ejb accessing the postgresql database. But when I run the client java application, I have the following error messages:
INFO: EJBCLIENT000069: Using legacy jboss-ejb-client.properties security configuration
Exception in thread "main" javax.ejb.EJBException: WFLYEJB0442: Unexpected Error
....
Caused by: java.lang.NoClassDefFoundError: org/postgresql/Driver
...
Caused by: java.lang.ClassNotFoundException: org.postgresql.Driver
The content of the module.xml file is:
<?xml version="1.0" encoding="utf-8" ?>
<module xmlns="urn:jboss:module:1.3" name="org.postgresql">
<resources>
<!--the name of your driver -->
<resource-root path="postgresql-42.2.6.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
</module>
The following lines have been added to the standalone.xml file:
<driver name="postgresql" module="org.postgresql">
<driver-class>org.postgresql.Driver</driver-class>
<xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-
class>
</driver>
The driver and the module.xml are in folder \modules\org\postgresql\main. I have successfully tested my code by moving it to a single-tier java application. I am using Eclipse jee latest verion, wildfly 16, postgresql 11. the driver is postgresql-42.2.6.jar
I have already spent several days battling with the problem, but no success. Help most welcome.
package loginPackage;
import java.sql.Connection;
import java.sql.DriverManager;
import org.postgresql.Driver;
import java.sql.SQLException;
public class LoginDao {
static String errorMessage;
static String connectionResult;
public static String getConnectionResult() {
return connectionResult;
}
public static void setConnectionResult(String connectResult) {
connectionResult = connectResult;
}
public String getErrorMessage() {
return errorMessage;
}
public static void setErrorMessage(String errorMsg) {
errorMessage = errorMsg;
}
public static void LoginCheck(String userCode, String userPswd) {
setConnectionResult(userConnect(userCode, userPswd));
}
public static String userConnect(String userCode, String userPaswd) {
try {
//Connection conn = null;
setConnectionResult("OK");
setErrorMessage("OK");
Driver driver = new org.postgresql.Driver();
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/TestDb", userCode, userPaswd);
System.out.println("Connected to PostgreSQL database!");
return "SUCCESS";
}
catch (Exception e) {
System.out.println("Failed to create JDBC db connection " + e.toString() + e.getMessage());
setErrorMessage(userCode + ", " + userPaswd + ", " + e.toString() + ", " + e.getMessage() + ", " + e.getStackTrace());
return "FAILURE" ;
}
}
}

Get database credentials from context.xml file

I have a java project that implements some APIs, in Eclipse.
I have db.java file that enables the communication with the MySQL database.
Instead of have the MySQL credentials in a java file, I would like to have them in /META-INF/context.xml file.
Do you know how to do this?
This is my current code:
public class db {
private String userName = null;
private String password = null;
private String dbName = null;
private String db_connect_string = null;
public db() {
this.db_connect_string = "jdbc:mysql://localhost/mydb";
this.dbName = "name";
this.userName = "uname";
this.password = "pass";
}
protected Connection getDBMySQLCon() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection(this.db_connect_string+"?useSSL=false", this.userName, this.password);
} catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
Instead of an XML file, you can have a properties file, that has the required information. Problem with XML file is that you will have to choose an XML parser and work with it.
If you want to go ahead with properties file you can consider the following snippet.
public void setProp() throws Exception{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
// you can get values you want as properties using
this.db_connect_string = p.getProperty("db_connect_string");
this.dbName = p.getProperty("dbName");
}
And your file structure should be something like
db_connect_string=connection.string
dbName=name
userName=uname
password=pass
This is part of the environment of the container.
/META-INF/context.xml
The context.xml overides the tomcate context entry.
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- Specify a JDBC datasource -->
<Resource name="jdbc/mydatabase"
auth="Container"
type="javax.sql.DataSource"
username="YOUR_USERNAME"
password="YOUR_PASSWORD"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://mysql.metawerx.net:3306/YOUR_DATABASE_NAME?
autoReconnect=true"
validationQuery="select 1"
maxActive="10"
maxIdle="4"/>
</Context>
// Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mydatabase");
// Get Connection and Statement
Connection c = ds.getConnection();
Statement s = c.createStatement();

Webapplication in Embedded Jetty getting Error 404 Not found

I want to deploy a Java Netbeans Webapp with an embedded Jetty Server; the server itself works, but I always get the following error:
I searched through mounds of examples on the web, configured & reconfigured my web.xml; although my configuration seems fine, I can't get it to work.
I should point out, that when I run the app from whithin Netbeans using the built-in Glassfish server, it works fine, which tells me that web.xml is probably configured well.
Can anyone help with this?
My code follows.
P.S. I know that it's been asked on SO, but those examples did not work for me either.
Project structure:
WebContext setup:
import org.eclipse.jetty.webapp.WebAppContext;
public class AppContextBuilder {
private WebAppContext webAppContext;
public WebAppContext buildWebAppContext() {
webAppContext = new WebAppContext();
webAppContext.setDescriptor(webAppContext + "/WEB-INF/web.xml");
webAppContext.setResourceBase("src/main/webapp");
webAppContext.setContextPath("/Holmes");
return webAppContext;
}
}
JettyServer.java:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
public class JettyServer {
private Server server;
public JettyServer() {
this(8585);
}
public JettyServer(Integer runningPort) {
server = new Server(runningPort);
}
public void setHandler(ContextHandlerCollection contexts) {
server.setHandler(contexts);
}
public void start() throws Exception {
server.start();
}
public void stop() throws Exception {
server.stop();
server.join();
}
public boolean isStarted() {
return server.isStarted();
}
public boolean isStopped() {
return server.isStopped();
}
}
Deploy.java (main method):
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
/**
*
* #author Motty Waldner <motty#timeworksny.com>
*/
public class Deploy {
private final static Logger log = Logger.getLogger(Deploy.class);
static JettyServer jettyServer = new JettyServer();
public static void main(String[] args) throws Exception {
// add hook to stop server upon service termination
// (service calls System.exit(0) upon termination,
// so it should work under normal circumstances)
addShutdownHook();
ContextHandlerCollection contexts = new ContextHandlerCollection();
Handler[] handlers = new Handler[]{new AppContextBuilder().buildWebAppContext().getHandler()};
contexts.setHandlers(handlers);
jettyServer = new JettyServer();
try {
jettyServer.start();
} catch (Exception e) {
log.error("Error Starting Jetty Server", e);
}
}
private static void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
jettyServer.stop();
log.info("Shutdown Hook is running: Jetty Server instance being stopped.");
} catch (Exception e) {
log.error("error", e);
}
log.info("Application Terminating ...");
}
});
}
}
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Test App</display-name>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name> struts2 </filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
<servlet-mapping>
<servlet-name>StrutsController</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Thanks in advance for the help!
Is there any stack trace logs available?
Without more logs, I can only imagine based on experience that it may be caused by directory resolving, it worked fine in your IDE since it can find the proper files without any further context configuration staff ,which may be not the case when you carry out a real deployment.
Maybe the url-pattern is wrong, try to change to something like:
<servlet-mapping>
<servlet-name>StrutsController</servlet-name>
<url-pattern>*</url-pattern>
</servlet-mapping>
change from
public class AppContextBuilder {
private WebAppContext webAppContext;
public WebAppContext buildWebAppContext() {
webAppContext = new WebAppContext();
webAppContext.setDescriptor(webAppContext + "/WEB-INF/web.xml");
webAppContext.setResourceBase("src/main/webapp");
webAppContext.setContextPath("/Holmes");
return webAppContext;
}
}
to
public class AppContextBuilder {
private WebAppContext webAppContext;
public WebAppContext buildWebAppContext() {
webAppContext = new WebAppContext();
webAppContext.setDescriptor(webAppContext + "/WEB-INF/web.xml");
webAppContext.setResourceBase(webAppContext);
webAppContext.setContextPath("/Holmes");
return webAppContext;
}
}
try this one let me know
Change
Handler[] handlers = new Handler[]{new AppContextBuilder().buildWebAppContext().getHandler()};
to
Handler[] handlers = new Handler[]{new AppContextBuilder().buildWebAppContext()};

Java WebApp and tomcat context.xml

I build webApp . When I run app from Eclipse everything work OK. Now I build WAR file, put in tomcat root, andI want to all my system property put in context.xml in tomcat. Then, when app is start, that values from context.xml is read and use in app.
Problem is I don't know how to get values from context.xml in my webapp?
This is context:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="" docBase="fileupload.war" privileged="true" antiResourceLocking="false" antiJARLocking="false">
<Resource
mail.smtp_server = "127.0.0.1"
mail.smtp_username = "no-reply#gmail.rs"
mail.mailTo = "test#gmail.com"
rootFolder = "D:/project/"
rootFolderBackup = "D:/project/Backup/"
/>
Here I want to get a values from context.xml :
#RequestMapping(value="api/files")
public class FileController {
final static Logger logger = Logger.getLogger(FileController.class);
#Autowired
ApplicationContext applicationContext;
private String mailTo;
private String sender;
private String rootFolder = "";
private String rootFolderBackup = "";
#PostConstruct
private void init(){
try {
InitialContext ic = new InitialContext();
Context xmlContext = (Context) ic.lookup("java:comp/env"); // thats everything from the context.xml and from the global configuration
DataSource myDatasource = (DataSource) xmlContext.lookup("rootFolder");
} catch (NamingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
This is common error :
Name [rootFolder] is not bound in this Context. Unable to find [rootFolder].
I try few solution which I found on web but not working...
My context.xml file is in C:\tomcat-7.0\conf\Catalina\localhost , and war file is in C:\tomcat-7.0\webapps
If you want to define application properties you should probably use Environment variables instead. Ex you can set a variable in any context.xml like this:
<Environment name="PROPERTIES_FILE" override="false" type="java.lang.String" value="C:/path/to/propfile.properties" />
<!--define more variables here -->
and then in your application you can read those environment properties from JNDI like this.
initCtx = new InitialContext();
String path = (String) initCtx.lookup("java:comp/env/PROPERTIES_FILE");
// fetch more variables here
Further reading:
https://tomcat.apache.org/tomcat-8.0-doc/config/context.html#Environment_Entries
https://tomcat.apache.org/tomcat-8.0-doc/jndi-resources-howto.html

Categories

Resources