Entity Bean can only use container-managed transaction demarcation?

In <<Designing Enterprise Application with J2EE 2nd>>
Section 2.3.3.3 Enterprise Bean Transactions,it says:Entity beans can only use container-managed transaction demarcation.
That means,i can not get UserTransaction from EJBContext.
Is that true?

Yes this is the requirement of the specs. Your ejb code generator should give you the error if you use usertransaction.
--Ashwani                                                                                                                                                                                                                                                                   

Similar Messages

  • MDB container managed transaction demarcation not working in wls 6.1 beta

    I have an MDB which sends the messages it receives onto another JMS
              destination within the onMessage method. These messages are not sent to
              the JMS destination unless I explicitly use a transacted session for the
              destination and subsequently commit the session. If I set the transacted
              parameter to Session as false the messages are sent. If I set the
              transacted parameter to true the messages will only be output if the
              session is committed. This is the standard behaviour for a JMS session
              but this is not the correct behaviour for an MDB running with
              container-managed transaction demarcation.
              For a start the transacted parameter to session should be ignored when
              run in the context of a container transaction and the commit method
              should thrown an exception as it is not allowed within the context of a
              container transaction.
              This is the MDB code and the deployment descriptor: -
              public class MessageBean implements MessageDrivenBean, MessageListener
              private String topicName = null;
              private TopicConnectionFactory topicConnectionFactory = null;
              private TopicConnection topicConnection = null;
              private TopicSession topicSession = null;
              private Topic topic = null;
              private TopicPublisher topicPublisher = null;
              private TextMessage textMessage=null;
              private transient MessageDrivenContext messageDrivenContext = null;
              private Context jndiContext;
              public final static String
              JMS_FACTORY="weblogic.examples.jms.TopicConnectionFactory";
              public final static String
              TOPIC="weblogic.examples.jms.exampleTopic";
              public MessageBean()
              public void setMessageDrivenContext(MessageDrivenContext
              messageDrivenContext)
              this.messageDrivenContext = messageDrivenContext;
              public void ejbCreate()
              public void onMessage(Message inMessage)
              try
              jndiContext = new InitialContext();
              topicConnectionFactory =
              (TopicConnectionFactory)jndiContext.lookup(JMS_FACTORY);
              topic = (Topic) jndiContext.lookup(TOPIC);
              topicConnection =
              topicConnectionFactory.createTopicConnection();
              topicConnection.start();
              // The transacted parameter should be ignored in the context of a
              container tx
              topicSession = topicConnection.createTopicSession(true,
              Session.AUTO_ACKNOWLEDGE);
              topicPublisher = topicSession.createPublisher(topic);
              textMessage = (TextMessage)inMessage;
              topicPublisher.publish(inMessage);
              // this is illegal in a container transaction
              topicSession.commit();
              topicConnection.close();
              catch (JMSException je)
              throw new EJBException(je);
              catch (NamingException ne)
              throw new EJBException(ne);
              public void ejbRemove()
              <?xml version="1.0" encoding="UTF-8"?>
              <!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise
              JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
              <ejb-jar>
              <enterprise-beans>
              <message-driven>
              <display-name>MessageBean</display-name>
              <ejb-name>MessageBean</ejb-name>
              <ejb-class>MessageBean</ejb-class>
              <transaction-type>Container</transaction-type>
              <message-driven-destination>
              <destination-type>javax.jms.Queue</destination-type>
              </message-driven-destination>
              <security-identity>
              <description></description>
              <run-as>
              <description></description>
              <role-name></role-name>
              </run-as>
              </security-identity>
              </message-driven>
              </enterprise-beans>
              <assembly-descriptor>
              <container-transaction>
              <method>
              <ejb-name>MessageBean</ejb-name>
              <method-name>*</method-name>
              </method>
              <trans-attribute>Required</trans-attribute>
              </container-transaction>
              </assembly-descriptor>
              </ejb-jar>
              

    Please see the response in the EJB newsgroup.
              Also, could you kindly only post to a single newsgroup?
              Thanks.
              "Jimmy Johns" <[email protected]> wrote in message
              news:[email protected]...
              > I have an MDB which sends the messages it receives onto another JMS
              > destination within the onMessage method. These messages are not sent to
              > the JMS destination unless I explicitly use a transacted session for the
              >
              > destination and subsequently commit the session. If I set the transacted
              >
              > parameter to Session as false the messages are sent. If I set the
              > transacted parameter to true the messages will only be output if the
              > session is committed. This is the standard behaviour for a JMS session
              > but this is not the correct behaviour for an MDB running with
              > container-managed transaction demarcation.
              >
              > For a start the transacted parameter to session should be ignored when
              > run in the context of a container transaction and the commit method
              > should thrown an exception as it is not allowed within the context of a
              > container transaction.
              >
              > This is the MDB code and the deployment descriptor: -
              >
              > public class MessageBean implements MessageDrivenBean, MessageListener
              > {
              > private String topicName = null;
              > private TopicConnectionFactory topicConnectionFactory = null;
              > private TopicConnection topicConnection = null;
              > private TopicSession topicSession = null;
              > private Topic topic = null;
              > private TopicPublisher topicPublisher = null;
              > private TextMessage textMessage=null;
              > private transient MessageDrivenContext messageDrivenContext = null;
              >
              > private Context jndiContext;
              >
              > public final static String
              > JMS_FACTORY="weblogic.examples.jms.TopicConnectionFactory";
              > public final static String
              > TOPIC="weblogic.examples.jms.exampleTopic";
              >
              > public MessageBean()
              > {
              > }
              >
              > public void setMessageDrivenContext(MessageDrivenContext
              > messageDrivenContext)
              > {
              > this.messageDrivenContext = messageDrivenContext;
              > }
              >
              > public void ejbCreate()
              > {
              > }
              >
              > public void onMessage(Message inMessage)
              > {
              > try
              > {
              > jndiContext = new InitialContext();
              > topicConnectionFactory =
              > (TopicConnectionFactory)jndiContext.lookup(JMS_FACTORY);
              > topic = (Topic) jndiContext.lookup(TOPIC);
              > topicConnection =
              > topicConnectionFactory.createTopicConnection();
              > topicConnection.start();
              > // The transacted parameter should be ignored in the context of a
              > container tx
              > topicSession = topicConnection.createTopicSession(true,
              > Session.AUTO_ACKNOWLEDGE);
              > topicPublisher = topicSession.createPublisher(topic);
              > textMessage = (TextMessage)inMessage;
              > topicPublisher.publish(inMessage);
              > // this is illegal in a container transaction
              > topicSession.commit();
              > topicConnection.close();
              > }
              > catch (JMSException je)
              > {
              > throw new EJBException(je);
              > }
              > catch (NamingException ne)
              > {
              > throw new EJBException(ne);
              > }
              > }
              >
              > public void ejbRemove()
              > {
              > }
              > }
              >
              >
              >
              >
              > <?xml version="1.0" encoding="UTF-8"?>
              >
              > <!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise
              > JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>
              >
              > <ejb-jar>
              > <enterprise-beans>
              > <message-driven>
              > <display-name>MessageBean</display-name>
              > <ejb-name>MessageBean</ejb-name>
              > <ejb-class>MessageBean</ejb-class>
              > <transaction-type>Container</transaction-type>
              > <message-driven-destination>
              > <destination-type>javax.jms.Queue</destination-type>
              > </message-driven-destination>
              > <security-identity>
              > <description></description>
              > <run-as>
              > <description></description>
              > <role-name></role-name>
              > </run-as>
              > </security-identity>
              > </message-driven>
              > </enterprise-beans>
              > <assembly-descriptor>
              > <container-transaction>
              > <method>
              > <ejb-name>MessageBean</ejb-name>
              > <method-name>*</method-name>
              > </method>
              > <trans-attribute>Required</trans-attribute>
              > </container-transaction>
              > </assembly-descriptor>
              > </ejb-jar>
              >
              >
              >
              >
              >
              >
              >
              >
              

  • JTA Container Managed Transaction Demarcation question?

    Hello, there is something I'm not quite sure about, concerning JTA Container managed transaction
    I have a remote stateful session bean with a method f().
    the method f() calls the methods g() and h() residing in a different stateless local bean DBLocalBean.
    (DBLocalBean only deals with database calls using the EntityManager)
    I would like to know where the commit is being executed? after f() or after g() and h()

    Hi Meir,
    It depends on the exact settings of the container managed transaction attributes. The most typical (and default) transaction attribute is TX_REQUIRED. TX_REQUIRED means that when a business method invocation arrives the container will either a) import any existing propagated client transaction context or b) if one is not available, start a new transaction.
    Assuming TX_REQUIRED for the three business methods in your example, the container would start a new transaction before invoking f() . Both g() and h() would execute in that same transaction since f's transaction would propagate to them. Finally, after f() returns, the container would commit the transaction it started.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Sending message to a JMS queue and making DB update through a single container managed transaction

    Can we use container managed transactions to send message to JMS queue and make DB updates in a sigle transaction. If yes then do we need 2pC license. I am using weblogic 6.0 SP2 and my database driver do not supports XA

    If your JMS provider is XA compliant, you can.
    If you are using WebLogic 6.0 JMS, it supports 2PC.
    The JDBC resource that does not support XA can participate in the global transaction
    creating a TXDataSource and setting "enable two-phase commit"=true in the Configuration
    panel.
    About the JMSConnectionFactory, on the console, in WebLogic 6.0, in the "Transaction"
    tab folder, set "User Transactions Enabled"=true.
    In your code, use non-transacted sessions.
    For 2pc protocol, you need a license or you'll get an exception.
    Sergi
    Manoj Bansal <[email protected]> wrote:
    Can we use container managed transactions to send message to JMS queue and
    make DB updates in a sigle transaction. If yes then do we need 2pC license.
    I am using weblogic 6.0 SP2 and my database driver do not supports XA

  • Container-managed / bean-managed transaction demarcation

    I am trying to make sure I understand container-managed and bean-managed transaction demarcation and in particular where you have one bean calling another bean. What happens where one of the beans has container-managed transaction demarcation and the other bean-managed transaction demarcation. In fact the initial question to ask is, is this allowed?
    Lets use an application scenario to illustrate the issue. The application has a payment transaction. Payments can be received in one of two ways:
    1. As a payment at a branch where the individual payment is processed on a client application and resulting in the processing of a single payment transaction.
    2. As a batch of payments received from a bank containing, potentially, thousands of payment transactions.
    The proposed implementation for this uses two session beans. The first is a Payment session bean that implements the business logic as appropriate calling entity beans to persist the change. The second is a BatchPayment session bean. This processes the batch of payment transactions received from the bank. The BatchPayment reads through the batch of payments from a bank calling the Payment session bean for each payment transaction.
    Lets look at the transactional properties of both session beans. In order to support the client application the Payment session bean can implicitly enforce transactional integrity and is therefore set to container-managed transaction demarcation. However the BatchPayment session bean will want to explicitly specify transaction demarcation for performance reasons. The transactional "commit" process is relatively expensive. When processing a large batch of transactions rather than performing a commit after every transaction is processed we want to perform the commit after a number of transactions have been processed. For example, we may decide that after every 100 transactions have been processed we commit. The processing will have a shorter elapsed time as we have not had to perform 99 commit processes. So the BatchPayment session bean will want to explicitly specify its transaction demarcation and will therefore be defined with bean-managed transaction demarcation.
    How would this be implemented? A possible solution is:
    Payment session bean implemented with container-managed transaction demarcation with transaction scope set to Required.
    BatchPayment session bean implemented with bean-managed transaction demarcation with transaction scope set to Required.
    When the client application is run it calls the Payment bean and the container-managed transaction demarcation ensures the transactional integrity of that transaction.
    When a BatchPayment process is run it explicitly determines the transaction demarcation. Lets say that after every 100 Payment transactions (through 100 calls to the Payment session bean) have been processed the BatchPayment bean issues a commit. In this scenario however we have mixed container-managed and bean-managed transaction demarcation. Hence my original question. Can container-managed and bean-managed transaction demarcation be mixed? If not how is it possible to implement the requirements as described above?
    Thanks for any thoughts.
    Paul

    BatchPayment session bean implemented with bean-managed transaction demarcation with transaction scope set to Required.Didn't quite understand this sentence.... if it's BMT it has no declarative transaction attributes such as "Required"....
    Anyway, first of all I'll have to ask, Why at all would you want to commit in the middle of the business method? to get as much through as possible before a potential crash? :-)
    Can container-managed and bean-managed transaction demarcation be mixed?Yes, of course. Just remember that the "direction" you are refering to ->
    a BMT SB that propagates it's transaction to a method in a CMT SB that is demarcated with "Required" is the simplest case. If it were "reversed", or for that matter any BMT that might be called within an active transaction context must perform logic to manipulate the transaction state. For instance(and most common case), checking to see if a transaction is active and if so not to do anything(just use the one that is already active).
    If not how is it possible to implement the requirements as described above?You could also implement this scenario with CMTs all the way through. your BatchPayment SB could consist of two methods, one (say, execute(Collection paymentsToExecute) ) with "Supports", and another(say executeBatchUnit(Collection paymentsToExecute, int beginIndex, int endIndex) ) with "RequiresNew".
    then have the first just call the other with indexes denoting each time a group of payments.
    Still, it does seem more suitable using BMT for these kind of things.....
    Hope this helped....

  • About Container-managed Transactions and Bean-managed Transactions

    as the document of weblogic7.0 describe the differents of Container-managed
              Transactions and Bean-managed Transactions,and in the document,It tell us
              details of using Bean-managed Transactions,such as \:
              import javax.naming.*;import javax.transaction.UserTransaction;.....
              import java.sql.*;import java.util.*;
              UserTransaction tx = (UserTransaction)
              ctx.lookup("javax.transaction.UserTransaction");tx.begin();
              tx.commit() //or tx.rollback
              but how to use Container-managed Transactions?
              what is EJB's deployment descriptor? can someone tell me?
              i wonder someone will show me an example of how to use Container-managed
              Transactions.
              thanks
              fish
              

    Many if not all of the WLS EJB examples use container-managed
              transactions. That's a good place to start.
              I'd also recommend that you pick up a decent EJB book. There's several
              on the market right now.
              -- Rob
              fish wrote:
              > <ejb-jar>
              > <enterprise-beans>
              > <session>
              > <ejb-name>testbean</ejb-name>
              > <home>test.test.TestHome</home>
              > <remote>test.test.Test</remote>
              > <ejb-class>test.test.TestBean</ejb-class>
              > <session-type>Stateful</session-type>
              > <transaction-type>Container</transaction-type>
              > </session>
              > </enterprise-beans>
              >
              > <assembly-descriptor>
              > <container-transaction>
              > <method>
              > <ejb-name>EmployeeRecord</ejb-name>
              > <method-name>*</method-name>
              > </method>
              > <trans-attribute>Required</trans-attribute>
              > </container-transaction>
              > </assembly-descriptor>
              > </ejb-jar>
              > ----------------------------------------------
              > seems i have to write ejb-jar.xml like this,am i right?
              > what about <ejb-client-jar>? is it needed in this xml file?
              >
              > thanks
              >
              > fish
              >
              >
              

  • Refresh object in container managed transaction

    i am using container managed transactions on my ejbs which in turn invoke toplink persistence services. consider the scenario where a record which is inserted has its primary key - a sequence generated number. i want to return this id to the calling module after committing. but as this is a CMT case, the commit doesn't really happen on uow.commit() and thus the object that i return back doesn't have the primary key.
    in a two-tier scenario, i find that the primary key is available right after commit for obvious reasons.
    is there a way to achieve this. how do i return the primary key or even the whole object about to be inserted to the caller ???

    I am assuming you are mapping POJO and not entity beans.
    The UnitOfWork has API that allows you to have the PK sequence values assigned prior to commit.
    UnitOfWork.assignSequenceNumber(Object)
    http://download-west.oracle.com/docs/cd/B10464_01/web.904/b10491/oracle/toplink/sessions/UnitOfWork.html#assignSequenceNumber(java.lang.Object)
    UnitOfWork.assignSequenceNumbers()
    I hope this addresses your issue.
    Doug

  • JMS Sender with ejb3 container managed transaction

    Hi all,
    I refer to the following link http://download.oracle.com/docs/cd/E11035_01/wls100/jms/trans.html#wp1035937
    I found that JTA support JMS.
    But I dont' want to use JTA explicitly, I want to use container manage transaction. eg. inside ejb3 stateless session bean.
    does it support JMS?
    With Regards,
    wp

    Hi,
    Yes, WebLogic JMS supports JTA (a.k.a XA, a.k.a global) transactions such as container managed transactions. There are two requirements for CMTs on SSB:
    (1) use an XML descriptor setting or EJB annotation to enable CMT for the SSB
    (2) use a WebLogic JMS connection factory that is configured to have "global (XA) transactions enabled"
    And I usually also recommend:
    (3) Consider using a JEE "res-ref" for the connection factory to enable pooling of JMS resources. See "Enhanced Support for Using WebLogic JMS with EJBs and Servlets" (http://download.oracle.com/docs/cd/E14571_01/web.1111/e13727/j2ee.htm#g1329180), and the "Integrating Remote JMS Providers" FAQ (http://download.oracle.com/docs/cd/E14571_01/web.1111/e13727/interop.htm#JMSPG553).
    (4) Avoid using SSBs to receive messages. MDBs are specifically designed for processing incoming messages.
    It's also possible to have WebLogic automatically enlist foreign (non-WebLogic) vendors in WebLogic transactions. See the "Integrating Remote JMS Providers" FAQ for details (http://download.oracle.com/docs/cd/E14571_01/web.1111/e13727/interop.htm#JMSPG553).
    Regards,
    tom

  • Can i user UserTransaction  in a Container-managed transaction Bean

    can i use UserTransaction to control transaction boundaries in a container-managed transaction bean method?
    below is the method:
    there is one-to-many between Employees and SalaryItem
    @TransactionAttribute(value = TransactionAttributeType.REQUIRED)
    private void initEmployeesSalary(Long salarySumId) {
    for(Employees employees: liEmployees){
    for (int i = 0; i < 20; i++) {                                                           
    SalaryItem item = new SalaryDetailItem();
    employees.addSalaryItem(item);
    when there are about 1000 employees,the method run very slow.
    What do you think I should do?
    null

    Hi again,
    The EJB specs say that a stateful Session Bean with CMT is NOT allowed to use the UserTransaction; see page 361 of the EJB2.0 specification. So combining them will not (or should not) work.
    I suggest CMT+SessionSynchronization combined with using a flag to indicate whether notify should be called or not. Otherwise, you could try splitting up the bean into two beans: one with CMT and another one without. The one without CMT could use the UserTransaction and notify.
    Also, you might want to check http://www.onjava.com/pub/a/onjava/2001/10/02/ejb.html
    Hope that helps a bit,
    Guy
    http://www.atomikos.com

  • Container managed transactions in 9.0.3 (plus AQ JMS/MDB)

    Something for "real programmers", similar to MDB Transaction Exception on OC4J 9.0.4 (MDB Transaction Exception on OC4J 9.0.4) but little bit different. Maybe author of the mentioned thread can find some answers here also.
    We have an MDB accessing AQ in database (this works either with 9i and 8i). MDB receives the message (actually TextMessage), retrieves the content/properties and calls some EJBs making database operations. When we used just the same DataSource for JMS resource provider and SQL operations, everything worked OK. But we need to move one step further - making calls to several databases, some 8i, some might 9i. We were able to start CMT for one DataSource, i. e. configuring OrionCMTDataSource over JDBC ORACLE driver (if you use different DataSource class, message remains stucked in queue and eventually expires. If you don't specify container managed transactions for MDB in ejb-jar.xml, it works with any DataSource class - but message is lost every time exception occurs - not very pleasant situation).
    We are trying to configure DataSources so they provide transactional support while using commit coordinator. There are some documents describing this - in 9iAS Data Sources and JTA, Orion Data Sources and possibly JTA description in 9i database documentation. Both ORACLE documents are very similar. Generally, these are main steps:
    1) configure each data source so they provides CMT support (wrap native driver/data source by OrionCMTDataSource class)
    2) create datasource commit-coordinator database, also using CMT(?)
    3) create user in commit-coordinator database and same in each other database with connect, resource, create session + force any transaction priviledge (since it would commit other users transactions)
    4) create database links from commit-coordinator database to each databases (but... see questions below)
    5) configure commit coordinator so it uses proper data source
    6) add each DB link as a property to data sources
    7) configure data source for JMS
    8) connect JMS resource provider with JMS data source
    9) Start container, send message, etc.
    So far the only result we've got is a trace file in database user dumps and generic "javax.transaction.SystemExeption: Could not commit: error code 29540". User dump occurs in a "remote" database, not the one where commit coordinator resides. If I drop database links, result is the same, so it seems like problem with data source itself. In a dump there is piece of text like this: "FATAL ERROR IN TWO-TASK SERVER: error = 12571" and "ksedmp: internal or fatal error
    Current SQL statement for this session:
    begin dbms_aqin.aq$_dequeue_in( :1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13, :14, :15, :16, :17, :18, :19, :20, :21, :22, :23, :24, :25, :26, :27, :28, :29); end; ". I think AQ call is just a coincidence since it is the first one involved in transactions. Down there in HEX part of a dump there is a message about protocol or network error ("probably ORA-28546")
    Here is an example of data source configuration we are using:
    <!-- Passport CMT DataSource -->
    <data-source
    name="PassportDS"
    class="com.evermind.sql.OrionCMTDataSource"
    location="jdbc/PassportDS"
    connection-driver="oracle.jdbc.driver.OracleDriver"
    username="int"
    password="int"
    url="jdbc:oracle:thin:@ws18885:1521:ICON"
    inactivity-timeout="30">
    <property name="dblink" value="ICON.WS18885.APPG.COM"/>
    There are some questions pending. Obvious one is if CMT is working or not at all and we should find some different solution (Bean managed transactions or use XA, hmmm). Other one might be that database link has to be "fully-qualified". I'm not sure what it means: using username and password? Using database name along with domain (if any)? So far it seems links are not used anyway.
    We've tried several databases, like 9.2.0.1 and 9.0.3 versions. Result is the same.
    We've tried to use XA data source of ORACLE (oracle.jdbc.xa.client.OracleXADataSource) and OrionCMT data source bound by xa-source-location to it but container gets stucked upon restart with "Investingating resource 'XADataSource PassportXADS' for recovery..." and similar messages for an hour.
    There is an OracleJTADataSource mentioned in several documents, but I cannot find any in jdbc classes - was it deprecated?
    Lies the problem in JMS itself? So far we've been able to use AQ in 8i and 9i and succesfully commit every transaction - provided transaction was local.
    Since XA itself is working I guess problem might be with configuration.
    I will appreciate any opinion on CMT... also, if you have any questions, please ask.
    Myrra

    Hi Per,
    I don't have an answer for you -- sorry {:-( -- only a suggestion (which
    you may have already tried, anyway :-). Have you tried running OC4J
    in "debug" mode? The following web-page gives details on how to do that:
    http://kb.atlassian.com/content/atlassian/howto/orionproperties.jsp
    Also, if you aren't already aware of them, the following web-sites
    may also be helpful (not in any particular order):
    http://www.orionserver.com
    http://www.orionsupport.com
    http://www.elephantwalker.com
    Good Luck,
    Avi.

  • Container-Managed Transaction Type Attributes not working as expected

    I am having a problem with the container-managed transactions not working as expected. I have 2 methods that work as follows:
    MethodA{
    for(a lot)
    call MethodB;
    @Transaction Type = RequiresNew
    MethodB{
    EntityManager Persist to database
    I want the code in MethodB to be committed to the database when methodB returns. The problem is that I am running out of memory and MethodA is failing. When methodA fails after numerous calls to MethodB nothing is persisted to the database.
    It is my understanding that when using requires new transactions that a new transaction is started for each call to the method and ends when the method returns while the calling method transaction is suspended.
    How am I misunderstanding the requiresNew transaction attribute. What can I do to make a batch insert into my database that will not run out of memory (commit when a methodB returns)?
    Thanks in advance.

    The problem is that EJB invocation semantics for security, container-managed transactions, etc.
    only apply when an invocation is made through an EJB reference. In your case, you are directly
    invoking the implementation method from within the bean. The EJB container has no idea that's
    happening. It's no different than invoking a utility method.
    In order to get the behavior you'd like, you need to retrieve a reference to your own bean and invoke
    through that. You can use SessionContext.getBusinessObject() to get the EJB reference for the
    business interface through which the method in question is exposed.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Entity beans caching non-persistent data between transactions

    Some of the properties in our entity bean implementation classes are not declared
    in our descriptor files, and therefore, are non-persistent (we are using container-managed
    persistence); I will refer to these properties as "non-persistent properties".
    In WebLogic 5.1, we've noticed that the non-persistent properties are cached in
    between transactions. For instance, I ask for a particular Person (Person(James)),
    and I set one of the non-persistent properties (Property(X)) inside Transaction(A).
    In Transaction(B) (which is exclusive of Transaction(A)), I access Property(X)
    and find that it is the same value as I had set in Transaction(A)- this gives
    the appearance that non-persistent entity properties are being cached in between
    transactions.
    The same appears to hold true in WebLogic 7 SP1, however, we must use the "Exclusive"
    concurrency-strategy to maintain this consistency.
    I am worried that this assumption we are making of non-persistent properties is
    not valid in all cases, and the documentation does not promise anything in the
    way of such an assumption. I am worried that the container could kill the Person(James)
    entity implementation instance in the pool after Transaction(A), and create a
    new Person(James) instance to serve Transaction(B)- once that happens our assumption
    fails.
    "Database" concurrency strategy seems to fail our assumption on a regular basis,
    but that makes sense, since the documentation states that the "database will maintain
    the cache", and the container seems more willing to kill instances when they are
    finished with, or create new instances for new transactions.
    So my question is this: What is exactly guaranteed by the "Exclusive" concurrency-strategy?
    Will the assumption that we've made above ever fail under this strategy?
    Thanks in advance for any help.
    Regards,
    James

    It simply means that there is only one entity bean instance per PK in the
    server, and transaction which uses it locks it exclusively.
    James DeFelice <[email protected]> wrote:
    Thank you for the suggestion. I have considered taking this path, but before I
    make a final decision, I was hoping to get a clear answer to the question that
    I stated below:
    What EXACTLY is guaranteed by the "Exclusive" concurrency-strategy? Maybe someone
    from BEA knows?
    "Cameron Purdy" <[email protected]> wrote:
    To be safe: You should clear those values before the ejb load or set
    them
    after (or both).
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com/coherence.jsp
    Tangosol Coherence: Clustered Replicated Cache for Weblogic
    "James DeFelice" <[email protected]> wrote in message
    news:[email protected]...
    Some of the properties in our entity bean implementation classes arenot
    declared
    in our descriptor files, and therefore, are non-persistent (we areusing
    container-managed
    persistence); I will refer to these properties as "non-persistentproperties".
    In WebLogic 5.1, we've noticed that the non-persistent properties arecached in
    between transactions. For instance, I ask for a particular Person(Person(James)),
    and I set one of the non-persistent properties (Property(X)) insideTransaction(A).
    In Transaction(B) (which is exclusive of Transaction(A)), I accessProperty(X)
    and find that it is the same value as I had set in Transaction(A)-this
    gives
    the appearance that non-persistent entity properties are being cachedin
    between
    transactions.
    The same appears to hold true in WebLogic 7 SP1, however, we must usethe
    "Exclusive"
    concurrency-strategy to maintain this consistency.
    I am worried that this assumption we are making of non-persistentproperties is
    not valid in all cases, and the documentation does not promise anythingin
    the
    way of such an assumption. I am worried that the container could killthe
    Person(James)
    entity implementation instance in the pool after Transaction(A), andcreate a
    new Person(James) instance to serve Transaction(B)- once that happensour
    assumption
    fails.
    "Database" concurrency strategy seems to fail our assumption on a regularbasis,
    but that makes sense, since the documentation states that the "databasewill maintain
    the cache", and the container seems more willing to kill instanceswhen
    they are
    finished with, or create new instances for new transactions.
    So my question is this: What is exactly guaranteed by the "Exclusive"concurrency-strategy?
    Will the assumption that we've made above ever fail under this strategy?
    Thanks in advance for any help.
    Regards,
    James
    Dimitri

  • Using container managed form-based security in JSF

    h1. Using container managed, form-based security in a JSF web app.
    A Practical Solution
    h2. {color:#993300}*But first, some background on the problem*{color}
    The Form components available in JSF will not let you specify the target action, everything is a post-back. When using container security, however, you have to specifically submit to the magic action j_security_check to trigger authentication. This means that the only way to do this in a JSF page is to use an HTML form tag enclosed in verbatim tags. This has the side effect that the post is not handled by JSF at all meaning you can't take advantage of normal JSF functionality such as validators, plus you have a horrible chimera of a page containing both markup and components. This screws up things like skinning. ([credit to Duncan Mills in this 2 years old article|http://groundside.com/blog/DuncanMills.php?title=j2ee_security_a_jsf_based_login_form&more=1&c=1&tb=1&pb=1]).
    In this solution, I will use a pure JSF page as the login page that the end user interacts with. This page will simply gather the input for the username and password and pass that on to a plain old jsp proxy to do the actual submit. This will avoid the whole problem of having to use verbatim tags or a mixture of JSF and JSP in the user view.
    h2. {color:#993300}*Step 1: Configure the Security Realm in the Web App Container*{color}
    What is a container? A container is basically a security framework that is implemented directly by whatever app server you are running, in my case Glassfish v2ur2 that comes with Netbeans 6.1. Your container can have multiple security realms. Each realm manages a definition of the security "*principles*" that are defined to interact with your application. A security principle is basically just a user of the system that is defined by three fields:
    - Username
    - Group
    - Password
    The security realm can be set up to authenticate using a simple file, or through JDBC, or LDAP, and more. In my case, I am using a "file" based realm. The users are statically defined directly through the app server interface. Here's how to do it (on Glassfish):
    1. Start up your app server and log into the admin interface (http://localhost:4848)
    2. Drill down into Configuration > Security > Realms.
    3. Here you will see the default realms defined on the server. Drill down into the file realm.
    4. There is no need to change any of the default settings. Click the Manage Users button.
    5. Create a new user by entering username/password.
    Note: If you enter a group name then you will be able to define permissions based on group in your app, which is much more usefull in a real app.
    I entered a group named "Users" since my app will only have one set of permissions and all users should be authenticated and treated the same.
    That way I will be able to set permissions to resources for the "Users" group that will apply to all users that have this group assigned.
    TIP: After you get everything working, you can hook it all up to JDBC instead of "file" so that you can manage your users in a database.
    h2. {color:#993300}*Step 2: Create the project*{color}
    Since I'm a newbie to JSF, I am using Netbeans 6.1 so that I can play around with all of the fancy Visual Web JavaServer Faces components and the visual designer.
    1. Start by creating a new Visual Web JSF project.
    2. Next, create a new subfolder under your web root called "secure". This is the folder that we will define a Security Constraint for in a later step, so that any user trying to access any page in this folder will be redirected to a login page to sign in, if they haven't already.
    h2. {color:#993300}*Step 3: Create the JSF and JSP files*{color}
    In my very simple project I have 3 pages set up. Create the following files using the default templates in Netbeans 6.1:
    1. login.jsp (A Visual Web JSF file)
    2. loginproxy.jspx (A plain JSPX file)
    3. secure/securepage.jsp (A Visual Web JSF file... Note that it is in the sub-folder named secure)
    Code follows for each of the files:
    h3. {color:#ff6600}*First we need to add a navigation rule to faces-config.xml:*{color}
        <navigation-rule>
    <from-view-id>/login.jsp</from-view-id>
            <navigation-case>
    <from-outcome>loginproxy</from-outcome>
    <to-view-id>/loginproxy.jspx</to-view-id>
            </navigation-case>
        </navigation-rule>
    NOTE: This navigation rule simply forwards the request to loginproxy.jspx whenever the user clicks the submit button. The button1_action() method below returns the "loginproxy" case to make this happen.
    h3. {color:#ff6600}*login.jsp -- A very simple Visual Web JSF file with two input fields and a button:*{color}
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:webuijsf="http://www.sun.com/webui/webuijsf">
        <jsp:directive.page
    contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"/>
        <f:view>
            <webuijsf:page
    id="page1">
    <webuijsf:html id="html1">
    <webuijsf:head id="head1">
    <webuijsf:link id="link1"
    url="/resources/stylesheet.css"/>
    </webuijsf:head>
    <webuijsf:body id="body1" style="-rave-layout: grid">
    <webuijsf:form id="form1">
    <webuijsf:textField binding="#{login.username}"
    id="username" style="position: absolute; left: 216px; top:
    96px"/>
    <webuijsf:passwordField binding="#{login.password}" id="password"
    style="left: 216px; top: 144px; position: absolute"/>
    <webuijsf:button actionExpression="#{login.button1_action}"
    id="button1" style="position: absolute; left: 216px; top:
    216px" text="GO"/>
    </webuijsf:form>
    </webuijsf:body>
    </webuijsf:html>
            </webuijsf:page>
        </f:view>
    </jsp:root>h3. *login.java -- implent the
    button1_action() method in the login.java backing bean*
        public String button1_action() {
            setValue("#{requestScope.username}",
    (String)username.getValue());
    setValue("#{requestScope.password}", (String)password.getValue());
            return "loginproxy";
        }h3. {color:#ff6600}*loginproxy.jspx -- a login proxy that the user never sees. The onload="document.forms[0].submit()" automatically submits the form as soon as it is rendered in the browser.*{color}
    {code}
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    version="2.0">
    <jsp:output omit-xml-declaration="true" doctype-root-element="HTML"
    doctype-system="http://www.w3.org/TR/html4/loose.dtd"
    doctype-public="-W3CDTD HTML 4.01 Transitional//EN"/>
    <jsp:directive.page contentType="text/html"
    pageEncoding="UTF-8"/>
    <html>
    <head> <meta
    http-equiv="Content-Type" content="text/html;
    charset=UTF-8"/>
    <title>Logging in...</title>
    </head>
    <body
    onload="document.forms[0].submit()">
    <form
    action="j_security_check" method="POST">
    <input type="hidden" name="j_username"
    value="${requestScope.username}" />
    <input type="hidden" name="j_password"
    value="${requestScope.password}" />
    </form>
    </body>
    </html>
    </jsp:root>
    {code}
    h3. {color:#ff6600}*secure/securepage.jsp -- A simple JSF{color}
    target page, placed in the secure folder to test access*
    {code}
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="2.1"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:webuijsf="http://www.sun.com/webui/webuijsf">
    <jsp:directive.page
    contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"/>
    <f:view>
    <webuijsf:page
    id="page1">
    <webuijsf:html id="html1">
    <webuijsf:head id="head1">
    <webuijsf:link id="link1"
    url="/resources/stylesheet.css"/>
    </webuijsf:head>
    <webuijsf:body id="body1" style="-rave-layout: grid">
    <webuijsf:form id="form1">
    <webuijsf:staticText id="staticText1" style="position:
    absolute; left: 168px; top: 144px" text="A Secure Page"/>
    </webuijsf:form>
    </webuijsf:body>
    </webuijsf:html>
    </webuijsf:page>
    </f:view>
    </jsp:root>
    {code}
    h2. {color:#993300}*_Step 4: Configure Declarative Security_*{color}
    This type of security is called +declarative+ because it is not configured programatically. It is configured by declaring all of the relevant parameters in the configuration files: *web.xml* and *sun-web.xml*. Once you have it configured, the container (application server and java framework) already have the implementation to make everything work for you.
    *web.xml will be used to define:*
    - Type of security - We will be using "form based". The loginpage.jsp we created will be set as both the login and error page.
    - Security Roles - The security role defined here will be mapped (in sun-web.xml) to users or groups.
    - Security Constraints - A security constraint defines the resource(s) that is being secured, and which Roles are able to authenticate to them.
    *sun-web.xml will be used to define:*
    - This is where you map a Role to the Users or Groups that are allowed to use it.
    +I know this is confusing the first time, but basically it works like this:+
    *Security Constraint for a URL* -> mapped to -> *Role* -> mapped to -> *Users & Groups*
    h3. {color:#ff6600}*web.xml -- here's the relevant section:*{color}
    {code}
    <security-constraint>
    <display-name>SecurityConstraint</display-name>
    <web-resource-collection>
    <web-resource-name>SecurePages</web-resource-name>
    <description/>
    <url-pattern>/faces/secure/*</url-pattern>
    <http-method>GET</http-method>
    <http-method>POST</http-method>
    <http-method>HEAD</http-method>
    <http-method>PUT</http-method>
    <http-method>OPTIONS</http-method>
    <http-method>TRACE</http-method>
    <http-method>DELETE</http-method>
    </web-resource-collection>
    <auth-constraint>
    <description/>
    <role-name>User</role-name>
    </auth-constraint>
    </security-constraint>
    <login-config>
    <auth-method>FORM</auth-method>
    <realm-name/>
    <form-login-config>
    <form-login-page>/faces/login.jsp</form-login-page>
    <form-error-page>/faces/login.jsp</form-error-page>
    </form-login-config>
    </login-config>
    <security-role>
    <description/>
    <role-name>User</role-name>
    </security-role>
    {code}
    h3. {color:#ff6600}*sun-web.xml -- here's the relevant section:*{color}
    {code}
    <security-role-mapping>
    <role-name>User</role-name>
    <group-name>Users</group-name>
    </security-role-mapping>
    {code}
    h3. {color:#ff6600}*Almost done!!!*{color}
    h2. {color:#993300}*_Step 5: A couple of minor "Gotcha's"_ *{color}
    h3. {color:#ff6600}*_Gotcha #1_*{color}
    You need to configure the "welcome page" in web.xml to point to faces/secure/securepage.jsp ... Note that there is *_no_* leading / ... If you put a / in there it will barf all over itself .
    h3. {color:#ff6600}*_Gotcha #2_*{color}
    Note that we set the <form-login-page> in web.xml to /faces/login.jsp ... Note the leading / ... This time, you NEED the leading slash, or the server will gag.
    *DONE!!!*
    h2. {color:#993300}*_Here's how it works:_*{color}
    1. The user requests the a page from your context (http://localhost/MyLogin/)
    2. The servlet forwards the request to the welcome page: faces/secure/securepage.jsp
    3. faces/secure/securepage.jsp has a security constraint defined, so the servlet checks to see if the user is authenticated for the session.
    4. Of course the user is not authenticated since this is the first request, so the servlet forwards the request to the login page we configured in web.xml (/faces/login.jsp).
    5. The user enters username and password and clicks a button to submit.
    6. The button's action method stores away the username and password in the request scope.
    7. The button returns "loginproxy" navigation case which tells the navigation handler to forward the request to loginproxy.jspx
    8. loginproxy.jspx renders a blank page to the user which has hidden username and password fields.
    9. The hidden username and password fields grab the username and password variables from the request scope.
    10. The loginproxy page is automatically submitted with the magic action "j_security_check"
    11. j_security_check notifies the container that authentication needs to be intercepted and handled.
    12. The container authenticates the user credentials.
    13. If the credentials fail, the container forwards the request to the login.jsp page.
    14. If the credentials pass, the container forwards the request to *+the last protected resource that was attempted.+*
    +Note the last point! I don't know how, but no matter how many times you fail authentication, the container remembers the last page that triggered authentication and once you finally succeed the container forwards your request there!!!!+
    +The user is now at the secure welcome page.+
    If you have read this far, I thank you for your time, and I seriously question your ability to ration your time pragmatically.
    Kerry Randolph

    If you want login security on your web app, this is one way to do it. (the easiest way i have seen).
    This method allows you to create a custom login form and error page using JSF.
    The container handles the actual authentication and protection of the resources based on what you declare in web.xml and sun-web.xml.
    This example uses a statically defined user/password, stored in a file, but you can also configure JDBC realm in Glassfish, so that that users can register for access and your program can store the username/passwrod in a database.
    I'm new to programming, so none of this may be a good practice, or may not be secure at all.
    I really don't know what I'm doing, but I'm learning, and this has been the easiest way that I have found to add authentication to a web app, without having to write the login modules yourself.
    Another benefit, and I think this is key ***You don't have to include any extra code in the pages that you want to protect*** The container manages this for you, based on the constraints you declare in web.xml.
    So basically you set it up to protect certain folders, then when any user tries to access pages in that folder, they are required to authenticate.
    --Kerry                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Executing SQL statements in container managed transactions

    I have a problem when using TopLink 9.0.3 with WebSphere 4, Oracle 9i and J2EE container managed transactions.
    The data changing SQL statements are executed at the end of the (container managed) transaction, not at the time of the calls to UnitOfWork.registerNewObjekt(),
    UnitOfWork.validate...() or UnitOfWork.commit...().
    UnitOfWork(2035008996)--validate object space.
    UnitOfWork(2035008996)--validate cache.
    UnitOfWork(2035008996)--JTS#beforeCompletion()
    UnitOfWork(2035008996)--Connection(398132708)--INSERT INTO SVM_PERSONEN (FAX, NAME, ID, [...]) VALUES ([...])
    UnitOfWork(2035008996)--JTS#afterCompletion(org.omg.CosTransactions.Status._StatusRolledBack=4)
    UnitOfWork(2035008996)--release unit of work
    But the end of the transaction is out of the application server code. The transaction ends after the invoke of the applixcation server method, as the stack trace of an occurring exception shows:
    remote exception
    javax.transaction.TransactionRolledbackException: CORBA TRANSACTION_ROLLEDBACK 0 No; nested exception is:
         org.omg.CORBA.TRANSACTION_ROLLEDBACK:
    org.omg.CORBA.TRANSACTION_ROLLEDBACK: com.ibm.websphere.csi.CSITransactionRolledbackException:
         at com.ibm.ejs.csi.TranStrategy.commit(TranStrategy.java:194)
         at com.ibm.ejs.csi.TranStrategy.postInvoke(TranStrategy.java:67)
         at com.ibm.ejs.csi.TransactionControlImpl.postInvoke(TransactionControlImpl.java:414)
         at com.ibm.ejs.container.EJSContainer.postInvoke(EJSContainer.java:1818)
         at de.gedas.svm.server.app.ejb.EJSRemoteStatelessNavigationEJB.findPersonenZulieferer(EJSRemoteStatelessNavigationEJB.java:964)
         at de.gedas.svm.server.app.ejb._EJSRemoteStatelessNavigationEJB_Tie._invoke(_EJSRemoteStatelessNavigationEJB_Tie.java:589)
         at com.ibm.CORBA.iiop.ExtendedServerDelegate.dispatch(ExtendedServerDelegate.java:506)
         at com.ibm.CORBA.iiop.ORB.process(ORB.java:2376)
         at com.ibm.CORBA.iiop.OrbWorker.run(OrbWorker.java:186)
         at com.ibm.ejs.oa.pool.ThreadPool$PooledWorker.run(ThreadPool.java:104)
         at com.ibm.ws.util.CachedThread.run(ThreadPool.java:137)
    So the application server code has no possiblity for special reaction to this error condition.
    How can I use TopLink to execute my SQL statement immidately, not at the the end of the transaction (which is out of the area of my code)? Only the transaction should end at the usual time, managed by the container.

    I don't think there is anyway to currently do this in a JTS managed environment, to handle the exceptions you could,
    - Make use of TopLink session ExceptionHandlers to handle the database errors during the JTS commit.
    i.e.
    uow.setExceptionHandler(yourExceptionHandler);
    or,
    - Let TopLink control the transactions instead of JTS.

  • MDB Container Managed Transaction and Log4J

    Hi,
    I'm programming and MDB that reads and updates a database then sends out an HTTP Post and logs using log4j. I've read that when an MDB is configured as CMT or container managed transaction and the OnMessage method executes without errors, the transaction is implicitly commited. You can rollback the transaction by explicitly calling setRollbackOnly() or when a RuntimeException has been thrown. My worry is that after I have sent out an HTTP POST (a transaction has been completed) I would have to log a transaction completion using log4j. My problems is if log4j throws a RuntimeException thereby rolling back my transaction which shouldn't be the case. What I have done is to catch all Exceptions (and swallow them) whenever I log using log4j after I have sent out an HTTP POST succesfully (since my transaction should be complete by then). Is this a correct workaround?
    Thanks :)

    Your approach is correct. If you think, Log4J might throw errors, swallow the exceptions and try not to roll back.

Maybe you are looking for

  • Adobe desktop app updater is not working properly

    Trying to update adobe desktop app but its giving me this popup accept button ( which is in right side) is not working. When I press cancle button (left side button) getting another popup I have no idea what to do...!!

  • Purchase order form: external send (mail)

    Hi experts when creating a purchase order, if the medium used is external  send, the system generates a mail with the purchase order form. What I would like to know if it is possible to customize the system in order to specify the subject of the mail

  • How to include a new field for checking duplicate customer master

    Dear All we have activated the standard procedure to check duplicate customer master data. This is a standard procedure as below :- Procedure: Run SM30, key in Table V_T100C, select Display or Maintain, set App area F2. Here you can change current se

  • Concept about ASM Dynamic Volume

    What is the concept behind ASM Dynamic Volume in coordination with ACFS and how a ADVM manages this ? Thanks in advance. Regards, Sandy

  • Ideas for cache scheduling

    I have a dashboard that contains 2 analyses (created in 'answers'). Is there a way to have the results refresh only once a week (I'm assuming an ibot schedule could be used)? The goal is that when a user views the report, no refreshing occurs (fast)