Access Application Module by SessionCookie

Hi!
I have created ApplicationModule in Model project of FusionWebApplication. The ApplicationModule is statefull and is successfully used in adf web page (defined in ViewController project).
I have configured ADF Security over Fusion Web Application, so WebService cannot be accessed without providing security credentials os SessionCookie.
In ViewController project I have created WebServicee base od POJO class. Inside its implementation method I want to access data via ApplicationModule.
This can be done by writing this code:
ApplicationModule am = Configuration.createRootApplicationModule("com.oracle.apps.hr.personnel.HiringModule",  "HiringModuleLocal");
I have configured ADF Security over Fusion Web Application, so WebService cannot be accessed without providing security credentials os SessionCookie (I cannot access webservice with SessionCookie if it is defined in Model, so creating web service from ApplicationModule is out of option).
Now my question is: I have read that ADF WebPage finds appropriate ApplicationModule of some user via DataBinding layer by SessionCookie. Is it possible to somehow simulate this way programatically - to somehow tell Configuration class to find/Create ApplicationModule via SessionCookie?
Currently I am using Soap webservice, but we are planning to use REST the same way - define access point in ViewController and invoke ApplicationModule via Configuration class.
Thnaks for help!

Yvonne,
I am using JDev 10.1.3.3.0.4157 (build 4157 I guess)
Yes, createRootApplicationModule is called from the doGet method in my servlet.
I have this running for a few days now and everything seems to work ok.
But it doesn’t sit right with me that I have to use a configuration with no security.
I also noticed the application Module tester does not work with jazn security.
It gives around the same error:
oracle.jbo.JboException: JBO-29000: Unexpected exception caught:
oracle.jbo.JboException, msg=JBO-33021: Failed authenticate user testAlthough this seems to catch atleast the username, which is something I didn’t get.
Anton

Similar Messages

  • What is the best way of accessing application module without page binding?

    Hi All
    I am using Jdeveloper 11g R2 (11.1.2.3) & Weblogic 10.3.5.0
    What is the best way of accessing application module without page binding?
    In my application after user authenticated from LDAP
    I need to read some information from database and set my menues.
    Thanks
    Mohsen

    Hi,
    if you don't have a binding the I am not sure the binding context is created. Anyway, try
    BindingContext.getCurrent().findDataControl("name here as ID in DataBindings.cpx") and see if it returns a valid instance
    Frank

  • Accessing application module instances directly from the AMPool

    Hi!
    I´m want to create an Application Module Pool Monitor, actually I need to know how many fetched rows an Application Module instance has.
    I made a jsp, that do the following:
    ApplicationPool pool = (ApplicationPool)poolMgr.getResourcePool(poolname);
    int instanceCount = pool.getInstanceCount();
    for (int i = 0; i < instanceCount; i++){       
    ApplicationModule am = pool.getInstance(i);
    and then works with the am instances, calculating the rows that each VO has fetched.
    Now, It is not yet clear to me if, when I use "pool.getInstance(i)",
    I'm locking the instance that is being use by another session (an user session), or trying to get a lock,
    and possibly creating a deadlock. Or the AMPool administrates the lock and I don´t need to worry about it.
    Thank in advance, and sorry for my bad english!
    (i forgot to mention, I´m using adf - bc 10.1.2 )
    Message was edited by:
    user506477

    Sure, we are having RAM problems, sometimes, and for reasons that are still unclear, a process begins to consume memory.
    What we need rigth now, is a tool that tell us how many rows in memory has each user, and which ViewObject is creating them. The idea is to make some kind of monitor that shows that, the AM that each user has, an the state of their VOs.
    I used the JSP in this page as a reference:
    http://radio.weblogs.com/0118231/stories/2004/05/10/gettingApplicationModulePoolStatisticsToAidWithSizeTuning.html
    I´m not trying to create a new AM management mechanism, simply a tool that shows the status of the application (and perhaps allows me, for instance, to clear the cache of a VO that has to many rows fetched).
    In my JSP I obtain an instance of the AMs using "pool.getInstance(i)", and access then the associated VOs. But I don´t know if accesing the AMs this way could create problems with users that have an AM assigned to them, for example, a deadlock.
    Thanks!

  • How to access application module from ActionForm Execute?

    I've got a very simple ADF/UIX/Struts application where I'm trying to create a simple Login function. I have a /loginAction data action pointing to a login.uix page forward. The login.uix page has a <struts:form> on it with a user and a password field. There is a LoginBean with the corresponding get/set values. I have an ADF model created with a boolean login(String username, String password) function exposed as a client method.
    Eventually, when I have this basic part working, then I'll actually be using an ActionForward mapping to dispatch to different home pages, based on the particular login account (the name of the forward will be stored in the authentication table).
    I've tried overriding Execute(), since that is where you can return the appropriate ActionForward mapping, but that does not have a DataActionContext passed in -- so I can't get to the application module.
    I've also looked at processComponentEvents, but that doesn't have any ActionForward results nor a way to pass back ActionErrors (in case the login fails).
    How do I call my login client method when a user has entered a username/password and pressed the Submit button?

    Here is another solution as provided by Oracle Support in response to a TAR that I opened:
    I had described my need to access a login() function defined in my Application Module, returning true/false if the login succeeds/fails. Here is the reply, posted with permission:
    I have gotten the following information back from one of the development folks pertaining to the question you asked.
    His suggestions are as follows:
    1) Expose the method as a client method on the App module
    2) On the pageflow create a new DataAction
    3) Drag and drop the logon method from the AppModule operations node and drop it onto the new data Action
    3) Edit the set-property values that are created in the Struts metadata for this new DataAction to use the correct expressions to get the logon info to pass to the middle tier.
    e.g.
    <action path="/authenticateUser" className="oracle.adf.controller.struts.actions.DataActionMapping" type="AuthenticateUserAction" name="DataForm"
    unknown="false">
    <set-property property="modelReference" value="authenticateUserUIModel"/>
    <set-property property="methodName" value="authenticateUserUIModel.authenticateUser"/>
    <set-property property="resultLocation" value="${requestScope.methodResult}"/>
    <set-property property="numParams" value="2"/>
    <set-property property="paramNames[0]" value="${param.logonUsername}"/>
    <set-property property="paramNames[1]" value="${param.logonPassword}"/>
    <forward name="fail" path="/logon.do"/>
    <forward name="success" path="/menu.do"/>
    </action>
    So in this case the values of the logonUsername and logonPassword fields in the form that submitted to this DataAction are passed as the two parameters that my authenticateUser method on the AppModule requires.
    I have also overriden the data action class to customise the findForward() method to route the user depending on if the method call worked or not.
    And here's the code for the customized FindForward in the DataAction:
    protected void findForward(DataActionContext actionContext) throws Exception
    HttpServletRequest request = actionContext.getHttpServletRequest();
    HttpSession session = request.getSession();
    String target = "fail";
    //Get the result of the Model Method call
    JUCtrlActionBinding method = actionContext.getCustomMethod();
    boolean successfulLogon = ((Boolean)method.getResult()).booleanValue();
    if (!successfulLogon)
    // If the logon fails we need to do the following
    // 1. Increament the counter once this exceeds 3 any logon will fail
    // 2. Create an error message to display on the logon screen
    // note this is a non specific error to prevent hackers from
    // knowing that they at least got the username right or from
    // knowing that there is a Max attempts value if they are trying
    // an automated attack
    Integer attempts = (Integer)session.getAttribute("logonAttempts");
    int intAttempts = 0;
    if (attempts != null)
    intAttempts = attempts.intValue();
    session.setAttribute("logonAttempts", new Integer(++intAttempts));
    //The error message comes out of the ApplicationResources.properties file.
    actionContext.getActionErrors().add("general",new ActionError("logon.error.logonFailed"));
    this.saveErrors(actionContext.getHttpServletRequest(),
    actionContext.getActionErrors());
    else
    //If connection was OK do we need to save the username in a cookie?
    String remember = (String)request.getParameter("logonRemember");
    int cookieLife = 0; //Expire
    if ( remember != null && remember.length()>0 )
    cookieLife = 2592000;
    String name = (String)request.getParameter("logonUsername");
    Cookie userCookie = new Cookie("CARA_USER_COOKIE",name);
    userCookie.setMaxAge(cookieLife);
    actionContext.getHttpServletResponse().addCookie(userCookie);
    target = "success";
    actionContext.setActionForward(target);
    I hope this helps anyone looking to implement something similar. It also illustrates the "preferred" way of executing a client method and working with the result.

  • Accessing application module in a POJO for SOA architecural question

    Hi,
    I have an architectural question. We have an app in jdev 11.1.1.1.0 that has app modules and jsf pages. It works great. I am of the thought that biz logic should not be contained in managed beans but in a POJO which is more tied to the model part. For example, if i have a method to calculate salaray, i would rather put that in a POJO that accesses appmodule to get the vo and related query instead of doing all this in a backing bean method.
    I understand from Steve's tips that accessing app module directly is not a good idea (see "When should I use Configuration.createRootApplicationModule(), and when not?" at http://radio-weblogs.com/0118231/2003/08/01.html) .
    ApplicationModule am = Configuration.createRootApplicationModule(
    "com.oracle.apps.hr.personnel.HiringModule",
    "HiringModuleLocal");
    But then how do you go about making your app more modularized and decoupled that can expose a particular SOA service such as POJO.calcSalary() if you are not supposed to access app module in a pojo. Any other way to do it?
    Another customer is asking pretty much along the same lines at Re: ADF BC 11 - best practice question

    Have you looked at AM level service methods?
    See 9.7 Customizing an Application Module with Service Methods
    http://download.oracle.com/docs/cd/E14571_01/web.1111/b31974/bcservices.htm#sm0206
    These service methods can be accessed from your JSF page with simple binding (see http://www.screentoaster.com/watch/stWUtcRkVLQ1FcRVxZXVhZ/service_method_on_am )
    And they can also be exposed through a web service interface to the AM, see: http://download.oracle.com/otn_hosted_doc/jdeveloper/11gdemos/CreatingSDO-Demo/CreatingSDO.html

  • Cannot Access Application Module from View Project (Swing)

    I recently started a new application workspace as a Swing project with Business Components. Jdev created 2 projects by default, a Model and a View. The model works fine, all the business components are funtctioning and the DB connection is good. When i try to create a reference to the application module in my View project i constantly get 'Class Not Found' exceptions no matter what i do. I am using the jbo.client.Configuration.getRootApplicationModule('amName', 'amConfig') method.
    What am i missing? How do i instantiate my application module from my View project?
    Thanks a lot.

    Just had to add the Model to the classpath...

  • Finding Application Module name in read-only view object classes

    Hi all,
    I have a fairly basic question about finding application module name when we are coding in ViewObject java classes.
    I want to know how can I obtain <<application module>> NAME that our current view object is contained in it at run-time. I think there should be a way to find current application module NAME, when we are in ViewObject classes including View Object, View Row or view object definition classes (I've overridden all mentioned classes).
    I should notify that since our view object is read-only I may not count on view object's entity classes, coz as you know a read-only view object don't have any entity in it!
    So, if you have any idea about finding current application module name in view object java classes please let me know.
    Appreciate for your replies,
    Nasser

    Thanks guy, it was helpful:)
    Now i can access application module name through viewObject classes.
    But another question is raised...sorry if i m boring:( I promise its the final question ;)
    Is there a way to get application module name in an extended version of JboException class?
    Thanks again for your reply:)
    Nasser

  • Help with Application Module

    I have created 3 application modules
    am1, am2, am3.
    am2, am3 are nested in am1
    Now on trying to access application module instance am2 or am3 in a custom static method in am1 throws this error:
    Exception in thread "main" oracle.jbo.InvalidOwnerException: JBO-25301: Application module is not a root app module but has no parent
         at oracle.jbo.server.ComponentObjectImpl.getRootApplicationModule(ComponentObjectImpl.java:168)
         at oracle.jbo.server.ApplicationModuleImpl.findApplicationModule(ApplicationModuleImpl.java:1295)
         at
    the code is as below incase needed:
    public class AppModule1Impl
    extends ApplicationModuleImpl
    /**This is the default constructor (do not remove)
    public AppModule1Impl()
    /**Sample main for debugging Business Components code using the tester.
    public static void main(String[] args)
    //launchTester("sni.pricing", /* package name */
    // "AppModule1Local" /* Configuration Name */);
    AppModule1Impl am=new AppModule1Impl();
    AppModule2Impl m2=(AppModule2Impl)am.getAppModule2();
    AppModule3Impl m3=(AppModule3Impl)am.getAppModule3();
    /**Container's getter for AppModule2
    public ApplicationModuleImpl getAppModule2()
    return (ApplicationModuleImpl) findApplicationModule("AppModule2");
    /**Container's getter for AppModule3
    public ApplicationModuleImpl getAppModule3()
    return (ApplicationModuleImpl) findApplicationModule("AppModule3");
    Message was edited by:
    Naga Kalyan

    You can't just instantiate an application module with new AppModuleImpl(). You have to set up an application module in a context. Therefor you have to create an root application module which set up all other stuff for the framework.
    The easiest way to set things up is to build an JUnit test case (Business Components Test Suit or Business Components Test Fixture). This will create the fixture class which handles the creation of the root application module and some code how to use it.
    Timo

  • How To Access HTTPS Web Service  in Application Module

    I need to know how to access HTTPS web service in application module.
    If you can provide the tutorial or guidance to achieve this really appreciate.
    Thanks
    Sameera

    Use the Web Service Proxy wizard in JDeveloper to create a class that calls your Web service, and then call this class from code in your AM.
    http://docs.oracle.com/cd/E16340_01/web.1111/b31974/web_services.htm#CJAHGIEF

  • Access an Application Module Client Interface in a JSF Web Application

    How to Access an Application Module Client Interface in a JSF Web Application
    I use this code but class ValueBinding is deprecated in JDeveloper11g
    FacesContext fc=FacesContext.getCurrentInstance();
    ValueBinding vb=fc.getApplication().createValueBinding("#{data}");
    BindingContext bc=(BindingContext)vb.getValue(fc);
    DCDataControl dc=bc.findDataControl("SRServiceDataControl");
    ApplicationModule am=(ApplicationModule)dc.getDataProvider();

    user581394,
    JDeveloper 11 and the introduction of ADF Faces RC introduces a new dependency, which is JSF 1.2. The createValueBinding on the FacesContext object is deprecated in JSF 1.2. To resolve an expression in JSF 1.2 use the following method or something similar.
        public static Object resolveExpression(String expression) {
            FacesContext facesContext = getFacesContext();
            Application app = facesContext.getApplication();
            ExpressionFactory elFactory = app.getExpressionFactory();
            ELContext elContext = facesContext.getELContext();
            ValueExpression valueExp =
                elFactory.createValueExpression(elContext, expression,
                                                Object.class);
            return valueExp.getValue(elContext);
        }--RiC                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Accessing Remote Data Over the Service-Enabled Application Module

    Hi,
    I am trying to access the service enabled module remotely(model project is deployed on different machine) deployed on Integrated WLS server. For that I have done the following step;
    1)     Created simple model project as producer.
    2)     Created the jar of model project(producer) .
    3)     Added the Bc_profileCommon.jar to the Consumer app.
    4)     Changed the connections.xml(Consumer) file accordingly (PFA).
    5)     Created the Entity Objects based on the wsdl in Consumer.
    6)     Created the JNDI on server and added the users with credentials.
    7)     I managed to access service enabled app module locally.
    But I am not able to understand following tags in the connections.xml(for remote access) file such as
    <StringRefAddr addrType="jndiProviderURL">
    <Contents>t3://10.180.190.214:7101</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="jndiSecurityPrincipal">
    <Contents>weblogic</Contents>
    </StringRefAddr>
    <SecureRefAddr addrType="jndiSecurityCredentials">
    <Contents>kiran</Contents>
    </SecureRefAddr>
    Also I am getting a warning for the SecureRefAddr as “No grammer available for the absent namespace contents of element of Contents cannot be validated.”
    Please let me know the significance of the red word. And what value I should set so that it will access the service enabled application module remotely?
    ** I am using Jdev 11.1.1.3.0

    As Bob rightly says you may have a problem if the machine you are trying to access is on a corporate network as you will need the permission and help of the network administrator to achieve this.
    I assume from your post that there is not a VPN connection set up on the remote PC network. Assuming that you have access to the router on the remote network then you will need to set up portforwarding on it at some point so I suggest you go to this page and see if your router is listed as you will need some instructions if you don't use the software suggested by Bob.
    When accessing a remote machine, PC or Mac, I have always used a secure connection to do so and the alternative to a VPN is an SSH tunnel. Unfortunately unlike the Mac Windows doesn't come with SSH server software installed so if you want to go down this route you will have to install and configure this first. I haven't tried this on Windows 7 yet but I have been successful on Windows XP and there are plenty of sites with instructions on how to set this up like this one here. Once the SSH server is set up on the PC and port 22 on your remote router has been forwarded then you can set up a SSH tunnel in the same way as described in my post in this thread http://discussions.apple.com/thread.jspa?messageID=10847513&#10847513
    Message was edited by: Sean Dale1

  • Sharing a BC4J application module amongst sessions

    Is there any method of sharing an application module amongst many sessions. Take BC4J/JSP on a single web server. We have a considerable amount of static lookup data that rarely changes and it seems daft to have to store this in the entity/view cache for every application module (one per active session).
    If we have a 100 sessions running I don't won't to store the lookup data 100 times. The smaller the session memory footprint the better.
    Anyone got any ideas?

    Hi,
    In 9.0.5 there is a property, "jbo.ampool.isuseexclusive", that may be used to configure this behaviour for an ApplicationPool.
    The summary is that when this property is false SessionCookie.useApplicationModule requests do not return an ApplicationModule that is reserved exclusively for that SessionCookie. Instead the AMs in the "intial pool" are shared by all SessionCookies that are using that pool.
    The reason that this is not formally documented is that it will not work with the declarative binding layer.
    Though BC4J itself is designed to be threadsafe you could still get race conditions on the default iterators. Imagine two threads that are looping through the rows of the default RSI of a deptVO in an unsynchronized block and, consequently, interleaving next calls.
    This is not an issue for programmatic clients as long as each thread of control instantiates their own RSI for access, simply does not use RowSetIterators, or implements synchronized, re-entrant use of an RSI.
    Please see the documentation for examples of developing a programmatic client that uses the pool APIs directly.
    Hope this helps,
    JR

  • How to programmatically call remote application module - JDev 10.1.3.3.0

    Hi,
    I've an ADF web application (10.1.3.3.0) deployed onto an OAS server. I'd like to be able to access view objects via the application module of this web app from a simple java class on another server.
    I've created a simple class to query a local application module (included in the same project as the simple class). This works fine but I'm not sure how to change this to access an application module when it's remote on another server. Can anyone assist?
    Here is my sample code for querying a local application module/view object:
        public static void main(String[] args) {
            ApplicationModule applicationModule =
                Configuration.createRootApplicationModule("com.almac.model.common",
                                                          "AppModuleLocal");
            try {
                ViewObject eventList = applicationModule.findViewObject("SipEventsView1");
                eventList.executeQuery();
                while (eventList.hasNext()) {
                    Row event = eventList.next();
                    System.out.println("Event Name: " + event.getAttribute("EveName"));
            } catch (JboException e) {
                System.out.println(e.getMessage());
            } finally {
                Configuration.releaseRootApplicationModule(applicationModule, true);
        }Thanks,
    Paul.

    You can expose an AM as an EJB or Web service to expose them for remote access:
    http://download.oracle.com/docs/cd/B32110_01/web.1013/b25947/web_services.htm#CJAEEICB

  • Error while calling webservice from application module

    Hi all
    I have generated a Proxy from a web Service and i am trying to call the web service from an Application Module it is throwing me error
    JBO-29000: Unexpected exception caught: oracle.classloader.util.AnnotatedNoClassDefFoundError, msg= Missing class: webservices.types.com.siebel.xml.order_interface.Orders Dependent class: java.lang.reflect.Array Loader: jre.bootstrap Code-Source: unknown Configuration: jre bootstrap
    Missing class: webservices.types.com.siebel.xml.order_interface.Orders Dependent class: java.lang.reflect.Array Loader: jre.bootstrap Code-Source: unknown Configuration: jre bootstrap
    My web Service is correct, as i have executed the client and it is working fine, but when i try to access the web service from an application module it is throwing me this error. So any light on this issue will be very helpful
    thanks

    This forum is for XML DB issues. XML DB is a feature of 9iR2 and later.You need t look in the XML Technology forum

  • HOWTO: Using a BC4J Application Module in an Stateless EJB Session Bean

    HOWTO: Using a BC4J Application Module in an Stateless EJB Session Bean
    by Steve Muench
    Overview
    BC4J provides automatic facilities for deploying any application module as a stateful EJB session bean. If you want to leverage the features of your BC4J application module from a stateless EJB session bean, it's not automatic but it is straightforward to implement. This howto article explains the details.
    For our example, we will create a stateless EJB session bean that uses a container-managed transaction. To keep things simple, let's assume the session bean has a single public method on its remote interface named createDepartment() with the following signature:
    public void createDepartment(int id, String name, String loc) throws AppException
    AppException is an example of an application-specific exception that our method will throw if any problems arise during its execution.The goal of this article is to illustrate how to use the BC4J application module named com.example.hr.HRApp as part of the implementation of this createDepartment method on our stateless enterprise bean. Let's assume that the HRApp application module has a view object member named Departments, based on the com.example.hr.DeptView view object, based on the familiar DEPT table and related to the com.example.hr.Dept entity object so our view can be updateable.
    Creating the Stateless Session Bean
    We can start by using the JDeveloper Enterprise Bean wizard to create a new stateless session bean called StatelessSampleEJB implemented by:[list][*]com.example.StatelessSampleEJBBean (Bean class)[*]com.example.StatelessSampleEJBHome (Home interface)[*]com.example.StatelessSampleEJB (Remote interface)[list]
    We then use the EJB Class Editor to add the createDepartment method to the remote interface of StatelessSampleEJB with the signature above. We edit the remote interface to make sure that it also reflects that the createDepartment method thows the AppException like this:
    package com.example;
    import javax.ejb.EJBObject;
    import java.rmi.RemoteException;
    public interface StatelessSampleEJB extends EJBObject {
      void createDepartment(int id, String name, String loc)
      throws RemoteException,AppException;
    }Before we start adding BC4J into the picture for our implementation, our StatelessSampleEJBBean class looks like this:
    package com.example;
    import javax.ejb.SessionBean;
    import javax.ejb.SessionContext;
    public class StatelessSampleEJBBean implements SessionBean {
      public void ejbCreate(){}
      public void ejbActivate(){}
      public void ejbPassivate(){}
      public void ejbRemove(){}
      public void setSessionContext(SessionContext ctx){
      public void createDepartment(int id, String name, String loc) 
      throws AppException {
        // TODO: Implement method here
    }We can double-click on the ejb-jar.xml file in our project to see the XML deployment descriptor for the bean we just created:
    <ejb-jar>
       <enterprise-beans>
          <session>
             <description>Session Bean ( Stateless )</description>
             <display-name>StatelessSampleEJB</display-name>
             <ejb-name>StatelessSampleEJB</ejb-name>
             <home>com.example.StatelessSampleEJBHome</home>
             <remote>com.example.StatelessSampleEJB</remote>
             <ejb-class>com.example.StatelessSampleEJBBean</ejb-class>
             <session-type>Stateless</session-type>
             <transaction-type>Container</transaction-type>
          </session>
       </enterprise-beans>
    </ejb-jar>We need to add the extra <assembly-descriptor> section in this file to indicate that the createDepartment method will require a transaction. After this edit, the ejb-jar.xml file looks like this:
    <ejb-jar>
       <enterprise-beans>
          <session>
             <description>Session Bean ( Stateless )</description>
             <display-name>StatelessSampleEJB</display-name>
             <ejb-name>StatelessSampleEJB</ejb-name>
             <home>com.example.StatelessSampleEJBHome</home>
             <remote>com.example.StatelessSampleEJB</remote>
             <ejb-class>com.example.StatelessSampleEJBBean</ejb-class>
             <session-type>Stateless</session-type>
             <transaction-type>Container</transaction-type>
          </session>
       </enterprise-beans>
       <assembly-descriptor>
          <container-transaction>
             <method>
                <ejb-name>StatelessSampleEJB</ejb-name>
                <method-name>createDepartment</method-name>
                <method-params>
                   <method-param>int</method-param>
                   <method-param>java.lang.String</method-param>
                   <method-param>java.lang.String</method-param>
                </method-params>
             </method>
             <trans-attribute>Required</trans-attribute>
          </container-transaction>
       </assembly-descriptor>
    </ejb-jar>
    Aggregating a BC4J Application Module
    With the EJB aspects of our bean setup, we can proceed to implementing the BC4J application module aggregation.
    The first thing we do is add private variables to hold the EJB SessionContext and the instance of the aggregated BC4J ApplicationModule, like this:
    // Place to hold onto the aggregated appmodule instance
    transient private ApplicationModule _am  = null;
    // Remember the SessionContext that the EJB container provides us
    private           SessionContext    _ctx = null;and we modify the default, empty implementation of the setSessionContext() method to remember the session context like this:
    public void setSessionContext(SessionContext ctx){ _ctx = ctx; }We add additional constants that hold the names of the J2EE datasource that we want BC4J to use, as well as the fully-qualified name of the BC4J application module that we'll be aggregating:
    // JNDI resource name for the J2EE datasource to use
    private static final String DATASOURCE = "jdbc/OracleCoreDS";
    // Fully-qualified BC4J application module name to aggregate
    private static final String APPMODNAME = "com.example.hr.HRApp";We expand the now-empty ejbCreate() and ejbRemove() methods to create and destory the aggregated instance of the BC4J application module that we'll use for the lifetime of the stateless session bean. When we're done, ejbCreate() it looks like this:
    public void ejbCreate() throws CreateException {
      try {
        // Setup a hashtable of environment parameters for JNDI initial context
        Hashtable env = new Hashtable();
        env.put(JboContext.INITIAL_CONTEXT_FACTORY,JboContext.JBO_CONTEXT_FACTORY);
        // NOTE: we want to use the BC4J app module in local mode as a simple Java class!
        env.put(JboContext.DEPLOY_PLATFORM, JboContext.PLATFORM_LOCAL);
        env.put(PropertyConstants.INTERNAL_CONNECTION_PARAMS,DATASOURCE);
        // Create an initial context, using this hashtable of environment params
        InitialContext ic = new InitialContext(env);
        // Lookup a home interface for the application module
        ApplicationModuleHome home = (ApplicationModuleHome)ic.lookup(APPMODNAME);
        // Using the home, create the instance of the appmodule we'll use
        _am = home.create();
        // Register the BC4J factory to handle EJB container-managed transactions
        registerContainerManagedTransactionHandlerFactory();
      catch(Exception ex) {
         ex.printStackTrace();
        throw new CreateException(ex.getMessage());
    }and ejbRemove() looks like this:
    public void ejbRemove() {
      try {
        // Cleanup any appmodule resources before getting shutdown
        _am.remove();
      catch(JboException ex) { /* Ignore */ }
    }The helper method named reigsterContainerManagedTransactionHandlerFactory() looks like this:
    private void registerContainerManagedTransactionHandlerFactory() {
      SessionImpl session = (SessionImpl)_am.getSession();
      session.setTransactionHandlerFactory(
        new TransactionHandlerFactory() {
          public TransactionHandler  createTransactionHandler() {
            return new ContainerManagedTxnHandlerImpl();
          public JTATransactionHandler createJTATransactionHandler() {
            return new ContainerManagedTxnHandlerImpl();
    }The last detail is to use the BC4J appmodule to implement the createDepartment() method. It ends up looking like this:
    public void createDepartment(int id, String name, String loc)
    throws AppException {
      try {
        // Connect the AM to the datasource we want to use for the duration
        // of this single method call.
        _am.getTransaction().connectToDataSource(null,DATASOURCE,false);
        // Use the "Departments" view object member of this AM
        ViewObject departments = _am.findViewObject("Departments");
        // Create a new row in this view object.
        Row newDept = departments.createRow();
        // Populate the attributes from the parameter arguments.
        newDept.setAttribute("Deptno", new Number(id));
        newDept.setAttribute("Dname", name);
        newDept.setAttribute("Loc", loc);
        // Add the new row to the view object's default rowset
        departments.insertRow(newDept);
        // Post all changes in the AM, but we don't commit them. The EJB
        // container managed transaction handles the commit.
        _am.getTransaction().postChanges();
      catch(JboException ex) {
        // To be good EJB Container-Managed Transaction "citizens" we have
        // to mark the transaction as needing a rollback if there are problems
        _ctx.setRollbackOnly();
        throw new AppException("Error creating dept "+ id +"\n"+ex.getMessage());
      finally {
        try {
          // Disconnect the AM from the datasource we're using
          _am.getTransaction().disconnect();
        catch(Exception ex) { /* Ignore */ }
    Building a Test Client
    With the EJB-Tier work done, we can build a sample client program to test this new stateless EJB Session Bean by selecting the bean in the Oracle9i JDeveloper IDE and choosing "Create Sample Java Client" from the right-mouse menu.
    When the "Sample EJB Client Details" dialog appears, we take the defaults of connecting to embedded OC4J container. Clicking the (OK) button generates the following test class:
    import java.util.Hashtable;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import com.example.StatelessSampleEJB;
    import com.example.StatelessSampleEJBHome;
    public class SampleStatelessSampleEJBClient {
      public static void main(String [] args) {
        SampleStatelessSampleEJBClient sampleStatelessSampleEJBClient =
           new SampleStatelessSampleEJBClient();
        try {
          Hashtable env = new Hashtable();
          env.put(Context.INITIAL_CONTEXT_FACTORY,
                  "com.evermind.server.rmi.RMIInitialContextFactory");
          env.put(Context.SECURITY_PRINCIPAL, "admin");
          env.put(Context.SECURITY_CREDENTIALS, "welcome");
          env.put(Context.PROVIDER_URL,
                  "ormi://localhost:23891/current-workspace-app");
          Context ctx = new InitialContext(env);
          StatelessSampleEJBHome statelessSampleEJBHome =
               (StatelessSampleEJBHome)ctx.lookup("StatelessSampleEJB");
          StatelessSampleEJB statelessSampleEJB;
          // Use one of the create() methods below to create a new instance
          // statelessSampleEJB = statelessSampleEJBHome.create();
          // Call any of the Remote methods below to access the EJB
          // statelessSampleEJB.createDepartment( int id, java.lang.String name, java.lang.String loc );
        catch(Throwable ex) {
          ex.printStackTrace();
    }We uncomment the call to the create() method and add a few calls to the createDepartment() method so that the body of the test program now looks like this:
    // Use one of the create() methods below to create a new instance
    statelessSampleEJB = statelessSampleEJBHome.create();
    // Call any of the Remote methods below to access the EJB
    statelessSampleEJB.createDepartment( 13, "Test1","Loc1");
    System.out.println("Created department 13");
    statelessSampleEJB.createDepartment( 14, "Test2","Loc2");
    System.out.println("Created department 14");
    try {
      // Try setting a department id that is too large!
      statelessSampleEJB.createDepartment( 23456, "Test3","Loc3");
    catch (AppException ax) {
      System.err.println("AppException: "+ax.getMessage());
    }Before we can successfully run our SampleStatelessSampleEJBClient we need to first run the EJB bean that the client will try to connect to. Since Oracle9i JDeveloper supports local running and debugging of the EJB-Tier without doing through a full J2EE deployment step, to accomplish this prerequisite step we just need to right-mouse on the StatelessSampleEJB node in the System Navigator and select "Run". This starts up the embedded OC4J instance and runs the EJB right out of the current out path.Finally, we can run the SampleStatelessSampleEJBClient, and see the output of the test program in the JDeveloper log window:
    Created department 13
    Created department 14
    AppException: Error creating dept 23456
    JBO-27010: Attribute set with value 23456 for Deptno in Dept has invalid precision/scale
    Troubleshooting
    One error that might arise while running the example is that the database connection information in your data-sources.xml for the jdbc/OracleCoreDS datasource does not correspond to the database you are trying to test against. If this happens, then double-check the file .\jdev\system\oc4j-config\data-sources.xml under the JDeveloper installation home directory to make sure that the url value provided is what you expect. For example, to work against a local Oracle database running on your current machine, listening on port 1521, with SID of ORCL, you would edit this file to have an entry like this for jdbc/OracleCoreDS :
    <data-source
        class="com.evermind.sql.DriverManagerDataSource"
        name="OracleDS"
        location="jdbc/OracleCoreDS"
        xa-location="jdbc/xa/OracleXADS"
        ejb-location="jdbc/OracleDS"
        connection-driver="oracle.jdbc.driver.OracleDriver"
        username="scott"
        password="tiger"
        url="jdbc:oracle:thin:@localhost:1521:ORCL"
        inactivity-timeout="30"
    />This is the data-sources.xml file that gets used by the embedded OC4J instance running in JDeveloper.
    Conclusion
    Hopefully this article has illustrated that it is straightforward to utilize the full power of BC4J in local mode as part of your EJB Stateless Session Beans using container-managed transaction. This example illustrated a single createDepartment method in the enterprise bean, but by replicating the application module interaction code that we've illustrated in createDepartment, any number of methods in your stateless session bean can use the aggregated application module instance created in the ejbCreate() method.
    Code Listing
    The full code listing for the SampleStatelessEJB bean implementation class looks like this:
    * StatelessSampleEJB
    * Illustrates how to use an aggregated BC4J application module
    * in local mode as part of the implementation of a stateless
    * EJB session bean using container-managed transaction.
    * HISTORY
    * smuench/dmutreja 14-FEB-2002 Created
    package com.example;
    import oracle.jbo.*;
    import oracle.jbo.server.*;
    import javax.ejb.*;
    import oracle.jbo.domain.Number;
    import oracle.jbo.common.PropertyConstants;
    import java.util.Hashtable;
    import javax.naming.InitialContext;
    import oracle.jbo.server.ejb.ContainerManagedTxnHandlerImpl;
    public class StatelessSampleEJBBean implements SessionBean {
      // JNDI resource name for the J2EE datasource to use
      private static final String DATASOURCE = "jdbc/OracleCoreDS";
      // Fully-qualified BC4J application module name to aggregate
      private static final String APPMODNAME = "com.example.hr.HRApp";
      // Place to hold onto the aggregated appmodule instance
      transient private ApplicationModule _am  = null;
      // Remember the SessionContext that the EJB container provides us
      private           SessionContext    _ctx = null;
      public void ejbCreate() throws CreateException {
        try {
          // Setup a hashtable of environment parameters for JNDI initial context
          Hashtable env = new Hashtable();
          env.put(JboContext.INITIAL_CONTEXT_FACTORY,JboContext.JBO_CONTEXT_FACTORY);
          env.put(JboContext.DEPLOY_PLATFORM, JboContext.PLATFORM_LOCAL);
          env.put(PropertyConstants.INTERNAL_CONNECTION_PARAMS,DATASOURCE);
          // Create an initial context, using this hashtable of environment params
          InitialContext ic = new InitialContext(env);
          // Lookup a home interface for the application module
          ApplicationModuleHome home = (ApplicationModuleHome)ic.lookup(APPMODNAME);
          // Using the home, create the instance of the appmodule we'll use
          _am = home.create();
          // Register the BC4J factory to handle EJB container-managed transactions
          registerContainerManagedTransactionHandlerFactory();
        catch(Exception ex) {
           ex.printStackTrace();
          throw new CreateException(ex.getMessage());
      public void ejbActivate(){}
      public void ejbPassivate(){}
      public void ejbRemove(){}
      public void setSessionContext(SessionContext ctx){ _ctx = ctx; }
      public void createDepartment(int id, String name, String loc)
      throws AppException {
        try {
          // Connect the AM to the datasource we want to use for the duration
          // of this single method call.
          _am.getTransaction().connectToDataSource(null,DATASOURCE,false);
          // Use the "Departments" view object member of this AM
          ViewObject departments = _am.findViewObject("Departments");
          // Create a new row in this view object.
          Row newDept = departments.createRow();
          // Populate the attributes from the parameter arguments.
          newDept.setAttribute("Deptno", new Number(id));
          newDept.setAttribute("Dname", name);
          newDept.setAttribute("Loc", loc);
          // Add the new row to the view object's default rowset
          departments.insertRow(newDept);
          // Post all changes in the AM, but we don't commit them. The EJB
          // container managed transaction handles the commit.
          _am.getTransaction().postChanges();
        catch(JboException ex) {
          // To be good EJB Container-Managed Transaction "citizens" we have
          // to mark the transaction as needing a rollback if there are problems
          _ctx.setRollbackOnly();
          throw new AppException("Error creating dept "+ id +\n"+ex.getMessage());
        finally {
          try {
            // Disconnect the AM from the datasource we're using
            _am.getTransaction().disconnect();
          catch(Exception ex) { /* Ignore */ }
      private void registerContainerManagedTransactionHandlerFactory() {
        SessionImpl session = (SessionImpl)_am.getSession();
        session.setTransactionHandlerFactory(
          new TransactionHandlerFactory() {
            public TransactionHandler createTransactionHandler() {
              return new ContainerManagedTxnHandlerImpl();
            public JTATransactionHandler createJTATransactionHandler() {
              return new ContainerManagedTxnHandlerImpl();

    Hi Steve, It4s me again;
    About the question I made, I tried with a single assembly-descriptor tag and a single container-transaction tag in the deployment descriptor of the session bean and these were the results.
    java.lang.NullPointerException
         void com.evermind.server.rmi.RMIConnection.EXCEPTION_ORIGINATES_FROM_THE_REMOTE_SERVER(java.lang.Throwable)
         java.lang.Object com.evermind.server.rmi.RMIConnection.invokeMethod(com.evermind.server.rmi.RMIContext, long, long, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RecoverableRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.ejb.StatelessSessionRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         void __Proxy1.modificaEnvoltura(java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String)
         void SamplemdeController.envolturaControlEJBClient.main(java.lang.String[])
    Then I tried with multiple assembly-descriptor tags each with a single container-transaction tag and the results were:
    java.lang.NullPointerException
         void com.evermind.server.rmi.RMIConnection.EXCEPTION_ORIGINATES_FROM_THE_REMOTE_SERVER(java.lang.Throwable)
         java.lang.Object com.evermind.server.rmi.RMIConnection.invokeMethod(com.evermind.server.rmi.RMIContext, long, long, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RecoverableRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.ejb.StatelessSessionRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         void __Proxy1.modificaEnvoltura(java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String)
         void SamplemdeController.envolturaControlEJBClient.main(java.lang.String[])
    Finally I tried with a single assembly-descriptor and multiple container tags and the results were:
    java.lang.NullPointerException
         void com.evermind.server.rmi.RMIConnection.EXCEPTION_ORIGINATES_FROM_THE_REMOTE_SERVER(java.lang.Throwable)
         java.lang.Object com.evermind.server.rmi.RMIConnection.invokeMethod(com.evermind.server.rmi.RMIContext, long, long, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.rmi.RecoverableRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         java.lang.Object com.evermind.server.ejb.StatelessSessionRemoteInvocationHandler.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         void __Proxy1.modificaEnvoltura(java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String)
         void SamplemdeController.envolturaControlEJBClient.main(java.lang.String[])
    How can I make my Stateless Session bean work out?

Maybe you are looking for

  • I would like to create a new page that does not show up in my "menu" .

    I would like to set up a new page on my website for a specific one-time use. I don't want the page to show up in my menu at the top. The new "hidden" page will have specific files that already exist on other pages but re-arranged for a specific clien

  • Unable to run a form(FOrms 5.0) on Web. Security exception E

    Hi, I am trying to run a simple form developed in Forms 5.0 over our intranet. Environment: On NT I am using Oracle 8.0.5, Developer/2000 Server and Internet Information Server 4.0. I have created a simple form and deployed on the server. (created th

  • Map cannot be loaded in import manager | MDM

    Hi ,   I am trying to upload some data in customer repository (I am on MDM 5.5 SP05) . I have a few XML files (IDOCS) from customer master in an ECC system ,which I am providing as a source for the import manager . In the source preview I can see the

  • Adobe Reader 8.1 plugin error

    I've uninstalled and reinstalled Adobe Reader 8.1 and have even run the patch for 8.1.2 and yet ever time I try to either open Adobe reader or a pdf file, I get an error message saying "Invalid plugin detected, Adobe reader needs to close" and I am u

  • HT201077 I have a slideshow how can I put it on Facebook

    I have an ipad3 did a slideshow but can't move it to Facebook? I don't have iPhoto I have the one that brings the ipad3,