Restore | Raw | History | First | Previous | Next | Last | Close

Tomcat 5.5 self-contained WAR Tomcat 5.5 self-contained WAR

WARNING: The example code on this page is still valid, but for newer deployments we highly recommend using the newer JDBC classes (see Using TransactionsEssentials with JDBC).

This sample application demonstrates how you can run Atomikos TransactionsEssentials® in a web application by fully embedding it in the WAR file.

It is a simple blueprint application that shows and updates the content of a single Derby database.

Download the sample application here:

To install it, simply copy the WAR file in Tomcat's webapps folder. You can then access it via this URL: http://localhost:8080/dbtest/.

Notes

Notes

  • This demo uses an embedded Derby database. If it doesn't exist a new one is created in TOMCAT_HOME/work or else, the existing one is reused.
  • The transactions logs and debug logs are stored in TOMCAT_HOME/work.

Configuration files

context.xml

<Context antiJARLocking="true">

  <Resource name="jdbc/myDB" auth="Container" type="com.atomikos.jdbc.SimpleDataSourceBean"
            factory="org.apache.naming.factory.BeanFactory"
            uniqueResourceName="jdbc/myDB"
            xaDataSourceClassName="org.apache.derby.jdbc.EmbeddedXADataSource"
            exclusiveConnectionMode="true"
            connectionPoolSize="3"
            connectionTimeout="10"
            xaDataSourceProperties="databaseName=../work/users1;createDatabase=create"/>

  <Transaction factory="com.atomikos.icatch.jta.UserTransactionFactory" />

</Context> 
<Context antiJARLocking="true">

  <Resource name="jdbc/myDB" auth="Container" type="com.atomikos.jdbc.SimpleDataSourceBean"
            factory="org.apache.naming.factory.BeanFactory"
            uniqueResourceName="jdbc/myDB"
            xaDataSourceClassName="org.apache.derby.jdbc.EmbeddedXADataSource"
            exclusiveConnectionMode="true"
            connectionPoolSize="3"
            connectionTimeout="10"
            xaDataSourceProperties="databaseName=../work/users1;createDatabase=create"/>

  <Transaction factory="com.atomikos.icatch.jta.UserTransactionFactory" />

</Context> 

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
 <!DOCTYPE web-app PUBLIC
   "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
   "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <listener>
    <listener-class>foo.ContextListener</listener-class>
  </listener>

  <resource-env-ref>
    <resource-env-ref-name>jdbc/myDB</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
  </resource-env-ref>
  
  <welcome-file-list>
    <welcome-file>test.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<?xml version="1.0" encoding="ISO-8859-1"?>
 <!DOCTYPE web-app PUBLIC
   "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
   "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <listener>
    <listener-class>foo.ContextListener</listener-class>
  </listener>

  <resource-env-ref>
    <resource-env-ref-name>jdbc/myDB</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
  </resource-env-ref>
  
  <welcome-file-list>
    <welcome-file>test.jsp</welcome-file>
  </welcome-file-list>
</web-app>

jta.properties

com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory
com.atomikos.icatch.log_base_dir=../work
com.atomikos.icatch.output_dir=../work
com.atomikos.icatch.console_log_level=DEBUG
com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory
com.atomikos.icatch.log_base_dir=../work
com.atomikos.icatch.output_dir=../work
com.atomikos.icatch.console_log_level=DEBUG

JSP sources

dbtest.jsp

<html>
  <head>
    <title>DB Test</title>
  </head>
  <body>

    <%
    String completion = request.getParameter("completion");
    foo.DBTest test = new foo.DBTest();
    test.init(completion);
    %>
    <h2>Transaction completion</h2>
    Transaction completion is :<strong><%= completion %></strong>

    <h2>Results</h2>
    Int stored in JDBC : <strong><%= test.getFoo() %></strong><br />

    <hr />

    <form action="test.jsp" method="get">
      <input type="radio" name="completion" value="commit" checked="true"> Commit<BR>
      <input type="radio" name="completion" value="rollback">Rollback<BR>
      <button type="submit">Completion</button>
    </form>
  </body>
</html>
<html>
  <head>
    <title>DB Test</title>
  </head>
  <body>

    <%
    String completion = request.getParameter("completion");
    foo.DBTest test = new foo.DBTest();
    test.init(completion);
    %>
    <h2>Transaction completion</h2>
    Transaction completion is :<strong><%= completion %></strong>

    <h2>Results</h2>
    Int stored in JDBC : <strong><%= test.getFoo() %></strong><br />

    <hr />

    <form action="test.jsp" method="get">
      <input type="radio" name="completion" value="commit" checked="true"> Commit<BR>
      <input type="radio" name="completion" value="rollback">Rollback<BR>
      <button type="submit">Completion</button>
    </form>
  </body>
</html>

Java sources

Context Listener.java

package foo;

import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;

import com.atomikos.icatch.jta.UserTransactionManager;


public class ContextListener implements ServletContextListener {
    
    private UserTransactionManager utm;

    public void contextInitialized(ServletContextEvent event) {
        try {
            utm = new UserTransactionManager();
            utm.init();
            System.out.println("initialized transaction manager");
        }
        catch (Exception ex) {
            utm = null;
            throw new RuntimeException("cannot initialize UserTransactionManager", ex);
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
        if (utm != null) {
            utm.close();
            System.out.println("shut down transaction manager");
        }
    }
}
package foo;

import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;

import com.atomikos.icatch.jta.UserTransactionManager;


public class ContextListener implements ServletContextListener {
    
    private UserTransactionManager utm;

    public void contextInitialized(ServletContextEvent event) {
        try {
            utm = new UserTransactionManager();
            utm.init();
            System.out.println("initialized transaction manager");
        }
        catch (Exception ex) {
            utm = null;
            throw new RuntimeException("cannot initialize UserTransactionManager", ex);
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
        if (utm != null) {
            utm.close();
            System.out.println("shut down transaction manager");
        }
    }
}

DBTest.java

package foo;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;

public class DBTest{

    int foo = -1;
    // value stored in DB

    public void init(String completion) {
        try{
            Context ctx = new InitialContext();

            // JDBC stuff
            DataSource ds =
                (DataSource)ctx.lookup("java:comp/env/jdbc/myDB");
            ensureTableExists(ds);

            UserTransaction ut = (UserTransaction)ctx.lookup("java:comp/UserTransaction");

            Connection conn = ds.getConnection();

            System.out.println("<<< beginning the transaction >>>");
            ut.begin();

             // JDBC statements
             Statement stmt = conn.createStatement();
             ResultSet rst =
                 stmt.executeQuery("select id, foo from testdata");
             if(rst.next()) {
                 foo=rst.getInt(2);
             }
             System.out.println("foo = "+ foo +" (before completion)");

             PreparedStatement pstmt = conn.prepareStatement("update testdata set foo=? where id=1");
             pstmt.setInt(1,++foo);
             pstmt.executeUpdate();

              if (completion != null && completion.equals("commit")) {
                  System.out.println("<<< committing the transaction >>>");
                  ut.commit();
              } else {
                  System.out.println("<<< rolling back the transaction >>>");
                  ut.rollback();
              }

             // we set foo to the value stored in the DB
             rst =
                 stmt.executeQuery("select id, foo from testdata");
             if(rst.next()) {
                 foo=rst.getInt(2);
             }
             System.out.println("foo = "+ foo +" (after completion)");

             conn.close();
             System.out.println("<<< done >>>");
        }catch(Exception e) {
            System.out.print("DBTest >> ");
            e.printStackTrace();
        }
    }

    public String getFoo() { return ""+foo; }
    
    private void ensureTableExists(DataSource ds) throws Exception {
        Connection c = ds.getConnection();
        
        try {
            Statement stmt = c.createStatement();
            stmt.executeUpdate("create table testdata (id integer not null primary key, foo integer)");
            stmt.executeUpdate("insert into testdata values(1, 1)");
            stmt.close();
            c.commit();
            System.out.println("<<< created table >>>");
        }
        catch (SQLException ex) {
            // ignore
        }
        
        c.close();
    }
}
package foo;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;

public class DBTest{

    int foo = -1;
    // value stored in DB

    public void init(String completion) {
        try{
            Context ctx = new InitialContext();

            // JDBC stuff
            DataSource ds =
                (DataSource)ctx.lookup("java:comp/env/jdbc/myDB");
            ensureTableExists(ds);

            UserTransaction ut = (UserTransaction)ctx.lookup("java:comp/UserTransaction");

            Connection conn = ds.getConnection();

            System.out.println("<<< beginning the transaction >>>");
            ut.begin();

             // JDBC statements
             Statement stmt = conn.createStatement();
             ResultSet rst =
                 stmt.executeQuery("select id, foo from testdata");
             if(rst.next()) {
                 foo=rst.getInt(2);
             }
             System.out.println("foo = "+ foo +" (before completion)");

             PreparedStatement pstmt = conn.prepareStatement("update testdata set foo=? where id=1");
             pstmt.setInt(1,++foo);
             pstmt.executeUpdate();

              if (completion != null && completion.equals("commit")) {
                  System.out.println("<<< committing the transaction >>>");
                  ut.commit();
              } else {
                  System.out.println("<<< rolling back the transaction >>>");
                  ut.rollback();
              }

             // we set foo to the value stored in the DB
             rst =
                 stmt.executeQuery("select id, foo from testdata");
             if(rst.next()) {
                 foo=rst.getInt(2);
             }
             System.out.println("foo = "+ foo +" (after completion)");

             conn.close();
             System.out.println("<<< done >>>");
        }catch(Exception e) {
            System.out.print("DBTest >> ");
            e.printStackTrace();
        }
    }

    public String getFoo() { return ""+foo; }
    
    private void ensureTableExists(DataSource ds) throws Exception {
        Connection c = ds.getConnection();
        
        try {
            Statement stmt = c.createStatement();
            stmt.executeUpdate("create table testdata (id integer not null primary key, foo integer)");
            stmt.executeUpdate("insert into testdata values(1, 1)");
            stmt.close();
            c.commit();
            System.out.println("<<< created table >>>");
        }
        catch (SQLException ex) {
            // ignore
        }
        
        c.close();
    }
}

Required libs

JAR nameSource
derby-10.2.2.0.jar Derby 10.2.2.0
jta.jar TransactionsEssentials 3.1.5
atomikos-util.jar TransactionsEssentials 3.1.5
transactions-api.jar TransactionsEssentials 3.1.5
transactions-jta.jar TransactionsEssentials 3.1.5
transactions.jar TransactionsEssentials 3.1.5
JAR nameSource
derby-10.2.2.0.jar Derby 10.2.2.0
jta.jar TransactionsEssentials 3.1.5
atomikos-util.jar TransactionsEssentials 3.1.5
transactions-api.jar TransactionsEssentials 3.1.5
transactions-jta.jar TransactionsEssentials 3.1.5
transactions.jar TransactionsEssentials 3.1.5
Attach
else
dbtest.war (2410.6 K)
version 2 uploaded by LudovicOrban on 05 Aug 2007 - 11:04
 
spacer
Copyright © 2014 Atomikos BVBA. Transaction Management for Extreme Transaction Processing and SOA Environments serving ISV, Commercial, OEM and Open Source Markets
Site map RSS ATOM