realPath for MockHttpServletRequest - spring

I am writing a Spring based Test case for my Spring Controller, in my controller we are using like this "request.getSession().getServletContext().getRealPath("/myFolderName");"
Its working fine for normal requests, but for unit test cases like MockHttpServletRequest it is the above method call is giving null. how can i get realPath for MockHttpServletRequest.
Thanks,
Praneeth.

By default MockHttpServletRequest acts as if root webapp folder is a classpath, therefore you should be able to use getRealPath() for classpath resources.
Alternatively, you can supply MockHttpServletRequest with MockServletContext, and MockServletContext can be configured with specific root folder for getRealPath(), etc.

Related

Spring Boot - How to add custom controller logic before user accesses static files

I'm working on a Spring Boot project, where some static contents are served from the src/main/resources/static directory.
My goal is that whenever a user tries to access static contents that end with a certain suffix (e.g. ".xlsx"), the request is intercepted and I check to see if the user has the right permission using Spring AOP, and reject the request if necessary. I've got the AOP part working in other scenarios, but not in this scenario yet.
Currently I've tried something like the following, but the method isn't being invoked upon accessing a file of ".xlsx" suffix:
#RequestMapping("/*.xlsx")
public void checkPermission() {
}
Can this be done without using Spring Security? Thanks in advance.
Have you tried Filter interface? much more available.
LINK: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/filter/OncePerRequestFilter.html
Using this you can easily parse the request before even it reaches the controller and add you business logic/validation to it.

Testing ControllerAdvice with AutoConfigureMockMvc and CompletableFuture

I have added a REST controller returning CompletableFutures to a project using a ControllerAdvice to translate exceptions into error DTOs.
My controller doesn’t throw the exceptions, wrapping them into failed CompletableFutures and returning these.
When running the full application and manually testing it works as expected, but in my tests the mockMvc won’t trigger the advices and always return HTTP 2xx.
Any idea why?
If you have a standalone setup of MockMvc, then you need to specify the controller advice to be used (if any) while creating the mockMvc instance as follows:
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new YourControllerAdvice())
.build();
The reason for this is that you don't have a context here for spring to detect the controller advice.
I figured out my test was not correct (or, to put it another way.. the testing framework is not designed as I expected ;)
When testing controllers returning CompletableFutures one needs to use asyncDyspatch as in
https://github.com/spring-projects/spring-framework/blob/master/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java

How can I start a standalone wiremock with stubs from spring-cloud-contracs?

I just would like to start a simple wiremock with the stubs from my spring cloud contract. There is a StubRunner class from Spring but the constructor makes no sense to me. It seems that the stubRunnerOptions contains all infos needed and I have no idea what I should provide for repositoryPath and stubsConfiguration.
public StubRunner(StubRunnerOptions stubRunnerOptions, String repositoryPath, StubConfiguration stubsConfiguration)
It works with the following code:
BatchStubRunner stubRunner = new BatchStubRunnerFactory(
options).buildBatchStubRunner();
RunningStubs runningCollaborators = stubRunner.runStubs();

Spring Boot: Retrieve config via rest call upon application startup

I d like to make a REST call once on application startup to retrieve some configuration parameters.
For example, we need to retrieve an entity called FleetConfiguration from another server. I d like to do a GET once and save the keep the data in memory for the rest of the runtime.
What s the best way of doing this in Spring? using Bean, Config annotations ..?
I found this for example : https://stackoverflow.com/a/44923402/494659
I might as well use POJOs handle the lifecycle of it myself but I am sure there s a way to do it in Spring without re-inventing the wheel.
Thanks in advance.
The following method will run once the application starts, call the remote server and return a FleetConfiguration object which will be available throughout your app. The FleetConfiguration object will be a singleton and won't change.
#Bean
#EventListener(ApplicationReadyEvent.class)
public FleetConfiguration getFleetConfiguration(){
RestTemplate rest = new RestTemplate();
String url = "http://remoteserver/fleetConfiguration";
return rest.getForObject(url, FleetConfiguration.class);
}
The method should be declared in a #Configuration class or #Service class.
Ideally the call should test for the response code from the remote server and act accordingly.
Better approach is to use Spring Cloud Config to externalize every application's configuration here and it can be updated at runtime for any config change so no downtime either around same.

Available paths listing for Spring actions

I have an application which exposes RESTful actions using spring annotations and Spring MVC.
It looks like
#RequestMapping(value = "/example/{someId}",
method = RequestMethod.GET, consumes=MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void isRegisteredToThread(#PathVariable long someId, HttpServletResponse response) {
[something]
}
What I want is an automatically generated listing of all URL's, methods and available parameters - possibly within a WSDL. Is there a plugin or is it somehwere available?
WSDL is not done for rest, it's used for SOAP.
You might use WADL, but I really do not suggest it.
In my project I always use swagger (there is a release for spring). You may find more info here https://github.com/martypitt/swagger-springmvc and here http://blog.zenika.com/index.php?post/2013/07/11/Documenting-a-REST-API-with-Swagger-and-Spring-MVC
Give it a try.
As an alternative, if you don't need something web-based, you may try rest-shell (https://github.com/spring-projects/rest-shell)
You could take a look at the source code of RequestMappingEndpoint provided by the Spring Boot and see how Spring Boot reports the mappings.
Looking through that code one can see that the mappings (both handler and method mappings) can easily be obtained from the applicationContext
(using
applicationContext.getBeansOfType(AbstractUrlHandlerMapping.class)
and
applicationContext.getBeansOfType(AbstractHandlerMethodMapping.class)
respectively). After you have obtained the mapping you can process them anyway you like.
You might want to create a library that could include in all your projects that processes the mapping your organizations desired form

Resources