How to convert grpc java proto "timestamp" to date? - java

Error in request.getProductexpirationdate() since its not "Date" in proto thats specified as "timestamp".
Entity class has a "Date" but proto has no "Date" only "timestamp" so its not compatible.
How do i convert timestamp to date to make it compatible and sending data format as Date?
// EntityTest.class
#Data
#NoArgsConstructor
#AllArgsConstructor
public class ProductEntity {
private Integer purchase_item;
private String productname;
private String productbrand;
private Double productprice;
private String productdescription;
private Integer productquantity;
private Date productexpirationdate;
}
//GRPC Service
//Error in request.getProductexpirationdate() since its not "Date"
#GrpcService
public class ProductGRPCserver extends ProductServiceImplBase{
#Autowired
private ProductServiceImpl productServiceImpl;
#Autowired
private ProductDAO productDAO;
#Override
public void insert(Product request, StreamObserver<APIResponse> responseObserver) {
ProductEntity productEntity = new ProductEntity();
productEntity.setPurchase_item(request.getPurchaseItem());
productEntity.setProductname(request.getProductname());
productEntity.setProductbrand(request.getProductbrand());
productEntity.setProductprice(request.getProductprice());
productEntity.setProductdescription(request.getProductdescription());
productEntity.setProductquantity(request.getProductquantity());
productEntity.setProductexpirationdate(request.getProductexpirationdate());
productServiceImpl.saveDataFromDTO(productEntity);
APIResponse.Builder responce = APIResponse.newBuilder();
responce.setResponseCode(0).setResponsemessage("Succefull added to database " +productEntity);
responseObserver.onNext(responce.build());
responseObserver.onCompleted();
}

Assuming you are referring to google.protobuf.Timestamp, the easiest way to convert is with the com.google.protobuf.util.Timestamps utility:
Timestamp timestamp = Timestamp.fromMillis(date.getTime());
Timestamp stores the date as seconds and nanoseconds since 1970 whereas Date stores milliseconds since 1970. If you consult the google.protobuf.Timestamp documentation, it mentions how to do this manually conversion:
// The example used currentTimeMillis(), but let's use Date instead.
// long millis = System.currentTimeMillis();
long millis = date.getTime();
Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
.setNanos((int) ((millis % 1000) * 1000000)).build();

Related

Is there any way to map MySql TIMESTAMP to java.lang.Long?

So I have this object saved to the database with one property being dateCreated which is, of course, saved as MySQL timestamp. But while sending the data to the client, I want to be in milliseconds. Right now, I've mapped it to the Date object and converting it to milliseconds further. But I thought, what if I could map my POJO in such a way that it retrieves values in milliseconds. Here is what I've tried.
OmsJob:
#Entity
#EntityListeners(PreventAnyUpdate.class)
#ConfigurationProperties("omsjob")
#Table(name = "OMSJob")
public class OmsJob {
#Id
#NotNull
#Column(name = "jobId")
private String id;
#NotNull
private Long dateCreated; // If I map this property to Date, it works fine
}
I thought I'll add a custom converter that'll convert java.util.Date or java.sql.Date to milliseconds. But it isn't working:
#Component
#ConfigurationPropertiesBinding
public class DateConverter implements Converter<Date, Long> {
#Override
public Long convert(Date date) {
return date.getTime();
}
}
The error I am getting is pretty obvious but is there any way to achieve what I am trying to?
ERROR 229770 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Unsupported conversion from TIMESTAMP to java.lang.Long
An attribute won't know about its converter until you declare it. Do it as follows:
#NotNull
#Convert (converter = DateConverter.class)
private Long dateCreated;
Also, change the converter as follows:
public class DateConverter implements AttributeConverter<Date, Long> {
#Override
public Date convertToDatabaseColumn(Long millis) {
retrun new Date(millis);
}
#Override
public Long convertToEntityAttribute(Date date) {
return date.getTime();
}
}

Deserialize part of JSON string to DateTime in POJO using Jackson

I am reading a json of the given form and storing it as a POJO.
{
"details" : [
{
"version" : 1,
"time" : "2021-01-01T00:00:00.000Z",
}
]
}
My POJO class looks like :
public class Details
{
private int version;
private String time;
public Integer getVersion(){
return version;
}
public void setVersion(int version){
this.version = version;
}
public String getTime(){
return time;
}
public void setTime(String time){
this.time = time;
}
}
The time is being read as a string. How do I deserialize it to DateTime using Jackson?
Should be able to use #JsonFormat annotation for your date. First change your time field from String to Date then do the following:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy'T'hh:mm:ss.SSS'Z'")
private Date time;
The following link shows how to do other different conversions especially if its a standard time format
https://www.baeldung.com/jackson-serialize-dates
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
Adding this worked for me.
In POJO, gave time as 'DateTime' instead of 'String'.
public class Details
{
private int version;
private DateTime time;
...
//getters & setters
}

Converting date from timestamp to human readable in entity constructor

Currently, the format of the Date requestDate variable stored looks like: 2017-02-17 00:00:00.0. I want to convert this into, for example: Friday, February 17, 2017. I would like to do the conversion here in my entity and return it so that when it's displayed it is more human readable. This will likely happen in the constructor, at this line: this.setRequestDate(doDateConversion(requestDate));. How can I make this conversion?
My Request entity:
#Entity
#Table(name = "Request")
public class RequestDO implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="request_id")
private Long id;
private Date requestDate;
private String description;
private RequestStatus status;
/*private Boolean read;*/
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="user_id", nullable = false)
private Users users;
public RequestDO() {}
public RequestDO(Users user, Date requestDate) {
this.setUsers(user);
this.setRequestDate(requestDate);
}
#Override
public String toString() {
return String.format(
"RequestDO[id=%d, inital='%s', requestDate='%s']",
getId()
, getUsers().getInitialName()
, getRequestDate());
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
}
You can use SimpleDateFormat to convert your Date to a readable String of your choice.
The time format String for your example is EEEE, MMMM, dd, yyyy. You have to create a new SimpleDateFormat object and format your date to a String. Examples...
But Spring provides some specials out of the box. For example you can use Jackson for date format: #JsonFormat(pattern="yyyy-MM-dd") more. It is also possible to add a data format in application.properties file : spring.jackson.date-format
Using SimpleDateFormat:
java.sql.Date date = new Date(System.currentTimeMillis());
System.out.println(new SimpleDateFormat("EEEE, MMMM dd, YYYY").format(date));
See this for more details.
I solved the problem by changing the dates as they are read in my controller, using SimpleDateFormat:
#RequestMapping(value = "/requests", method = RequestMethod.GET)
public String getAllRequests(Model model, RequestModel requestModel) throws ParseException {
List<RequestDO> requestDOArrayList = new ArrayList<RequestDO>();
for (RequestDO requestDO : requestRepository.findAll()) {
log.info(requestDO.toString());
// Display all dates in Requests list in human-readable form
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(requestDO.getRequestDate().toString());
log.info(String.valueOf(date));
requestDO.setRequestDate(date);
requestDOArrayList.add(requestDO);
}
model.addAttribute("requests", requestDOArrayList);
log.info(requestDOArrayList.toString());
return "requests";
}

UTC Time is not getting stored in oracle column(TIMESTAMP WITH TIMEZONE) using JPA

I am getting UTC time in string format that we need to persist into database.
from UTC datetime string Calender object created using below code.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
OffsetDateTime dateTime = OffsetDateTime.parse(rqTime,formatter);
System.out.println(dateTime);
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTime(Date.from(dateTime.toInstant()));
Then set above created calender instance to JPA
EventDetails eventDetails = new EventDetails();
eventDetails.setTimeWithZone(cal);
event.insertEventDetails(eventDetails);
Entity class information
#Entity
#Table(name="mytimestamptz")
public class EventDetails implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name ="made_on" , columnDefinition = "TIMESTAMP WITH TIME ZONE")
#Type(type="com.elitecore.isl.bl.xlink.custom.UTCCalendarType")
private Calendar timeWithZone ;
#Id
#SequenceGenerator(name = "generator", sequenceName = "SEQ_EVENTID", allocationSize = 1)
#Column(name ="id")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
private Long id;
This code insert UTC DAte String "2016-01-01T13:14:15+0000" as "01-JAN-2016 13:14:15 +0530" in database even if we have specified the timezone information (Refer UTCCalendarType).
UTCCalendarType created to store datetime in UTC format in database
public class UTCCalendarType extends CalendarType {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
/**
* This is the original code from the class, with two changes. First we pull
* it out of the result set with an example Calendar. Second, we set the new
* calendar up in UTC.
*/
#Override
public Object get(ResultSet rs, String name) throws SQLException {
Timestamp ts = rs.getTimestamp(name, new GregorianCalendar(UTC));
if (ts != null) {
Calendar cal = new GregorianCalendar(UTC);
cal.setTime(ts);
return cal;
} else {
return null;
}
}
#Override
public void set(PreparedStatement st, Object value, int index) throws SQLException {
final Calendar cal = (Calendar) value;
cal.setTimeZone(UTC);
System.out.println("IST TIME : "+cal.getTime());
st.setTimestamp(index, new Timestamp(cal.getTime().getTime()),Calendar.getInstance(UTC));
}
}
I am not getting whats going wrong in this code.
why it is storing ASIA/KOLKATA TIMEZONE in database.
Kindly provide valuable input on this.
Maybe it is just a problem of data representation: the date is stored correctly, but the DBMS (or the query browser) shows it in its local format.
You can test if it's the case by using specific functions (e.g. sys_extract_utc(timestamp) for ORACLE), or by comparing with some other valid stored date by query.
Hope it helps.

Timestamp invalid hour in Java

I am using JPA with my Java project, and the timestamp is not working very well : it only shows 2015-08-12 00:00:00.0 (the day is correct but the hour is not)
#Entity
public class Session implements Serializable {
..
#Temporal(TemporalType.DATE)
private Date timestamp;
..
public Session(String sessionId) {
super();
this.sessionId = sessionId;
this.timestamp = new Date();
}
public Session() {
super();
this.timestamp = new Date();
}
}
Do you know how to fix this?
You should use TemporalType.TIMESTAMP that will map the field to a java.sql.Timestamp, hence it will contain also time related info, not only regarding date. In comparison, the type you used, TemporalType.DATE are mapped to java.sql.Date, class containing information like day, month year.
So, your code will transform in:
#Entity
public class Session implements Serializable {
..
#Temporal(TemporalType.TIMESTAMP)
private Date timestamp;
..
public Session(String sessionId) {
this.sessionId = sessionId;
this.timestamp = new Date();
}
public Session() {
this.timestamp = new Date();
}
}

Categories

Resources