JBoss EAP 7 with Oracle Datasource - java

I am trying to access an Oracle DB connection using Jboss datasource but it's throwing java.lang.NullPointerException.
Below is my code and jboss shows below logs during startup.
What's wrong in my code?
WFLYJCA0001: Bound data source [java:/jdbc/testOracleDS]
#WebServlet("/Index")
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
private DataSource dataSource;
Connection conn = null;
public Index() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
try {
DataSource anotherDataSource = InitialContext.doLookup("java:/jdbc/testOracleDS");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
conn = dataSource.getConnection();
System.out.println("connection established");
response.getWriter().println("connection established");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("failed to establish connection: " + e);
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

I fixed this issue by adjusting code, The Datasource variable was not correctly initialized
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
private DataSource dataSource;
Connection conn = null;
public Index() {
super();
// TODO Auto-generated constructor stub
}
public void init() throws ServletException {
try {
dataSource = InitialContext.doLookup("java:/jdbc/testOracleDS");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
conn = dataSource.getConnection();
System.out.println("connection established");
response.getWriter().println("connection established");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("failed to establish connection: " + e);
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}}

Related

Database Connection was closed - but the connection is not null

I have a class which connect to a MSSQL Database.
The connection is successfully because if i run the code in my debugger (Eclipse) i can see that the connection is not null.
Also the If-Statement is called because the connection is not null
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String query = "My Query";
con = DBVerbindung();
//The connection is not null
if (con != null) {
try {
//Here the connection is closed
stmt = con.prepareStatement(query);
} catch (Exception e) {
e.printStackTrace();
}
}
private Connection DBVerbindung() {
return DatabaseConnection.Verbindung();
}
}
But in the next line if i want to call the preparedStatement i got a Connection fail error:
Here is my DatabaseConnection Class
public class DatabaseConnection {
public static Connection Verbindung() {
final String connectionUrlMsSQLDEV = "jdbc:sqlserver://XXXXX:1234;databaseName=hrpap_itha_apps_dev;user=HRPAP-dev;password=XXXXX";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try (Connection conn = DriverManager.getConnection(connectionUrlMsSQLDEV)) {
if (conn != null) {
System.out.println("Verbunden!");
} else {
System.out.println("Fehler: Verbindung konnte nicht hergestellt werden! ---> " + DatabaseConnection.class.getName() );
}
return conn;
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
So why is the connection at this point null ?
Thanks

how to not print exception by using HandlerExceptionResolver

public class AtrExceptionResolver implements HandlerExceptionResolver {
private final static Log log =LogFactory.getLog(AtrExceptionResolver.class);
#Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
boolean ajaxrequest = false;
if (request.getRequestURI().indexOf("/ajax/") > 0)
ajaxrequest = true;
if (ex instanceof AtrException) {
AtrException atrE = (AtrException) ex;
log.error(
"AtrException:code:" + atrE.getCode() + ",desc:"
+ atrE.getMsg(), ex);
if (ajaxrequest) {
PrintWriter out = null;
try {
out = response.getWriter();
out.print("{\"e\":\"" + atrE.getCode()
+ "\",\"message\":\"" + atrE.getMsg() + "\"}");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.close();
}
} else {
try {
goToError(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
log.error("Exception:desc:" + ex.getMessage(), ex);
if (ajaxrequest) {
PrintWriter out = null;
try {
out = response.getWriter();
out.print("{\"e\":\"3\",\"message\":\"system error\"}");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
out.close();
}
} else {
try {
goToError(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
private void goToError(HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.sendRedirect(request.getContextPath() + "/jsp/error.jsp");
}
atrException is defined by myself,so I do not want to printStackTrace() in console.only print it in log.
I debug it,found it print by standardwrappervalve.invoke().
How to not print atrException message in console?
If I understand your question then you want the exception stack trace in a String object which you can use it for logging.
You can use below method.
public String getErrorLog(Throwable throwable) {
if (throwable != null) {
StringWriter errors = new StringWriter();
throwable.printStackTrace(new PrintWriter(errors));
return errors.toString();
}
return "";
}
Returned value is stack trace which you can log.
return new ModelAndView();
This way can solve.

java.lang.NullPointerException in GlassFishServer

Attempting to add a record into database using a shared connection(connection created upon intialising a request) Here i'm request.getAttribute() method to retrieve attribute from RequestListener.java and assigning it to Connection type reference.
here's my code:RequestListener.java
public class RequestListener implements ServletRequestListener {
#Override
public void requestDestroyed(ServletRequestEvent sre) {
try {
Connection connection=(Connection) sre.getServletContext().getAttribute("conn");
connection.close();
} catch (SQLException ex) {
Logger.getLogger(RequestListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void requestInitialized(ServletRequestEvent sre) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost/school?user=root&password=mysql");
sre.getServletContext().setAttribute("conn",connection);
} catch (Exception ex) {
Logger.getLogger(RequestListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
error:java.lang.NullPointerException
at servlets.One.processRequest(One.java:45)
at servlets.One.doGet(One.java:89)
//////
One.java (servlet)
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String t1=request.getParameter("text1");
out.println("A");
Connection connection = (Connection) request.getAttribute("conn");
//line45 **PreparedStatement ps = connection.prepareStatement("insert into tb1 values(?)");**
ps.setString(1, t1);
ps.executeUpdate();
ps.close();
request.setAttribute("conn", connection);
request.getRequestDispatcher("B").forward(request, response);
request.getRequestDispatcher("Two").forward(request, response);
} catch (SQLException ex) {
Logger.getLogger(One.class.getName()).log(Level.SEVERE, null, ex);
}
}
RequestListener.java
"sre.getServletContext().setAttribute("conn",connection)" has to corrected as sre.getServletRequest().setAttribute("conn",connection) and avoid sending requests to two servlets as "request.getRequestDispatcher("B").forward(request, response);
request.getRequestDispatcher("Two").forward(request, response);" which results a illegalStateException

servlet page shows blank when accessed later

I have a strange issue with servlet page. I have simple web application which contains just a servlet.I deployed it in Tomcat 7. When user enters url, the servlet should get directly executed, get the data from the database and print the output. But it shows blank page after some time. When I undeploy and deploy, it shows data. After some time when I access the page, it shows blank page. Then again when I redeploy, it shows data. Can someone please let me know how to resolve this? I have no clue why it happens. Below is my code.
I am using mysql database.mysql-connector-java-5.1.29-bin.jar added in lib folder and added to buildpath.
public class Homeservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static final String mysqldblink = "************";
static final String mysqlUsername = "username";
static final String mysqlPassword = "pw";
Connection connection =null;
Statement stmt = null;
/**
* #see HttpServlet#HttpServlet()
*/
public Homeservlet() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(mysqldblink,
mysqlUsername, mysqlPassword);
stmt = connection.createStatement();
}
catch(Exception E)
{
E.printStackTrace();
}
}
#Override
public void service(ServletRequest request, ServletResponse response)
{
PrintWriter pw = null;
try {
String query = "querytogetdata";
pw = response.getWriter();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
pw.println(rs.getString(1));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}finally{
try{
pw.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void destroy( ) {
// Close the connection
try {
if (connection != null)
connection.close( );
if(stmt != null)
stmt.close();
} catch (SQLException ignore) { }
}
}

EJB : Achieving Transaction propagation through Bean Managed Transaction?

I have a requirement of trying to achieve transaction propagation across multiple stateful beans
I have 3 Stateful EJB;s in my application.. The start and end transaction is controlled be an external java application through remote interface method invocation.
#Remote
#Stateful
public class MyEJB1 implements RemoteEJB1{
#EJB
private RemoteEJB2 ejb2;
#Resource
UserTransaction utx;
public void startTransaction() {
try {
utx.begin();
} catch (NotSupportedException e) {
throw new EJBException(e);
} catch (SystemException e) {
throw new EJBException(e);
}
}
public void commitTransaction() {
try {
utx.commit();
} catch (SecurityException e) {
throw new EJBException(e);
} catch (IllegalStateException e) {
throw new EJBException(e);
} catch (RollbackException e) {
throw new EJBException(e);
} catch (HeuristicMixedException e) {
throw new EJBException(e);
} catch (HeuristicRollbackException e) {
throw new EJBException(e);
} catch (SystemException e) {
throw new EJBException(e);
}
}
public RemoteEJB2 getEJB2() {
return ejb2;
}
}
public class MyEJB2 implements RemoteEJB2{
#EJB
private RemoteEJB3 ejb3;
#Resource(name = "java:jboss/datasources/MyDS")
private DataSource ds;
public RemoteEJB3 getEJB3() {
return ejb3;
}
#TransactionAttribute(TransactionAttributeType.MANDATORY)
public void insertElement(String elementName) {
PreparedStatement pStat = null;
Connection con = null;
try {
con = ds.getConnection();
String sql = "insert into TRANSACTIONTEST(COL1,COL2) values(?,?)";
pStat = con.prepareStatement(sql);
pStat.setString(1, elementName);
pStat.setDouble(2, Math.random());
pStat.executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class MyEJB3 implements RemoteEJB3{
#Resource(name="java:jboss/datasources/MyDS")
private DataSource ds;
#TransactionAttribute(TransactionAttributeType.MANDATORY)
public void updateElement(String newName) {
PreparedStatement pStat = null;
Connection con = null;
try{ con = getDs().getConnection();
String sql ="update TRANSACTIONTEST set COL1=?";
pStat = con.prepareStatement(sql);
pStat.setString(1, newName);
pStat.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Test Class:
public class MyTest{
public static void main(String[] args) throws Exception {
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
MyEJB1 ejb1 = context.lookup("ejb:/EJBTrials/MyEJB1!edu.in.ejbinterfaces. RemoteEJB1?stateful");
ejb1.startTransaction();
RemoteEJB2 ejb2 = ejb1.getEJB2();
ejb2.insertElement (“Test”);
RemoteEJB3 ejb3 = ejb2.getEJB3();
ejb3.updateElement (“UpdatedTest”);
ejb1.commitTransaction();
}
}
I would ideally like the whole transaction(record insertions in db) to be completed after invocation of commitTransaction() on RemoteEJB1 bean.
I tried combination of BMT for EJB1 and CMT for EJB2 and EJB3 which lead to EJBTransactionRequiredException being thrown
I tried to make all beans as BMT. However according to EJB3.1 spec BMT cannot be propagated across multiple beans.
Could you let me know of any ideas/links which I could use to solve this problem?
Reference Application Server : JBOSS AS 7.1
Could you let me know of any ideas/links which I could use to solve this problem?
If I understand your issue correctly, wath you need is called Client-Managed trasaction demarcation. UnLike Container Maneged Transaction, in this case the client is responsable to set the transaction boundaries (start and commit/rollback the transaction). You can get some ideas of how to implement it here.

Categories