Exception design mismatch to the requirement in application - java

In my application, i have decided to integrate hoptoad error logging system in it. But as the application is huge, it requires a lot of manual work to call the log method present in the hoptoad class in each and every catch block. As of now, i have included the method call for error logging in few catch blocks. This is a spring, hibernate, flex, drools, maven managed application.
hoptoadUtil.logToHoptoad(throwable);
My doubt is - can i call this method globally for the application ,i.e., ask spring to call this log method in hoptoad class wherever any exception or error occurs.

Spring AOP might help you, check this link for an example
http://www.mkyong.com/spring/spring-aop-examples-advice/

Related

How to handle classes that need web resources?

I'm making a project in Java where I have a class that on its initialization connects to an API to retrieve some info. Based on that info it then provides several methods to use and analyse it.
But what if the web request fails ? Or if I have some other issue. Every method will now fail because they don't have the info required
What I did is having a boolean named loadInfo, and also a public method didLoadInfo, so that the client knows the state of the object. I also add a reloadInfo method to try to reload all info, and every method throws an exception if they are called when the loadInfo variable is false. That exception is a checked exception.
Is there another better way to handle this situation ? The exception thrown by all the methods should be checked or unchecked ?
EDIT:
Is a good idea to maintain default values, but how would you let the client know that the info returned may not be up to date ? Maybe another boolean indicating the info state ?
I think in this kind of scenarios you should use REST, so that your java components will be running on web server independently.
If you UI is up and running(it could be on angular or react js or html) and have REST calls in place to call java REST API, also you can configure other API in same web project independent of REST classes and will be initialized as soon at web context is loaded( for example if you are using spring, as soon as application context is loaded).
Since you are calling other services to retrieve info, use Netflix Hysytix to handle failure gracefully with a fallback method. Obviously, you have many more options to fallback logic.
Check out the official Hystrix Library here.
If you have time, check out my article on LinkedIn.

Is there a way to have spring run additional code at application startup failure?

We have a spring web-application running on a Tomcat server that we would like to have some additional code run ONLY if there is an issue with the webapp's startup.
However, any errors we receive will come from either Bean Creation Issues (which, hopefully we would catch before ever releasing) or a Flyway upgrade script issue. Both cases, the exceptions are caught within the spring core somewhere, and I'd like to run some additional code in those situations before the webapp failure finishes. I'm not 100% sure how to set this up though, considering where the exceptions are thrown.
I've been looking at Spring's Life Cycle configuration annotations, and while I have considered running the code in the #PreDestroy method we're providing, that means it would run our code every time we restarted the webapp, instead of just on startup failures. Is there a way to indicate the differences between a normal shutdown and a failed startup using the life cycle annotations?
You could register your own ServletContextListener instead of the Spring's one and delegate contextInitialized method invocation to the Spring implementation you use for loading Spring context (whichever one you use, for example org.springframework.web.context.ContextLoaderListener).
Then catch and handle the desired exceptions.

Stop the deployment if any error in the servlet context listener [duplicate]

I have a ServletContextListener which performs some database management functions when my Java EE application starts. This runs in my application before JPA and other pieces of the application are started/loaded. If the database maintenance fails I am logging the errors. If the database maintenance fails the application will not function properly and I would like to halt the application.
How can I gracefully and correctly stop the application from ServletContextListener.contextInitialized?
Solution given by Viven below is close but not quite. When I throw a RuntimeException Glassfish is left in an inconsistent state where its admin console is not accessible but some process is still running and keeping port 3700 (IIOP?) open which then prevents a restart.
In your listener, catch any exceptions and use servlet context attributes to store flags or other useful information about the error. You should probably also log something to indicate that the app is non-functional.
At this point, your options may be dictated by the architecture of your app. If all requests are handled by a single controller/dispatcher servlet, it might make sense to have its init method check the context attributes and throw an UnavailableException. Just be aware that the exception only applies to the specific servlet throwing it. This makes the approach less manageable if your app contains many servlets or allows direct access to other resources.
Another option would be to create a filter that intercepts every request, checks the context attributes and then throws an exception. Other variations are certainly possible.
If your ServletContextListener throws an exception, the webapp won't load correctly and the application server may block all subsequent request (and respond with a 500 error).
It isn't exactly preventing the application to start, nor stopping the application, but it prevents any further usage of the app and could be useful in your case.
After proper verification in the spec, this behaviour isn't mandatory in the specification. The server may (not must) return 500 errors. This solution has to be used carefully, therefore.
See this Answer for a quote from the Servlet spec.

Accessing application code from overridden Tomcat class

I'm currently creating my own JDBCRealm and more specifically, I'm overriding the Authenticate method. The override was no problem, and I got it to work using SHA authentication.
The problems starting arising when I needed to access a different column that isn't covered by Tomcat's own methods, like getPassword(username) and getPrincipal(username).
I have a Hibernate method that retrieves a user based on their username and it looks like:
UsersDTO user = UsersDAO.getUser(username);
The problem is, that because the code is part of the Tomcat library and not the application, calling the method doesn't work. It throws no exceptions and nothing gets logged to catalina.out, it just presents me with a 500 HTTP error.
I have tried numerous things, but I'm at a loss at the moment. Can anyone shed a light on my problem?
You cannot call classes loaded by the app classloader from classes loaded by the server classloader.
You should deploy your jars in a way that all the invocations are done between classes loaded by the same classloader, or from classes loaded by a lower level classloader to classes loaded by a higher level classloader.
Take a look at this. It's related to Weblogic, but the same concepts apply to Tomcat.
http://docs.oracle.com/cd/E24329_01/web.1211/e24368/classloading.htm
Tomcat is implemented with Apache Commons Logging library. So with proper implementation of that logging library in your code, tomcat should be able to log your error properly.
see reference here

What is the cause of EJB 2.x "reentrant method call detected" Exceptions? How to solve them?

I'm mantaining a EJB 2 CMP legacy app runing on a JBoss 4.0.4 GA application server with deployed entity/stateless session beans. All the EJB boilerplate code is generated via XDoclet from the EntityEJB/EntityEJBManager annotations.
I've noticed that when my GUI client invokes the facade create method, I have lots of cases of EJBException in my server log with the "Reentrant method call detected" message, which rollbacks the transaction.
What does this Exception means? How can I avoid having such error (which unfortunately, I wasn't able to reproduce yet)
Update: Found this link that explains what is meant by reentrancy, however, seems to me that it says my app cannot be accesed concurrently?
I've seen this before where EJB1 calls EJB2 which calls back to EJB1 within the container as part of the same transaction.
You can tell the container to allow this by marking EJB1 as reentrant which will allow it to be accessed multiple times in the same transaction.
This is done in the deployment descriptor with the following tag:
<reentrant>True</reentrant>
There should be a corresponding EntityEJB annotation that XDoclet can use to generate this for you.
we just came across the same problem and our solution was two-fold. Firstly we ensure that none of ejb's had transaction attributes of NotSupported within our ejb-jar.xml. We then used "instance per transaction" as our optimistic locking strategy. It's a bit of a belt-and-braces approach, but it works
It does mean that the Entity bean in question cannot be accessed concurrently, which makes sense since it would likely corrupt the data.

Categories