I have strange problem with Dates - java.util.Date. In my database I have a row with a date like that:
It show it is 10:30 time. But when I create an REST api and go to the developer tools in Chrome I see that the time was changed with 2 hours, e.g:
In my application properties I added two things:
spring.jackson.date-format=yyyy-MM-dd'T'HH:mm:ss.SSSZ
spring.jackson.serialization.write-dates-as-timestamps: false
And my model class looks like (with #JsonFormat):
import java.util.Date; <- look I have java.util.Date, not Yoda.
import com.carwash.utils.JsonDateSerializer;
import com.carwash.utils.ReviewStatus;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
#Data
public class ReservationModel {
private String code;
//#JsonSerialize(using=JsonDateSerializer.class)
#JsonFormat(pattern="yyyy-MM-dd HH:mm")
private Date date;
Related
I am trying to run a spring developed web app and I'm getting the following error.
My folder structure is as follows.
Here is my PersonRepositary.java code which is inside the repositary folder.
package com.travelx.travelx.repositary;
import org.springframework.data.repository.CrudRepository;
import com.travelx.travelx.models.Person;
public interface PersonRepositary extends CrudRepository<Person, Integer> {
}
The RegisterController.java file which is in the controllers folder is ac follows.
package com.travelx.travelx.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.travelx.travelx.models.Person;
import com.travelx.travelx.repositary.PersonRepositary;
#RestController
#RequestMapping("register")
public class RegisterController {
#Autowired
private PersonRepositary personRepositary;
#PostMapping("login")
public String registerPerson(#RequestBody Person person) {
personRepositary.save(person);
return "You are Registered!";
}
}
And the TravelXApplication.java file which is in the controllers is below.
package com.travelx.travelx.controllers;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan
#EntityScan
#EnableJpaRepositories
public class TravelxApplication {
public static void main(String[] args) {
SpringApplication.run(TravelxApplication.class, args);
}
}
I'm trying to make a web page where a person can register to a site. Here, I'm using xampp as my platform to handle the back end. As shown in the image, the controllers, repositories and and models are implemented in separate folders. I'm new to Spring. So no matter how hard I to find what the problem is, I cant seem to find it. Can some one help me please?
--------------UPDATE------------------
I've moved my TravelXApplication.java to the com.travelx.travelx and now this error is gone.Spring works fine. However when I open my form, insert data and try to save it, the browser gives me the following error.
How do I solve it?
Your PersonRepositary is not registered as a bean in your Spring context. In practice, this means that Spring is not be able to inject it in your RegisterController.
I suspect that #EnableJpaRepositories, #EntityScan and #ComponentScan are unnecessary in your main application class and are actually causing Spring automatic configuration to be overridden. Try deleting these three annotations from TravelxApplication.
Here's the answer to why it should still work without annotations.
Update: just noticed that your TravelxApplication is located in the controllers package, but then it won't have visibility to your repository. Make sure to move your main class to the com.travelx.travelx package.
I have this html code:
<input class="form-control col-sm-8" type="date" th:field="*{completiondate}">
and this model :
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
public class EventReport {
private Long id;
private Date creationdate;
private String status;
private Date completiondate;
...
}
completion date is not a required value and can be null sometimes. When user submits the post form I take the following
Field error in object 'treeTrimsEventReport' on field
'completiondate': rejected value [];
Obviously I don't have errors when I select a value for date and the app works fine.
How can I give null on completion date without errors?
I think it is a binding error.
You need to tell spring how to convert form data which comes as text (String) to the type in your model (here a Date).
You may do it with this annotation on the field in EventReport :
import org.springframework.format.annotation.DateTimeFormat
...
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date completiondate;
(change the pattern to match the one you wish to show to the user)
Spring gives you other option to tell it how to bind data.
Have a look at the reference manual, in this chapter for all options :
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-initbinder
I am running a server under WebSphere Application Server (17.0.0.1/wlp-1.0.16.cl170120170227-0220) and have added the changes recommended in this post (How to change Jackson version in JAX-RS app (WebSphere Liberty)) for upgrading the level of Jackson in WAS Liberty. I am using Postman to test my server. When I submit a GET request for an object, it completes successfully. (After adding this change, my server can return my objects in either XML or JSON.). However, I am now seeing these messages in the server console when my server builds the Response object.
[INFO ] FFDC1015I: An FFDC Incident has been created: "org.jboss.weld.exceptions.AmbiguousResolutionException: WELD-001318: Cannot resolve an ambiguous dependency between:
- Managed Bean [class com.ibm.zss.boundary.JaxbJsonProvider] with qualifiers [#Any #Default],
- Managed Bean [class com.ibm.zss.boundary.JsonProvider] with qualifiers [#Any #Default] com.ibm.ws.jaxrs20.cdi.component.JaxRsFactoryImplicitBeanCDICustomizer 425" at ffdc_17.06.13_15.59.57.0.log
com.ibm.zss.boundary.JaxbJsonProvider and com.ibm.zss.boundary.JsonProvider are the classes I added based on the instructions from the previous post.
I also updated my server.xml to include:
<feature>jsonp-1.0</feature>
<feature>jaxrs-2.0</feature>
I've been searching for solutions for handling a WELD ambiguousResolutionException, but most of them address issues with classes where the developer has control over what is being injected. So, I don't know if I have any control over the code that I need to change for this problem.
For completeness, here are the classes which I added to my application:
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
#Provider
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class JaxbJsonProvider extends JacksonJaxbJsonProvider {
}
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
#Provider
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class JsonProvider extends JacksonJsonProvider {
public JsonProvider() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(objectMapper.getVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
setMapper(objectMapper);
}
}
Can you either mark it an #Specializes or an #Alternative with low #Priority, depending on whether you want it to be used for injection points?
I am new to Slick. I am using mysql and I am trying to retrieve some datetime from the database. Here are my imports
import slick.driver.MySQLDriver.simple._
import scala.slick.driver._
import java.util.Date
and here the line of the class where the mapping is
def creationDate = column[Date]("creation_date")
But I am getting this error
could not find implicit value for parameter tt: slick.ast.TypedType[java.util.Date]
Is there a way to import a datetime from mysql to a java.util.Date without using String?
Thank you
The reason you can't use java.util.Date in the Column is
it's not supported in Slick, see the documentation in Table Rows part.
The following primitive types are supported out of the box for JDBC-based databases in JdbcProfile (with certain limitations imposed by the individual database drivers):
Date types: java.sql.Date, java.sql.Time, java.sql.Timestamp
Thus, no implicit TypedType[C] is provided.
def column[C](n: String, options: ColumnOption[C]*)
(implicit tt: TypedType[C]): Rep[C] = {
If you try to find the children of TypedType, you will find three time-relevant class in slick.driver.JdbcTypesComponent.
DateJdbcType for java.sql.Date
TimestampJdbcType for java.sql.Timestamp
TimeJdbcType for java.sql.Time
Also, the types defined are in line with what is stated in the documentation, three time-relevant type.
I use Timestamp with Slick 3.0 in my program as following:
import slick.driver.MySQLDriver.api._
import java.sql.Timestamp
case class Temp(creation_date: Timestamp)
class Tests(tag: Tag) extends Table[Temp](tag, "tests") {
def creationDate = column[Timestamp]("creation_date")
def * = creationDate <> ((creationDate: Timestamp) =>
Temp.apply(creationDate), Temp.unapply _)
}
In that way, you just have to convert Timestamp to any time-relevant type you want back and forth, but that should be no big deal.
Anyway, hope it helps.
Have you tried Joda-Time ?
If not, you should give it a serious thought. And there is a slick-mapper project for it https://github.com/tototoshi/slick-joda-mapper
import org.joda.time.DateTime
import com.github.tototoshi.slick.MySQLJodaSupport._
// then it works just the same
def creationDate = column[DateTime]("creation_date")
If you want to use java.util.Date as is,
create mapping Date type to Timestamp.
import slick.driver.MySQLDriver.api._
import java.util.Date
import java.sql.Timestamp
implicit def mapDate = MappedColumnType.base[Date, Timestamp](
d => new Timestamp(d.getTime),
identity
)
I am developing a light weight server App with a RESTful api implemented with Jersey 2.12 and Jackson 2.
I am writing tests while developing using JUnit and JerseyTest. I know that my Jersey Resources work as expected including the marshalling from and to JSON because I tested them manually with the PostMan Chrome plugin.
My GET tests with query parameters work well too, based on the example in the Jersey documentation
Here is a simplified (I have left out boilerplate code to make the idea clearer) example of a test I'd like to write:
import static org.junit.Assert.assertTrue;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import com.acme.api.rest.SessionsEndPoint;
import com.acme.api.rest.beans.UserCredentialsBean;
public class TestSession extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(SessionsEndPoint.class);
}
#Test
public void test() {
UserCredentialsBean userCredentialsBean = new UserCredentialsBean();
userCredentialsBean.setUserId("alice");
userCredentialsBean.setPassword("secret");
WebTarget theTarget = target("sessions/login");
Response response = theTarget.request().post( Entity.entity(UserCredentialsBean.class, "application/json"));
assertTrue(true);
}
}
The basic problem I have is that I cannot find any documentation on how to properly use the WebTarget class for post requests. the WebTarget theTarget is constructed correctly but the line:
Response response = theTarget.request().post( Entity.entity(UserCredentialsBean.class, "application/json"));
does not work.
As I understand the WebTarget class is fairly new in the JerseyTest framework. Is there anybody who can point me at any recent documentation, examples, or just explain here how I can get this to work?
I did do a lot of googling before I posted my question here, but after checking back my eyes suddenly fell on this Related Question. I did search on SO several times but never found this question. Anyway, here's the solution to my problem:
I started implementing as explained in the accepted answer and got it to work quickly.
Then I decided that you it should be possible to avoid using JSON string representations at all, and I got that to work to.
The code above works if modified as follows:
import static org.junit.Assert.assertTrue;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import com.acme.api.rest.SessionsEndPoint;
import com.acme.api.rest.beans.UserCredentialsBean;
public class TestSession extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(SessionsEndPoint.class);
}
#Test
public void test() {
UserCredentialsBean userCredentialsBean = new UserCredentialsBean();
userCredentialsBean.setUserId("alice");
userCredentialsBean.setPassword("secret");
LoginResponseBean loginResponseBean =
target("sessions/login")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(
Entity.entity(
userCredentialsBean,
MediaType.APPLICATION_JSON_TYPE
),
LoginResponseBean.class
);
assertTrue(
loginResponseBean.isSuccess()
&&
loginResponseBean.getToken().length()==36
);
}
}
LoginResponseBean is a plain Java Bean. Just getters and setters and a default constructor.
Marshalling to- and from JSON is done by the framework, either by moxy or jackson as the JSON provider.