getting exception while initialising ejb object - java

Below is the exception I am getting while initializing any ejb object.
Could any one tell what is the reason of below exception and how can I resolve it???
Is is Application exception or Environment Exception???
Thanks in Advance... waiting for response ...
[7/12/10 5:05:24:226 EDT] 00000037 ExceptionUtil E CNTR0020E: EJB threw an unexpected (non-declared) exception during invoc
ation of method "init" on bean "BeanId(RDxEAR#vs-tle-beans-server.jar#VLSContextHome, C5E6CBE5-0129-4000-E000-C9DF093361B8)".
Exception data: java.rmi.RemoteException
at com.versata.tl.vls.ejb.VLSContextBean.init(VLSContextBean.java:298)
at com.versata.tl.vls.ejb.EJSRemoteStatefulVLSContextHome_acff79a1.init(Unknown Source)
at com.versata.tl.vls.ejb._EJSRemoteStatefulVLSContextHome_acff79a1_Tie.init(_EJSRemoteStatefulVLSContextHome_acff79a
1_Tie.java:2119)
at com.versata.tl.vls.ejb._EJSRemoteStatefulVLSContextHome_acff79a1_Tie._invoke(_EJSRemoteStatefulVLSContextHome_acff
79a1_Tie.java:395)
at com.ibm.CORBA.iiop.ServerDelegate.dispatchInvokeHandler(ServerDelegate.java:621)
at com.ibm.CORBA.iiop.ServerDelegate.dispatch(ServerDelegate.java:474)
at com.ibm.rmi.iiop.ORB.process(ORB.java:503)
at com.ibm.CORBA.iiop.ORB.process(ORB.java:1571)
at com.ibm.rmi.iiop.Connection.respondTo(Connection.java:2703)
at com.ibm.rmi.iiop.Connection.doWork(Connection.java:2577)
at com.ibm.rmi.iiop.WorkUnitImpl.doWork(WorkUnitImpl.java:62)
at com.ibm.ejs.oa.pool.PooledThread.run(ThreadPool.java:118)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1473)
[7/12/10 5:05:24:231 EDT] 00000037 LocalTranCoor E WLTC0017E: Resources rolled back due to setRollbackOnly() being called.

Looks like the 'Caused by' information is not there, but it seems by part of the stack trace that the Stateful bean's #Init method corresponding to the EJBHome.create() method is throwing a RuntimeException. The 'Resources rolled back' message is likely not the cause of the problem but simply the container carrying it it's job of cleaning up after the runtime exception.
First thing to do is either:
1. Surround the body of the init() method with something that catches and logs the RuntimeException so you can look at where the real source of the problem is, or better...
2. Put that exception logging into an interceptor so it can easily be reused on any other beans in the future.
If you do find the RuntimeException and determine it is an exception you do what to throw without a transaction rollback or your bean instance being destroyed you can use the #ApplicationException annotation on the exception class to turn it into an exception that is safe to throw. If it is a built in exception you can mark it in the ejb-jar.xml file. Note, though, that this affects all usage of the exception type, so be very careful and avoid doing things like java.lang.RuntimeException. Best to mark very specific subclasses of RuntimeException to avoid completely disabling the container's ability to clean up after unexpected exceptions.

Related

Spring Boot- Throw an Error and Stop application starting up on some criteria

I am working on an application where in a bean's post construct method i am adding some logic to create an object. Now , what I want to do is, if there is an exception and the creation of the object has some error, then do not let the application start up. Yes, I can see an exception being thrown on the console when it starts up, if there is any issue with the construction of an object, but I would like something better than that to inform me that construction of an object has failed, and what better criteria than application failing to start up.
Any help is much appreciated.
Thank you in advance.
You can look for FailureAnalyzer for this type of requirements where additional information will given in case application start failes. If any exception raised during application start, all the FailureAnalyzer classes will be invoked in a sequence. If any of the FailureAnalyzer class returning FailureAnalysis object then the exception won't be propagated to further FailureAnalysis classes.
Please make sure you register your FailureAnalysis class in resource/META-INF/spring.factories file.
#Component
public class SomeObject {
#PostConstruct
public void init() throws Exception {
throw new Exception("SomeObject init threw exception");
}
}
public class ObjConstructionFailureAnalyzer extends
AbstractFailureAnalyzer<BeanCreationException> {
#Override
protected FailureAnalysis analyze(Throwable rootFailure,
BeanCreationException cause) {
System.out.println("\n===>ObjConstructionFailureAnalyzer::analyze()\n");
String desciption = "Object creation failed, [Reason]: " +
cause.getMessage();
String action = "Please handle exceptions in your init methods";
return new FailureAnalysis(desciption, action, cause);
}
}
In spring.factories file
org.springframework.boot.diagnostics.FailureAnalyzer=examples.stackoverflow.ObjConstructionFailureAnalyzer
Exception stacktrace
===>ObjConstructionFailureAnalyzer::analyze()
2018-02-21 10:16:59.552 ERROR 9500 --- [ main]
o.s.b.d.LoggingFailureAnalysisReporter :
*************************** APPLICATION FAILED TO START
Description:
Object creation failed, [Reason]: Error creating bean with name
'someObject': Invocation of init method failed; nested exception is
java.lang.Exception: SomeObject init threw exception
Action:
Please handle exceptions in your init methods
You can additionally visit here for code sample.

Catch EJBTransactionRolledbackException before it is logged to file

My setup:
I have an EJB bean (deployed in an ear on a JBoss 6.4) with a method that calculates some values and stores it in a database. The method is started in a new transaction. It looks like this:
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void doStuff() {
MyObject value = calculateSomeValues();
entityManager.merge(value);
entitiyManager.flush();
}
By design, it is possible that the flush will fail due to a ConstraintViolationException. As this is a new transaction, the exception will be wrapped in an EJBTransactionRolledbackException and thrown as a RuntimeException. I have set up logging for ejb exceptions as it is useful to find them in the whole system. However as I know that the ConstraintViolationException will occur now and then, I would like to catch it and rollback before the logging system logs it as an error (the constraint violation is not seen as an exception, but it is required from the database's point of view). At the moment, my log file is clogged with entries like this one:
ERROR [org.jboss.as.ejb3.invocation] (default-threads - 49) JBAS014134: EJB Invocation failed on component
How can I catch the exception in such a way that the logger is prevented from printing these errors? (Note: I still want it to log all other EJBTransactionRolledbackExceptions)
I don't have JBoss 6 deployed, so I cannot immediately test whether the precise exception types work also for JBoss 6 (I tried this on WildFly 8).
A possible solution is to put in your EJB a method annotated by #AroundInvoke (at least if you don't have other interceptors on this EJB):
#AroundInvoke
public Object myConstraintViolationInterceptor(InvocationContext ctx) throws Exception
{
try {
return ctx.proceed();
}
catch(PersistenceException e) {
if (e.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
//some action taken
}
else {
throw e;
}
return null;
}
}
By the way, if your ConstraintViolationException is actually optimistic locking exception in disguise (that is, it is thrown because another user has modified some data in the meantime), maybe it is better to report it to the user.

Mutation SURVIVED but runtime exception was thrown in the code under test

I have a Class calling a super-Method for registering a Bean Mapper. Other methods Use a super-Method for mapping Beans which relies on having the responsible Bean Mapper registered before.
If a Bean is being mapped without a matching registered Mapper, a custom Runtime-Exception is thrown.
When I remove the registration of the Bean-Mapper myself, 240 Tests are failing because the called super.map() method raises a Runtime-Exception.
But PIT tells me: SURVIVED.
removed call to org/laladev/moneyjinn/businesslogic/service/impl/AbstractService::registerBeanMapper → SURVIVED
Why?
Yes - At least one of the "Error"-Tests is listed as an examinded Test.
When I remove the line myself and execute all of my Tests, plenty of them are counted as Errors with:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is Mapper undefined!
It is a Spring Boot App and the container is fired up automatically during unittesting by Spring for all my "end user tests" (JSON/REST in+out) which are something like 95% of all my tests.

Transactional error while commiting

I am trying to solve this error in Payara41 server Java EE 7, this sample works on WildFly-9 Java 7 EE and on Glassfish-3.1 Java EE 6 (without #Transactional and #TransactionalManagement)
#Stateful
#Transactional //default TxType.REQUIRED
#TransactionManagement(TransactionManagementType.BEAN)
public class ImprovementDaoImpl extends AbstractBaseDaoClass implements ImprovementDao {
/*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
#PersistenceContext(unitName = "pu", type = PersistenceContextType.EXTENDED)
private EntityManager em;
#Resource
private UserTransaction tx;
...
}
Here's some stacktrace, what apperas after executing tx.flush();:
javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRED encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
(...)
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
So far I've tried to use interceptor and #TransactionAttribute, but none helped...
Thanks for any advice/help! :)
I know this is old, but hopefully this helps someone out there...
Question 21363423: Throwing an application exception causes TransactionalException says
You are throwing an exception from a method whose invocation will be
intercepted at runtime and additional logic wrapped around it:
transaction management;
exception handling.
Your exception cannot transparently jump over that logic, and the
specification (probably) says a TransactionalException will be thrown,
wrapping your original exception...
Question 18888572: How do you find out what Exception caused the CDI Transaction Rollback?
Shows how to use a CDI Interceptor to catch the exceptions. I can't tell from the limited info from the OP what his/her specific issue is, but when I received this exception I has to review the WebLogic server log and found the entry where it told me a unique contraint was violated.. Time to add some interceptors...

How do you find out what Exception caused the CDI Transaction Rollback?

We are using CDI with CMT (container managed transactions) to connect to the database in the web app and mark methods called from the front-end that require a transaction with:
#Transactional(value=TxType.REQUIRES_NEW)
This will create a new CDI transaction, however now if an exception occurs doing this code block or any other code block called from this method it will throw the error message:
javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRES_NEW encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
...
Caused by: javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRES_NEW encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
...
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
Is there anyway to get CDI to re-throw the nested error so that you can easily debug what the real cause of the rollback was?
(Running on Java-EE7, Glassfish 4.0, JSF 2.2.2)
It seems the easiest way to do this is by using a CDI Interceptor to catch the exceptions. We can define the CDI Interceptor as follows:
#InterceptorBinding
#Target({ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface TransactionDebugger {
}
Once we have defined the CDI Interceptor, we need to create class that is executed when the Interceptor annotation is used. We define an #AroundInvoke so that our code is called before the code in the method we annotate. invocationContext.proceed() will call the method we annotate and give us the result (if any) it returned. So we can put a try, catch (Exception) around this call to catch any kind of Exception that is thrown. Then we can log this exception using the logger (log4j used here), and re-throw the Exception so that any upstream code is also informed of it.
Re-throwing the Exception will also allow us to use CMT (Container Managed Transactions) as then ultimately the container will catch the Exception and throw a transaction RollbackException. However, you could easily use UserTransactions with this also and perform a manual rollback when an exception is caught instead of re-throwing it.
#Interceptor
#TransactionDebugger
public class TransactionInterceptor {
private Logger logger = LogManager.getLogger();
#AroundInvoke
public Object runInTransaction(InvocationContext invocationContext) throws Exception {
Object result = null;
try {
result = invocationContext.proceed();
} catch (Exception e) {
logger.error("Error encountered during Transaction.", e);
throw e;
}
return result;
}
}
Next we must include our new Interceptor in our beans.xml (generally located in src/META-INF), since Interceptors are not enabled by default in CDI. This must be done in ALL projects where the annotation is used, not just the project where the annotation is defined. This is because CDI initializes Interceptors on a per project basis:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
<interceptors>
<class>package.database.TransactionInterceptor</class>
</interceptors>
</beans>
Finally, we must annotate the methods that we call with our new CDI Interceptor. Here we annotate them with #Transactional to start a transaction, and #TransactionDebugger to catch any Exception that occurs within the transaction:
#Transactional #TransactionDebugger
public void init() {
...
}
This will now log ANY error that occurs while executing the init() code. The logging granularity can be changed by changing the try, catch from Exception to a sub-class of Exception in the Interceptor implementation class TransactionInterceptor.
The TransactionalException is thrown at the commit time, i.e. after your code has been fully executed. Since the transaction is marked for rollback, commit cannot take place and the exception is thrown.
However, the transaction was marked for rollback sometime during the execution. I assume you do not mark it for rollback manually, therefore an exception must have been thrown. The exception is either a RuntimeException or it is annotated with #ApplicationException(rollback = true). Since you don't get this exception, the exception must have been caught somewhere. Are you sure you do not catch exceptions thrown from a business method in your code?
To answer the question... No, I don't think it is possible to rethrow the original exception, because it is thrown at different time and place.

Categories