The difference between exchange method and execute method in spring rest template? - spring

I have three questions!
First.
I am using the spring framework for sending the data through rest protocol.
restTemplate.exchange(requestUrl,HttpMethod.POST, request, listVo.getClass());
org.springframework.web.client.RestTemplate.exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<? extends Object> responseType, Object... uriVariables) throws RestClientException
I used it without any problem, but I want to know the purpose of the parameter, responseType.
The client don't use response data, but just use response status code / msg. So, I sent some meaningless
String data instead. But the error thrown that they accept "null". So I sent a "null" String. not null.
Then, the error got rid of. But there was another problem. Right after the client received the data from the server and paused for a long time. Then next line of codes are executed. What is problem?
Second
I can't find any references that use execute method of Spring RestTemplate.
Third
Like the title, What is the difference between the exchange method and the execute method in spring rest template?
Thanks for your time and effort.
Cheers.

exchange return type is ResponseEntity<T> while execute is T

Taken from "Pivotal Certified Spring Web Application Developer Exam" book
The execute and exchange methods can be used for any type of REST calls
The execute method can also be given a RequestCallback implementation as a parameter, which tells the RestTemplate what to do with the request before sending it to the server.

Related

Save the Spring Security Context back to session for subsequent use

My SpringBoot application is a packaged software application, to customize it I want to manipulate the authentication object when users first login, and I expect this object would be pushed back to the user's session for subsequent connection.
I managed to use an Around advice to intercept a REST endpoint that will be triggered when first login:
#Around("execution( * com.myproject.CurrentUser.get(..)))"
public ResponseEntity getCurrentUser(ProceedingJoinPoint pjp) throws Exception {
SecurityContextHolder.getContext().setAuthentication(getNewAuthentication());
((ServletRequestAttributes) RequestContextController.currentRequestAttributes())
.getRequest().getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING.SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
ResponseEntity response = (ResponseEntity) pjp.proceed();
return response;
}
The getNewAuthentication() method is confirmed OK, it returns a PreAuthenticatedAuthenticationToken that includes additional authorities.
However in the subsequent REST calls when I check the Security Context object the authentication is still the original one.
May I know what would be the proper way to do this? I need to manipulate the authentication object at the very beginning and make sure the subsequent calls will make use of it.
Any idea?

Spring webflow prevent GET method in transition

I am using spring webflow 2.3.1.RELEASE in my project.
The customer's security team raised and issue witch is "It is possible to change the http method from POST to GET and the application accepts the change and continues working."
So I need to prevent this change and make my transitions accept only POST method. Or throw exception if I get any request parameter other than execution in the url.
How can I do this?
You could create your own FlowExecutionListener and throw an exception when the request method is different than POST and/or when request parameters are present.
see the documentation here and API here
I solved the problem using interceptors of the FlowHandlerMapping.
I've created a class and named it MethodInterceptor, implementend org.springframework.web.context.request.WebRequestInterceptor.
in the "public void preHandle(WebRequest request) throws Exception" method, I checked the request method, if it was get, I checked the request parameters to be either empty or contain only the execution parameter. If the condition didn't meet, I threw an exception.

How can I see the json coming from the client when using Spring-MVC?

A client software is trying to access my Spring-MVC rest server, but it's getting a 400 (Bad Request) response every time. I know my server is fine (it's in use by many other clients), but I cannot debug the client application, so I cannot see what it is sending.
Is there a way for me to see what JSON I am receiving before Spring tries to convert it to an entity and fails? It's okay if I can only do this at debug time, I just need to be able to give support to this application's creators.
Just in case, here is the spring-mvc controller method:
#Named
#RequestMapping(value = "/taskmanager/task")
public class TaskManagerTaskRest {
#RequestMapping(value = "", method = RequestMethod.POST)
#ResponseBody
public void createTask(#RequestBody Task task, HttpServletRequest request,
HttpServletResponse response) throws CalabacinException {
// This code never gets executed because the Task json is invalid, but I don't know how I could see it.
...
...
}
}
Try to use Fiddler. It will help you to catch HTTP requests/responses. You will be able to see your JSON.
You can create and use a AbstractRequestLoggingFilter filter implementation and conditionally log the relevant parts of the request. You should use ContentCachingRequestWrapper to wrap the request.

spring deferredresult

I am new to spring and want to implement long polling for a website to display admin message immediately when it becomes available to all clients,i searched google for hours and could only find out deferredresult(spring 3.2) can be used to implement it.my question is how i can achieve long polling with deferredresult, I would appreciate it if anyone could refer me to such a tutorial.
Another option is to use AsyncContext. This will keep the initial GET request "open" and enable you to send multiple messages as part of the response, unlike DeferredResult which allows to send only ONE response message. Here is a good-link that explains how !
Straight from the horses mouth.
You have two basic options: Option 1 is a Callable
, where the Callable returns the String view name (you may also be able to use #ResponseBody or some of the other normal Spring return types like ModelAndView, but I have never investigated that).
Option two is to return DeferredResult, which is like Callable. except you can pass that off to a separate thread and fill in the results there. Again, not sure if you can return a ModelAndView or use #ResponseBody to return XML/JSON, but I am sure you can.
Short background about DeferredResult:
Your controller is eventually a function executed by the servlet container (for that matter, let's assume that the server container is Tomcat) worker thread. Your service flow start with Tomcat and ends with Tomcat. Tomcat gets the request from the client, holds the connection, and eventually returns a response to the client. Your code (controller or servlet) is somewhere in the middle.
Consider this flow:
Tomcat get client request.
Tomcat executes your controller.
Release Tomcat thread but keep the client connection (don't return response) and run heavy processing on different thread.
When your heavy processing complete, update Tomcat with its response and return it to the client (by Tomcat).
Because the servlet (your code) and the servlet container (Tomcat) are different entities, then to allow this flow (releasing tomcat thread but keep the client connection) we need to have this support in their contract, the package javax.servlet, which introduced in Servlet 3.0 . Spring MVC use this new Servlet 3.0 capability when the return value of the controller is DeferredResult or Callable, although they are two different things. Callable is an interface that is part of java.util, and it is an improvement for the Runnable interface. DeferredResult is a class designed by Spring to allow more options (that I will describe) for asynchronous request processing in Spring MVC, and this class just holds the result (as implied by its name) while your Callable implementation holds the async code. So it means you can use both in your controller, run your async code with Callable and set the result in DeferredResult, which will be the controller return value. So what do you get by using DeferredResult as the return value instead of Callable? DeferredResult has built-in callbacks like onError, onTimeout, and onCompletion. It makes error handling very easy. In addition, as it is just the result container, you can choose any thread (or thread pool) to run on your async code. With Callable, you don't have this choice.
Here you can find a simple working examples I created with both options, Callable and DeferredResult.

How do I use HandlerAdapter in the Spring MVC framework to test #ResponseBody controller actions?

I'm currently using Spring MVC's HandlerAdapter to test the annotations of my Spring controller actions to make sure the path variables, request parameters, session attributes, #Valid, etc. are being written correctly.
I've come across a problem where if a controller action has #ResponseBody and doesn't return a ModelAndView, I cannot test the response using the HandlerAdapter.
I found a question on this site that is related, but the accepted answer given is not satisfactory:
How to unit test a ResponseBody or ResponseEntity sent by a spring mvc Controller?
How can I test the annotations and the results at the same time? Or do I need to write two tests - one to test the annotations, and another to call the controller method directly?
Thanks
If you have a #ResponseBody then the handler shouldn't return a ModelAndView, it should write directly to the Response using a MessageConvert.
One approach would be to intercept the Response and read it instead of reading the returned value.
please have a look at this answer I just found to your very same question I had:
I found that very useful and I'm implementing this solution in my test code.

Resources