Spring Boot Application: No converter found for return value of type - rest

I am writing a simple REST API according to this Spring-Boot tutorial. On my local dev machines (Ubuntu 15.04 and Windows 8.1) everything works like a charm.
I have an old 32-bit Ubuntu 12.04 LTS server lying around on which I wanted to deploy my REST service.
The starting log is ok, but as soon as I send a GET request to the /user/{id} endpoint, I get the following error:
java.lang.IllegalArgumentException: No converter found for return value of type: class ch.gmazlami.gifty.models.user.User
And then down the stacktrace:
java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.LinkedHashMap
The entire stacktrace is posted here.
I looked into some answers referring this error, but those don't seem to apply to my problem, since I'm using Spring-Boot, no xml configs whatsoever.
The affected controller is:
#RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public ResponseEntity<User> getUser(#PathVariable Long id){
try{
return new ResponseEntity<User>(userService.getUserById(id), HttpStatus.OK);
}catch(NoSuchUserException e){
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
Any help would be greatly appreciated. It is very weird since the exact same things work on other machines perfectly.

This happened to me, on one resource only (one method) and I did not understand why. All methods within classes in the same package, with the same annotations, same call to ResponseEntity.ok(...) etc. just worked.
But not this one.
It turns out I had forgottent to generate the getters on my POJO class !
As soon as I had added them it worked.
Hopefully it can save somebody some time eventually...

you should make some changes to your pom.xml and mvc-dispatcher-servlet.xml files:
Add the following dependecies to your pom.xml :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
and update your mvc-dispatcher-servlet.xml:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>

This happens when you forget the "build" call:
return ResponseEntity.status(HttpStatus.BAD_REQUEST);
should be:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();

I meet with this problem, because I omitted Getters and Setters method.

To add to the rest of the answers: the methods must be public.
My IDE flagged that the methods could be "package only", prompting me to remove the "public" portion of the declaration (which I foolishly did).
I added public to my methods and solved the problem.

I was using IntelliJ Idea and its auto-generated getters and setters. Since I had a boolean field called success, the getter was named isSucccess(). I renamed it getSuccess() and the error went away.

Related

Getting error log while previewing report from Jasper [duplicate]

I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.
It is important to keep two or three different exceptions straight in our head in this case:
java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.
Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared's answer for detailed explanation.
NoClassDefFoundErrorDemo.java
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}
}
SimpleCalculator.java
public class SimpleCalculator {
static int undefined = 1 / 0;
}
NoClassDefFoundError In Java
Definition:
Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.
If a class was present during compile time but not available in java classpath during runtime.
Examples:
The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty("java.classpath") and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar's name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what's wrong.
Just try to run with explicitly -classpath option with the classpath you think will work and if it's working then it's a sure short sign that someone is overriding java classpath.
Permission issue on JAR file can also cause NoClassDefFoundError in Java.
Typo on XML Configuration can also cause NoClassDefFoundError in Java.
when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.
Possible Solutions:
The class is not available in Java Classpath.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Any start-up script is overriding Classpath environment variable.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Resources:
3 ways to solve NoClassDefFoundError
java.lang.NoClassDefFoundError Problem patterns
I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.
set classpath=%classpath%;axis.jar
I was able to get it to pick up the proper version by using:
set classpath=axis.jar;%classpath%;
One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:
throw a RuntimeException in the static block of your class Example
Intercept it (or if it just doesn't matter like it is thrown in a test case)
Try to create an instance of this class Example
static class Example {
static {
thisThrowsRuntimeException();
}
}
static class OuterClazz {
OuterClazz() {
try {
new Example();
} catch (Throwable ignored) { //simulating catching RuntimeException from static block
// DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
}
new Example(); //this throws NoClassDefFoundError
}
}
NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.
This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.
In a way you're "sharing" the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.
This is the best solution I found so far.
Suppose we have a package called org.mypackage containing the classes:
HelloWorld (main class)
SupportClass
UtilClass
and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).
The file structure will look like this:
When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
I was using Spring Framework with Maven and solved this error in my project.
There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.
Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.
#xli's answer gave me insight into what may be wrong in my code.
I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the java rootloader. Because the different class loaders are in different security domains (according to java) the jvm won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR java ARGS]'
It produces output showing the loaded class, and the loader env that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
The technique below helped me many times:
System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());
where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.
Java ClassNotFoundException vs NoClassDefFoundError
[ClassLoader]
Static vs Dynamic class loading
Static(Implicit) class loading - result of reference, instantiation, or inheritance.
MyClass myClass = new MyClass();
Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()
MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();
Every class has a ClassLoader which uses loadClass(String name); that is why
explicit class loader uses implicit class loader
NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.
ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used - for example reflection.
In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.
See Stack Overflow question How to increase the Java stack size?.
Two different checkout copies of the same project
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
Closing the trunk copy of the project and running the test case again got rid of the problem.
I fixed my problem by disabling the preDexLibraries for all modules:
dexOptions {
preDexLibraries false
...
I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program's JVM option(It's one megabyte by default since JDK5.0). It's believed the program does not have enough stack to load class.
In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn't working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.
Update [https://www.infoq.com/articles/single-file-execution-java11/]:
In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don't have to run javac + java (of course,
leaving them confused why that is).
NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:
try {
// Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}
I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.
Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.
Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..
If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn't add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.
This error can be caused by unchecked Java version requirements.
In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.
sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu
Then doing a clean install as described below.
When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.
mvn clean install -DskipTests
Now that everything has been built and installed, you can go ahead and run the tests.
mvn test
I got NoClassDefFound errors when I didn't export a class on the "Order and Export" tab in the Java Build Path of my project. Make sure to put a checkmark in the "Order and Export" tab of any dependencies you add to the project's build path. See Eclipse warning: XXXXXXXXXXX.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.
It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.
Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).
I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.
I had this error but could not figure out the solution based on this thread but solved it myself.
For my problem I was compiling this code:
package valentines;
import java.math.BigInteger;
import java.util.ArrayList;
public class StudentSolver {
public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
//DOING WORK HERE
}
public static void main(String[] args){
//TESTING SOLVE FUNCTION
}
}
I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver
I was getting the NoClassDefError.
To fix this I simply removed: package valentines;
I'm not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn't interpret it to my problem.
My solution to this was to "avail" the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac ..., I was not able to run the resulting class file using java ..., because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.
javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java
So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got
Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError:
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider
And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.
Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).
And the problem gone away.
I had the same problem, and I was stock for many hours.
I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.
For example,
private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");
I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.
My solution was: Restart Eclipse. Since then I haven't seen this message again :-)

ExpectedException with #Rule in junit test on eclipse IDE does not work

I need to make a test in junit that passes if an exception is thrown, but fail time and again.
I read a bunch of questions and answers on the topic here in stackoverflow and on other sources. Eventually I came across this page, that explains the usage of Class ExpectedException, by junit.org.
Since I could not get my own test working I copied their bare-bones example and it still did not work.
here is my code:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.rules.ExpectedException;
class AssertExceptionTest {
#Rule
public ExpectedException thrown= ExpectedException.none();
#Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}
#Test
public void throwsExceptionWithSpecificType() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}
}
Citing from the page I mentioned above, the explanation goes "...After specifiying the type of the expected exception your test is successful when such an exception is thrown and it fails if a different or no exception is thrown...
Problem is that the test still fails, no matter what I do, and it fails because of what I am trying to verify: throwing NullPointerException.
I thought that maybe, because I am using junit 5, my test fails. However, this question from stackoverflow suggests otherwise: the guy asking the question mentions he is using junit 5 in eclipse the same way as in my code, successfully.
Technical details:
eclipse version: 2019-12 (4.14.0)
junit version: junit 5
working on Ubuntu, version: 18.04.2 LTS.
Update:
I used assertThrows(), and it worked for me. However, I am still puzzled over the reason I didn't succeed with the methods described above, which many people here suggest.
Thanks in advance!
JUnit 5 does not support JUnit 4 Rules out of the box.
To make your code working:
Add the following dependency (version might change over time, of course)
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-migrationsupport</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
Next, put #EnableRuleMigrationSupport on top of your test class.
That's it. See this for more information.

IllegalStateException when trying to query a MongoDB domain class using Grails 2.3.7

I am working on a legacy project that uses Grails 2.3.7 (with Maven) and Java 7, and I have to add a connection to a MongoDB database while keeping the existing Hibernate ones.
I have added the following to my pom.xml file:
<dependency>
<groupId>org.grails.plugins</groupId>
<artifactId>mongodb</artifactId>
<type>zip</type>
<version>3.0.2</version>
</dependency>
And this to the BuildConfig.groovy file:
plugins {
compile ':mongodb:3.0.2'
compile 'org.grails.plugins:mongodb:3.0.2'
}
(I have tried it both with and without the compile 'org.grails.plugins:mongodb:3.0.2' line)
On the DataSource.groovy file I have configured the db connection as follows:
grails {
mongodb {
host = "xxx.xxx.xxx.xxx"
port = "27017"
databaseName = "db"
username = "user"
password = "pass"
}
}
and the connection itself seems to be working, because if I change any value in there the Grails application does not even start.
I have then created a simple Domain class, Thingy.groovy:
class Thingy {
String identifier
String description
static mapWith = "mongo"
static constraints = {
}
}
And now, when I start the app, any call to methods of that class throws an IllegalStateException: "Method on class [Thingy] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.". However, if at the same place I call any methods of the old Domain classes that use the other datasource, they work like a charm.
Also, when starting the server I get another exception which I guess might be related, but I'm not sure what to do with it either: ERROR - Error configuring dynamic methods for plugin [mongodb:3.0.2]: org/grails/datastore/mapping/query/api/BuildableCriteria
java.lang.NoClassDefFoundError: org/grails/datastore/mapping/query/api/BuildableCriteria.
I have also tried using the MongoDB plugin 3.0.3, but with the same results.
This answer https://stackoverflow.com/a/35710495/451420 gave me a clue. I had to update the grails-datastore-core and grails-datastore-gorm versions manually as well:
<dependency>
<groupId>org.grails</groupId>
<artifactId>grails-datastore-gorm</artifactId>
<version>3.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.grails</groupId>
<artifactId>grails-datastore-core</artifactId>
<version>3.1.4.RELEASE</version>
</dependency>
In case it helps anyone else, I found out which versions to use by looking at the <dependencies> inside the POM file of the mongodb plugin (https://repo.grails.org/grails/plugins/org/grails/plugins/mongodb/3.0.3/mongodb-3.0.3.pom)

Customised ObjectMapper not working with spring boot hateoas

I have developed an rest service using spring-boot and Spring-boot-starter hateoas. And I am facing an issue with customizing ObjectMapper. The code goes below for the same:
Application.java
#Configuration
#Import(BillServiceConfig.class)
#EnableAutoConfiguration
#EnableEurekaClient
#ComponentScan({"com.bill"})
#EnableWebMvc
#EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class Application extends WebMvcConfigurerAdapter{
#Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(true).dateFormat(new SimpleDateFormat("MM-yyyy-dd"));
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
builder.configure(objectMapper);
return builder;
}
Dependencies:
dependencies {
compile "org.springframework.boot:spring-boot-starter-hateoas"
compile "org.springframework.boot:spring-boot-starter-ws"
compile "org.springframework.boot:spring-boot-starter-actuator"
Bill.java:
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonRootName("bills")
public class Bill{
BillController.java:
public ResponseEntity<Resources<Resource<Bill>>> getBills(){
The output I am getting is:
{
_embedded: {
billList:
But I require "bills" in place of "billList". It is because of ObjectMapper is not getting customized. Am I missing any configuration, Kindly help me out in this issue. Thanks in advance.
I'm using spring-boot 1.5 RC1. If you remove the #EnableHypermediaSupport annotation spring-boot should configure spring-hateoas with ISO 8601 dates for you so long as you have java time module on the classpath.
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
This worked for me anyway.
If you want further custom configuration see the solutions at http://github.com/spring-projects/spring-hateoas/issues/333
Root of this problem - default ObjectMapper from Spring MVC is used instead of one configured by author.
This happens because of #EnableWebMvc.
Quote from Spring Boot guide
Normally you would add #EnableWebMvc for a Spring MVC app, but Spring
Boot adds it automatically when it sees spring-webmvc on the
classpath.
However if you one puts it, Spring MVC will create its own set of MessageConverters and won't use yours ObjectMapper.
PS even though I post this answer so late, may be it will help others.

Embedded PostgreSQL for Java JUnit tests

Is there an embedded PostgreSql so that we could unit test our PostgreSql driven application?
Since PostgreSql has some dialects, it's better to use embedded PostgreSql itself than other embedded databases.
Embedded does not necessarily mean it must be embedded in the JVM process. It also does not necessarily need to use in-memory persistence. It should be loaded automatically by the dependency management (Maven, Gradle), so that Unit tests can run on every machine without having to install and configure a local PostgreSQL server.
The is an "embedded" PostgresSQL server that has been designed for unit testing from Java:
https://github.com/yandex-qatools/postgresql-embedded
Embedded postgresql will provide a platform neutral way for running postgres binary in unit tests. Much of the code has been crafted from Flapdoodle OSS's embed process
As an aside, there also exists similar projects for Mongo, Redis, Memcached and nodejs.
No, there is no embedded PostgreSQL, in the sense of an in-process-loadable database-as-a-library. PostgreSQL is process oriented; each backend has one thread, and it spawns multiple processes to do work. It doesn' make sense as a library.
The H2 database supports a limited subset of the PostgreSQL SQL dialect and the use of the PgJDBC driver.
What you can do is initdb a new temporary database, start it with pg_ctl on a randomized port so it doesn't conflict with other instances, run your tests, then use pg_ctl to stop it and finally delete the temporary database.
I strongly recommend that you run the temporary postgres on a non-default port so you don't risk colliding with any locally installed PostgreSQL on the machine running the tests.
(There is "embedded PostgreSQL in the sense of ecpg, essentially a PostgreSQL client embedded in C source code as preprocessor based C language extensions. It still requires a running server and it's a bit nasty to use, not really recommended. It mostly exists to make porting from various other databases easier.)
I tried the project suggested by #btiernay (yandex-qatools). I spent a good few days with this and without any offence it's over engineered solution which doesn't work in my case as I wanted to download the binaries from internal repository rather than going to public internet. In theory it supports it but in fact it doesn't.
OpenTable Embedded PostgreSQL Component
I ended up using otj-pg-embedded and it works like a charm. It was mentioned in comments so I thought I'll mention it here as well.
I used it as standalone DB and not via rule for both unit tests and local development.
Dependency:
<dependency>
<groupId>com.opentable.components</groupId>
<artifactId>otj-pg-embedded</artifactId>
<version>0.7.1</version>
</dependency>
Code:
#Bean
public DataSource dataSource(PgBinaryResolver pgBinaryResolver) throws IOException {
EmbeddedPostgres pg = EmbeddedPostgres.builder()
.setPgBinaryResolver(pgBinaryResolver)
.start();
// It doesn't not matter which databse it will be after all. We just use the default.
return pg.getPostgresDatabase();
}
#Bean
public PgBinaryResolver nexusPgBinaryResolver() {
return (system, machineHardware) -> {
String url = getArtifactUrl(postgrePackage, system + SEPARATOR + machineHardware);
log.info("Will download embedded Postgre package from: {}", url);
return new URL(url).openConnection().getInputStream();
};
}
private static String getArtifactUrl(PostgrePackage postgrePackage, String classifier) {
// Your internal repo URL logic
}
You can use a container instance of PostgreSQL.
Since spinning a container is a matter of seconds, this should be good enough for unittests.
Moreover, in case you need to persist the data, e.g. for investigation, you don't need to save the entire container, only the data files, which can be mapped outside of the container.
One of example of how to do this can be found here.
If you are looking to run an in-process version of postgres from an Integration (or similar) test suite, the postgresql-embedded worked fine for me.
I wrote a small maven plugin that can be used as a maven wrapper around a forked version of postgresql-embedded.
I am using the container instance of PostgreSQL in the tests.
https://www.testcontainers.org/#about
https://www.testcontainers.org/modules/databases/jdbc/
dependencies:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.15.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.15.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.15.3</version>
<scope>test</scope>
</dependency>
And do the tests:
#SpringBootTest
#ActiveProfiles({"test"})
#Testcontainers
class ApplicationTest {
#Container
static PostgreSQLContainer<?> postgreSQL = new PostgreSQLContainer<>("postgres:12.7");
#DynamicPropertySource
static void postgreSQLProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.username", postgreSQL::getUsername);
registry.add("spring.datasource.password", postgreSQL::getPassword);
}
#Test
void someTests() {
}
in application-test.yml:
source:
datasource:
url: jdbc:tc:postgresql:12.7:///databasename