Bind a String value to an enum in a #RequestBody entity in Spring Boot - spring

I am using Spring Boot to write a web service. I have an entity Animal and an enum Kind that can be either Kind.DOG or Kind.CAT. The Animal class contains private Kind kind as one of its instance variables. When I make an HTTP request, I pass in a string value for kind and when the request maps to the header:
#RequestMapping(method=RequestMethod.POST, value="/create")
public ResponseEntity<Animal> createAnimal(#RequestBody Animal animal)
I want kind to be internally converted to Kind.DOG/Kind.CAT if I am passed in either "dog" or "cat". Right now, if I pass in DOG or CAT, it works fine but if's lowercase it doesn't. Can someone tell me what to do? I tried the following:
#InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(Kind.class, new KindEnumConverter());
}
#RequestMapping(method=RequestMethod.POST, value="/create")
public ResponseEntity<Animal> createAnimal(#RequestBody Animal animal)
and
public class KindEnumConverter extends PropertyEditorSupport {
#Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(Kind.valueOf(text.toUpperCase()));
}
}
but it didn't work.

InitBinder won't work with #RequestBody as per my experience.
We use Spring Boot and the way I solved this problem is, I excluded all the jackson related dependencies from spring-boot-starter-web, so that I can use latest jackson.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</exclusion>
</exclusions>
</dependency>
And then I added the latest jackson dependencies as:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.1</version>
</dependency>
Now that we have the new jackson library we can just set this in the application.properties file:
spring.jackson.mapper.accept_case_insensitive_enums=true
In case you use YAML, then:
spring:
jackson:
mapper:
accept_case_insensitive_enums: true
Inspiration: https://stackoverflow.com/a/44217670/1781024

Related

Forward to JSP within Spring Controller after form submission

Using Spring #Controller, #RequestMapping and #ModelAttribute, I'd like to achieve a basic form submission flow in which the user is forwarded to a new JSP with attributes set. Spring provides different ways to achieve this, but I have received various errors.
Example 1
Based on tutorial: https://www.baeldung.com/spring-mvc-form-tutorial
form.html
<form action="/submitForm" method="POST">
<input type="text"id="field1" name="field1">
<!-- other input fields -->
<button type="submit">Submit</button>
</form>
success.jsp
<p>Thanks for signing up ${userName}!!</p>
MyController.java
#Controller
public class MyController{
#RequestMapping(
value = "/submitForm",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String post(#ModelAttribute SignupRequest request, ModelMap model){
// At this point, the SignupRequest is populated correctly
model.addAttribute("userName", request.getUserName());
return "success";
}
}
Results
Using return "success" - the result is HTTP 404 Not Found
Using return "success.jsp", the result is HTTP 405 Request method
'POST' not supported
Using return "redirect:/success.jsp", the client is redirected,
but attributes are not set, and ${userName} is visible.
Example 2
Based on the accepted answer here: Redirect after POST method in spring MVC
MyController.java
#Controller
public class MyController{
#RequestMapping(
value = "/submitForm",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ModelAndView post(#ModelAttribute SignupRequest request){
// At this point, the SignupRequest is populated correctly
ModelAndView mAV = new ModelAndView("redirect:/success.jsp");
mAV.addObject("userName", request.getUserName());
return mAV;
}
}
Result
the client is redirected, but attributes are not set, and ${userName} is visible.
What is the correct way to do this?
Thanks!
EDIT
Additional details
Using SpringBoot with embedded Tomcat. JSP file located in src>main>resources>public. The raw JSP is being served. I believe the project is not treating JSP as it should. Adding POM deps.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.23.1-GA</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
#Controller
public class MyController{
#RequestMapping(
value = "/submitForm",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public RedirectView post(#ModelAttribute SignupRequest request, RedirectAttributes ra){
// At this point, the SignupRequest is populated correctly
RedirectView rw = new RedirectView();
rw.setUrl("success.jsp");
ra.addFlashAttribute("userName", request.getUserName());
return rw;
}
}

Spring reactive boot app (2.0.0.RC1) as servlet in WebLogic 12c starts but NPE thrown on access

Running Spring boot reactive application based off of 2.0.0.RC1. It works by itself with a netty embedded container just fine.
Switching it to a servlet, sorting out the dependencies - exclusions, provisions, weblogic.xml instructions etc, then deploying to WebLogic 12c (12.1.3) container will start the application successfully. However when trying to access the rest url, handled by a single controller, WebLogic throws NPE. It never reaches Spring controller.
Error 500--Internal Server Error
java.lang.NullPointerException
at weblogic.servlet.internal.ServletResponseImpl.sendContentError(ServletResponseImpl.java:713)
at weblogic.servlet.internal.ServletResponseImpl.sendError(ServletResponseImpl.java:761)
at weblogic.servlet.internal.ServletResponseImpl.sendError(ServletResponseImpl.java:693)
at org.springframework.boot.web.servlet.support.ErrorPageFilter.handleErrorStatus(ErrorPageFilter.java:144)
at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:117)
at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:90)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:108)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3451)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.__run(WebAppServletContext.java:3417)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2280)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2196)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2174)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1632)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:256)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
I will paste the excerpts of all relevant sources below. First boot app:
#SpringBootApplication
#Configuration
//#EnableAutoConfiguration
//#ComponentScan(basePackages = {"ca.corp.uservice", "ca.corp.uservice.filecache"})
//#ImportResource({"/WEB-INF/ws-dispatcher-servlet.xml"})
//#EnableWebSecurity
public class FileCacheBootApp extends SpringBootServletInitializer implements WebApplicationInitializer {
public static void main(String[] args) {
SpringApplication.run(FileCacheBootApp.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(FileCacheBootApp.class);
}
...
}
Next the controller:
#RestController
#RequestMapping("/filecache")
public class FileCacheController implements FileCacheApi {
#Autowired
private FileCacheRepository repo;
// -------------- GET ---------------
#GetMapping(value = "{token}")
#Override public Mono<FileCacheable> get(#PathVariable("token") String token) {
return repo.findByToken(token).map(f -> load(f));
}
#GetMapping(value = "app")
#Override public Mono<FileCacheable> get(#RequestParam Long appid, #RequestParam String type, #RequestParam Integer langcode) {
return repo.findByUnique(appid, type, langcode).map(f -> load(f));
}
#GetMapping(value = "zip")
#Override public Mono<FileCacheable> get(#RequestParam String name, #RequestParam Integer langcode) {
return repo.findByNameAndLang(name, langcode);
}
...
}
And finally pom, spring fmw and servlet. Needed to do some jumps here to get it to run w/o conflicts in WebLogic container.
<!-- SPRING FRAMEWORK -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot-version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
<version>${spring-boot-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>${spring-boot-version}</version>
<exclusions>
<exclusion>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- SERVLET, VALIDATION and EL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.1-b04</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b09</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
Weblogic.xml
<weblogic-version>12.1.3</weblogic-version>
<context-root>file-cache-uservice</context-root>
<container-descriptor>
<prefer-application-packages>
<package-name>org.springframework.*</package-name>
<package-name>org.hibernate.*</package-name>
<package-name>javax.validation.*</package-name>
<package-name>javax.validation.spi.*</package-name>
<package-name>org.apache.logging.log4j.*</package-name>
<package-name>org.slf4j.*</package-name>
</prefer-application-packages>
</container-descriptor>
I am trying to be as specific as possible w/o being an info overkill. If you'd like to know more details though... be glad to provide.
Any info or a pointer on the source of the NPE is appreciated.
Solved it. This bit was confusing... I added a dependency for the boot-web back in:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot-version}</version>
<exclusions>
<exclusion>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</exclusion>
</exclusions>
</dependency>
and then everything started responding. Which kind of makes sense except for the fact that you can't have that dependency if you run WebFlux boot stand alone.
It's a bit unclear as to why standalone (embedded container) cannot have web dependency, and external container must have it. But it works now.

Use joinfaces with war in wildfly 10

I'm using joinfaces and trying to get up with wildfly 10, but it's like having a tomcat embedded inside the dependency.
<dependency>
<groupId>org.joinfaces</groupId>
<artifactId>jsf-spring-boot-starter</artifactId>
<version>2.4.0</version>
</dependency>
I made the necessary config
#SpringBootApplication
public class LicitarApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(LicitarApplication.class, args);
}
#Override
public SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(LicitarApplication.class);
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<!--<version>3.1.0</version>-->
</dependency>
It starts but when it almost ends it gives error:
NoSuchMethodError: DigesterFactory.newDigester
java.lang.NoSuchMethodError: org.apache.tomcat.util.descriptor.DigesterFactory.newDigester(ZZLorg/apache/tomcat/util/digester/RuleSet;Z)Lorg/apache/tomcat/util/digester/Digester;
I'm not sure if it's the best option, but for me this problem was solved when I remove the jar dependency tomcat-embed-jasper. I've just inserted the code below in my pom.xml:
<dependency>
<groupId>org.joinfaces</groupId>
<artifactId>jsf-spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</exclusion>
</exclusions>
</dependency>
jsf-spring-boot-starter is meta starter. It pulls mojarra-spring-boot-starter and tomcat-spring-boot-starter by default.
If you use wildfly, I think you should remote tomcat-spring-boot-starter and add undertow-spring-boot-starter. See detailed documentation.

Spring Boot dont recognice Spring MVC

I am starting with SpringBoot, looks great, but I have some questions that I can't understand or find explained in the docs.
I created a new project with the Web, JPA, Security and MySQL dependencies. When my project is created, I go to create a #Controller class. Spring don't find #RequestMapping or ModelAndView classes.
I guessed that use the Web module of SpringBoot will add all the necessary dependencies to use SpringMVC (I read some examples and none add extra dependencies) and all work great with MVC.
These are my dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-groovy-templates</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
</dependency>
</dependencies>
Other example, is the WebMvcConfigurerAdapter (from spring-mcv) class that I can't resolve:
org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
This class is from, but I don't see Springboot include this dependy:
org.springframework
spring-webmvc
Maybe I am wrong and read some post that center all the info in Spring Boot, but don't show manual config in the poms.
WebApplication class (Auto Generated):
#SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
ServletInitializer.java class (Auto generated)
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebApplication.class);
}
}
Looks like my maven local repository is corrupted.
I was using these libraries in other projects and all works fine. Sorry for the time wasted. Anyway, I let the response for some users with similar problems.

Mockito with static methods in util classes

I tried to find but couldnt get what i was looking for. Is it possible to do something like following in mockito?
when(TestServiceUtil.getTestItem()).thenReturn(someItem);
In your pom.xml, add the following dependencies:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.6</version>
<scope>test</scope>
</dependency>
above your test class:
#RunWith(PowerMockRunner.class)
public class YourClassName
[...]
#Before
public void beforeTest() throws SQLException {
PowerMockito.mockStatic(TestServiceUtil.class);
Now you can use (as you had it):
when(TestServiceUtil.getTestItem()).thenReturn(someItem);
Last words - don't overuse PowerMockito. Focus on clean, object oriented code.

Resources