I'm using XA (2-phase) transaction. I want to log to one log-table through Log class and Entity Manager. My method inside EJB Session bean looks like:
private void logError(Throwable throwable) {
LogEntity logEntity = new LogEntity();
// Set everything
entityManager.persist(logEntity);
}
I want to it in isolated (autonomous) transaction independent of any "outer" transaction. I have already tried to add #TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW) and #TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED) before method name and does not work.
Before I call EJB3 method I create user transaction like:
try {
UserTransaction transaction = (UserTransaction)context.lookup("javax.transaction.UserTransaction");
transaction.begin();
// Call EJB3 method
transaction.commit();
} catch (Throwable t) {
t.printStackTrace();
try {
transaction.rollback();
} catch (SystemException e) {
e.printStackTrace();
}
}
I want to Log no matter if commit is done or not. How to?
Regards
Transaction attributes are only relevant when called through a proxy. They do not apply to direct calls, which includes private methods. Try something like the following (which uses EJB 3.1 no-interface view, though you could create a separate local interface for logging if you only have EJB 3.0):
#Stateless
#Local(BusinessInterface.class)
#LocalBean
public class MyBean {
#EJB MyBean logger;
#TransactionAttribute(REQUIRED)
public void businessMethod() {
try {
...
} catch (Throwable t) {
logger.logError(t);
...
}
}
#TransactionAttribute(NOT_SUPPORTED)
public void logError(Throwable t) {
...
}
}
The important piece is that the call to logError happens through an injected EJB proxy, which allows the container to have control to suspend the XA transaction for the duration of the logError method.
Related
Bank.java
#Stateless
#Local
public class Bank implements IBank {
#EJB
IConfigBean iConfigBean;
#EJB
IDbs iDBS;
#EJB
IPosb iPosb;
#Override
public void doTransaction() {
System.out.println("--Bank Transaction Started--");
try {
Config config1 = getConfig(1);
iConfigBean.create(config1);
iDBS.doDBSTransaction();
Config config3 = getConfig(3);
iConfigBean.create(config3);
iPosb.doPOSBTransaction();
Config config5 = getConfig(5);
iConfigBean.create(config5);
} catch (Exception e) {
e.printStackTrace();
System.out.println("---Bank Exception--");
}
System.out.println("--Bank Transaction End--");
}
#Override
public Config getConfig(int inserttionOrderNo) {
Config config = new Config();
config.setType("EJBTransactionTESTING - " + inserttionOrderNo);
return config;
}
}
DBS.java
#Stateless
#Local
public class DBS implements IDbs {
#EJB
IConfigBean iConfigBean;
#Override
public void doDBSTransaction() {
System.out.println("--DBS Transaction Started--");
try {
Config config2 = getConfig(2);
iConfigBean.create(config2);
} catch (Exception e) {
e.printStackTrace();
System.out.println("--DBS Exception--");
}
System.out.println("--DBS Transaction End--");
}
#Override
public Config getConfig(int inserttionOrderNo) {
Config config = new Config();
config.setType("EJBTransactionTESTING - " + inserttionOrderNo);
return config;
}
}
POSB.java
#Stateless
#Local
public class POSB implements IPosb {
#EJB
IConfigBean iConfigBean;
#Override
public void doPOSBTransaction() {
System.out.println("--POSB Transaction Started--");
try {
Config config4 = getConfig(4);
iConfigBean.create(config4);
if (true) {
//For Test 1
//throw new NullPointerException();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("--POSB Exception--");
}
if (true) {
//For Test 2
// throw new NullPointerException();
}
System.out.println("--POSB Transaction End--");
}
#Override
public Config getConfig(int inserttionOrderNo) {
Config config = new Config();
config.setType("EJBTransactionTESTING - " + inserttionOrderNo);
return config;
}
}
I am new to Stack Overflow and Its my new question so correct me If I am wrong.
Environment is..
Windows 10
Java 1.8
Eclipse
Tomcat 8.5
EJB3
I have Three stateless bean, Please look at the Sequence Diagram of the Transaction flow.
I purposely making NullPointer Exception at two places during the transaction to know the difference and I have marked with Lightening Bold symbol in sequence diagram.
I am not using any #TransactionAttribute to any methods.
Test 1 - Null Pointer in Inside the try block (Lightening Bold symbol with Green)
When I start the testing, Got Null pointer exception and all the transaction are not marked for roll back and data also got inserted in db.
I can only see Null pointer exception in the console log.
Test 2 - Null Pointer in Outside the try - catch method (Lightening Bold symbol with Red)
When I start the testing, Got Null pointer exception plus EJBTransactionRolledbackException and all the transaction marked for roll back and no data inserted in db.
I can see NullPointer and EJBTransactionRolledback Exception in the console log.
Question here is,
Why EJB transaction is not marked for roll back If I made Null pointer inside try block
Why EJB transaction is roll back happens If I made null pointer outside try block
Thanks in advance.
Keep in mind EJB calls, all the "magic" made by container happens there, including transaction markup. It's possible due to the fact that EJB calls are not direct, but always go through proxy.
You have such calls in your code:
iPosb.doPOSBTransaction();
So, if unchecked exception (NPE for example) is thrown in this method and not caught - it's ultimately caught by container due to EJB proxy wrapping the call above. In this case transaction only could be rolled back.
Adding a call to a method of the same bean in your method (without using #EJB reference), does not change that:
#Override
public void doPOSBTransaction() {
try {
Config config4 = getConfig(4);
iConfigBean.create(config4);
if (true) {
newMethod();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("--POSB Exception--");
}
if (true) {
newMethod();
}
}
private void newMethod(){
throw new RuntimeException();
}
You can easily check that commit/rollback behaviour is just the same in this case, no matter that a method is added to call stack.
So the important thing you have to remember is that all container tricks work only on #EJB calls. So, for example, it's pointless to place transactional annotation on a private method - it won't be used ever.
Another important point is about checked exceptions. By default these do not cause transaction rollback indeed. But it's still possible to annotate your checked exception like below to make it rollback ongoing transaction:
#ApplicationException(rollback = true)
I have a 3-layer application with a client-container, EJB-container (business-layer and data-access-layer). I want to make transactions in my client by using BMT. My EJBs on the EJB-container are all working with CMT.
But I am not sure if that actually works, since the client is not working in an EJB-container. The client injects the EJBs of the EJB-container with lookups on a Context object, which seem to work fine. I declared my client-side class as:
#Singleton
#TransactionManagement(TransactionManagementType.BEAN)
Is this correct? I guess the client side class which is used by my GUI has to be a singleton.
I have these objects:
private Context jndiCntx;
private UserTransaction tx;
#PostConstruct
public void initialize() throws Exception {
jndiCntx = new InitialContext();
tx = (UserTransaction) jndiCntx.lookup("java:comp/UserTransaction");
tx.begin();
}
And this PostConstruct initializes the transaction.
Here is where I get a NullPointerException (in commitOrder()):
#Override
public void commitOrder() throws ApplicationException {
try {
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new ApplicationException("", "commitOrder() failed!");
}
}
#Override
public void cancelOrder() throws ApplicationException {
try {
tx.rollback();
} catch (Exception e) {
throw new ApplicationException("", "cancelorder() failed!");
}
}
So it seems like that I don't get a UserTransaction object. I am slightly confused by the different ways of using contexts and transactions. What am I doing wrong? And by the way: What is the difference between using a Transaction with a TransactionManager and using a UserTransaction?
I have a MessageBean which reads from a Queue we'll name MainQ.
If the execution of the onMessage code throws a user-based Exception with a type we'll name UserException I want to catch this and put this message on a separate Queue named UserErrorQ.
If the exception is not of this type, the Exception is thrown on to be handled by the DMQ.
Here is my issue:
in my catch block I attempt, through a ErrorQueueHandler, to put this new message on the UserErrorQ. This results in an error when I attempt to connect to the connectionFactory to send the message to the UserErrorQ.
Apparently creating a new connection to a QueueConnectionFactory(javax.jms.ConnectionFactory) is causing problems
Error:
com.sun.messaging.jms.JMSException: MQRA:DCF:allocation failure:createConnection:Error in allocating a connection. Cause: javax.transaction.RollbackException
at com.sun.messaging.jms.ra.DirectConnectionFactory._allocateConnection(DirectConnectionFactory.java:548)
at com.sun.messaging.jms.ra.DirectConnectionFactory.createConnection(DirectConnectionFactory.java:265)
at com.sun.messaging.jms.ra.DirectConnectionFactory.createConnection(DirectConnectionFactory.java:244)`
MessageBean:
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message message) {
try{
.
.
}catch(Exception e){
if(isUserExceptionWrappedInException(e){
errorQueueHandler.sendToErrorQueue(message);
}
}
}
private boolean isUserExceptionWrappedInException(Throwable t) {
if (t == null)
return false;
else if (t instanceof UserException)
return true;
else
return isUserExceptionWrappedInException(t.getCause());
}
ErrorQueueHandler:
public void sendToErrorQueue(Message message) {
try {
createConnection();
send((TextMessage)message);
} finally {
closeConnection();
}
}
private void createConnection() throws Exception {
try {
connection = connectionfactory.createConnection();
connection.start();
} catch (JMSException e) {
String msg = "Error while attempting to initialize connection to jms destination " + ERROR_QUEUE;
throw new OperationalException(msg, e, OperationalExceptionType.APPLIKASJONSTJENER);
}
}
As mentioned, the error occurs when attempting to make the connection. Anyone have a fix for this?
So, I have figured out the answer to my own question.
The reason for the connectionException was that the ErrorQueueHandler was not an EJB, but rather injected via CDI. There are no new instantiations allowed within a rollback state because the container discards the bean instance, which is why it failed. My REQUIRES_NEW annotation was also ignored as this belongs to the javax api, which will not affect a CDI injected bean.
Here are a few things to note:
Make sure the EJB has either no constructors, or public ones. The modifiers are important as the container needs these to be correct for it to instantiate the EJB.
There are a few problems with this approach.
As I am attempting to write the message to a separate error queue instead of the DMQ, I will have to consume the message and not throw the error on afterwards. Because the MDB is in a rollback state, the JMS spec clearly states that this will cause the message to be redelivered. What you will experience is that after writing to you custom errorQueue, the message will bounce right back to the queue and you now have an infinite loop.
Luckily i also have a solution:
The main issue here is controlling your transactions. For this scenario, i need 3 transactions:
One transaction for the MDB so that it is able to acknowledge the message event though i have a RuntimeException.
One transaction for the logic of the onMessage method so that i am able to do a rollback when i get an exception, but also still be able to write to the ErrorQueue.
One transaction for connecting and writing to the ErrorQueue while in a rollback state.
Code:
MessageBean:
#EJB
QueueService queueService;
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message message) {
try{
queueService.processMessageInNewTrasaction(message);
}catch(Exception e){
throw e;
}
}
QueueService:
import javax.jms.Message;
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
#Stateless
public class QueueService {
#EJB
ErrorQueueHandler errorQueueHandler;
public void processMessageInNewTransaction(Message message){
try {
.
.
} catch(Exception e) {
if(isUserExceptionWrappedInException(e)
errorQueueHandler.sendToErrorQueue(message);
}
}
private boolean isUserExceptionWrappedInException(Throwable t) {
if (t == null)
return false;
else if (t instanceof UserException)
return true;
else
return isUserExceptionWrappedInException(t.getCause());
}
}
ErrorQueueHandler:
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
#Stateless
public class ErrorQueueHandler{
public void sendToErrorQueue(Message message){
.
.
}
}
useful resource: http://weblogic-wonders.com/weblogic/2011/01/10/working-with-jms-and-the-standard-issues-in-jms/
I have a rest class which accepts a multipart request, saves a file in a particular location and calls an ejb service to save so hash in our database.
The flow is like below
Rest -> service -> dao
In my service class I am injecting the dao. Due to some reason the dao is not initialized and injected into the service class and I get a null pointer exception.
The file should be deleted in this case because ejbs have transaction management capabilities. But the file is not being deleted.
Do I need to additionally enable transaction management somewhere in the container?
My rest class is not an ejb. Is it because my rest class is not an ejb, that is why the file is not being deleted?
BTW I am using jboss eap 6.1
Can anyone please help?
For simplicity I have written a new code with almost same thing my original code is doing
#Stateless
#Local
#TransactionManagement
public class ImportUpgradeServiceImpl implements ImportUpgradeService {
#Inject
private UpgradePackageDao upgradePackageDao;
#Override
public boolean savePackage() {
File file = new File("d:\\ejbtest.log");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
upgradePackageDao.savePackageHash(null);
return false;
}
}
Below is my DAO
public class UpgradePackageDaoImpl implements UpgradePackageDao {
#Override
public void savePackageHash(String hash) {
throw new RuntimeException("cannot save");
}
}
I ran the ejb with #TransactionManagement and without #TransactionManagement. Both scenarios I can still see "ejbtest.log" file created in my D: drive
Below is what I did, I need to implement rollback, using #transactional annotation, but not working as expected, what else need to be done for proper rollback to happen ?? I want that when the code is executed result in db should be "testingOne" , currently it is set to "notRollBacked". Can you please point my mistake.
public Response deleteUser(Request argVO)throws Exception
{
Users users = UsersLocalServiceUtil.getUsers("sagar");
users.setUserName("testingOne");
UsersLocalServiceUtil.updateUsers(users);
try
{
testRollbackFunction();
}
catch (Exception ex)
{
}
return new Response();
}
#Transactional(isolation = Isolation.PORTAL, rollbackFor =
{PortalException.class, SystemException.class})
private void testRollbackFunction() throws Exception
{
Users users = UsersLocalServiceUtil.getUsers("sagar");
users.setUserName("notRollbacked");
UsersLocalServiceUtil.updateUsers(users);
throw new PortalException();
}
****************Edit 1*************
I did what was mentioned in answers:
I did taken bean from context
and written a class/bean as
#Transactional(isolation = Isolation.PORTAL, rollbackFor =
{PortalException.class, SystemException.class})
public class RollBack
{
#Transactional(isolation = Isolation.PORTAL, rollbackFor =
{PortalException.class, SystemException.class})
public void thisWillRollBack() throws Exception
{
Users users = UsersLocalServiceUtil.getUsers("sagar");
users.setBarringReason("notRollbacked");
UsersLocalServiceUtil.updateUsers(users);
throw new PortalException();
}
}
spring xml file bean refrence set as :
<bean id="rollBackBean" class="com.alepo.RollBack">
</bean>
public Response myMethod(Request argVO)throws Exception
{
Users users = UsersLocalServiceUtil.getUsers("sagar");
users.setBarringReason("testingOne");
UsersLocalServiceUtil.updateUsers(users);
try
{
Test test = new Test();
Object obj = test.getBean();
RollBack rollBack = (RollBack)obj;
rollBack.thisWillRollBack();
}
catch (Exception ex)
{
ex.printStackTrace();
}
return new Response();
}
#################EDIT 4
now calling rollback function as :
RollBack rollBack = (RollBack)PortalBeanLocatorUtil.getBeanLocator().locate("rollBackBean");
rollBack.thisWillRollBack();
No Test class in picture now ...no new anywhere ...
still NOT WORKING .......
If you have a #Transactional annotation on method, Spring wraps the call to this method with aspect handling the transaction.
So:
1) Only public methodes can be wrapped in aspect
2) You call wrapped code only if you call the method on a bean taken from / injected by Spring container.
In your case:
1) The code isn't wrapped in transactional aspect because it is not public method
2) Event if it was, it is called directly from within the class, so you wouldn't call wrapped version anyway.
So the solution is to make separate bean with #Transactional method, inject it into and call it from Response class.
Of course you need <tx:annotation-driven/> in your spring-xml or instruct Spring otherwise to process #Transactional annotations (see the reference).
The issue is you are outside the application context. You are creating a new instance of a class, NEW is bad in Spring, very bad. Get an instance of Test from the application context, not by creating a new instance unless you start your application context in Test. Try to Autowire test in your class you mention above or inject it from Spring and then let me know, but the code you are showing above will never work with transaction management.