How to stop the entire java webapp when the servlet fails to initialize - servlets

I want my web application to fail on startup if any of my servlet fails to initialize.
I would expect if I throw an exception form the Servlet.init() method it would cause the entire app to fail, but apparently it doesn't. The web container (Tomcat 7 in my case) just fails to load that particular servlet, but the application is reported to be successfully deployed anyway.
It behaves as expected if an exception thrown from e.g. ServletContextListener.contextInitialized() method, but why the exception thrown from the Servlet.init() doesn't have this effect?
Is there any way to stop the application in case of a Servlet initialization error?

Try this following steps:
Keep your servlet in load-on-startup list such that your servlet
is initialized on application start.
In Servlet.init() method, set an attribute in ServletContext saying the servlet is initialzied. ex, myServletInited
Implement ServletContextListener.contextInitialzied() method. Check if myServletInited is present. If is does not present throw an exception which fails the application.

Related

How to fix javax.naming.NameNotFoundException: DQ not bound exception in Spring JMS?

This problem occurs when I am trying to send message to receiver from sender. I uses HornetQ JMS server to send message. How can I fix this problem?
WARNING: Exception encountered during context initialization -
cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'topicDestination' defined in class path
resource [springconfig.xml]: Invocation of init method failed; nested
exception is javax.naming.NameNotFoundException: DQ not bound
I try this code in Springconfig.xml file later
property name="jndiName" value="queue/DQ"
and also edit
hornetq-2.4.0.Final\config\stand-alone\shared-store\hornetq-jms.xml
and add queue in hornetq-jms.xml file
--queue name="taxQueue"
entry name="/queue/DQ"
it will run correctly.

Server was unable to process request. in web service method call

Through my project i am making an web service call by adding web reference.
In my project i am creating object like below
PortalService portalService=new PortalService();
if (portalService != null)
{
DataSet ds = portalService.getStateList(3);
}
Its going inside if loop after creating object. But when calling web service method its giving me exception like below
[SoapException: Server was unable to process request. ---> Object reference not set to an instance of an object.]
Why this exception occuring? How do i make web service call?
The code is ok. It looks like there is an exception happening inside the service itself. I would look at the service code, and try to track down the issue. Perhaps the input is not valid?

How do I trap a SerializationException in Web API?

I have an ASP.NET Web API web service which throws a SerializationException in certain circumstances. The problem is that I'm unable to trap and log this exception server-side -- the only place it shows up is in the body of the HTTP response to the client.
I registered an ExceptionFilterAttribute as described in Exception Handling in ASP.NET Web API and verified that it works properly when I throw an exception within my controller. Unfortunately the SerializationException is being thrown during the response (after the controller) and appears to be completely swallowed up by ASP.NET. I also tried hooking Application_Error() in Global.asax.cs but it didn't show up there either.
How can I catch SerializationException exceptions during the Web API response?
If, instead of returning an object, you use the ApiController.CreateResponse() method and return a HttpResponseMessage you can then do response.Content.LoadIntoBufferAsync().Wait() and that will force the serialization to happen whilst you are still in the action and therefore can catch the exception.
BTW, Serialization of responses actually happens at the host layers(in HttpControllerHandler, when hosted in IIS and in HttpSelfhostServer, when hosted in SelfHost) which is way below the stack and not immediately after the response is returned from an action.
WebAPI Stack Poster: http://www.asp.net/posters/web-api/ASP.NET-Web-API-Poster-grayscale.pdf
That said, I am not able to come up with a straight forward way to achieve this. This is cumbersome, but may be override the default Xml and Json formatter's WriteToStreamAsync methods and try-catch-log any exceptions?
Alternatively, you can enable Web API Tracing which would log the exceptions happening during serialization. But yeah, if you do not know for the requests which cause the serialization errors, then you might want to enable tracing all the time which i am not sure is something you might want to do.
You can catch all Web API exceptions by registering an implementation of IExceptionHandler.
See Web API Global Error Handling
...there are a number of cases that exception filters can’t handle. For example:
Exceptions thrown from controller constructors.
Exceptions thrown from message handlers.
Exceptions thrown during routing.
Exceptions thrown during response content serialization .
One thing not mentioned in that article is that your IExceptionHandler must be registered, either by GlobalConfiguration.Configuration.Services.Add(...) or via an IoC container configured to be used by DependencyResolver.

Propagating AccessDeniedException in Spring Security

In my web application I am using Spring Security and Spring MVC.
I have secured a couple of methods with #Secured annotation and configured Spring Security in such a way that when one of those methods is accessed without the proper role, the user is taken to the login page. However, I do not want that behaviour when the offending request comes from Ajax, so I implemented the custom #ExceptionHandler annotated method to determine the request's context.
This is my exception handler:
#ExceptionHandler(AccessDeniedException.class)
public void handleAccessDeniedException(AccessDeniedException ex, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (isAjax(request)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
throw ex;
}
}
This way I can both handle the exception myself (for example, log an attempt of accessing the #Secured method) and then let Spring do its part and redirect the user to the login page by rethrowing the AccessDeniedException. Also, when the request comes from Ajax I set the response status to SC_UNAUTHORIZED and handle the error on the client side.
Now, this seems to be working fine, but I am getting the following ERROR each time I rethrow the exception from the handleAccessDeniedException method:
ERROR org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke #ExceptionHandler method: public void app.controller.BaseController.handleAccessDeniedException(org.springframework.security.access.AccessDeniedException,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.lang.Exception
org.springframework.security.access.AccessDeniedException:
at app.controller.BaseController.handleAccessDeniedException(BaseController.java:23)
at app.controller.BaseController$$FastClassByCGLIB$$8f052058.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
(...)
I have not added any exception handling specifics to spring xml configuration files.
I do not see any issues with the app itself, but the error is there and since I am quite new to Spring MVC and Spring Security, I am guessing that I am not doing this properly. Any suggestions? Thanks!
Your exception handler isn't supposed to throw another exception. It's supposed to deal with it and send a response. It's a good idea to check the code if you get an error from a class to see how it behaves.
For the non-ajax case, you'd be better to redirect the response to the login page, if that's what you want. Alternatively, you can customize the AuthenticationEntryPoint used by Spring Security instead and omit AccessDeniedExceptions from MVC handling. The behaviour would essentially be the same as the defaul LoginUrlAuthenticationEntryPoint but you would extend it to return a 403 when an ajax request is detected.

Throwing Exception with inner SecurityException only displays inner exception in ASP.NET MVC

If I add the following line to an ASP.NET MVC action method
throw new Exception("outer", new SecurityException("inner"));
the error that is actually displayed on the yellow screen of death is the inner SecurityException with absolutely no mention of the outer exception.
SecurityException
Description: The application attempted to perform an operation not
allowed by the security policy. To grant this application the
required permission please contact your system administrator or change
the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: inner
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[SecurityException: inner]
Is this expected behavior?
It doesn't seem to matter what type the outer exception is. Even if it is another SecurityException, the message is never displayed. The default SecurityException error message is so vague that I want to catch it and add some more specific information. This works fine if I do not include the original SecurityException as the innerException but ideally I would like to do this.
This behaviour originates in the ASP.NET "core", not in ASP.NET MVC. Unfortunately, the error formatter classes are internal, and the consuming types do not provide any extension points that would allow one to tweak the behaviour without replacing the error reporting mechanism. The workaround is to replace the default "yellow screen of death" page by a custom error page/view in which one exposes the information that one prefers.
This is exactly what one should usually be doing for production. In your case, it just means that you would have an alternate version for debug instead of using the ASP.NET-provided default.
in general you should never throw Exception class/object directly but only derived ones, for example:
throw new SecurityException("user should not be allowed to access this method...");
in a situation like this what are you missing in the log or in the page?
if you use an application global exception handler and you log from there with either Log4Net or NLog you should be able to access all exception chain from outer to inner and so on depending on how you configure and use the logging framework. The Yellow page of IIS / ASP.NET might not be complete but should show the stack trace anyway.
if you want to throw your own exception from a catch block you wrap the actual exception coming from the catch in this way:
throw new SecurityException("user should not be allowed...", exc);
Edit: tried what you suggested and got the following logged in a text file by Log4Net:
System.Security.SecurityException: more explicit exception --->
System.Security.SecurityException: original exception at
EDICheckerApp.Program.boom() in
C:\DEV_RPP\Program.cs:line 45
--- End of inner exception stack trace --- at EDICheckerApp.Program.boom() in
C:\DEV_RPP\Program.cs:line 49
at EDICheckerApp.Program.Main(String[] args) in
C:\DEV_RPP\Program.cs:line 27

Resources