Tag: Datasource

Resteasy and JPA with Hibernate as Provider in JBoss AS7

Hi,

The Java Persistence Architecture API (JPA) is a Java specification for accessing, persisting, and managing data between Java objects / classes and a relational database. JPA was defined as part of the EJB 3.0 specification as a replacement for the EJB 2 CMP Entity Beans specification. JPA is now considered the standard industry approach for Object to Relational Mapping (ORM) in the Java Industry.

JBoss also provides feature to deploy JAX-RS based applications including package “org.jboss.resteasy.*”. Here in this example we will see how to integrate the Resteasy wtih JPA. In this process we will see how to use various annotations like @XmlRootElement, @ApplicationPath @Entity @PersistenceContext etc.. A Quick tour on JAX-RS Reference Guide will be better.

The JBoss Application Server JPA subsystem implements the JPA 2.0 container-managed requirements. JPA Applications use the Hibernate (core) 4.0 persistence provider, that is included with JBoss AS. Hibernate 4 is packaged with the AS and is the default persistence provider. The JPA 2.0 Specifications can be found in the following link: http://jcp.org/aboutJava/communityprocess/pfd/jsr317/index.html

A Best reference for JPA features inside JBoss AS7 can be foun in the following link: JPA Reference Guide

However in this current emo we will just create a Simple JPA persistence unit and then we will try to insert some employee detils insie the DataBase using the JAX-RS as frontend. So basically this is just as a startup.

In this example we will mainly focus on following points

Point-1). For Web Applications we should put the “persistence.xml” file inside “${WEB_APPLICATION}/WEB-INF/classes/META-INF/persistence.xml”
For EJB Applications we should put the “persistence.xml” file inside “${EJB_JAR}/META-INF”

Point-2). To inject the EntityManager inside our Web Components we can use the annotation @javax.persistence.PersistenceContext(unitName=”name”)

Point-3). How to use the JAX-RS resteasy implementations and various annotations associated with it.

<<< I S S U E >>>: I tried to use the @javax.ejb.EJB annotation to inject an Enterprise Java Bean inside Rest Easy component but it did not work Like @EJB(lookup=”jndiName”) , which need to be checked (May be it’s work as designed). But it worked fine inside a Servlet in another case.

Server Side Configuration

Point-1). Here we are using JBoss AS7 latest build “jboss-as-7.1.0.CR1” which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Point-2). In order to get more details on how to create MySQL DataSource in JBoss AS7 you can refer to the following article: http://middlewaremagic.com/jboss/?p=872
Create a DataSource inside “${JBOSS_HOME}/standalone/configuration/standalone-full.xml” file as following:

        <subsystem xmlns="urn:jboss:domain:datasources:1.0">
            <datasources>
                <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="H2DS" enabled="true">
                    <connection-url>
                        jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
                    </connection-url>
                    <driver>
                        h2
                    </driver>
                    <security>
                        <security-domain>
                            encrypted-ds
                        </security-domain>
                    </security>
                </datasource>


                <!-- Below is the DataSource Configuration which we added for our JPA TestCase-->
                <datasource jndi-name="java:/MySqlDS" pool-name="MySqlDS_Pool" enabled="true" jta="false" use-ccm="false">
                    <connection-url>
                        jdbc:mysql://localhost:3306/testDB
                    </connection-url>
                    <driver-class>
                        com.mysql.jdbc.Driver
                    </driver-class>
                    <driver>
                        mysql-connector-java-5.1.13-bin.jar
                    </driver>
                    <security>
                        <user-name>someDBUserName</user-name>
                        <password>someDBPassword</password>
                    </security>
                </datasource>
                <!-- Above is the DataSource we created on MySQL Database -->


                <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>
                            org.h2.jdbcx.JdbcDataSource
                        </xa-datasource-class>
                    </driver>
                </drivers>
            </datasources>
        </subsystem>

Point-3). Restart your JBoss AS7 from inside “/home/userone/jboss-as-7.1.0.CR1/bin” directory as following:

.
 ./standalone.sh -c standalone-full.xml
.

Developing JPA Part Of the Test Case

Step1). Create a directory somewhere in your filesystem like “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7” where we will place our application build related stuff. Then create another directory “src” inside “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7” where we will be placing our source codes and JSPs.

Step2). Now first of all we will create an Entity “Employee.java” as following inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory. NOTICE: we used the annotation “@XmlRootElement”

package jpa;
import java.io.Serializable;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@Entity
@Table(name="Employee")
public class Employee implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	private Integer empno;
	private String ename;

        public Employee() {
    	 System.out.println("[Employee] Employee Object Created. "+this);
        }

	public Integer getEmpno() {
                System.out.println("[Employee] getEmpno() called on "+this);
		return this.empno;
	}

	public void setEmpno(Integer empno) {
                System.out.println("[Employee] setEmpno("+empno+") called on "+this);
		this.empno = empno;
	}

	public String getEname() {
                System.out.println("[Employee] getEname() called on "+this);
		return this.ename;
	}

	public void setEname(String ename) {
                System.out.println("[Employee] setEname("+ename+") called on "+this);
		this.ename = ename;
	}

}

Step3). Now we will create a Simple Stateless SessionBean remote Interface “EmployeeServiceRemote.java” inside “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

package jpa;
import java.util.Collection;
import javax.ejb.Remote;
@Remote

public interface EmployeeServiceRemote{
  public void doAction();
  public Employee createEmployee(Integer id, String name);
  public void removeEmployee(Integer id);
  public Employee findEmployee(Integer id);
  public Collection<Employee> findAllEmployees() ;

}

Step4). Now we will Stateless Session Bean class “EmployeeService.java” by implementing the interface “EmployeeServiceRemote.java”. Place this file as well inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

package jpa;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class EmployeeService implements EmployeeServiceRemote {
  @PersistenceContext(unitName="EmployeeService")
  EntityManager em;

  public EmployeeService() {
	  System.out.println("n[EmployeeService] EmployeeService Created. this: "+this);
  }

  public Employee createEmployee(Integer id, String name) {
    Employee emp = new Employee();
    emp.setEmpno(id);
    emp.setEname(name);
    em.persist(emp);
    emp = findEmployee(id);
    System.out.println("n[EmployeeService] Inside createEmployee() findEmployee result: "+emp+"t this: "+this);
    em.flush();
    return emp;
  }

  public void removeEmployee(Integer id) {
    System.out.println("n[EmployeeService] Inside removeEmployee("+id+") this: "+this);
    Employee emp = findEmployee(id);
    if (emp != null) {
      em.remove(emp);
    }
  }

  public Employee findEmployee(Integer id) {
    System.out.println("n[EmployeeService] Inside findEmployee("+id+") this: "+this);
    return em.find(Employee.class, id);
  }

  @SuppressWarnings("unchecked")
  public Collection<Employee> findAllEmployees() {
    System.out.println("n[EmployeeService] Inside findAllEmployees() this: "+this);
    Query query = em.createQuery("SELECT e FROM Employee e");
    return (Collection<Employee>) query.getResultList();
  }

  public void doAction(){
  }
}

Step5). Now we will write the “persistence.xml” file inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
	xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
	<persistence-unit name="EmployeeService"> <!-- transaction-type="JTA" -->
		<jta-data-source>java:/MySqlDS</jta-data-source>
		<class>jpa.Employee</class>
		<properties>
			<property name="hibernate.hbm2ddl.auto" value="create-drop" />
                        <property name="hibernate.show_sql" value="true" />
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
		</properties>
	</persistence-unit>
</persistence>

NOTE: We need to make sure that this “persistence.xml” file goes inside the “${war.name}/WEB-INF/classes/META-INF” directory of our WAR file.
Due to the property “hibernate.hbm2ddl.auto” the Employee table will be automatically created in the database as soon as we deploy the application on JBoss and will be automatically droped as soon as we undeploy our application. Valid values for this property are “validate | update | create | create-drop”

Developing JAX-RS Part Of the Test Case

Step6). Now we will write a simple “index.jsp” page to just provide a some input forms so that a user can enter the employee name and id details , Place this file as well inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

<html>
<head>
<title>JPA With Rest Demo In JBoss AS7</title>
</head>
<body>

<h1>Add An Employee</h1>
   <table border="10%">
      <form action="services/create" method="post">
         <TR><TD>Enter Employee ID </TD><TD> <input name="empno" type="text" value="" /> </TD></TR>
         <TR><TD>Enter Employee Name </TD><TD> <input name="empname" type="text" value="" /> </TD></TR>
         <TR><TD><input type="submit" value="Add Employee" /></TD><TD> <input type="reset" value="Clear" /></TD></TR>
      </form>
    </table>

<h1>Remove An Employee</h1>
   <table border="10%">
     <form action="services/removeemployee" method="post">
         <TR><TD>Enter Employee ID </TD><TD> <input name="empno" type="text" value=""/> </TD></TR>
         <TR><TD></TD><TD><input type="submit" value="Remove Employee" /></TD></TR>
   </form>
    </table>

<h1>Find An Employee</h1>
   <table border="10%">
      <form action="services/findemployee" method="post">
         <TR><TD>Enter Employee ID </TD><TD> <input name="empno" type="text" value=""/> </TD></TR>
         <TR><TD></TD><TD><input type="submit" value="Find Employee" /></TD></TR>
      </form>
    </table>

<h1>Find All Employees</h1>
   <a href="services/findall">Find All Employees</a>  

</body>
</html>

Step7). We will write the “MyRestService.java” inside the “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” as following in order to insert the details entered by the user in previous index.jsp page.

package rest;
import java.util.Collection;

//Rest related imports
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

// EJB Related imports
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ejb.EJB;
import jpa.Employee;
import jpa.EmployeeServiceRemote;

@ApplicationPath("/services")
@Path("/")
public class MyRestService extends Application
{
   /* ::::NOTE::::
        The Following Injection is not Working which need to be checked. So Here i am doing the old style lookup for the EJB.

        @EJB(lookup="java:global/JPA_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote")
        jpa.EmployeeServiceRemote remote;
   */

  jpa.EmployeeServiceRemote remote;
  public MyRestService()
     {
       try{
            InitialContext ctx=new InitialContext();
            remote = (EmployeeServiceRemote) ctx.lookup("java:global/JPA_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote");
          }
       catch(NamingException ne) 
          {
            System.out.println("n[MyRestService]NamingException: "+ne);
            ne.printStackTrace();
          }
     }


  @POST
  @Path("/create")
  @Produces(MediaType.APPLICATION_XML)  
  @Consumes("application/x-www-form-urlencoded")
  public Employee createEmployee(@FormParam("empno") Integer id, @FormParam("empname") String name) 
    {
        System.out.println("n[MyRestService]jpa.EmployeeServiceRemote remote = "+remote);
        Employee emp=null;
        if(remote!=null)
           emp=remote.createEmployee(id,name);
        else
          {
           emp=new Employee();
           emp.setEname(name);
           emp.setEmpno(id);
          }
        return emp;
    }        


  @POST
  @Path("/removeemployee")
  @Consumes("application/x-www-form-urlencoded")
  @Produces(MediaType.TEXT_HTML)  
  public String removeEmployee(@FormParam("empno") Integer id) 
    {
        System.out.println("n[MyRestService]Inside removeEmployee("+id+") this: "+this);
        remote.removeEmployee(id);
        return "Emplloyee Removed with Id: "+id;
    }


  @POST
  @Path("/findemployee")
  @Produces(MediaType.APPLICATION_XML)  
  @Consumes("application/x-www-form-urlencoded")
  public Employee findEmployee(@FormParam("empno") Integer id) 
    {
        System.out.println("n[MyRestService]Inside findEmployee("+id+") this: "+this);
        Employee emp=remote.findEmployee(id);
        return  emp;
    }


  @GET
  @Produces(MediaType.APPLICATION_XML)  
  @Path("/findall")
  public Collection<Employee> findAllEmployees() 
   {
       System.out.println("n[MyRestService]Inside findAllEmployees() this: "+this);
       Collection<Employee> collection=remote.findAllEmployees();
       return collection;
   }
}

Step8). As this is going to be a WebApplication so we will provide a simple default “web.xml” file inside “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/src” directory as following:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

</web-app>

Building and deploying the Application

Step9). Now the most important part, here we are going to develop “build.xml” ANT file, which will build, deploy our web application on the JBoss AS7.1 CR1 Server, so write the following “build.xml” file inside “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7” directory.

<project name="JPA_BASIC_Demo" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.CR1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="JPA_With_JAXRS_BASIC_Demo.war" />
 
   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>
   </path>
 
        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}/WEB-INF/classes/META-INF"/>
        </target>
 
        <target name="build" depends="init">
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath" />
           <copy todir="${tmp.dir}/WEB-INF/classes">
                <fileset dir="${src.dir}" includes="**/*.java"/>
           </copy>
           <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>
           <copy file="${src.dir}/web.xml" tofile="${tmp.dir}/web.xml"/>

           <!-- Make Sure that the persistence.xml file is placed inside "${war.name}/WEB-INF/classes/META-INF" directory -->
           <copy file="${src.dir}/persistence.xml" tofile="${tmp.dir}/WEB-INF/classes/META-INF/persistence.xml"/>

           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>

           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete>
        </target>
 
        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/>
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script to point to your own JBoss AS7 directory.

Step10). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step11). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7” and then run the ant to build the webservice. by running the command “ant”

[userone@localhost JPA2_JAXRS_And_Hibernate4_On_AS7]$ ant
Buildfile: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build.xml

init:
   [delete] Deleting directory /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build
    [mkdir] Created dir: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build
    [mkdir] Created dir: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp
    [mkdir] Created dir: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/WEB-INF/classes/META-INF

build:
    [javac] /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build.xml:25: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 4 source files to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/WEB-INF/classes
     [copy] Copying 4 files to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp
     [copy] Copying 1 file to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp
     [copy] Copying 1 file to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/WEB-INF/classes/META-INF
      [jar] Building jar: /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/tmp/JPA_With_JAXRS_BASIC_Demo.war
     [copy] Copying 1 file to /home/userone/JPA2_JAXRS_And_Hibernate4_On_AS7/build

deploy:
     [echo] *******************  Deploying the WAR file JPA_With_JAXRS_BASIC_Demo.war *********************
     [echo] ********** build/JPA_With_JAXRS_BASIC_Demo.war to //home/userone/jboss-as-7.1.0.CR1/standalone/deployments **********
     [copy] Copying 1 file to //home/userone/jboss-as-7.1.0.CR1/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 2 seconds

Step12). Now you will see the following kind of output on your JBoss AS7.1 console which means the application is deployed successfully:

20:21:15,570 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) Starting deployment of "JPA_With_JAXRS_BASIC_Demo.war"
20:21:15,589 INFO  [org.jboss.jpa] (MSC service thread 1-2) JBAS011401: Read persistence.xml for EmployeeService
20:21:15,598 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-3) JNDI bindings for session bean named EmployeeService in deployment unit deployment "JPA_With_JAXRS_BASIC_Demo.war" are as follows:

	java:global/JPA_With_JAXRS_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote
	java:app/JPA_With_JAXRS_BASIC_Demo/EmployeeService!jpa.EmployeeServiceRemote
	java:module/EmployeeService!jpa.EmployeeServiceRemote
	java:global/JPA_With_JAXRS_BASIC_Demo/EmployeeService
	java:app/JPA_With_JAXRS_BASIC_Demo/EmployeeService
	java:module/EmployeeService

20:21:15,617 INFO  [org.jboss.jpa] (MSC service thread 1-6) JBAS011402: Starting Persistence Unit Service 'JPA_With_JAXRS_BASIC_Demo.war#EmployeeService'
20:21:15,619 INFO  [org.hibernate.ejb.Ejb3Configuration] (MSC service thread 1-6) HHH000204: Processing PersistenceUnitInfo [
	name: EmployeeService
	...]
20:21:15,628 INFO  [org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator] (MSC service thread 1-6) HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
20:21:15,635 INFO  [org.hibernate.dialect.Dialect] (MSC service thread 1-6) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
20:21:15,635 INFO  [org.hibernate.engine.jdbc.internal.LobCreatorBuilder] (MSC service thread 1-6) HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
20:21:15,636 INFO  [org.hibernate.engine.transaction.internal.TransactionFactoryInitiator] (MSC service thread 1-6) HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory
20:21:15,636 INFO  [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (MSC service thread 1-6) HHH000397: Using ASTQueryTranslatorFactory
20:21:15,643 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] (MSC service thread 1-6) HHH000227: Running hbm2ddl schema export
20:21:15,643 INFO  [stdout] (MSC service thread 1-6) Hibernate: drop table if exists Employee
20:21:15,645 INFO  [stdout] (MSC service thread 1-6) Hibernate: create table Employee (empno integer not null, ename varchar(255), primary key (empno))
20:21:15,768 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] (MSC service thread 1-6) HHH000230: Schema export complete
20:21:15,776 INFO  [org.jboss.web] (MSC service thread 1-4) registering web context: /JPA_With_JAXRS_BASIC_Demo
20:21:15,788 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018559: Deployed "JPA_With_JAXRS_BASIC_Demo.war"

Step13). Now access the WebApplication like following :
http://localhost:8080/JPA_With_JAXRS_BASIC_Demo/

JPA_With_JAXRS


.
.
Thanks 🙂
Middleware Magic Team


Enabling DataSource Spy Logging in JBoss AS7

Hi,

Some times we face issues while invoking some JDBC statements using the DataSource JDBC Connection. Many times it is not easily identifiable that which part of the JDBC code is actually causing the failure or issue. So it is better to have a Spy logging kind of feature inside the datasource which can tell us all the activities which an application performs on the Jdbc connection & Statements retrieved from the DataSource.

JBoss AS7 uses Jacmar for implementing it’s datasource mechanism. Also JBoss AS7 provides a very effecient way of enabling the spy logging which can log all the informations related to the connection/statements and any method whcih is invoked on the JDBC Objects.

In order to enable the DataSource Spy logging in JBoss AS7 we will need to do the following two things:

Step1). Enable the “jboss.jdbc.spy” to DEBUG inside your “standalone-full.xml” or “domain.xml” file present inside “jboss-as-7.1.0.Beta1/standalone/confguration” directory as following:

        <subsystem xmlns="urn:jboss:domain:logging:1.1">
            <console-handler name="CONSOLE">
                <level name="INFO"/>
                <formatter>
                    <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
                </formatter>
            </console-handler>
            <periodic-rotating-file-handler name="FILE">
                <formatter>
                    <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
                </formatter>
                <file relative-to="jboss.server.log.dir" path="server.log"/>
                <suffix value=".yyyy-MM-dd"/>
                <append value="true"/>
            </periodic-rotating-file-handler>
            <logger category="com.arjuna">
                <level name="WARN"/>
            </logger>
            <logger category="org.apache.tomcat.util.modeler">
                <level name="WARN"/>
            </logger>
            <logger category="sun.rmi">
                <level name="WARN"/>
            </logger>
            <logger category="jacorb">
                <level name="WARN"/>
            </logger>
            <logger category="jacorb.config">
                <level name="ERROR"/>
            </logger>

            <!-- ************* Enabling Spy logging category ************ -->
            <logger category="jboss.jdbc.spy">
                <level name="TRACE"/>
            </logger>
            <!-- *************************************************-->

            <root-logger>
                <level name="INFO"/>
                <handlers>
                    <handler name="CONSOLE"/>
                    <handler name="FILE"/>
                </handlers>
            </root-logger>
        </subsystem>

Step2). Create a DataSource from JBoss Console or using “jboss-admin.sh” utility. You can refer to the following article for more details on creating DataSources:
How to create Oracle DataSource And Install Oracle JDBC Driver in JBoss AS7
OR
How to create MySQL datasource And Install MySQL JDBC driver in JBoss AS7

NOTE: The only thing you need to remember is to add the spy=”true” attribute in your DataSource configuration as following:

        <subsystem xmlns="urn:jboss:domain:datasources:1.0">
            <datasources>
                <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="H2DS" enabled="true">
                    <connection-url>
                        jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
                    </connection-url>
                    <driver>
                        h2
                    </driver>
                    <security>
                        <security-domain>
                            encrypted-ds
                        </security-domain>
                    </security>
                </datasource>


                <!-- ****** Below is MySqlDS with Spy logging enabled ****** -->
                <datasource jndi-name="java:/MySqlDS" pool-name="MySqlDS_Pool" enabled="true" spy="true" jta="false" use-ccm="false">
                    <connection-url>
                        jdbc:mysql://localhost:3306/testDB
                    </connection-url>
                    <driver-class>
                        com.mysql.jdbc.Driver
                    </driver-class>
                    <driver>
                        mysql-connector-java-5.1.13-bin.jar
                    </driver>
                    <security>
                        <security-domain>
                            encrypted-ds
                        </security-domain>
                    </security>
                </datasource>
                <!-- ****** Above is MySqlDS with Spy logging enabled ****** -->


                <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>
                            org.h2.jdbcx.JdbcDataSource
                        </xa-datasource-class>
                    </driver>
                </drivers>
            </datasources>
        </subsystem>

NOTE: In order to enable the spy logging you must follow both the steps “Step-1” and “Step-2” together.

Step3). Now suppose if you have following kind of JSP Page inside your application which uses the JBoss DataSource Jdbc Connection in order to perform some JDBC operations:

<%@page contentType="text/html" import="java.util.*,javax.naming.*,javax.sql.DataSource,java.sql.*"%>

<%
DataSource ds = null;
Connection con = null; 
PreparedStatement pr = null; 
InitialContext ic; 

out.println("<html>");
out.println("<body>");
out.println("<center>");

	try 
	{
		ic = new InitialContext();
		ds = (DataSource)ic.lookup("java:/MySqlDS");
		con = ds.getConnection(); 
		
		out.println("<font color=green>");
		out.println("<b>Got Connection </b> = "+con);
		out.println("<br><br><br><br><br><br><b> This means our DataSource has been configured properly </b> ");
		out.println("</font>");
		System.out.println("==> Got Connection = "+con);

                Statement stmt=con.createStatement();
                ResultSet rs=stmt.executeQuery("SELECT * FROM emp");
                out.println("<TABLE>");
                while(rs.next())
                 {
                     out.println("<TR><TD>"+rs.getString(1)+"</TD><TD>"+rs.getString(2)+"</TD></TR>");
                 }
                out.println("</TABLE>");
	}

	catch (SQLException s)
	{
		out.println("<font color=red>");
		out.println("<b>!!! Did not get the connection </b> = " +s);
		out.println("<br><br><br><br><br><br><b>This means we might have to check our datasource configuration (i.e. URL, Username, Password etc) or might be the database is down </b> ");
		out.println("</font>");
		System.out.println("!!! Did not get the connection = " +s);
	}

	catch(Exception e)
	{
		out.println("<font color=red>");
		out.println("<b>!!! Exception thrown </b> = " +e);
		out.println("<br><br><br><br><br><br><b>This means we might have to check our datasource configuration (i.e. URL, Username, Password etc) or might be the database is down </b> ");
		out.println("</font>");
		System.out.println("!!! Exception thrown = "+e);
	}

	finally
	{
		if(con != null)
		{
			con.close();
		}      
	} 

out.println("</center>");
out.println("</body>");
out.println("</html>");
%>

Step4). Restart your JBoss after enabling the Spy Logging and then access the application which performs some activity on the JDBC Connection retrieved from the JBoss AS7 DataSource. The you will notice in your “server.log” file following kind of DEBUG messages:

23:01:14,744 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [Connection] createStatement()
23:01:14,748 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [Statement] executeQuery(SELECT * FROM emp)
23:01:14,756 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [ResultSet] next()
23:01:14,756 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [ResultSet] getString(1)
23:01:14,757 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [ResultSet] getString(2)
23:01:14,757 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [ResultSet] next()
23:01:14,757 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [Connection] close()

Means whatever operations our application is performing on the JDBC Connection/Statement…etc objects everything is being logged. This can be very helpful in debugging/troubleshooting many JDBC Related issues.

Following is not part of Spy Logging but Useful

If you are running in Development environment and if it’s OK to have more logging then you can also enable the following category “org.jboss.jca” in your “standalone-full.xml” or “domain.xml” file to get more informations related to your DataSource:

            <logger category="org.jboss.jca">
                <level name="TRACE"/>
            </logger>
23:58:12,112 TRACE [org.jboss.jca.core.connectionmanager.NoTxConnectionManager] (http-localhost-127.0.0.1-8080-1) Subject: Subject:
	Principal: root
	Private Credential: javax.resource.spi.security.PasswordCredential@dd9c93cc

23:58:12,122 DEBUG [org.jboss.jca.core.connectionmanager.pool.idle.IdleRemover] (http-localhost-127.0.0.1-8080-1) internalRegisterPool: about to notify thread: old next: 1322937792121, new next: 1322937792121
23:58:12,123 TRACE [org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject] (http-localhost-127.0.0.1-8080-1) ManagedConnectionPool: 52e0cdc9
Method: getConnection(Subject:
	Principal: root
	Private Credential: javax.resource.spi.security.PasswordCredential@dd9c93cc
, null)
ManagedConnectionFactory:
  Class: org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory
  Object: 4200309
ConnectionListenerFactory:
  Class: org.jboss.jca.core.connectionmanager.notx.NoTxConnectionManagerImpl
  Object: 51a745fc
Pool:
  Name: MySqlDS_Pool
PoolConfiguration:
  MinSize: 0
  MaxSize: 20
  BlockingTimeout: 30000
  IdleTimeout: 1800000
  BackgroundValidation: false
  BackgroundValidationMillis: 0
  StrictMin: false
  UseFastFail: false
Available:
InUse:
Statistics:
  ActiveCount: 0
  AvailableCount: 20
  AverageBlockingTime: 0
  AverageCreationTime: 0
  CreatedCount: 0
  DestroyedCount: 0
  MaxCreationTime: 0
  MaxUsedCount: 0
  MaxWaitCount: 0
  MaxWaitTime: 0
  TimedOut: 0
  TotalBlockingTime: 0
  TotalCreationTime: 0
23:58:12,124 TRACE [org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory] (http-localhost-127.0.0.1-8080-1) Using properties: {user=root, password=--hidden--}
23:58:12,124 TRACE [org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory] (http-localhost-127.0.0.1-8080-1) Checking driver for URL: jdbc:mysql://localhost:3306/testDB
23:58:12,125 TRACE [org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory] (http-localhost-127.0.0.1-8080-1) Driver not yet registered for url: jdbc:mysql://localhost:3306/testDB
23:58:12,125 DEBUG [org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory] (http-localhost-127.0.0.1-8080-1) Driver loaded and instance created:com.mysql.jdbc.Driver@75589559
23:58:12,180 DEBUG [org.jboss.jca.core.tx.jbossts.XAResourceRecoveryImpl] (Periodic Recovery) RecoverySecurityDomain was empty
23:58:12,180 DEBUG [org.jboss.jca.core.tx.jbossts.XAResourceRecoveryImpl] (Periodic Recovery) Subject for recovery was null
23:58:12,338 TRACE [org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject] (http-localhost-127.0.0.1-8080-1) supplying new ManagedConnection: org.jboss.jca.core.connectionmanager.listener.NoTxConnectionListener@4b7d94f8[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection@21bf4c80 connection handles=0 lastUse=1322936892337 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject@163778cf pool internal context=org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreArrayListManagedConnectionPool@52e0cdc9]
23:58:12,338 TRACE [org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject] (http-localhost-127.0.0.1-8080-1) Got connection from pool: org.jboss.jca.core.connectionmanager.listener.NoTxConnectionListener@4b7d94f8[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection@21bf4c80 connection handles=0 lastUse=1322936892337 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject@163778cf pool internal context=org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreArrayListManagedConnectionPool@52e0cdc9]
23:58:12,347 INFO  [stdout] (http-localhost-127.0.0.1-8080-1) ==> Got Connection = org.jboss.jca.adapters.jdbc.jdk6.WrappedConnectionJDK6@28892a87
23:58:12,350 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [Connection] createStatement()
23:58:12,355 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [Statement] executeQuery(SELECT * FROM emp)
23:58:12,362 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [ResultSet] next()
23:58:12,363 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [ResultSet] getString(1)
23:58:12,363 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [ResultSet] getString(2)
23:58:12,363 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [ResultSet] next()
23:58:12,363 DEBUG [jboss.jdbc.spy] (http-localhost-127.0.0.1-8080-1) java:/MySqlDS [Connection] close()
23:58:12,365 TRACE [org.jboss.jca.core.connectionmanager.listener.NoTxConnectionListener] (http-localhost-127.0.0.1-8080-1) unregisterConnection: 0 handles left
23:58:12,365 TRACE [org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject] (http-localhost-127.0.0.1-8080-1) ManagedConnectionPool: 52e0cdc9
Method: returnConnection(4b7d94f8, false)
ManagedConnectionFactory:
  Class: org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory
  Object: 4200309
ConnectionListenerFactory:
  Class: org.jboss.jca.core.connectionmanager.notx.NoTxConnectionManagerImpl
  Object: 51a745fc
Pool:
  Name: MySqlDS_Pool
PoolConfiguration:
  MinSize: 0
  MaxSize: 20
  BlockingTimeout: 30000
  IdleTimeout: 1800000
  BackgroundValidation: false
  BackgroundValidationMillis: 0
  StrictMin: false
  UseFastFail: false
Available:
InUse:
  4b7d94f8 (NORMAL)
Statistics:
  ActiveCount: 1
  AvailableCount: 19
  AverageBlockingTime: 0
  AverageCreationTime: 212
  CreatedCount: 1
  DestroyedCount: 0
  MaxCreationTime: 212
  MaxUsedCount: 1
  MaxWaitCount: 0
  MaxWaitTime: 0
  TimedOut: 0
  TotalBlockingTime: 0
  TotalCreationTime: 212
23:58:12,366 TRACE [org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject] (http-localhost-127.0.0.1-8080-1) Returning connection to pool org.jboss.jca.core.connectionmanager.listener.NoTxConnectionListener@4b7d94f8[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection@21bf4c80 connection handles=0 lastUse=1322936892366 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject@163778cf pool internal context=org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreArrayListManagedConnectionPool@52e0cdc9]

.
.
Thanks
MiddlewareMagic Team


Using Encrypted DataSource Password in JBoss AS7

Hi,

Securing our Application Server resources is one of the most important administrative task. JBoss AS7 uses picketbox security implementations. In this example we will see how we can provide an Encrypted Password for our DataSources rather than using the ClearText Password. The picketbox provides us a class for encrypting the Cleartext passwords using class “org.picketbox.datasource.security.SecureIdentityLoginModule”

BUT in earlier versions on JBoss the Class was available as part of a different package “org.jboss.resource.security.SecureIdentityLoginModule” … So while using JBoss AS7 we must always make sure that we are using the right SecureIdentityLoginModule class as “org.picketbox.datasource.security.SecureIdentityLoginModule”

In this demonstration we will be using JBoss AS7 ( jboss-as-7.1.0.Beta1 ) which can be downloaded from the following link:
http://www.jboss.org/jbossas/downloads

Step1). Create a DataSource as following:

        <subsystem xmlns="urn:jboss:domain:datasources:1.0">
            <datasources>
                <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="H2DS" enabled="true">
                    <connection-url>
                        jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
                    </connection-url>
                    <driver>
                        h2
                    </driver>
                    <security>
                        <user-name>sa</user-name>
                        <password>sa</password>
                    </security>
                </datasource>
                
                <!-- ************************************************* -->
                <!-- We Added the below DataSource configuration Here -->
                <datasource jndi-name="java:/MySqlDS" pool-name="MySqlDS_Pool" enabled="true" jta="false" use-ccm="false">
                    <connection-url>
                        jdbc:mysql://localhost:3306/testDB
                    </connection-url>
                    <driver-class>
                        com.mysql.jdbc.Driver
                    </driver-class>
                    <driver>
                        mysql-connector-java-5.1.13-bin.jar
                    </driver>
                    <security>
                        <security-domain>
                            encrypted-ds
                        </security-domain>
                    </security>
                </datasource>
                <!-- ************************************************* -->

                <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>
                            org.h2.jdbcx.JdbcDataSource
                        </xa-datasource-class>
                    </driver>
                </drivers>
            </datasources>
        </subsystem>

NOTE:
In above case as we are using “mysql-connector-java-5.1.13-bin.jar” JDBC Driver which is a JDBC 4 compliant Driver so we just placed this Jar file inside the “jboss-as-7.1.0.Beta1/standalone/deployments” directory before creating the DataSource.

NOTE:
In the above DataSource configuration you will notice that inside the security tags we have NOT provided the Username and password rather we are providing the security-domain name (encrypted-ds) which we are going to configure in our next steps.

NOTE:
For more information on installing JDBC Driver and creating DataSources you can refer to the following article: http://middlewaremagic.com/jboss/?p=872

NOTE:
The simplest thing what you can do is just create a DataSource through JBoss Console as mentioned in the above link and then edit the following section of your DataSource to use security-domain rather than user-name and password attributes.

    <security>
         <user-name>dbUserOne</user-name>
         <password>PasswordXYZ</password>
    </security>

Step2). Open a Shell Prompt and then set the CLASSPATH to point to the following JAR’s “picketbox-4.0.6.Beta1.jar” and “jboss-logging-3.1.0.CR2.jar” because these Jars are required to encrypt the clear text password.

[userone@localhost ~]$      export JBOSS_HOME=/home/userone/jboss-as-7.1.0.Beta1
.
[userone@localhost ~]$      export CLASSPATH=${JBOSS_HOME}/modules/org/picketbox/main/picketbox-4.0.6.Beta1.jar:${JBOSS_HOME}/modules/org/jboss/logging/main/jboss-logging-3.1.0.CR2.jar:$CLASSPATH

[userone@localhost ~]$      java  org.picketbox.datasource.security.SecureIdentityLoginModule PasswordXYZ
Encoded password: -5bbc51443039e029747687c1d9ec6a8d
.

NOTE: In above demo suppose our Database Poassword is “PasswordXYZ” so after running the above command we got the encrypted password as “-5bbc51443039e029747687c1d9ec6a8d”

Step3). Now We need to create a “security-domain” inside out “${JBOSS_HOME}/standalone/configuration/standalone-full.xml” file as following, By providing the above Encrypted Password:

                <security-domain name="encrypted-ds" cache-type="default">
                    <authentication>
                        <login-module code="org.picketbox.datasource.security.SecureIdentityLoginModule" flag="required">
                            <module-option name="username" value="dbUserOne"/>
                            <module-option name="password" value="-5bbc51443039e029747687c1d9ec6a8d"/>
                            <module-option name="managedConnectionFactoryName" value="jboss.jca:service=LocalTxCM,name=MySqlDS_Pool"/>
                        </login-module>
                    </authentication>
                </security-domain>

Step4). That’s all now just restart your JBoss profile like following:

.
./standalone.sh -c standalone-full.xml 
.

Testing JBossAS7 DataSource connections using CLI

Step5). Following are the JBoss CLI command which you can use to test your DataSource is working fine or not.
In Standalone mode:

[standalone@localhost:9999 /] /subsystem=datasources/data-source=MySqlDS_Pool:test-connection-in-pool
{
    "outcome" => "success",
    "result" => [true]
}

In Domain mode:

[domain@localhost:9999 /] /host=master/server=server-one/subsystem=datasources/data-source=MySqlDS_Pool:test-connection-in-pool
{
    "outcome" => "success",
    "result" => [true]
}

What if you enter a Wrong Encrypted password in your JBoss Configuration?

Then you will see following kind of exception in your .JBoss Console:

03:19:12,578 INFO  [org.jboss.as.osgi] (MSC service thread 1-4) JBAS011907: Register module: Module "deployment.mysql-connector-java-5.1.13-bin.jar:main" from Service Module Loader
03:19:12,641 ERROR [org.jboss.as.connector.subsystems.datasources.AbstractDataSourceService$AS7DataSourceDeployer] (MSC service thread 1-2) Exception during createSubject()PB00024: Access Denied:Unauthenticated caller:null: java.lang.SecurityException: PB00024: Access Denied:Unauthenticated caller:null
	at org.jboss.security.plugins.JBossSecuritySubjectFactory.createSubject(JBossSecuritySubjectFactory.java:89) [picketbox-4.0.9.Final.jar:4.0.9.Final]
	at org.jboss.jca.deployers.common.AbstractDsDeployer$1.run(AbstractDsDeployer.java:1047) [ironjacamar-deployers-common-1.0.11.Final.jar:1.0.11.Final]
	at org.jboss.jca.deployers.common.AbstractDsDeployer$1.run(AbstractDsDeployer.java:1042) [ironjacamar-deployers-common-1.0.11.Final.jar:1.0.11.Final]
	at java.security.AccessController.doPrivileged(Native Method) [rt.jar:1.7.0_05]
	at org.jboss.jca.deployers.common.AbstractDsDeployer.createSubject(AbstractDsDeployer.java:1041) [ironjacamar-deployers-common-1.0.11.Final.jar:1.0.11.Final]
	at org.jboss.jca.deployers.common.AbstractDsDeployer.deployDataSource(AbstractDsDeployer.java:581) [ironjacamar-deployers-common-1.0.11.Final.jar:1.0.11.Final]
	at org.jboss.jca.deployers.common.AbstractDsDeployer.createObjectsAndInjectValue(AbstractDsDeployer.java:282) [ironjacamar-deployers-common-1.0.11.Final.jar:1.0.11.Final]
	at org.jboss.as.connector.subsystems.datasources.AbstractDataSourceService$AS7DataSourceDeployer.deploy(AbstractDataSourceService.java:283) [jboss-as-connector-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.connector.subsystems.datasources.AbstractDataSourceService.start(AbstractDataSourceService.java:116) [jboss-as-connector-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
	at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.7.0_05]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.7.0_05]
	at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_05]

AND

ERROR [org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject] (management-handler-thread - 3) IJ000614: Exception during createSubject() PB00024: Access Denied:Unauthenticated caller:null: java.lang.SecurityException: PB00024: Access Denied:Unauthenticated caller:null
	at org.jboss.security.plugins.JBossSecuritySubjectFactory.createSubject(JBossSecuritySubjectFactory.java:89) [picketbox-4.0.9.Final.jar:4.0.9.Final]
	at org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject$1.run(PoolBySubject.java:121) [ironjacamar-core-impl-1.0.11.Final.jar:1.0.11.Final]
	at org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject$1.run(PoolBySubject.java:116) [ironjacamar-core-impl-1.0.11.Final.jar:1.0.11.Final]
	at java.security.AccessController.doPrivileged(Native Method) [rt.jar:1.7.0_05]
	at org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject.createSubject(PoolBySubject.java:115) [ironjacamar-core-impl-1.0.11.Final.jar:1.0.11.Final]
	at org.jboss.jca.core.connectionmanager.pool.strategy.PoolBySubject.testConnection(PoolBySubject.java:85) [ironjacamar-core-impl-1.0.11.Final.jar:1.0.11.Final]
	at org.jboss.as.connector.subsystems.common.pool.PoolOperations$TestConnectionInPool.invokeCommandOn(PoolOperations.java:121) [jboss-as-connector-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.connector.subsystems.common.pool.PoolOperations$1.execute(PoolOperations.java:60) [jboss-as-connector-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.AbstractOperationContext.executeStep(AbstractOperationContext.java:397) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.AbstractOperationContext.doCompleteStep(AbstractOperationContext.java:284) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.AbstractOperationContext.completeStep(AbstractOperationContext.java:211) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.connector.subsystems.common.pool.PoolOperations.execute(PoolOperations.java:74) [jboss-as-connector-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.AbstractOperationContext.executeStep(AbstractOperationContext.java:397) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.AbstractOperationContext.doCompleteStep(AbstractOperationContext.java:284) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.AbstractOperationContext.completeStep(AbstractOperationContext.java:211) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.ModelControllerImpl$DefaultPrepareStepHandler.execute(ModelControllerImpl.java:473) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.AbstractOperationContext.executeStep(AbstractOperationContext.java:397) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.AbstractOperationContext.doCompleteStep(AbstractOperationContext.java:284) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.AbstractOperationContext.completeStep(AbstractOperationContext.java:211) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.ModelControllerImpl.internalExecute(ModelControllerImpl.java:126) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.ModelControllerImpl.execute(ModelControllerImpl.java:111) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler.doExecute(ModelControllerClientOperationHandler.java:139) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.controller.remote.ModelControllerClientOperationHandler$ExecuteRequestHandler$1.execute(ModelControllerClientOperationHandler.java:108) [jboss-as-controller-7.1.2.Final.jar:7.1.2.Final]
	at org.jboss.as.protocol.mgmt.AbstractMessageHandler$2$1.doExecute(AbstractMessageHandler.java:295)
	at org.jboss.as.protocol.mgmt.AbstractMessageHandler$AsyncTaskRunner.run(AbstractMessageHandler.java:512)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) [rt.jar:1.7.0_05]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) [rt.jar:1.7.0_05]
	at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_05]
	at org.jboss.threads.JBossThread.run(JBossThread.java:122) [jboss-threads-2.0.0.GA.jar:2.0.0.GA]

And your CLI comman to test DataSource connections will fail like following:

[standalone@localhost:9999 /] /subsystem=datasources/data-source=MySqlDS_Pool:test-connection-in-pool
{
    "outcome" => "failed",
    "failure-description" => "JBAS010440: failed to invoke operation: JBAS010447: Connection is not valid",
    "rolled-back" => true
}

.
.
Thanks
MiddlewareMagic Team


Copyright © 2010-2012 Middleware Magic. All rights reserved. |