Spring boot Jackson with Date - java

In my Spring boot application i should show a date string on html. I using this code to get a time jason:
spring:
jackson:
date-format: HH:mm:ss.SSSSSS
joda-date-time-format: HH:mm:ss.SSSSSS
it can be word when i run with IDEA, but it can't work when i use maven to packet a jar and run this jar.
there is exception message :
beans.factory.BeanCreationException: Error creating bean with name 'jacksonObjectMapperBuilder' defined in class path resource [org/springframework/boot/autoconfigure/jackson/JacksonAutoConfiguration$Jac
ksonObjectMapperBuilderConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframe
work.http.converter.json.Jackson2ObjectMapperBuilder]: Factory method 'jacksonObjectMapperBuilder' threw exception; nested exception is java.lang.IllegalArgumentException: name
how should do to get a jason time String?
here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<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-thymeleaf</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-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
and my table class is that:
#Entity
public class TimeData {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Temporal(TemporalType.TIME)
#JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "HH:mm:ss.SSSSSS",timezone = "GMT+8")
private Date curingTime;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getCuringTime() {
return curingTime;
}
public void setCuringTime(Date curingTime) {
this.curingTime = curingTime;
}
}
in my spring boot application i should to return a jason String with TimeData.
it can be get well run with IDEA ,but couldn't run with jar .

This smells like a classpath issue. Your stacktrace also has nothing to do with your actual code. I think you may be pulling in incompatible versions of the same library somehow. Ensure you actually need all those dependencies and see what you can remove and try rerunning your jar.

Related

Transient/Final Variable in Spring boot entity causing Error

I am a new to Spring boot so I apologize if this is a easily resolved issue.
I am seeing a problem running springboot after I added a #Transient final variable to my entity. Essentially I need a constant variable in my class that stores a string that I do not want stored in the database.
Adding in just this variable causes no issues with spring and the program runs as expected however, if I add a getter for this variable Springboot raises the exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Here is my code causing the issue (I am not even calling the getter yet and it's causing this issue):
#ApiModel(description = "This class represents a device with its basic information.")
#Entity
#Table(name = "device")
public class Device {
#Transient
private final String invisibleName = "Jwfqp4bbqiFzRLcFVV3qf";
#Id
#ApiModelProperty(notes = "A UUID number to identify the device in the system.")
private String deviceId;
#ApiModelProperty(notes = "The device IP address of the device, this is also a unique identifier.")
private String ipAddress;
public Device() {
}
#Id
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceUuid) {
this.deviceId = deviceUuid;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getInvisibleName(){
return invisibleName;
}
}
Here is my pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>project-name</artifactId>
<version>0.0.1</version>
<packaging>war</packaging>
<name>projectName</name>
<description>Project Name</description>
<properties>
<java.version>1.8</java.version>
<log4j2.version>2.16.0</log4j2.version>
</properties>
<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-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>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
One important thing that I've noticed is that I can resolve the building issue by adding a useless parameter to the the getter such as:
public String getInvisibleName(int temp){
return invisibleName;
}
but If possible I would like to get to the bottom of this issue so I don't have useless parameters in my getter.
Let me know if I need to provide any additional information.
Thanks
Thank you all for your help. I removed the extraneous #Id on the 'getDeviceId' and moved the #Transient to the getter. I also noticed that apparently Spring had created an 'invisibleName' entry in the database causing a mismatch with my #Entity class. I removed the field from the database and that resolved the issue.
You should move the #Transient annotation above the getInvisibleName() method.

Spring AWS - required bean could not be found

I am trying to start my Spring server but keep getting this error:
Description:
Parameter 0 of constructor in com.rm.awsimageupload.filestore.FileStore required a bean of type 'com.amazonaws.services.s3.AmazonS3' that could not be found.
Action:
Consider defining a bean of type 'com.amazonaws.services.s3.AmazonS3' in your configuration.
I have tried:
pasting in the keys as strings right into the BasicAWSCredentials
putting the keys into application.properties and then using #Value to access them. With this approach, I get this error:
Error creating bean with name 'amazonConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'local.AWS_ACCESS_KEY_ID' in value "${local.AWS_ACCESS_KEY_ID}"
application.properties
AWS_ACCESS_KEY_ID=NOTAREALKEY
AWS_SECRET_ACCESS_KEY=NOTAREALSECRET
FileStore.java
#Configuration
public class AmazonConfig {
#Value("${application.AWS_ACCESS_KEY_ID}")
private String AWS_ACCESS_KEY_ID;
#Value("${application.AWS_SECRET_ACCESS_KEY}")
private String AWS_SECRET_ACCESS_KEY;
public AmazonS3 S3() {
AWSCredentials awsCredentials = new BasicAWSCredentials(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY
);
return AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).withRegion(Regions.SA_EAST_1).build();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.rm</groupId>
<artifactId>aws-image-upload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aws-image-upload</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.787</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Not exactly sure what to do... I am following a tutorial on how to do this and my config pretty much matches this instructor's. Any suggestions?
Your are missing #Bean annotation on public AmazonS3 S3()
#Bean
public AmazonS3 S3() {
AWSCredentials awsCredentials = new BasicAWSCredentials(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY
);
return AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).withRegion(Regions.SA_EAST_1).build();
}
Regarding the 2nd issue for properties values, not sure if this the typo here
local.AWS_ACCESS_KEY_ID in logs vs application.AWS_ACCESS_KEY_ID in code sample.
You need to use the same keys name as in your properties file
So you config class should be having
#Value("${AWS_ACCESS_KEY_ID}")
private String AWS_ACCESS_KEY_ID;
#Value("${AWS_SECRET_ACCESS_KEY}")
private String AWS_SECRET_ACCESS_KEY;

How to validate integer input in my form page?

I m creating from page for customer so everything works well until i wanted to force the user to enter a number in the field "free passes" i got error
i've tried to creat a field with Integer type named freePasses in the Customer class then generate the getter and setters for it, i've alslo modify my .properties file
Customer.java
#Min(value = 0 , message="the value must be equal or greater than 0")
#Max(value = 10, message = "the value must be equal or less than 10")
#NotNull(message = "is required")
private Integer freePasses;
public Integer getFreePasses() {
return freePasses;
}
public void setFreePasses(Integer freePasses) {
this.freePasses = freePasses;
}
applocation.properties
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
typeMismatch.customer.freePasses = invalid Number
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>8.5.20</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.17.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Failed to convert property value of type java.lang.String to required type java.lang.Integer for property freePasses; nested exception is java.lang.NumberFormatException: For input string: "44xxxx"
I think <form:input type=?number? path="date" /> will work.
create file: src/resources/messages.properties
and write this line:
typeMismatch.customer.freePasses= Invalid number
Solution 1 : Add below code in your spring configuration xml file
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="resources/messages"></property>
</bean>
Solution 2 : change in your input element
<form:input type="number" path="freePasses" /> this worked for me try this
In messages.properties file, after the error type, you must to specify the modell attribute (which is in your CustomerController) name, not the class name. So typeMismatch.attribute name.freePasses= Invalid number.

Spring application doesn't work after building in jar

I have a simple Spring application:
Main class:
#SpringBootApplication
#EnableScheduling
public class SchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulerApplication.class, args);
}
}
And class for scheduled job
#Component
public class Executor {
private static final Logger log = LoggerFactory.getLogger(Executor.class);
private Integer jobCounter = 1;
#Scheduled(fixedDelay = 1000)
public void run() {
log.info("Start task (" + jobCounter + ")");
log.info("Stop task");
jobCounter ++;
}
}
This is pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.alexeyzhulin</groupId>
<artifactId>scheduler</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>scheduler</name>
<description>Task scheduler</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
That is my project structure
It works fine under the IDE (IntelliJ IDEA), but when I compiled this code to jar file and run:
java -jar scheduler.jar
I got a long stack of errors like this
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [ru.alexeyzhulin.SchedulerApplication]; nested exception is java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.f actories. If you are using a custom packaging, make sure that file is correct.
What have I missed?
Add the following element under your sprig boot maven plugin in pom.
<configuration>
<fork>true</fork>
<mainClass>Your-main-config-class</mainClass>
</configuration>
It seems that your SpringBootApplication class located in a wrong place.
It should be properly located. Usually it is in a root of your artifact package.
For example:
ru.alexeyzhulin.scheduler
ru.alexeyzhulin.scheduler.SchedulerApplication
ru.alexeyzhulin.scheduler.Executor
or
ru.alexeyzhulin.scheduler
ru.alexeyzhulin.scheduler.SchedulerApplication
ru.alexeyzhulin.scheduler.components
ru.alexeyzhulin.scheduler.components.Executor
And look at it:
Failed to process import candidates for configuration class

Spring boot jersey error

I generated a project on start.spring.io with the following project dependencies:
Jersey (JAX-RS)
JPA
PostgreSQL
Web
When I try to access localhost:8080/homeroom/webapi/test I get a page with the following error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
I get this error no matter what url I try to access.
In my console info I can see it print Mapping servlet: 'jerseyServlet' to [/webapi/*] so I know my config class is being registered. When I change #ApplicationPath("/webapi") to #ApplicationPath("/"), a GET on localhost:8080/homeroom/test or localhost:8080/homeroom/ returns a blank page instead, with no text or error.
Why can't I access my resource?
This is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.homeroomed</groupId>
<artifactId>homeroom</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>HomeRoom</name>
<description>HomeRoom REST API</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<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-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc41</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I'm trying to do a descriptor-less deploy so I have:
#Component
#ApplicationPath("/webapi")
public class MyJerseyConfig extends ResourceConfig{
public MyJerseyConfig() {
// String packageName =TestJerseyResource.class.getPackage().getName();
// this.packages(packageName);
this.register(TestJerseyResource.class);
// System.out.println("The package is:"+packageName);
}
}
And I have the following resource:
#Component
#Path("/test")
public class TestJerseyResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getTest()
{
return "Hi!";
}
}
I'm running the project from:
#SpringBootApplication
public class HomeRoomApplication {
public static void main(String[] args) {
SpringApplication.run(HomeRoomApplication.class, args);
}
}
UPDATE:
So 2 things:
I had to use spring annotations #Controller and #RequestMapping instead of Jersey's #PATH and #GET, and had to GET /webapi/test instead of /homeroom/webapi/test
The reason you can't access your resource from looking at the information you provided is you there is no /homeroom anywhere I saw in your code.
This is a valid URL for your project:
http://localhost:8080/webapi/test
If you wanted homeroom to be in the URL you could change the application path value to homeroom instead of webapi.
Well, quoting from #ApplicationPath JavaDoc:
May only be applied to a subclass of Application.
https://docs.oracle.com/javaee/6/api/javax/ws/rs/ApplicationPath.html
That might be part of the problem...

Categories

Resources