Spring Controller synchronized - spring

Is Spring Controller obeys the synchronized process by adding keyword in the method?
When tried to provide synchronize it seems method not blocked and two threads are executing the same method at same time. Checked with Thread.sleep(50000)
Have used #Scope("request")

You'll need to add appropriate synchronization around critical sections in your code.

Related

Handling expected exceptions from dao

I am currently coding a spring-mvc (jsp) project with three layers (controller -> service -> dao) and I am wondering what is the correct way of handling expected exceptions from dao invocations (e.g trying to persist an User that already exists, if it exists then call the register view again with a message saying that the user already exists), at first I thought it would be a good idea to catch the exception in the dao (e.g DataIntegrityViolationException) and throw my arbitrary checked exception so then I can do an exception handler for it in the controller but I fear if I do this then I might have conflicts if I want to make my service methods #Transactional later on since spring won't know how to rollback the transaction.
If this is correct then I have two ideas:
try/catch DataAccessException in the controller when I invoke the service call userService.register(..)
Use something among the lines like userService.findByUsername(username) in the controller (which returns an Optional) and if its present I notify the user before even calling userService.register(..)
Also, our teacher emphasizes on following DDD behavior and trying to avoid leaking business logic in our controllers and I fear both of this solutions do that but I don't really know how to handle it otherwise.
Spring already converts checked JDBC exceptions into more informative unchecked exceptions, which play well with service layer transactions. All your custom checked exceptions do is force you to type more. Spring gives you reasonable defaults, take advantage of them.
Create an exception handler. Spring has multiple ways to implement this, none of them involve writing catch blocks for exceptions in your controller.
Put the business logic in the service, not the controller. It seems like your findByUsername and register can be combined in one transactional service method.

TransactionalEventListener won't kick in

I have a problem with #TransactionalEventListener.
Given:
Kotlin 1.3.50
Spring Webflux
Spring Data
Hibernate 5
Postgres JDBC (not RDBC!)
What happens:
Request to controller was made.
Service did some job within method marked as #Transactional an event and published event.
Response returned to client
Event listener marked as #Async, #TransactionalEventListener and #Transactional doesn't kick in.
What I did:
I have debugged into service method which publishes an event to find out whether an actual transaction is in progress with the help of some static utility method I don't remember, which told me what I suspected - it is in progress.
Then I enabled debug output to see log saying: No transaction is in progress. Discarding event.
I mean, both publishing and consuming sides do have annotation #Transactional on them. No alterations to default params of annotations were made.
I have found similar situation in this question question but no one answered that.
Also, I have read an article at dzone but there seems to be no mentioning of my case.
Workaround:
I can avoid this by either replacing #TransactionalEventListener to #EventListener (alas, remove transaction bound processing) or by changing param fallbackExecute to true which effectively is the same as first solution.
Suspected parties:
Possibly absence of reactive transaction manager in an webflux environment could be the case? And some weird bug not accounting JpaTransactionManager?

Using RequestScope without ServletModule

I was exploring #RequestScoped and was wondering if there's way to use it without installing ServletModule. I am using Guice 3.0 + Jersey 1.17 and probably don't want to use GuiceContainer & GuiceServletContextListener.
I want object creation(injections) per request depending on some user input in the Jersey request. Is it possible? What can be performance & security considerations of using GuiceContainer if I had to replace my existing ServletContextListener with that of Guice?
If there's a way of using RequestScope as per my needs, can you give me some references for the same?
It is possible to bind a custom Scope implementation to a predefined scoping annotation like #RequestScoped. It does mean that then you cannot use ServletModule, since you can't bind two different implementations to the same scoping annotation.
See the documentation on Custom Scopes for details. You will need to write code to determine what constitutes a "request" for purposes of scoping, and trigger entering and exiting the scope as necessary.
For example, in the normal Guice implementation, ServletScopes.RequestScope uses a ThreadLocal initialized in GuiceFilter to keep track of what the current request is.

Spring overwriting controller

I provide a highly customisable application to my clients which is working totally by itself. But If one my client wants to overwrite any Controller, I want to replace my implementation by theirs. However just overwriting the controller causes an ambiguous definition of mappings.
I have been using Component Scanning to load beans.
The potential solutions came to my mind are:
Using component scanner with excluding by a custom filter? (This seems not so easy)
Using a xxxxPostProcessor to remove some beans? (How?)
Any help?
If I got your Question properly,
You can differ implementation by changing URL to particular Implementation name
Say Telecom is interface and AirtelImpl and RelianceImpl are Controllers then
Your request mapping
#RequestMapping(value= "/airtel/doBilling")
#RequestMapping(value= "/reliance/doBilling")
In this way, Implementation flow will differ.
I have followed these steps:
Created a custom annotation: #Devoted
Created a custom ImportBeanDefinitionRegistrar. Iterated already registered bean definitions to find out `#Devoted #Controller's and removed them.
Based on a request I will provide implementation details.

Unable to call an interceptor before MultipartResolver in Spring

In my spring-3 application I have an AuthenticationInterceptor (which is basically an interceptor) that checks for the privileges for a user. I am using a Spring's MultipartResolver to try an upload a file to the server.
The problem that I now face is that I wish to perform different actions based on user privileges, in case of a MaxUploadSizeExceededException.
However I see that this exception is occurring at the DispatcherServlet level and is caught by HandlerExceptionResolver
I want to be able to call my AuthenticationInterceptor before any of this happens?
Is there a straightforward way.
The problem is that the exception occurs BEFORE the request is dispatched to a controller and because of that, your interceptor also never fires. I guess you have that part figured out already.
Want to get around that...
For starters, I would move the authentication mechanism out IN FRONT of the servlet by using servlet filters. This being said, it makes little or no sense to roll your own solution in that space when a great product like Spring Security can do that for you.
Once you transition to Spring Security (or similar), the user's SecurityContext (roles, permissions, etc.) will have been resolved by the time the exception occurs and is caught.
Now, if I'm reading your question correctly, it seems you might like to respond to the exception differently based on the user's roles, permissions, etc. That should be possible at this point. You'd implement a custom HandlerExceptionResolver that inspects the SecurityContext to see if the user has a certain role or permission and then respond accordingly.
Hope that helps!
There are two basic ways to handle doing something in-stream before the Handler code gets called:
Implement the HandlerInterceptor interface, and code the code you want to run in the preHandle method
Create an Aspect using #Aspect and configure a pointcut to run #Before the method call
In either case, you could check the logged-in user's Roles using SecurityContextHolder.getContext().getAuthentication().getAuthorities() and then decide what to do based on Role membership.

Resources