How serialize time zone part of ZonedDateTime with jackson correctly - offset is handled correctly - jackson

My Jackson is configured with
disabled DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE (jsr310 is also in place)
Thus de/serializing ZonedDateTime is at least correctly preserving the offset part. But the serialization of a ZonedDateTime is removing the zone. Is there a configuration to preserve the zone info?
Or in other words how to get this test green?:
#Test
public void zonedDateTime() throws JsonProcessingException {
ZonedDateTime time = random.nextObject(ZonedDateTime.class);
String string = om.writeValueAsString(time);
ZonedDateTime timeReadBack = om.readValue(string, ZonedDateTime.class);
assertThat(timeReadBack, is(time));
}
If not possible only with configuration is there code for correct de/serilization?

Related

Locale aware bean validation message interpolation at ExceptionMapper in openliberty

I have a JAX-RS #POST endpoint whose input data has to be #Valid:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response myEndpoint(#javax.validation.Valid MyInputData input) { /*...*/ }
With MyInputData class annotated with many constraints:
#lombok.Data
public class InputData {
#Size(min = 1, max = 3)
private String someString;
/* ... */
}
Beyond that I have an ExceptionMapper<ConstraintViolationException> that transform the Exception into a Collection<String> (basically every single ConstraintViolation transformed to String using its getMesssage() method), then returns a Response.status(Status.BAD_REQUEST).entity(list).build().
Everything is working nicely. Fed an invalid input and I get back a HTTP 400 with a nice array of constraint violations in json format.
So far, so good...
BUT... the messages are in server's locale. Even if HTTP post sends a Accept-language header (and it is correctly detected when getting HttpServletRequest::getLocale).
By the time the ExceptionMapper gets hold of ConstraintViolation every message has already been interpolated, so no chance set the client locale.
Since the validation runs even before the JAX-RS resource (indeed, the JAX-RS resource isn't even called in case of invalid input), this locale aware message interpolator must be configured somewhere else.
Where? Is there already a MessageInterpolator implementation whose operation takes the HttpServletRequest locale into account?

How to set Duration dynamically for ResponseCacheAttribute

I have a .Net Core 3.1 Web Api application and use the ResponseCache attribute on a controller action.
[HttpGet]
[ResponseCache(Location = ResponseCacheLocation.Any, Duration = 30, VaryByQueryKeys = new[] { "id"})]
public string Get([FromQuery] int id)
{...}
While this is working fine with the hardcoded value for Duration, I need to set this dynamically from the config somehow.
I already tried:
Configuring it in Response Caching Middleware, but then it applies to all controller actions.
Deriving from ResponseCacheAttribute does not work, as it's internal.
Is there a simple way to achieve what I want, or do I have to write the whole thing (custom ResponseCacheAtrribute + ResponseCacheFilter + ResponseCacheFilterExecutor) by myself ?
I make a new attribute which inherits from the ResponseCacheAttribute which adds most of what I need. For example -
public class ResponseCacheTillAttribute : ResponseCacheAttribute
{
public ResponseCacheTillAttribute(ResponseCacheTime time = ResponseCacheTime.Midnight)
{
DateTime today = DateTime.Today;
switch (time)
{
case ResponseCacheTime.Midnight:
DateTime midnight = today.AddDays(1).AddSeconds(-1);
base.Duration = (int)(midnight - DateTime.Now).TotalSeconds;
break;
default:
base.Duration = 30;
break;
}
}
}
The Enum looks like
public enum ResponseCacheTime
{
Midnight
}
This allows me to build in specific times that I may need. I haven't fully tested this but confirmed I see the information in the response output.
You should be able to add any arguments or information you need into the attribute.

How to pass system date in sendkeys in Selenium Webdriver (not hardcoded)

WatchFromDate().sendKeys("2018-07-03");
// public WebElement WatchFromDate()
{
return driver.findElement(fromDate);
}
By fromDate= By.id("from");
the steps to send the system date in selenium could obtain the date with a specific format and then send this variable. Something like that:
public void WatchFromDate(){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
driver.findElement(fromDate).sendKeys(dtf.format(localDate));
}
The dtf variable defines the format for the date (i.e. 2018/07/13)
The localDate variable obtain the current date, but this date has too much precision.
The dtf.format(localDate) sentence adjust the current date obtained in the localDate, to the defined format in dtf variable.

NHibernate5: converting dates to local dates when they're persisted without a specific kind

Now that NHibernate 5 is out, I was wondering what's the recommended approach to load dates as local dates when they're persisted as datetime2 in a SQL Server 2016 database. Until now, dates were interpreted as local (so, the properties ended up with the correct values), but now, the behavior has changed and I'm unable to use the LocalDateTime.
Unfortunately, my donmain's behavior relies in getting those dates automatically loaded as local dates...
Any pointers on how to solve this?
Thanks,
Luis
Since I didn't found a way to disable this behavior, I've ended up creating a new type that will simply adjust the format of the data (considering always that it was saved in local format):
public class LocalDateTimeTypeNoThrow : LocalDateTimeType {
public LocalDateTimeTypeNoThrow() {
}
public LocalDateTimeTypeNoThrow(DateTimeSqlType sqlType) : base(sqlType) {
}
public override string Name => "LocalDateTimeNoThrow";
public override void Set(DbCommand st, object value, int index, ISessionImplementor session) {
var dateValue = (DateTime) value;
//removed throwing from here
st.Parameters[index].Value = AdjustDateTime(dateValue);
}
}
If there's a better way, please let me know.
Luis

SpringFox Date format to milliseconds

I'm using SpringFox (Swagger) to document my REST APIs. One of the nice features in Swagger is to show example model and the data type format.
Now, I configured my APIs to produce and consume dates in milliseconds but when I'm looking at the sample JSON model the date format is following: "2015-09-21T00:51:32.617Z". See screenshot below. Is it possible to tell SpringFox (Swagger) how to format the date properly?
You could try:
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfo())
.directModelSubstitute(YourDateTimeClass.class, Integer.class);
Basically you are telling Swagger to replace the date class with an Integer which could represent the milliseconds.
This is related to the underlying Jackson serialiser. You have to set the correct date format for it otherwise by default it's using timestamps.
Here is an example configuration
#Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
MappingJackson2HttpMessageConverter jsonMessageConverter = (MappingJackson2HttpMessageConverter) converter;
ObjectMapper objectMapper = jsonMessageConverter.getObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
break;
}
}
}
}
This way it will use an ISO-8601 date-time format. Here is another blog post that explains how to set your own preferred date format: http://yysource.com/2016/06/change-default-date-for-jackson-in-spring-boot-application/
I got a similar problem as yours, and I resolved it by adding the following config in my Spring Boot's application.properties file:
spring.jackson.date-format=com.fasterxml.jackson.databind.util.ISO8601DateFormat