Tag: EJB

Calling EJB3 to EJB3 Locally using @EJB Annotation

Hi,

Jay SenSharma

Jay SenSharma

Here is a simple demo of calling an EJB3 Stateless bean through another EJB3 bean which is reside inside the same EAR file. To refer to a Local EJB using @EJB annotation we must use the  Tag <ejb-local-ref> inside our “ejb-jar.xml” as described in the following post.

Many times we get following kind of error at the time of Deploying the application while using @EJB annotation…

Caused By: javax.naming.NameNotFoundException: While trying to look up ejb-info

Which usually happens because our deployment descriptors  are not configured properly to lookup a Local Bean and when the WebLogic Container tries to inject the Local EJB in to another Bean/WebApplication it fails due. Example:

http://forums.oracle.com/forums/thread.jspa?threadID=2174802&tstart=0

Step1). Create a directory somewhere in your file system like “C:\demo\src”

Step2). Now place the following files inside “C:\demo\src” directory:

“CalculatorLocal.java”

//CalculatorRemote.java
package calculator;
import javax.ejb.*;
@Local
public interface CalculatorLocal
{
  public int add(int x,int y);
}

“CalculatorBean.java”

package calculator;
import javax.ejb.*;

@Stateless(name="CalculatorBean")
public class CalculatorBean implements CalculatorLocal
 {
   public int add(int x,int y)
    {
	  System.out.println("\n\t[CalculatorBean]  add() invoked.");
      return (x+y);
    }
 }
 

“CallerRemote.java”

//CalculatorRemote.java
package caller;
import javax.ejb.*;
@Remote
public interface CallerRemote
{
     public String testMethod();
   	 public String callEJBOne(int a, int b);
}
 

“CallerBean.java”

//CalculatorBean.java
package caller;
import javax.ejb.*;
import javax.naming.*;
import java.util.*;

@Stateless(name = "CallerName", mappedName = "CallerMappedName")
public class CallerBean implements CallerRemote
 {
	 @EJB calculator.CalculatorLocal local;
     public String testMethod()
	    {
		   System.out.println("\n\n\t Bean testMethod() called....");
		   return "DONE----returned";
	    }

	public String callEJBOne(int a, int b)
	    {
           int result=0;
		   try{
		   System.out.println("\n\n\t Bean callEJBOne(a,b) called....");
           result=local.add(a,b);
		   }
		   catch(Exception e){ e.printStackTrace(); }
		   return "DONE----result = "+result;
	    }
 }
 

“ejb-jar.xml”

<ejb-jar 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/ejb-jar_3_0.xsd">

<enterprise-beans>
	<session>
		<ejb-name>CallerBean</ejb-name>
		<business-remote>caller.CallerRemote</business-remote>
		<ejb-class>caller.CallerBean</ejb-class>
		<session-type>Stateless</session-type>
		<ejb-local-ref>
		        <ejb-ref-name>ejb/CalculatorLocal</ejb-ref-name>
				<local>calculator.CalculatorLocal</local>
		</ejb-local-ref>
	</session>
</enterprise-beans>
</ejb-jar>

“application.xml”

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.4">
   <display-name>EJB3_to_EJB3_Local_Injection</display-name>

   <module>
	<ejb>ejbOne.jar</ejb>
    </module>

   <module>
	<ejb>ejbTwo.jar</ejb>
    </module>

</application>

“TestClientEjb3.java”

import caller.CallerRemote;
import javax.naming.*;
import java.util.*;
public class TestClientEjb3
{
	public static void main(String[] args)  throws Exception
	{
		  String  result="";
		System.out.println("\n\n\t Hello ...");
		   try{
                 Properties pr=new Properties();
                 pr.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
	             pr.put(Context.PROVIDER_URL,"t3://localhost:7001");

		   InitialContext ic=new InitialContext(pr);
           CallerRemote remote=(CallerRemote)ic.lookup("CallerMappedName#caller.CallerRemote");
           result=remote.callEJBOne(1000,2000);
		   }
		   catch(Exception e){ e.printStackTrace(); }
		  System.out.println("ONE----result = "+result);
	    }
}

Step3). Now place the following “build.xml” file inside “C:\demo” directory:

<project name="webservices-complex" default="deploy">

<property name="wls.username" value="weblogic" />
<property name="wls.password" value="weblogic" />
<property name="wls.hostname" value="localhost" />
<property name="wls.port" value="7001" />
<property name="wls.server.name" value="AdminServer" />
<property name="wl.home" value="C:/bea1033/wlserver_10.3" />

<property name="src.dir" value="src" />
<property name="deploy.stuff" value="deploy" />
<property name="build.dir" value="build" />
<property name="ear.name" value="EJB3LocalLookupEAR" />
<property name="ear.dir" value="${deploy.stuff}/${ear.name}" />
<property name="ejb.jar.name.1" value="ejbOne.jar" />
<property name="ejb.jar.name.2" value="ejbTwo.jar" />
<property name="client.jar.name" value="testClient.jar" />

<path id="wl.classpath">
        <fileset dir="${wl.home}/server/lib">
              <include name="*.jar"/>
        </fileset>
        <fileset dir="${ear.dir}">
              <include name="${ejb.jar.name.1}"/>
              <include name="${ejb.jar.name.2}"/>
        </fileset>
</path>

<path id="client.classpath">
        <fileset dir="${wl.home}/server/lib">
              <include name="weblogic.jar"/>
			  <exclude name="jrmp.jar"/>
        </fileset>
        <fileset dir="${build.dir}">
              <include name="${client.jar.name}"/>
        </fileset>
</path>

<target name="init">
	<mkdir dir="${build.dir}"/>
	<mkdir dir="${ear.dir}"/>
	<mkdir dir="${ear.dir}/META-INF"/>
	<mkdir dir="${deploy.stuff}" />
</target>

<target name="compile1" depends="init">
	<javac srcdir="${src.dir}" destdir="${build.dir}"  includes="CalculatorBean.java,CalculatorLocal.java"/>
	<jar destfile="${ear.dir}/${ejb.jar.name.1}" basedir="${build.dir}" />
    <delete dir="${build.dir}" />
</target>

<target name="compile2" depends="compile1">
	<mkdir dir="${build.dir}"/>
	<mkdir dir="${build.dir}/META-INF" />
	<javac srcdir="${src.dir}" destdir="${build.dir}"  includes="CallerBean.java,CallerRemote.java" classpathref="wl.classpath"/>
	<copy file="${src.dir}/ejb-jar.xml" tofile="${build.dir}/META-INF/ejb-jar.xml"/>
	<jar destfile="${ear.dir}/${ejb.jar.name.2}" basedir="${build.dir}" />
    <copy file="${src.dir}/application.xml" tofile=	"${ear.dir}/META-INF/application.xml" />
	<delete dir="${build.dir}"/>
</target>

<target name="deploy" depends="compile2">
<wldeploy action="deploy" name="${ear.name}" source="${ear.dir}" user="${wls.username}"
password="${wls.password}" verbose="true" adminurl="t3://${wls.hostname}:${wls.port}" targets="${wls.server.name}"/>
</target>

<target name="undeploy">
<wldeploy action="undeploy" failonerror="false" name="EJB3LocalLookupEAR" user="${wls.username}"
     password="${wls.password}" verbose="true" adminurl="t3://${wls.hostname}:${wls.port}" targets="${wls.server.name}"/>
</target>

<target name="compileClient">
	<delete dir="${build.dir}"/>
	<mkdir dir="${build.dir}"/>
	<javac srcdir="${src.dir}" destdir="${build.dir}"  includes="CallerRemote.java" classpathref="wl.classpath"/>
	<javac srcdir="${src.dir}" destdir="${build.dir}"  includes="TestClientEjb3.java" classpathref="wl.classpath"/>
	<jar destfile="${build.dir}/${client.jar.name}" basedir="${build.dir}" />
</target>

<target name="run" depends="compileClient">
    <java classname="TestClientEjb3" classpathref="client.classpath"/>
</target>

</project>

Step4). Now run the “. ./setWLSEnv.sh” to set the CLASSPATH and PATH then run the ANT script like following:

building_And_Deploying_Ejb3Local_App

building_And_Deploying_Ejb3Local_App

Step5). Now invoke the Client like following:

Running_The_Client

Running_The_Client

NOTE: Above instruction is for EJB to EJB lookup.

But if you are trying to inject an EJB  Bean inside your Servlet (WebApplication) then you must make sure that you are using the following link of “webxml”   which uses Servlet 2.5  XSD specification:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">

</webapp>

.

.

Thanks

Jay SenSharma


WebLogic WorkManager with EJB3 And MaxThread Constraint

Hi,
Jay SenSharma

Jay SenSharma

WebLogic Provides us a feature to manage the WebLogic Threads per application using WorkManagers. In this demo we will see how we can instruct WebLogic to allocate only one thread to process the Clients request. We will develop a simple EJB3 application and we will assign a WorkManager with MaxThreadConstraint as 2. It means for Any number of Clients request to that EJB, the WebLogic will allocate only 1 Thread for request processing.
.
Step1). Please follow the instructions mentioned in the  link: http://middlewaremagic.com/weblogic/?p=2691 to create WebLogic WorkManager in seconds using WLST. Just make sure that you chose the following values for Max and Min Threads to see how this sample works. Later you can use your own values.
MaxThread=2
MinThread=2
.
Step2). Now create a Directory somewhere in your file system like:  ”C:\temp\EJB3_With_WorkManager”
.
Step3). Now create a EJB remote Interface “CalculatorRemote.java” inside “C:\temp\EJB3_With_WorkManager” like following:
//CalculatorRemote.java
package calculator;
import javax.ejb.*;
@Remote
public interface CalculatorRemote
{
  public int add(int x,int y);
}
Step4). Now ssame way create a Stateless Session Bean “CalculatorBean.java” inside “C:\temp\EJB3_With_WorkManager” like following:
//CalculatorBean.java
package calculator;
import javax.ejb.*;
@Stateless
public class CalculatorBean implements CalculatorRemote
 {
   public int add(int x,int y)
    {
	  System.out.println("Current ThreadName Is: "+Thread.currentThread().getName());
      return (x+y);
    }
 }
Step5). Now create a directory with name “META-INF” inside “C:\temp\EJB3_With_WorkManager” and then create a file “weblogic-ejb-jar.xml”  inside “C:\temp\EJB3_With_WorkManager\META-INF”  directory like following so that we can assign the WebLogic WorkManager to the EJB using “dispatch-policy” tag:
<?xml version='1.0' encoding='UTF-8'?>
<weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/10.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <weblogic-enterprise-bean>
    <ejb-name>CalculatorBean</ejb-name>
    <stateless-session-descriptor>
      <pool></pool>
      <stateless-clustering>
        <home-is-clusterable>false</home-is-clusterable>
        <stateless-bean-is-clusterable>false</stateless-bean-is-clusterable>
      </stateless-clustering>
    </stateless-session-descriptor>
    <transaction-descriptor></transaction-descriptor>
    <jndi-name>X</jndi-name>
    <dispatch-policy>JackWorkManager</dispatch-policy>
    <remote-client-timeout>0</remote-client-timeout>
  </weblogic-enterprise-bean>
</weblogic-ejb-jar>
Step6). Now run the “setWLSEnv.cmd” in a command prompt to set the classpath then Compile and EJBs and then make a Jar of it like following:
compiling_Ejb3

compiling_Ejb3

Step7). Now deploy the above created EJB3 jar file “Ejb3.jar” in WebLogic Server.
.
Step8). Check the AdminConsole where you are able to see the WorkManager properly assigned to your EJB3 or Not?
 EJB3_Workmanager_Console_look

EJB3_Workmanager_Console_look

Step9). Now Create a Client somewhere in your file system and set the Classpath to Ejb3.jar which we created above…. Client program like following “Ejb3Client.java”.  This client is going to send 5000 fresh requests to the WebLogic Server.
package calculator;
import javax.naming.*;
import java.util.*;
public class  Ejb3Client
{
	public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
	private static String serverUrl ="t3://localhost:7001";
	public static void main(String[] ar)  throws Exception
	{
		for(int i=0;i<=5000;i++)
		 {
           InitialContext ic=null;
           try{
		        Hashtable env = new Hashtable();
		        env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
		        env.put(Context.PROVIDER_URL, serverUrl);
  		        ic = new InitialContext(env);
              }
            catch(Exception e)
             {
			    System.out.println("\n\t Didnot get InitialContext: "+e);
			 }
           try
             {

                Object obj=ic.lookup("calc#calculator.CalculatorRemote");
                CalculatorRemote remote=(CalculatorRemote)obj;
                System.out.println("\n\n\tRemote=>"+remote.getClass());

				System.out.println("\n\n\tClassLoading=>1");
                Class.forName("calculator.CalculatorRemote");
				System.out.println("\n\n\tClassLoading=>2");

                System.out.println("\n\n\t SUM = "+remote.add(Integer.parseInt(ar[0]),Integer.parseInt(ar[1])));
             }
           catch(Exception e)
             {
                System.out.println("\n\n\t jack Exception => "+e);
                e.printStackTrace();
             }
           System.out.println("\n\t Iteration ------------ "+i);
	    }
	}
}
Step10). Run the client and then check the Server STDOUT that all the 5000 request will be processed only by a Two Execute Thread….It means due to MaxThreadConstraint=2 the WebLogic will not allocate more than two thread to process clients request.
EJB3_Workmanager_Client_Console_Output

EJB3_Workmanager_Client_Console_Output

In the output (STDOUT) of the Server you will see that there are only 2 Threads which are processing all the 5000 Clients request…..

Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
Current ThreadName Is: [ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
.
.
Thanks
Jay SenSharma

Tuning EJB3 Application using Plan.xml

Hi,

Jay SenSharma

Jay SenSharma

In response to comment posted regarding tunning of EJB3 app:   http://middlewaremagic.com/weblogic/?p=1696#comment-1356

Here is a Simple Demonstration of Changing the Tunable Parameters of an EJB3.0 application using “Plan.xml”. As we have many annotations available as part of EJB3.0 Specifications But we dont have the Annotations available for many Tunable parameters like “max-beans-in-free-pool”, “initial-beans-in-free-pool”…etc. If we want to change/add these values for our EJB3.0/EJB2.x Application then we have have to change provide our own “weblogic-ejb-jar.xml” file.

But In Most of the production scenarios The WebLogic Administrator doesnt have priviledge to change any thing inside the EJB jar module. So in that case A WebLogic AdminiStartor can use the “Plan.xml” file to change these Tunable Parameters Settings…

Step1). Create a Directory somewhere in your file system.
Example: C:\EJB3_Plan_XML_Demo

Step2). Create a Directory “EJB3App” inside Directory “C:\EJB3_Plan_XML_Demo”

Step3). Provide the EJB3 Business Interface “CalculatorRemote.java” inside “C:\EJB3_Plan_XML_Demo\EJB3App”

package calculator;
import javax.ejb.*;
@Remote
public interface CalculatorRemote
{
public int add(int x,int y);
public int sub(int x,int y);
public int mult(int x,int y);
public int div(int x,int y);
}

Step4). Provide the EJB3 Stateless Bean Implementation class “CalculatorBean.java” inside “C:\EJB3_Plan_XML_Demo\EJB3App”

package calculator;
import javax.ejb.*;
@Stateless
public class CalculatorBean implements CalculatorRemote
{
public int add(int x,int y)
{
return (x+y);
}
public int sub(int x,int y)
{
return(x-y);
}
public int mult(int x,int y)
{
return (x*y);
}
public int div(int x,int y)
{
return (x/y);
}
}

Step5). Now Create a directory “META-INF” inside “C:\EJB3_Plan_XML_Demo\EJB3App” and then provide an Empty “weblogic-ejb-jar.xml” file as following:

<weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/weblogic-ejb-jar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-ejb-jar http://www.bea.com/ns/weblogic/weblogic-ejb-jar/1.0/weblogic-ejb-jar.xsd">
</weblogic-ejb-jar>

NOTE: Step5 is the Most important Step because if we want to override setting of any descriptor then at least that file must exist inside our application….doesn’t matter if it is Empty or having some contents inside it.

Step6). Now a command prompt and the run the “setWLSEnv.cmd” and then Compile the above two ejb stuffs.

Compiling_EJB3_App

Compiling_EJB3_Ap

Step7). Write the “build.xml” file to deploy your Application…inside “C:\EJB3_Plan_XML_Demo” like following:

<project name="webservices-hello_world" default="deploy">
<!-- set global properties for this build -->
<property name="wls.username" value="weblogic" />
<property name="wls.password" value="weblogic" />
<property name="wls.hostname" value="localhost" />
<property name="wls.port" value="7001? />
<property name="wls.server.name" value="AdminServer" />

<target name="deploy">
<wldeploy action="deploy" name="EJB3App" source="EJB3App"
user="${wls.username}" password="${wls.password}" verbose="true"
adminurl="t3://${wls.hostname}:${wls.port}" targets="${wls.server.name}" />
</target>

<target name="undeploy">
<wldeploy action="undeploy" name="EJB3App" failonerror="false"
user="${wls.username}" password="${wls.password}" verbose="true"
adminurl="t3://${wls.hostname}:${wls.port}" targets="${wls.server.name}" />
</target>

</project>

Step8). Now open a Command prompt and then run “setWLSEnv.cmd” then run the above ant “build.xml” file to deploy your application:

Deploying_EJB3_App_using_Ant

Deploying_EJB3_App_Using_Ant

Step9). Now Login to Admin Consoel to see how many initial beans have been created for our EJB3App.

Step10). Now Provide the “plan.xml” file inside “C:\EJB3_Plan_XML_Demo” location as following to change the “initial-bean-in-free-pool” setting for our EJB3App…

<?xml version=’1.0' encoding=’UTF-8'?>
<deployment-plan xmlns="http://www.bea.com/ns/weblogic/deployment-plan" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/deployment-plan http://www.bea.com/ns/weblogic/deployment-plan/1.0/deployment-plan.xsd" global-variables="false">
<application-name>EJB3App</application-name>

<variable-definition>
<variable>
<name>initialPoolVariable</name>
<value>15</value>
</variable>
</variable-definition>

<module-override>
<module-name>EJB3App</module-name>
<module-type>ejb</module-type>
<module-descriptor external="true">
<root-element>weblogic-ejb-jar</root-element>
<uri>META-INF/weblogic-ejb-jar.xml</uri>
<variable-assignment>
<name>initialPoolVariable</name>
<xpath>/weblogic-ejb-jar/weblogic-enterprise-bean/[ejb-name="CalculatorBean"]/stateless-session-descriptor/pool/initial-beans-in-free-pool</xpath>
</variable-assignment>
</module-descriptor>
</module-override>

<config-root>C:\EJB3_Plan_XML_Demo\</config-root>
</deployment-plan>

Step11). provide the “build_with_plan.xml” file inside “C:\EJB3_Plan_XML_Demo” to redepoy the application with the settings provided as part of our “plan.xml” file. Like following :

Redeploying_EJB_Using_Pla

Redeploying_EJB_Using_Pla

Step12). Now again Login to AdminConsole and then see the Monitoring Tab of your EJB3App … like following:

AfterRedeploying_UsingPlan

AfterRedeploying_UsingPlan

.

.

Thanks

Jay SenSharma


Resource DataSource Injection in EJB3

Hi,

Jay SenSharma

Jay SenSharma

Here we are going to see how we can use the DataSources inside our EJB3.0 Application. Basically there are two Options to get the DataSource object inside the EJB3 Beans.

Option-1). Using Traditional Way we can get the dataSource Object by Looking up in the JNDI tree of the Server to get teh dataSource object.
Option-2). Using the resource Injection techniqueue we can get the DataSource object in two lines of codes…(it reduces the code length as well)
In the below demonstration we will use two fidderent methods to get the DataSource objects in above two ways using two different Business methods.

Step1). Please refer to the following Link to Create a DataSource through the Admin Console…http://middlewaremagic.com/weblogic/?p=2050

Step2). Now Create a Directory somewhere in your file system like “C:\Resource_Injection” this directory is going to become our EAR Application.

Step3). Now Create another Directotry “MyEJB” inside “C:\Resource_Injection”.

Step4). Write the EJB Interface “CalculatorRemote.java” inside “C:\Resource_Injection\MyEJB” like following:

package calculator;
import javax.ejb.*;
import javax.sql.DataSource;
@Remote
public interface CalculatorRemote
{
public String getDataSourceUsingTraditionalWay(String query);
public String getDataSourceUsingResourceInjection(String query);
}

Step4a). Write the EJB Stateless Session Bean class “CalculatorBean.java” inside “C:\Resource_Injection\MyEJB” like following:

package calculator;
import javax.ejb.*;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
import javax.annotation.*;

@Stateless(mappedName="calc")
public class CalculatorBean implements CalculatorRemote
{
@Resource(mappedName="TestDSJndi")
DataSource injectedDataSource;
public String getDataSourceUsingResourceInjection(String query)
{
System.out.println("inside betterWayToGetDataSourceUsingResourceInjection() method ");
System.out.println("betterWayToGetDataSourceUsingResourceInjection() got DS = "+injectedDataSource);
String result=this.executeSQL(query,injectedDataSource);
return result;
}

public String getDataSourceUsingTraditionalWay(String query)
{
DataSource traditionalDS=null;
try{
InitialContext ic=new InitialContext();
traditionalDS=(DataSource)ic.lookup("TestDSJndi");
System.out.println("\n\t Inside getDataSourceUsingTraditionalWay.....Got DataSource = "+traditionalDS);
}
catch(Exception e)
{
System.out.println("\n\t Unable to get DataSource using getDataSourceUsingTraditionalWay: "+e);
}
String result= this.executeSQL(query,traditionalDS);
return result;
}

public String executeSQL(String query,DataSource ds)
{
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
String resultString="";
try{
con=ds.getConnection();
stmt=con.createStatement();
rs=stmt.executeQuery(query);
int tableCount=1;
System.out.println("\n\t Following Tables Are Available in Systables of Pointbase..");
while(rs.next())
{
String tableName=rs.getString(2);
System.out.println("\t Table-"+tableCount+":\t"+tableName);
tableCount++;
resultString=resultString+"<BR>"+tableName;
}
}
catch(Exception e)
{
System.out.println("\n\t Exception Occured: "+e);
}
finally
{
try { if(rs!=null) rs.close(); }
catch (Exception rse) {}
try { if(stmt!=null) stmt.close(); }
catch (Exception sse) {}
try { if(con!=null) con.close(); }
catch (Exception cse) {}
}
return "Result Of Query: "+query+" is Following: "+resultString;
}
}

Step5). Open a command prompt then run “setWLSEnv.cmd” here and then compile the EJBs like following:

Compiling EJB  Classes

Compiling EJB Classes

Step6). Now Create a Directory “MyWebApp” inside “C:\Resource_Injection”

Step7). Now Create “WEB-INF” Directory and provide the following “web.xml” file inside “C:\Resource_Injection\MyWebApp\WEB-INF”

<?xml version='1.0' encoding='UTF-8'?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</web-app>


NOTE: Make Sure that you are using the Latest “web.xml” Schema because the Resource Injection and EJB Injection is supported from Servlet Specification 2.5…So make sure that u are not using any “web.xml” file which is using DTD declarations.

Step8). Provide the following “index.jsp” file inside “C:\Resource_Injection\MyWebApp” directory.

<%@ page import="javax.sql.*,calculator.*, javax.naming.*" %>
<%
InitialContext ic=new InitialContext();
CalculatorRemote remote=(CalculatorRemote)ic.lookup("calc#calculator.CalculatorRemote");
String result=remote.getDataSourceUsingTraditionalWay("SELECT * FROM SYSTABLES");
System.out.println("\n\t Result TRADITIONAL WAY: "+result);
out.println("<h2>Result TRADITIONAL WAY</h2><BR> "+result);

System.out.println("<h2>Standard Way of Getting DataSource Using Resource Injection BELOW</h2>");
String resultInjected=remote.getDataSourceUsingResourceInjection("SELECT * FROM SYSTABLES");
System.out.println("\n\t Result RECOMMENDED INJECTED WAY: "+resultInjected);
out.println("<h2>Result RECOMMENDED INJECTED WAY</h2><BR> "+resultInjected);
%>

Step9). Create a “META-INF” directory inside “C:\Resource_Injection” to provide the EAR deployment descriptors inside it. Create a file “application.xml” inside “C:\Resource_Injection\META-INF” like following:

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.4">
<module>
<ejb>MyEJB</ejb>
</module>
<module>
<web>
<web-uri>MyWebApp</web-uri>
<context-root>MyWebApp</context-root>
</web>
</module>
</application>

Step10). Your Application is ready for deployment…Open Admin Console and then Deploy the “Resource_Injection” there….this is your EAR application.

Step11). Hit the Application like : http://localhost:7001/MyWebApp/index.jsp

.
.
Thanks
Jay SenSharma


EJB3 WebLogic10.3 and Generics Issue

Hi,

Jay SenSharma

Jay SenSharma

If we use any Generic implementation in EJB3.0 deployed on weblogic Server then we face some errors like following:

Example:
package test;
import java.util.List;
public interface TestGenericsInEJB3
{
public List callPlainMethod();
public List<User> callGenericMethod();
}

If our EJB3 Bean uses the above Interface as a remote Interface then we will find the following kind of exception while invoking it remotely.

java.lang.AssertionError: Can not find generic method public abstract java.util.List<test.
TestGenericsInEJB3> callGenericMethod() in EJB Object
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.getTargetMethod(RemoteBusinessIntfProxy.java:159)
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:53)
at $Proxy79.
callGenericMethod(Unknown Source)
at jsp_servlet.__index._jspService(__index.java:53)

There are two following possibilities for the above Exception:

Case-1: When the business interface extends java.rmi.Remote, and extends some generic methods from a super class, the deployment will fail.
Workaround: This case is a limitation in WLS 10.3 or greater and hence no workaround applicable.

Case-2: When the business interface doesn’t extend java.rmi.Remote, the invocation on the generic business methods will fail.
Workaround: It can be resolved by downloading the needed classes from the server side. If network downloading is disabled, however, the invocation will fail still.

If network downloading isn’t permitted in the user’s environment, it is recommended that you run appc first, then add the generated classes to the classpath of the client side. Please refer to the following link to see how we can generate the EJB Client Jar: http://middlewaremagic.com/weblogic/2010/04/02/generating-ejb3-clientjar/

.
.
Thanks
Jay SenSharma


Generating EJB3 ClientJar using APPC utility

Hi,

Jay SenSharma

Jay SenSharma

Why We Need to generate EJB Client Jar (Stubs) for Client side Usages?

Many times we see various issues in the absence of client Jar at client side like NoSuchMethodError, CORBA errors,the following Kind of Stack Trace at client end, while invoking the EJB methods:

java.lang.AssertionError: java.lang.ClassNotFoundException: com.abc.bcd.GetCredit
at weblogic.ejb.container.internal.RemoteBusinessIntfGenerator.generateRemoteInterface (RemoteBusinessIntfGenerator.java:57)
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.readObject (RemoteBusinessIntfProxy.java:205)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)

Example: http://forums.oracle.com/forums/thread.jspa?threadID=839694&tstart=0

Here In this Demonstration we will see following 3-Things…

PART-A). How to Develope a Simple EJB3 Stateless Application.

PART-B). How to Generate the EJB3 Deployment Descriptors using APPC utility from EJB Jar Application.

PART-3). Then How to Edit this EJB3 Deployment Descriptors to Generate ClientJars & Assign Custom JNDI Name to our EJB.

We will see some other options as well to explore the “weblogic.Appc” utility in this sample.

…………….. =========================================

******** Begin Of PART-A Below *********

…………….. =========================================
Step1). So we begin by creating a Simple Directory somewhere inside our file system: Example create a Directory inside : “C:\CustomJNDIName”

Step2). Create “src” directory inside “C:\CustomJNDIName” location.

Step3). Provide the “ReplicableSFSRemoteIntf.java” program inside “C:\CustomJNDIName\src”

package sfsb3;
import javax.ejb.*;
@Remote
public interface ReplicableSFSRemoteIntf {
public void removeWithRetain()throws Exception;
public void removeWithoutRetain() throws Exception;
public String printBean ();
public int testIncrement() throws Exception;
public int testDecrement() throws Exception;
public int getCount() throws Exception;
}

Step4). Provide the “ReplicableSFSLocalIntf.java” program inside “C:\CustomJNDIName\src”

package sfsb3;
import javax.ejb.*;
@Local
public interface ReplicableSFSLocalIntf {
public void removeWithRetain() throws Exception;
public void removeWithoutRetain() throws Exception;
public String printBean ();
public int testIncrement() throws Exception;
public int testDecrement() throws Exception;
public int getCount() throws Exception;
}

Step5). Now provide The Bean Implementation class “ReplicableSFSBean.java” program inside “C:\CustomJNDIName\src”

package sfsb3;
import javax.ejb.*;
@Stateful
public class ReplicableSFSBean implements ReplicableSFSRemoteIntf, ReplicableSFSLocalIntf
{
int count = 0;
public ReplicableSFSBean() {
System.out.println("\n\t ReplicableSFSBean--> ReplicableSFSBean() invoked");
}
@Init("create")
public void initMethod() throws CreateException {
System.out.println("\n\t ReplicableSFSBean--> public void initMethod() invoked");
}

@Remove(retainIfException=true)
public void removeWithRetain() throws Exception{
System.out.println("\n\t ReplicableSFSBean--> removeWithRetain() invoked");
}

@Remove
public void removeWithoutRetain() throws Exception{
System.out.println("\n\t ReplicableSFSBean--> removeWithoutRetain() invoked");
}

public String printRemoteIntf () {
System.out.println("\n\t ReplicableSFSBean ---> public String printRemoteIntf () invoked");
return "ReplicableSFSRemoteObjectIntf";
}

public String printLocalIntf () {
System.out.println("\n\t ReplicableSFSBean ---> public String printLocalIntf () invoked");
return "ReplicableSFSLocalObjectIntf";
}

public String printBean () {
System.out.println("\n\t ReplicableSFSBean ---> public String printBean () invoked");
return "ReplicableSFSBean";
}

public int testIncrement() throws Exception
{
System.out.println("\n\t ReplicableSFSBean ---> public int testIncrement() invoked");
count=count+5;
return count;
}

public int testDecrement() throws Exception
{
System.out.println("\n\t ReplicableSFSBean ---> public int testDecrement() invoked");
count=count-2;
return count;
}

public int getCount() throws Exception
{
System.out.println("\n\t ReplicableSFSBean ---> public int getCount() invoked");
return count;
}
}

Step6). Now develop the ANT Build file “build.xml” inside “C:\CustomJNDIName” as following:

<project name="Test-Client_Jar_EJB3" default="deploy" basedir=".">

<property name="wl.home.lib" value="C:\bea103\wlserver_10.3\server\lib" />
<property name="wls.username" value="weblogic" />
<property name="wls.password" value="weblogic" />
<property name="wls.hostname" value="localhost" />
<property name="wls.port" value="7001" />
<property name="admin.server.name" value="AdminServer" />
<property name="deploy.target" value="AdminServer" />

<property name="src.dir" value="src"/>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="${build.dir}"/>
<property name="jar.file.name" value="SFSB_EJB3"/>
<property name="deploy.name" value="SFSB_EJB3" />
<property name="deploy.source" value="SFSB_EJB3.jar" />

<path id="custom.classpath">
<fileset dir="${wl.home.lib}">
<include name="*.jar"/>
</fileset>
</path>

<taskdef name="wldeploy" classname="weblogic.ant.taskdefs.management.WLDeploy"/>

<target name="init" depends="clean">
<mkdir dir="${build.dir}"/>
</target>

<target name="clean" >
<delete dir="build"/>
</target>

<target name="compile" depends="init">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" destdir="${classes.dir}" />
</target>

<target name="jar" depends="compile">
<mkdir dir="${jar.dir}"/>
<jar destfile="${jar.dir}/${jar.file.name}.jar" basedir="${classes.dir}"/>
</target>
</project>

Step 7). Now Open a Command Window ….then run “setWLSEnv.sh” or “setWLSEnv.cmd” then run the above Ant script to Build the EJB jar file.

OUTPUT:

C:\CustomJNDIName>ant  jar
Buildfile: build.xml

clean:
[delete] Deleting directory C:\CustomJNDIName\build

init:
[mkdir] Created dir: C:\CustomJNDIName\build

compile:
[mkdir] Created dir: C:\CustomJNDIName\build\classes
[javac] Compiling 3 source files to C:\CustomJNDIName\build\classes

jar:
[jar] Building jar: C:\CustomJNDIName\build\SFSB_EJB3.jar

BUILD SUCCESSFUL
Total time: 1 second

…………….. =========================================

******** Begin Of PART-B Below *********

…………….. =========================================
Step 8). Just Observer the Generated Jar “SFSB_EJB3.jar” inside “C:\CustomJNDIName\build”. It doesnt have any Deployment descriptors.

Step9). To generate the Deployment descriptors from the Jar “SFSB_EJB3.jar” we can use the following “weblogic.appc” Attribute:


C:\CustomJNDIName\build>   <strong>java weblogic.appc -source 1.5 -output OUTPUT -writeInferredDescriptors SFSB_EJB3.jar</strong>

—————-

Step10). Now open the OUTPUT directory which is created inside “C:\CustomJNDIName\build” directory and then observe that the Default EJB3 Descriptors are Created inside “META-INF” directory like following:

“ejb-jar.xml”

<?xml version='1.0' encoding='UTF-8'?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" metadata-complete="true">

<enterprise-beans>
<session>
<ejb-name>ReplicableSFSBean</ejb-name>
<business-local>sfsb3.ReplicableSFSLocalIntf</business-local>
<business-remote>sfsb3.ReplicableSFSRemoteIntf</business-remote>
<ejb-class>sfsb3.ReplicableSFSBean</ejb-class>
<session-type>Stateful</session-type>
<remove-method>
<bean-method>
<method-name>removeWithRetain</method-name>
<method-params></method-params>
</bean-method>
<retain-if-exception>true</retain-if-exception>
</remove-method>
<remove-method>
<bean-method>
<method-name>removeWithoutRetain</method-name>
<method-params></method-params>
</bean-method>
<retain-if-exception>false</retain-if-exception>
</remove-method>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>

<assembly-descriptor></assembly-descriptor>
</ejb-jar>

Default “weblogic-ejb-jar.xml” as following:

<weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/weblogic-ejb-jar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-ejb-jar http://www.bea.com/ns/weblogic/weblogic-ejb-jar/1.0/weblogic-ejb-jar.xsd">

</weblogic-ejb-jar>


…………….. =========================================

******** Begin Of PART-C Below *********

…………….. =========================================
Step 11). Now Edit the “ejb-jar.xml” file …by adding the <ejb-client-jar>My_Ejb3_Client.jar</ejb-client-jar> Tag inside it. Like following:

<?xml version='1.0' encoding='UTF-8'?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" metadata-complete="true">
<enterprise-beans>
<session>
<ejb-name>ReplicableSFSBean</ejb-name>
<business-local>sfsb3.ReplicableSFSLocalIntf</business-local>
<business-remote>sfsb3.ReplicableSFSRemoteIntf</business-remote>
<ejb-class>sfsb3.ReplicableSFSBean</ejb-class>
<session-type>Stateful</session-type>
<remove-method>
<bean-method>
<method-name>removeWithRetain</method-name>
<method-params></method-params>
</bean-method>
<retain-if-exception>true</retain-if-exception>
</remove-method>
<remove-method>
<bean-method>
<method-name>removeWithoutRetain</method-name>
<method-params></method-params>
</bean-method>
<retain-if-exception>false</retain-if-exception>
</remove-method>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
<assembly-descriptor></assembly-descriptor>

<ejb-client-jar>My_Ejb3_Client.jar</ejb-client-jar>

</ejb-jar>

Step 12). Now edit the “weblogic-ejb-jar.xml” file to assign a Simple Custom JNDI name to Our EJB …like following:

<weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/90" xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic-ejb-jar.xsd">

<weblogic-enterprise-bean>
<ejb-name>ReplicableSFSB</ejb-name>
<stateful-session-descriptor>
<business-interface-jndi-name-map>
<business-remote>sfsb3.ReplicableSFSRemoteIntf </business-remote>
<jndi-name>ReplicableSFSB</jndi-name>
</business-interface-jndi-name-map>
</stateful-session-descriptor>
</weblogic-enterprise-bean>

</weblogic-ejb-jar>

Step13). Now You can assemble your Edited EJB in the following location: “C:\CustomJNDIName\build\OUTPUT”. In the command prompt move inside this directory and Just Build the EJB jar again….

C:\CustomJNDIName\build\OUTPUT> jar cvf Edited_SFSB_EJB3.jar .

or

C:\CustomJNDIName\build\OUTPUT> jar cvf Edited_SFSB_EJB3.jar META-INF sfsb3

or

C:\CustomJNDIName\build\OUTPUT> jar cvf Edited_SFSB_EJB3.jar META-INF sfsb3 _WL_GENERATED

————–

Step14). Now Your “Edited_SFSB_EJB3.jar” is ready for deployment ….But we want to generate the client artifacts before deploying the Edited EJB…So for that we are going to use a New “buildClientJar.xml” inside “C:\CustomJNDIName\build\OUTPUT” Location like following:

<project name="Test-Client_Jar_EJB3" default="deploy" basedir=".">
<property name="wl.home.lib" value="C:\bea103\wlserver_10.3\server\lib" />
<property name="wls.username" value="weblogic" />
<property name="wls.password" value="weblogic" />
<property name="wls.hostname" value="localhost" />
<property name="wls.port" value="7001" />
<property name="admin.server.name" value="AdminServer" />
<property name="deploy.target" value="AdminServer" />

<property name="src.dir" value="src"/>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="${build.dir}"/>
<property name="jar.file.name" value="Edited_SFSB_EJB3"/>
<property name="deploy.name" value="Edited_SFSB_EJB3" />
<property name="deploy.source" value="Edited_SFSB_EJB3.jar" />

<path id="custom.classpath">
<fileset dir="${wl.home.lib}">
<include name="*.jar"/>
</fileset>
</path>

<taskdef name="weblogicAppc" classpathref="custom.classpath" classname="weblogic.ant.taskdefs.j2ee.Appc"/>
<taskdef name="wldeploy" classname="weblogic.ant.taskdefs.management.WLDeploy"/>

<target name="appc">
<weblogicAppc source="${jar.file.name}.jar" keepgenerated="true"
verbose="true" output="." clientJarOutputDir="." />
</target>

<target name="deploy" depends="appc">
<wldeploy action="deploy" name="${deploy.name}" source="${deploy.source}" user="${wls.username}" nostage="true"
password="${wls.password}" verbose="true" adminurl="t3://${wls.hostname}:${wls.port}" targets="${deploy.target}" />
</target>

<target name="redeploy">
<wldeploy action="redeploy" name="${deploy.name}" user="${wls.username}" nostage="true" source="${deploy.source}"
password="${wls.password}" verbose="true" adminurl="t3://${wls.hostname}:${wls.port}" targets="${deploy.target}" />
</target>

<target name="undeploy">
<wldeploy action="undeploy" name="${deploy.name}" failonerror="false" user="${wls.username}"
password="${wls.password}" verbose="true" adminurl="t3://${wls.hostname}:${wls.port}" targets="${deploy.target}" />
</target>
</project>

Step15). Now as soon as you run the above Ant Script you will find that “My_Ejb3_Client.jar” Client Jar file is generated inside the Current Directory and The EJB is deployed on the Server….

C:\CustomJNDIName\build\OUTPUT> ant -buildfile buildClientJar.xml

.

.

Thanks

Jay SenSharma


EJB3.0 TimerService Example/Demo

Hi,

Jay SenSharma

Jay SenSharma

The EJB3 timer service is an EJB-container provided service that allows you to create timers that schedule callbacks to occur when a timer object expires. Timer objects can be created for entity beans, message-driven beans, and stateless session beans. Timer objects expire at a specified time, after an elapsed period of time, or at specified intervals. For instance, you can use the timer service to send out notification when an EJB remains in a certain state for an elapsed period of time.  http://download.oracle.com/docs/cd/E15051_01/wls/docs103/ejb/implementing.  html

Here we are going to create a very simple EJB3 Stateless Timer.

Step1).  Create a Directory somewhere in your filesystem: F:\DELETE\EJB3_TimerService

Step2).  Create a Directory “EJBTimerTest” inside “F:\DELETE\EJB3_TimerService

Step3). Now Create 3 folders inside “F:\DELETE\EJB3_TimerService\EJBTimerTest” with the following names “META-INF”, “MyEJBApp” and “MyWebApp”.

Step4). Write the “JackTimer.java” interface inside “F:\DELETE\EJB3_TimerService\EJBTimerTest\MyEJBApp” directory.

package ejbs;
import javax.ejb.*;
@Local
public interface JackTimer
{
public void createTimer();
}
Step5). Write the StatelessBean “JackTimerBean.java” inside “F:\DELETE\EJB3_TimerService\EJBTimerTest\MyEJBApp” directory
package ejbs;
import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.ejb.Local;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

@Stateless (name="JackTimerBean", mappedName="JackTimerBean")
@Local (JackTimer.class)
@TransactionManagement(value=TransactionManagementType.BEAN )
@TransactionAttribute(value=NOT_SUPPORTED)
public class JackTimerBean implements JackTimer
{

@Resource
TimerService timerService;
public void createTimer()
{
System.out.println("\n\tinside createTimer() ....GOT the injected TimerService: "+timerService);
System.out.println("\n\tCrating timer");
System.out.println("\n\ttimerService [" + timerService + "]");
Timer timer = timerService.createTimer(20000,"Created new timer");
}

@Timeout
public void timeout(Timer timer)
{
System.out.println("\n\tTimeout occurred !!!");
}
}
Step6). compile the above two classes…   (Your EJB3.0 Timer is ready)

javac -d . *.java

Step7). Now move inside your WebApplication “F:\DELETE\EJB3_TimerService\EJBTimerTest\MyWebApp” and then write “index.jsp” page…

<html>
<body>
<h3>
<center><BR><BR>
<a href="TestServlet">Click Here to See EJB Injection in a Servlet...(It will Succeed)</a>
</body>
</html>
Step8). Place the following “web.xml” file indide “F:\DELETE\EJB3_TimerService\EJBTimerTest\MyWebApp\WEB-INF”
<?xml version="1.0"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>servlets.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>TestServlet</url-pattern>
</servlet-mapping>

</web-app>
Step9). Now write “TestServlet.java” class inside “F:\DELETE\EJB3_TimerService\EJBTimerTest\MyWebApp\WEB-INF\classes”
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.ejb.EJB;
public class TestServlet extends HttpServlet
{
@EJB
private ejbs.JackTimer reconTimer;

public void service (HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
  {
  PrintWriter out=res.getWriter();
  out.println("\n\tTestServlet service()\n\t EJBBean injection: reconTimer = "+reconTimer);
  System.out.println("\n\n\t EJBBean injection: reconTimer = "+reconTimer);
  reconTimer.createTimer();
 }
}
Step10). Compile the “TestServlet.java”
javac -d . TestServlet.java
Step11). write “application.xml” file inside… “F:\DELETE\EJB3_TimerService\EJBTimerTest\META-INF” directory
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.4">
<description>Split Directory Example</description>
<display-name>Split Directory Example</display-name>

<module>
<ejb>MyEJBApp</ejb>
</module>

<module>
<web>
<web-uri>MyWebApp</web-uri>
<context-root>MyWebApp</context-root>
</web>
</module>

</application>
.
Step12). Write the following “build.xml” file to deploy and undeploy your Enterprise application “EJBTimerTest”.(your EAR application Name)…
Please place the build.xml file in the following location (Just beside your EAR application): “F:\DELETE\EJB3_TimerService”
<project name="webservices-hello_world" default="deploy">
<!-- set global properties for this build -->
<property name="wls.username" value="weblogic" />
<property name="wls.password" value="weblogic" />
<property name="wls.hostname" value="localhost" />
<property name="wls.port" value="7001" />
<property name="wls.server.name" value="AdminServer" />

<target name="deploy">
<wldeploy action="deploy"  name="EJBTimerTest" source="EJBTimerTest" user="${wls.username}"
password="${wls.password}" verbose="true" adminurl="t3://${wls.hostname}:${wls.port}" targets="${wls.server.name}" />
</target>

<target name="undeploy">
<wldeploy action="undeploy" name="EJBTimerTest" failonerror="false" user="${wls.username}"
password="${wls.password}" verbose="true" adminurl="t3://${wls.hostname}:${wls.port}" targets="${wls.server.name}" />
</target>
</project>
.
Step 13). Now open a Shell prompt and then run “setWLSEnv.sh” then move to “F:\DELETE\EJB3_TimerService” directory in the Shell …and finally run the ANT
Step 14). Hit the URL:    http://localhost:7001/MyWebApp/index.jsp
As soon as you hit the Servlet …you will see that the EJB3.0 Timer created…and after “20000 millisecond” (20-seconds) it will timeout…as mentioned in the Bean class “JackTimerBean.java”.  The output of this program execution you can see in the Server STDOUT.
.
.
.
Thanks
Jay SenSharma

Securing EJB2.x Stateless Using RunAs

Hi,

Jay SenSharma

Jay SenSharma

Here is Simple demonstration of securing EJB2.x Stateless Session bean using the following Tags in “weblogic-ejb.jar.xml”…

if create-as-principal-name is set then use that principal
else If a run-as role has been specified for the bean in ejb-jar.xml then use a principal according to the rules for setting the run-as-role-assignment
else run ejbCreate as an anonymous principal.
The create-as-principal-name element only needs to be specified if operations within ejbCreate require more permissions than the anonymous principal would have.
This element effects the ejbCreate methods of stateless session beans and message-driven beans.

</span>
<pre><security-role-assignment>
<role-name>runAs_role_X</role-name>
<principal-name>jack</principal-name>
</security-role-assignment>
<run-as-role-assignment>
<role-name>runAs_role_X</role-name>
<run-as-principal-name>jack</run-as-principal-name>
</run-as-role-assignment>

Step1).Login to Admin Console and the “Security Realms”–>myRealm–>Users& Groups—>”

Here create a user with name = “jack” and password =”password”

Step2). Develop the Home Interface of our EJB…”IRemoteHome.java


package runassample;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface IRemoteHome extends EJBHome {
public ITestRemote create() throws CreateException, RemoteException;
}

Step3). Now develope the Remote Intyerface…”ITestRemote.java


package runassample;
import java.rmi.Remote;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
public interface ITestRemote extends EJBObject{
public String display(String name,String password) throws RemoteException;
public String SayHello(String hell) throws RemoteException;
}

Step4). Now develop the Stateless bean Class… “TestRun.java

package runassample;
import java.util.Hashtable;
import javax.ejb.SessionBean;
import weblogic.ejb.GenericSessionBean;
public class TestRun extends GenericSessionBean implements SessionBean {
private static final long serialVersionUID = 1L;

public void ejbCreate() {
System.out.println("\n\n\t ejbCreate() called on EJB TestRun.");
}

public String display(String name,String password){
System.out.println("\n\t executing display(String name) of TestRun Sessionean");
return "Hello Mr. "+name+"\t your Password is : "+password;
}
public String SayHello(String hell){

return hell;
}
}

Step5).Provide the “ejb-jar.xml” inside “META-INF” directory

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar id="ejb-jar_ID" version="2.1" 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/ejb-jar_2_1.xsd">
<display-name>Test</display-name>

<enterprise-beans>
<session>
<ejb-name>TestRun</ejb-name>
<home>runassample.IRemoteHome</home>
<remote>runassample.ITestRemote</remote>
<ejb-class>runassample.TestRun</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<security-identity>
<run-as>
<role-name>runAs_role_X</role-name>
</run-as>
</security-identity>
</session>
</enterprise-beans>

<assembly-descriptor>
<security-role>
<role-name>runAs_role_X</role-name>
</security-role>
<method-permission>
<role-name>runAs_role_X</role-name>
<method>
<ejb-name>TestRun</ejb-name>
<method-name>display</method-name>
<method-params>
<method-param>java.lang.String</method-param>
<method-param>java.lang.String</method-param>
</method-params>
</method>
</method-permission>
</assembly-descriptor>
</ejb-jar>

Step6). Now Develope “weblogic-ejb-jar.xml” inside “META-INF” directory

<?xml version="1.0" encoding="UTF-8"?>
<weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/90"
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic-ejb-jar.xsd">

<weblogic-enterprise-bean>
<ejb-name>TestRun</ejb-name>
<stateless-session-descriptor>
<pool></pool>
<stateless-clustering></stateless-clustering>
</stateless-session-descriptor>
<transaction-descriptor></transaction-descriptor>
<jndi-name>TestRun</jndi-name>
<remote-client-timeout>0</remote-client-timeout>
</weblogic-enterprise-bean>
<security-role-assignment>
<role-name>runAs_role_X</role-name>
<principal-name>jack</principal-name>
</security-role-assignment>

<run-as-role-assignment>
<role-name>runAs_role_X</role-name>
<run-as-principal-name>jack</run-as-principal-name>
</run-as-role-assignment>
</weblogic-ejb-jar>

Step7). Complie and Deploy the EJB on The Server.

Step8). Write the EJB Client to access the EJB…

import java.util.Hashtable;
import javax.naming.*;
import runassample.*;
public class RunAsEjbClient
{
public static void main(String ar[]) throws Exception
{
Context ctx = null;
java.sql.Connection conn = null;
Hashtable<String,String> ht = new Hashtable<String,String>();
ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,"t3://localhost:7001");
ht.put(Context.SECURITY_PRINCIPAL,ar[0]);
ht.put(Context.SECURITY_CREDENTIALS,ar[1]);

ctx = new InitialContext(ht);
runassample.IRemoteHome home = (runassample.IRemoteHome) ctx.lookup("TestRun");
runassample.ITestRemote remote=home.create();
System.out.println("\n\tremote.display(\"TestUser\",\"password\")"+remote.display(ar[0],ar[1]));
}
}

OUTPUT:

Run the client like:


<strong>C:\DELETE\RUN_AS_EJB>java RunAsEjbClient jack <span style="color: green;">password</span></strong>

remote.display("TestUser","password")Hello Mr. jack      your Password is : password

<strong>C:\DELETE\RUN_AS_EJB>java RunAsEjbClient jack <span style="color: red;">Wrongpassword</span></strong>
Exception in thread "main" javax.naming.AuthenticationException [Root exception is java.lang.SecurityException: User: jack, failed to be  authenticated.]
at weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:42)
at weblogic.jndi.WLInitialContextFactoryDelegate.toNamingException(WLInitialContextFactoryDelegate.java:783)
at weblogic.jndi.WLInitialContextFactoryDelegate.pushSubject(WLInitialContextFactoryDelegate.java:677)
at weblogic.jndi.WLInitialContextFactoryDelegate.newContext(WLInitialContextFactoryDelegate.java:468)
at weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialContextFactoryDelegate.java:375)
at weblogic.jndi.Environment.getContext(Environment.java:315)
at weblogic.jndi.Environment.getContext(Environment.java:285)
at weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:117)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.<init>(InitialContext.java:197)
at RunAsEjbClient.main(RunAsEjbClient.java:16)
Caused by: java.lang.SecurityException: User: jack, failed to be authenticated.
at weblogic.common.internal.RMIBootServiceImpl.authenticate(RMIBootServiceImpl.java:116)
at weblogic.common.internal.RMIBootServiceImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:477)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:473)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)

Thanks

Jay SenSharma


Monitoring EntityBeans Using JMX

Hi,

Jay SenSharma

Jay SenSharma

Many times we want to collect the Runtime statistics of our Application components like EJB’s. Here is a simple JMX example code to monitor the “EntityBean” Runtime informations.

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import javax.naming.Context;
import javax.naming.InitialContext;
import weblogic.management.MBeanHome;
import weblogic.management.runtime.ServerRuntimeMBean;
import weblogic.management.runtime.EJBPoolRuntimeMBean;
import weblogic.management.runtime.EntityEJBRuntimeMBean;
public class EntityMonitor
{
String url=”t3://localhost:9001″; // url for managed server
String username=”weblogic”;
String password=”weblogic”;
InitialContext ctx=null;
void getContext()throws Exception
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, “weblogic.jndi.WLInitialContextFactory”);
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_PRINCIPAL, username );
env.put(Context.SECURITY_CREDENTIALS, password);
ctx = new InitialContext(env);
MBeanHome home_x = (MBeanHome)ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
Set set=home_x.getMBeansByType(“EntityEJBRuntime”);
Iterator it=set.iterator();
while(it.hasNext())
{
EntityEJBRuntimeMBean entity=(EntityEJBRuntimeMBean)it.next();
System.out.println(“\n\n\tEntity::”+entity);
EJBPoolRuntimeMBean poolRuntime=entity.getPoolRuntime();
System.out.println(“\n\tEJBPoolRuntimeMBean :”+poolRuntime);
System.out.println(“\n\tgetPooledBeansCurrentCount(): “+poolRuntime.getPooledBeansCurrentCount());
System.out.println(“\n\tgetAccessTotalCount(): “+poolRuntime.getAccessTotalCount());
System.out.println(“\n\tgetDestroyedTotalCount(): “+poolRuntime.getDestroyedTotalCount());
System.out.println(“\n\tgetIdleBeansCount(): “+poolRuntime.getIdleBeansCount());
System.out.println(“\n\tgetBeansInUseCount(): “+poolRuntime.getBeansInUseCount());
System.out.println(“\n\tgetBeansInUseCurrentCount(): “+poolRuntime.getBeansInUseCurrentCount());
System.out.println(“\n\tgetWaiterTotalCount(): “+poolRuntime.getWaiterTotalCount());
System.out.println(“\n\tgetWaiterCurrentCount(): “+poolRuntime.getWaiterCurrentCount());
System.out.println(“\n\tgetTimeoutTotalCount(): “+poolRuntime.getTimeoutTotalCount());
}
}
public static void main(String []args)throws Exception
{
EntityMonitor rep = new EntityMonitor ();
rep.getContext();
}
}
———————————-
.
.

Regards
Jay SenSharma


Custom JNDI EJB3

Hi All,

Jay SenSharma

Jay SenSharma

I have observed that many Oracle WebLogic Application Server Developers and Administrators face an issue when they deploy their EJB3.0 based applications in WebLogic container, The WebLogic Generates a JNDI name in following format “mappedName#packageName/remoteInterfaceName”. Many Users wants to use their own Custom JNDI (User Defined JNDI)name rather than above kind of Complex JNDI name.
So here is a Simple EJB3.0 Example which describes us how to define our own Custom JNDI name for an EJB component in WebLogic Server.

Step1). First of all Create a Simple Business Interface “ReplicableSFSRemoteIntf.java”


package sfsb3;
import javax.ejb.*;

@Remote

public interface ReplicableSFSRemoteIntf {
public void removeWithRetain()throws Exception;
public void removeWithoutRetain() throws Exception;
public String printBean ();
public int testIncrement() throws Exception;
public int testDecrement() throws Exception;
public int getCount() throws Exception;
}

Step2). Now we need to Create the Bean class “ReplicableSFSBean.java” like following


package sfsb3;
import javax.ejb.*;
@Stateful
public class ReplicableSFSBean implements ReplicableSFSRemoteIntf
{
int count = 0;
public ReplicableSFSBean() {
System.out.println("\n\t ReplicableSFSBean--> ReplicableSFSBean() invoked");
}

@Init("create")
public void initMethod() throws CreateException {
System.out.println("\n\t ReplicableSFSBean--> public void initMethod() invoked");
}

@Remove(retainIfException=true)
public void removeWithRetain() throws Exception{
System.out.println("\n\t ReplicableSFSBean--> removeWithRetain() invoked");
}

@Remove
public void removeWithoutRetain() throws Exception{
System.out.println("\n\t ReplicableSFSBean--> removeWithoutRetain() invoked");
}

public String printRemoteIntf () {
System.out.println("\n\t ReplicableSFSBean ---> public String printRemoteIntf () invoked");
return "ReplicableSFSRemoteObjectIntf";
}

public String printLocalIntf () {
System.out.println("\n\t ReplicableSFSBean ---> public String printLocalIntf () invoked");
return "ReplicableSFSLocalObjectIntf";
}

public String printBean () {
System.out.println("\n\t ReplicableSFSBean ---> public String printBean () invoked");
return "ReplicableSFSBean";
}

public int testIncrement() throws Exception
{
System.out.println("\n\t ReplicableSFSBean ---> public int testIncrement() invoked");
count=count+5;
return count;
}

public int testDecrement() throws Exception
{
System.out.println("\n\t ReplicableSFSBean ---> public int testDecrement() invoked");
count=count-2;
return count;
}

public int getCount() throws Exception
{
System.out.println("\n\t ReplicableSFSBean ---> public int getCount() invoked");
return count;
}
}

Step3). Now compile above classes using simple “javac”

Step 4). Now we need to provide our own “ejb-jar.xml” file like following (We need to provide our own Deployment Descriptors to customize the JNDI name because there is no J2EE specific or WebLogic Specific annotation available at this point to define it with customization).


<ejb-jar 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/ejb-jar_3_0.xsd">

<enterprise-beans>
<session>
<ejb-name>ReplicableSFSB</ejb-name>
<business-local>sfsb3.ReplicableSFSLocalIntf</business-local>
<business-remote>sfsb3.ReplicableSFSRemoteIntf</business-remote>
<ejb-class>sfsb3.ReplicableSFSBean</ejb-class>
<session-type>Stateful</session-type>
</session>
</enterprise-beans>
</ejb-jar>

Step5). Now we need to provide the “weblogic-ejb-jar.xml” file here we are going to define our own User Defined Custom JNDI name.


<weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/90" xmlns:j2ee=" http://java.sun.com/xml/ns/j2ee" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/90  http://www.bea.com/ns/weblogic/90/weblogic-ejb-jar.xsd">

<weblogic-enterprise-bean>
<ejb-name>ReplicableSFSB</ejb-name>
<stateful-session-descriptor>
     <business-interface-jndi-name-map>
            <business-remote>sfsb3.ReplicableSFSRemoteIntf </business-remote>
            <jndi-name>ReplicableSFSB</jndi-name>
      </business-interface-jndi-name-map>
</em> </stateful-session-descriptor>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>

Step6). Now place above Deployment descriptors in META-INF directory and create a Jar of it and then Deploy it on WebLogic Server.

Step 7). To test the Custom JNDI name in Oracle WebLogic Server, we need to write a Simple Client Application so that we can perform a JNDI lookup in WebLogic Server JNDI tree for the Business component.


package sfsb3;
import javax.naming.*;
import java.util.*;
public class Ejb3Client
{
public final static String JNDI_FACTORY = "weblogic.jndi.WLInitialContextFactory";
private static String serverUrl ="t3://localhost:7001";
public static void main(String[] ar) throws Exception
{
InitialContext ic=null;
try{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, serverUrl);
ic = new InitialContext(env);
}
catch(Exception e){
System.out.println("\n\t Didnot get InitialContext: "+e);
}
try{
Object obj=ic.lookup("ReplicableSFSB");
sfsb3.ReplicableSFSRemoteIntf home=(sfsb3.ReplicableSFSRemoteIntf)obj;
System.out.println("\n\n\tRemote=>"+home.getClass());
System.out.println("\n\n\tRemote testIncrement() =>"+home.testIncrement());
}
catch(Exception e)
{
System.out.println("\n\n\t jack Exception => "+e);
e.printStackTrace();
}
}
}

Regards
Jay SenSharma


  • Testimonials

  • RSS Middleware Magic – JBoss

  • Receive FREE Updates


    FREE Email updates of our new posts Enter your email address:



  • Magic Archives

  • Sitemeter Status

  • ClusterMap 7-Nov-2011 till Date

  • ClusterMap 6-Nov-2010 till 7-Nov-2011

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