I am trying to read the below data into a java object, but it is somehow failing.
Expected input data to my method getInternalNodeMetadata:
Event [status=PUBLISHED, header=EventHeader{bu_id='2', mart_id='null', eventProducer=DCSQUARE, eventType='CARRIER', eventTimestamp=Wed Oct 28 13:54:02 IST 2020, callbackEnpoint='http://test.com/test-app/services/carriers/3000', eventFulfiller=DCSQUARE, modeOfOperation=INSERT, additionalData='null', comments='null', tenants='[TenantInfo {bu_id=2, mart_id=2}]'}, payload=null]
public Flux<Event> getInternalNodeMetadata(Flux<Message<String>> message) {
System.out.println(message.toString());
return message.flatMap(it -> {
System.out.println("Payload: " + it.getPayload());
String eventMessage = it.getPayload().substring(5,it.getPayload().length());
System.out.println("eventMessage: " + eventMessage);
Event event = null;
try {
event = objectMapper.readValue(eventMessage, Event.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
List<Event> internalNodeMetadataList = new ArrayList<>();
internalNodeMetadataList.add(event);
return Flux.fromIterable(internalNodeMetadataList);
});
}
The above code is failing at the line
event = objectMapper.readValue(eventMessage, Event.class);
I have used jackson-databind: 2.11.4 jar ( for reading the value from object mapper class com.fasterxml.jackson.databind.ObjectMapper )
Error stacktrace:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.test.events.Event` out of START_ARRAY token
at [Source: (String)" [status=PUBLISHED, header=EventHeader{bu_id='2', mart_id='null', eventProducer=DCSQUARE, eventType='CARRIER', eventTimestamp=Wed Oct 28 13:54:02 IST 2020, callbackEnpoint='http://test.com/test-app/services/carriers/3000', eventFulfiller=DCSQUARE, modeOfOperation=INSERT, additionalData='null', comments='null', tenants='[TenantInfo {bu_id=2, mart_id=2}]'}, payload=null]"; line: 1, column: 2]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3468)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3436)
at com.test.node.metadata.core.NodeMetadataServiceFacade.lambda$getInternalNodeMetadata$0(NodeMetadataServiceFacade.java:47)
Can some please help me out of this. Thanks in advance!
Here is my Event class
package com.test.events;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(
name = "Event",
propOrder = {"status", "header", "payload"}
)
#XmlRootElement(
name = "Event"
)
public class Event<T> implements Serializable {
private static final long serialVersionUID = 1L;
#XmlElement(
name = "status",
required = true
)
private Status status;
#XmlElement(
name = "header",
required = true
)
private EventHeader header;
private T payload;
public Event() {
this.status = Status.FAIL;
}
public Event(EventHeader header, T payload) {
this.status = Status.FAIL;
this.header = header;
this.payload = payload;
}
public EventHeader getHeader() {
if (this.header == null) {
this.header = new EventHeader();
}
return this.header;
}
public EventHeader setHeader(EventHeader header) {
this.header = header;
return this.header;
}
public T getPayload() {
return this.payload;
}
public Event setPayload(T payload) {
this.payload = payload;
return this;
}
public Status getStatus() {
return this.status;
}
public Event setStatus(Status status) {
this.status = status;
return this;
}
public String toString() {
return "Event [status=" + this.status + ", header=" + this.header + ", payload=" + this.payload + "]";
}
}
Here is my EventData class
package com.test.events;
import com.test.com.util.DateTypeAdapter;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(
name = "EventHeader"
)
#XmlRootElement(
name = "EventHeader"
)
public class EventHeader implements Serializable {
private static final long serialVersionUID = 1L;
#XmlElement(
name = "WM_BU.ID",
required = true
)
private String bu_id;
#XmlElement(
name = "WM_MART.ID",
required = false
)
private String mart_id;
#XmlElement(
name = "EventProducer",
required = true
)
private EventHeader.CPSystem eventProducer;
#XmlElement(
name = "EventType",
required = true
)
private String eventType;
#XmlElement(
name = "EventTimestamp",
required = true
)
#XmlJavaTypeAdapter(DateTypeAdapter.class)
private Date eventTimestamp;
#XmlElement(
name = "CallbackEnpoint",
required = false
)
private String callbackEnpoint;
#XmlElement(
name = "EventFulfiller",
required = true
)
private EventHeader.CPSystem eventFulfiller;
#XmlElement(
name = "ModeOfOperation",
required = true
)
private EventHeader.ModeOfOperation modeOfOperation;
#XmlElement(
name = "AdditionalData",
required = false
)
private String additionalData;
#XmlElement(
name = "Comments",
required = false
)
private String comments;
#XmlElement(
name = "Tenants",
required = false
)
private List<TenantInfo> tenants;
public EventHeader() {
}
public EventHeader(String bu_id, String mart_id, EventHeader.CPSystem eventProducer, String eventType, Date eventTimestamp, String callbackEnpoint, EventHeader.CPSystem eventFulfiller, EventHeader.ModeOfOperation modeOfOperation, String additionalData, String comments) {
this.bu_id = bu_id;
this.mart_id = mart_id;
this.eventProducer = eventProducer;
this.eventType = eventType;
this.eventTimestamp = eventTimestamp;
this.callbackEnpoint = callbackEnpoint;
this.eventFulfiller = eventFulfiller;
this.modeOfOperation = modeOfOperation;
this.additionalData = additionalData;
this.comments = comments;
}
public EventHeader(String bu_id, String mart_id, EventHeader.CPSystem eventProducer, String eventType, Date eventTimestamp, String callbackEnpoint, EventHeader.CPSystem eventFulfiller, EventHeader.ModeOfOperation modeOfOperation, String additionalData, String comments, List<TenantInfo> tenants) {
this.bu_id = bu_id;
this.mart_id = mart_id;
this.eventProducer = eventProducer;
this.eventType = eventType;
this.eventTimestamp = eventTimestamp;
this.callbackEnpoint = callbackEnpoint;
this.eventFulfiller = eventFulfiller;
this.modeOfOperation = modeOfOperation;
this.additionalData = additionalData;
this.comments = comments;
this.tenants = tenants;
}
public String getBu_id() {
return this.bu_id;
}
public void setBu_id(String bu_id) {
this.bu_id = bu_id;
}
public String getMart_id() {
return this.mart_id;
}
public void setMart_id(String mart_id) {
this.mart_id = mart_id;
}
public EventHeader.CPSystem getEventProducer() {
return this.eventProducer;
}
public void setEventProducer(EventHeader.CPSystem eventProducer) {
this.eventProducer = eventProducer;
}
public String getEventType() {
return this.eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public Date getEventTimestamp() {
return this.eventTimestamp;
}
public void setEventTimestamp(Date eventTimestamp) {
this.eventTimestamp = eventTimestamp;
}
public String getCallbackEnpoint() {
return this.callbackEnpoint;
}
public void setCallbackEnpoint(String callbackEnpoint) {
this.callbackEnpoint = callbackEnpoint;
}
public EventHeader.CPSystem getEventFulfiller() {
return this.eventFulfiller;
}
public void setEventFulfiller(EventHeader.CPSystem eventFulfiller) {
this.eventFulfiller = eventFulfiller;
}
public EventHeader.ModeOfOperation getModeOfOperation() {
return this.modeOfOperation;
}
public void setModeOfOperation(EventHeader.ModeOfOperation modeOfOperation) {
this.modeOfOperation = modeOfOperation;
}
public String getAdditionalData() {
return this.additionalData;
}
public void setAdditionalData(String additionalData) {
this.additionalData = additionalData;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public List<TenantInfo> getTenants() {
return this.tenants;
}
public void setTenants(List<TenantInfo> tenants) {
this.tenants = tenants;
}
public String toString() {
return "EventHeader{bu_id='" + this.bu_id + '\'' + ", mart_id='" + this.mart_id + '\'' + ", eventProducer=" + this.eventProducer + ", eventType='" + this.eventType + '\'' + ", eventTimestamp=" + this.eventTimestamp + ", callbackEnpoint='" + this.callbackEnpoint + '\'' + ", eventFulfiller=" + this.eventFulfiller + ", modeOfOperation=" + this.modeOfOperation + ", additionalData='" + this.additionalData + '\'' + ", comments='" + this.comments + '\'' + ", tenants='" + this.tenants + '\'' + '}';
}
public static enum CPSystem {
DCSQUARE,
IMS,
OMS,
FOCI,
MCSE,
LMS,
LMDE,
SIMS,
GSCOPE,
PARTNER_MASTER,
PARTNER_PORTAL,
CAP,
SYNAPSE,
LIMO;
private CPSystem() {
}
}
public static enum ModeOfOperation {
INSERT,
UPDATE,
DELETE,
PUT,
POST;
private ModeOfOperation() {
}
}
}
Here is my DataTypeAdapter class
package com.test.common.util;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.datatype.DatatypeConfigurationException;
public class DateTypeAdapter extends XmlAdapter<String, Date> {
public static final String DATE_TIME_FORMAT_REGEX = "[0-9]{4}-(0[1-9]{1}|1[0-2]{1})-([0-2][0-9]|3[0-1])T([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(([.]([0-9]{3}))?+)[-+][0-9]{2}:[0-9]{2}";
public DateTypeAdapter() {
}
public Date unmarshal(String v) throws ParseException {
if (v != null && v.trim().length() > 0) {
try {
if (!v.matches("[0-9]{4}-(0[1-9]{1}|1[0-2]{1})-([0-2][0-9]|3[0-1])T([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(([.]([0-9]{3}))?+)[-+][0-9]{2}:[0-9]{2}")) {
throw new ParseException("Invalid date format provided. Allowed date format should follow the format {yyyy-MM-ddThh:mm:ss.millisecs-+Zone}. e.g. 2015-11-30T16:12:05.195-08:00", 0);
} else {
Calendar cal = DatatypeConverter.parseDateTime(v);
cal.setLenient(false);
return cal.getTime();
}
} catch (IllegalArgumentException var3) {
throw new ParseException("Invalid date format " + v, 0);
}
} else {
return null;
}
}
public String marshal(Date v) throws ParseException, DatatypeConfigurationException {
Calendar c = Calendar.getInstance();
c.setTime(v);
String dateTime = DatatypeConverter.printDateTime(c).replace("Z", "+00:00");
return dateTime;
}
}
You are sending an array of Events to "getInternalNodeMetadata" and trying to deserialize it to single Event, that is why you are getting the error , you need it to deserialize it to a list of events
event = objectMapper.readValue(eventMessage, Event.class);
Here you probably need to do something like
List<Event> eventList = mapper.readValue(eventMessage, List.class);
Related
I have a base class
public class Box<T> {
private T entity;
public T getEntity() {
return entity;
}
void setEntity(T entity) {
this.entity = entity;
}
}
It has 2 implementations.
// Class Person
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// Class Machine
public class Machine {
private String macAddress;
private String type;
public Machine(String macAddress, String type) {
this.macAddress = macAddress;
this.type = type;
}
}
If I want to serialise either of classA or class B objects, I will do it like this
Type typeTokenPerson = new TypeToken< Box <Person>>() {}.getType();
String userJson = gson.toJson(boxWithPersonObject, typeTokenPerson);
But the problem here is I need to know the type at compile time. I have a use case where I don't know this at compile-time, in other words, I have a json which I want to deserialize into either Person or Animal and I want to do this at runtime based on some condition.
Is there a way to do this usig Gson ?
Example:
Lets say we have a json like this
{
"entity": {
"name": "ABC",
"age": 10
}
}
This is of type Person. I want to deserialise this into an object of type Box<Person>
Gson can do it like this.
package com.example.demo;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.time.Duration;
import java.time.LocalDateTime;
public class GsonDemo {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private <T> Box<T> parseResponse(String responseData) {
Gson gson = new Gson();
Type jsonType = new TypeToken<Box<T>>() {
}.getType();
Box<T> result = gson.fromJson(responseData, jsonType);
return result;
}
#Test
public void test() {
LocalDateTime start = LocalDateTime.now();
try {
String json = "{ \"entity\": { \"name\": \"ABC\", \"age\": 10 }}";
Box<Person> objectBox = parseResponse(json);
System.out.println(objectBox);
String json2 = "{\n \"entity\": { \"macAddress\": \"DEF\", \"type\": \"def\" }}";
Box<Machine> objectBox2 = parseResponse(json2);
System.out.println(objectBox2);
} catch (Exception e) {
logger.error("Error", e);
}
LocalDateTime end = LocalDateTime.now();
logger.info("Cost time {}", Duration.between(start, end).toMillis() + "ms");
}
public class Box<T> {
private T entity;
public T getEntity() {
return entity;
}
void setEntity(T entity) {
this.entity = entity;
}
#Override
public String toString() {
return "Box{" + "entity=" + entity + '}';
}
}
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public String toString() {
return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
public class Machine {
private String macAddress;
private String type;
public Machine(String macAddress, String type) {
this.macAddress = macAddress;
this.type = type;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Machine{" + "macAddress='" + macAddress + '\'' + ", type='" + type + '\'' + '}';
}
}
}
I have the following files:
UnitController.java
package com.fidolease.fidolease.controllers;
import com.fidolease.fidolease.exceptions.ResourceNotFoundException;
import com.fidolease.fidolease.models.Unit;
import com.fidolease.fidolease.repository.UnitRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/api/v1")
public class UnitController {
#Autowired
private UnitRepository unitRepository;
#GetMapping("/units")
public List<Unit> getAllUnits(){
return unitRepository.findAll();
}
#GetMapping("/units/{id}")
public ResponseEntity<Unit> getUnitById(#PathVariable(value = "id") Long unitId)
throws ResourceNotFoundException {
Unit unit = unitRepository.findById(unitId)
.orElseThrow(() -> new ResourceNotFoundException("Unit not found for this id :: " + unitId));
return ResponseEntity.ok().body(unit);
}
}
ErrorDetails.java
package com.fidolease.fidolease.exceptions;
import java.util.Date;
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
}
}
GlobalExceptionHandler.java
package com.fidolease.fidolease.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import java.util.Date;
#ControllerAdvice
public class GlobalExceptionHandler {
#ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> resourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
#ExceptionHandler(Exception.class)
public ResponseEntity<?> globalExceptionHandler(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
ResourceNotFoundException.java
package com.fidolease.fidolease.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends Exception{
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message){
super(message);
}
}
Unit.java
package com.fidolease.fidolease.models;
import javax.persistence.*;
#Entity
#Table(name = "units")
public class Unit {
private long id;
private String unit_heading;
private int unit_type_id;
private int number_of_bedroom;
private double number_of_bathroom;
private int number_of_balcony;
private int leasing_info_id;
private String date_of_posting;
private String date_available_from;
private int posted_by;
private boolean is_active;
private String unit_description;
private int carpet_area;
private String unit_number;
private int unit_floor_number;
private int parent_unit_id;
public Unit(){ }
public Unit(String unit_heading, int unit_type_id, int number_of_bedroom, double number_of_bathroom,
int number_of_balcony, int leasing_info_id, String date_of_posting, String date_available_from,
int posted_by, boolean is_active, String unit_description, int carpet_area, String unit_number,
int unit_floor_number, int parent_unit_id) {
this.unit_heading = unit_heading;
this.unit_type_id = unit_type_id;
this.number_of_bedroom = number_of_bedroom;
this.number_of_bathroom = number_of_bathroom;
this.number_of_balcony = number_of_balcony;
this.leasing_info_id = leasing_info_id;
this.date_of_posting = date_of_posting;
this.date_available_from = date_available_from;
this.posted_by = posted_by;
this.is_active = is_active;
this.unit_description = unit_description;
this.carpet_area = carpet_area;
this.unit_number = unit_number;
this.unit_floor_number = unit_floor_number;
this.parent_unit_id = parent_unit_id;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId(){
return this.id;
}
public void setId(long id){
this.id = id;
}
#Column(name = "unit_heading", nullable = false)
public String getUnit_heading(){
return this.unit_heading;
}
public void setUnit_heading(String unit_heading){
this.unit_heading = unit_heading;
}
#Column(name = "unit_type_id", nullable = false)
public int getUnit_type_id(){
return this.unit_type_id;
}
public void setUnit_type_id(int unit_type_id){
this.unit_type_id = unit_type_id;
}
#Column(name = "number_of_bedroom", nullable = false)
public int getNumber_of_bedroom(){
return this.number_of_bedroom;
}
public void setNumber_of_bedroom(int number_of_bedroom){
this.number_of_bedroom = number_of_bedroom;
}
#Column(name = "number_of_bathroom", nullable = false)
public double getNumber_of_bathroom(){
return this.number_of_bathroom;
}
public void setNumber_of_bathroom(double number_of_bathroom){
this.number_of_bathroom = number_of_bathroom;
}
#Column(name = "number_of_balcony", nullable = false)
public int getNumber_of_balcony(){
return this.number_of_balcony;
}
public void setNumber_of_balcony(int number_of_balcony){
this.number_of_balcony = number_of_balcony;
}
#Column(name = "leasing_info_id", nullable = false)
public int getLeasing_info_id(){
return this.leasing_info_id;
}
public void setLeasing_info_id(int leasing_info_id){
this.leasing_info_id = leasing_info_id;
}
#Column(name = "date_of_posting", nullable = false)
public String getDate_of_posting(){
return this.date_of_posting;
}
public void setDate_of_posting(String date_of_posting){
this.date_of_posting = date_of_posting;
}
#Column(name = "date_available_from", nullable = false)
public String getDate_available_from(){
return this.date_available_from;
}
public void setDate_available_from(String date_available_from){
this.date_available_from = date_available_from;
}
#Column(name = "posted_by", nullable = false)
public int getPosted_by(){
return this.posted_by;
}
public void setPosted_by(int posted_by){
this.posted_by = posted_by;
}
#Column(name = "is_active", nullable = false)
public boolean getIs_active(){
return this.is_active;
}
public void setIs_active(boolean is_active){
this.is_active = is_active;
}
#Column(name = "unit_description", nullable = false)
public String getUnit_description(){
return this.unit_description;
}
public void setUnit_description(String unit_description){
this.unit_description = unit_description;
}
#Column(name = "carpet_area", nullable = false)
public int getCarpet_area(){
return this.carpet_area;
}
public void setCarpet_area(int carpet_area){
this.carpet_area = carpet_area;
}
#Column(name = "unit_number", nullable = false)
public String getUnit_number(){
return this.unit_number;
}
public void setUnit_number(){
this.unit_number = unit_number;
}
#Column(name = "unit_floor_number", nullable = false)
public int getUnit_floor_number(){
return this.unit_floor_number;
}
public void setUnit_floor_number(int unit_floor_number){
this.unit_floor_number = unit_floor_number;
}
#Column(name = "parent_unit_id", nullable = false)
public int getParent_unit_id(){
return this.parent_unit_id;
}
public void setParent_unit_id(int parent_unit_id){
this.parent_unit_id = parent_unit_id;
}
#Override
public String toString() {
return "Unit{" +
"id=" + id +
", unit_heading='" + unit_heading + '\'' +
", unit_type_id=" + unit_type_id +
", number_of_bedroom=" + number_of_bedroom +
", number_of_bathroom=" + number_of_bathroom +
", number_of_balcony=" + number_of_balcony +
", leasing_info_id=" + leasing_info_id +
", date_of_posting='" + date_of_posting + '\'' +
", date_available_from='" + date_available_from + '\'' +
", posted_by=" + posted_by +
", is_active=" + is_active +
", unit_description='" + unit_description + '\'' +
", carpet_area=" + carpet_area +
", unit_number='" + unit_number + '\'' +
", unit_floor_number=" + unit_floor_number +
", parent_unit_id=" + parent_unit_id +
'}';
}
}
UnitRepository.java
package com.fidolease.fidolease.repository;
import com.fidolease.fidolease.models.Unit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UnitRepository extends JpaRepository<Unit, Long> {
}
FidoLeaseApplication.java
package com.fidolease.fidolease;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class FidoleaseApplication {
public static void main(String[] args) {
SpringApplication.run(FidoleaseApplication.class, args);
}
}
When I run the application, I get the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'unitRepository' defined in com.fidolease.fidolease.repository.UnitRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': 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
When I searched around, it seemed as if the error might occur if I don't have JPA in my pom file but after searching it, I have the following:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Does anyone have any suggestions as to what I am doing wrong here or maybe a reference to some documentation that may explain my issue? Thank you all for your time and if there is anything I can do to clarify, please let me know.
EDIT: The following is my properties file:
spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://digitaloceanservername:theport/mydbname
spring.datasource.username=myusername
spring.datasource.password=mypassword
Edit 2: Adding the full strack trac -> https://pastebin.com/RskBMJjL
There is a bug in your setter method for unit_number, it is not taking a parameter. It should be:
public void setUnit_number(String unit_number){
this.unit_number = unit_number;
}
I am trying to unmarshal XML to java class as follows:-
My xml file as follows:-
<Features_res>
<StartWeek>202017</StartWeek>
<EndWeek>202035</EndWeek>
<Pno12>ABCDEEB</Pno12>
<FeatureList>
<Feature>
<Code>T002</Code>
</Feature>
<Feature>
<Code>T002</Code>
</Feature>
</FeatureList>
</Features_res>
Java InteriorResponse:-
#XmlRootElement(name = "Features_res")
public class InteriorResponse {
#XmlElement(name = "StartWeek")
private int sWeek;
#XmlElement(name = "EndWeek")
private int eWeek;
#XmlElement(name = "Pno12")
private String p12;
List<Feature> featureList;
public InteriorResponse() {
}
public InteriorResponse(int startWeek, int endWeek, String pno12) {
super();
this.sWeek = startWeek;
this.eWeek = endWeek;
this.p12 = pno12;
}
public int getStartWeek() {
return sWeek;
}
public void setStartWeek(int startWeek) {
this.sWeek = startWeek;
}
public int getEndWeek() {
return eWeek;
}
public void setEndWeek(int endWeek) {
this.eWeek = endWeek;
}
public String getPno12() {
return p12;
}
public void setPno12(String pno12) {
this.p12 = pno12;
}
public List<Feature> getFeatureList() {
return featureList;
}
#XmlElement(name = "FeatureList")
public void setFeatureList(List<Feature> featureList) {
this.featureList = featureList;
}
}
Another Java Feature:-
#XmlRootElement(name = "Feature")
public class Feature {
//#XmlElement(name = "Feature")
private String feature_;
#XmlElement(name = "code")
private String code_;
public String getCode() {
return code_;
}
public void setCode(String code) {
this.code_ = code;
}
public String getFeature_() {
return feature_;
}
public void setFeature_(String feature_) {
this.feature_ = feature_;
}
}
I am using above class as :-
public static void xmlToInterior() {
File file = new File("minxml.xml");
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(InteriorResponse.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
InteriorResponse interiorFeatures = (InteriorResponse) unmarshaller.unmarshal(file);
List<Feature> list_feat = interiorFeatures.getFeatureList();
for(Feature ft : list_feat) {
System.out.println(ft.getCode());
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
Output I have as:-
list_feat
code_ null
feature_ null
And list_feat has size 1. It should 2.
Also I have to name class member sWeek instead of startWeek. Otherwise, jaxbContext = JAXBContext.newInstance(InteriorResponse.class) throws exception like 2 element exist with same name.
XML additional part
I thought I could do the reaming part of the XML. I was trying part by part. But I couldn't do it. I really need to find some good tutorial or book about JXB. All I find a short overview of JXB. Any suggestion about where to read in details?
<Features_res>
<StartWeek>202017</StartWeek>
<EndWeek>202035</EndWeek>
<Pno12>ABCDEEB</Pno12>
<FeatureList>
<Feature>
<Code>T002</Code>
</Feature>
<Feature>
<Code>T002</Code>
</Feature>
</FeatureList>
<OptionList>
<Option>001048</Option>
<Option>000050</Option>
<Option>000790</Option>
</OptionList>
</Features_res>
So I made new class as:-
public class OptionList {
private List<Option> options;
#XmlElement(name = "Option")
public List<Option> getOptions() {
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
}
Another class as :-
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
public class Option {
#XmlElement(name = "Option")
private String option_;
public String getOption() {
return option_;
}
public void setOption(String option) {
this.option_ = option;
}
}
And updated for InteriorResponse class as:-
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "Features_res")
public class InteriorResponse {
#XmlElement(name = "StartWeek")
private int sWeek;
#XmlElement(name = "EndWeek")
private int eWeek;
#XmlElement(name = "Pno12")
private String p12;
private FeatureList featureList;
private OptionList optionList;
public InteriorResponse() {}
public InteriorResponse(int startWeek, int endWeek, String pno12) {
super();
this.sWeek = startWeek;
this.eWeek = endWeek;
this.p12 = pno12;
}
public int getStartWeek() {
return sWeek;
}
public void setStartWeek(int startWeek) {
this.sWeek = startWeek;
}
public int getEndWeek() {
return eWeek;
}
public void setEndWeek(int endWeek) {
this.eWeek = endWeek;
}
public String getPno12() {
return p12;
}
public void setPno12(String pno12) {
this.p12 = pno12;
}
#XmlElement(name = "FeatureList")
public FeatureList getFeatureList() {
return featureList;
}
public void setFeatureList(FeatureList featureList) {
this.featureList = featureList;
}
#XmlElement(name = "OptionList")
public OptionList getOptionList() {
return optionList;
}
public void setOptionList(OptionList optionList) {
this.optionList = optionList;
}
#Override
public String toString() {
return "InteriorResponse{"
+ "sWeek="
+ sWeek
+ ", eWeek="
+ eWeek
+ ", p12='"
+ p12
+ '\''
+ ", featureList="
+ featureList
+ '}';
}
}
I couldn't get the Option.
option null
The total xml is really huge. I still would like to try the remaing parts by myself part by part.
You need to design your classes according to XML structure. Find below the classes.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "Features_res")
public class InteriorResponse {
#XmlElement(name = "StartWeek")
private int sWeek;
#XmlElement(name = "EndWeek")
private int eWeek;
#XmlElement(name = "Pno12")
private String p12;
private FeatureList featureList;
private OptionList optionList;
public InteriorResponse() {}
public InteriorResponse(int startWeek, int endWeek, String pno12) {
super();
this.sWeek = startWeek;
this.eWeek = endWeek;
this.p12 = pno12;
}
public int getStartWeek() {
return sWeek;
}
public void setStartWeek(int startWeek) {
this.sWeek = startWeek;
}
public int getEndWeek() {
return eWeek;
}
public void setEndWeek(int endWeek) {
this.eWeek = endWeek;
}
public String getPno12() {
return p12;
}
public void setPno12(String pno12) {
this.p12 = pno12;
}
#XmlElement(name = "FeatureList")
public FeatureList getFeatureList() {
return featureList;
}
public void setFeatureList(FeatureList featureList) {
this.featureList = featureList;
}
#XmlElement(name = "OptionList")
public OptionList getOptionList() {
return optionList;
}
public void setOptionList(OptionList optionList) {
this.optionList = optionList;
}
#Override
public String toString() {
return "InteriorResponse{"
+ "sWeek="
+ sWeek
+ ", eWeek="
+ eWeek
+ ", p12='"
+ p12
+ '\''
+ ", featureList="
+ featureList
+ ", optionList="
+ optionList
+ '}';
}
}
Class for Feature object
import javax.xml.bind.annotation.XmlElement;
public class Feature {
#XmlElement(name = "Code")
private String code_;
public String getCode() {
return code_;
}
public void setCode(String code) {
this.code_ = code;
}
#Override
public String toString() {
return "Feature{" + "code_='" + code_ + '\'' + '}';
}
}
Class for FeatureList
import javax.xml.bind.annotation.XmlElement;
import java.util.List;
public class FeatureList {
private List<Feature> features;
#XmlElement(name = "Feature")
public List<Feature> getFeatures() {
return features;
}
public void setFeatures(List<Feature> features) {
this.features = features;
}
}
Class for OptionList
import javax.xml.bind.annotation.XmlElement;
import java.util.List;
public class OptionList {
private List<String> option;
#XmlElement(name = "Option")
public List<String> getOption() {
return option;
}
public void setOption(List<String> option) {
this.option = option;
}
}
For testing and simplicity, I have written a small java test program below.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.List;
public class Test {
public static void main(String[] args) {
File file =
new File("E:\\so\\xml\\minxml.xml");
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(InteriorResponse.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
InteriorResponse interiorFeatures = (InteriorResponse) unmarshaller.unmarshal(file);
List<Feature> list_feat = interiorFeatures.getFeatureList().getFeatures();
List<String> optionList = interiorFeatures.getOptionList().getOption();
for (String option : optionList) {
System.out.println("Option Value : " + option);
}
for (Feature ft : list_feat) {
System.out.println(ft.getCode());
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
I also provide the sample xml structure below.
<Features_res>
<StartWeek>202017</StartWeek>
<EndWeek>202035</EndWeek>
<Pno12>ABCDEEB</Pno12>
<FeatureList>
<Feature>
<Code>T002</Code>
</Feature>
<Feature>
<Code>T002</Code>
</Feature>
</FeatureList>
<OptionList>
<Option>001048</Option>
<Option>000050</Option>
<Option>000790</Option>
</OptionList>
</Features_res>
I knew very little about JAXB stuff. I have learned a lot from Sambit who helped a lot and gave me the way to start with this JAXB. Later I have implemented my version with less number of Java class and more smart use of JAXB annotations.
My version of InteriorResponse class:-
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#XmlRootElement(name = "Features_res")
public class InteriorResponse {
#XmlElement(name = "StartWeek")
private int startWeek;
#XmlElement(name = "EndWeek")
private int endWeek;
#XmlElement(name = "Pno12")
private String pno12;
#XmlElementWrapper(name = "FeatureList")
#XmlElement(name = "Feature")
private List<Feature> featureList;
#XmlElementWrapper(name = "OptionList")
#XmlElement(name = "Option")
private List<String> optionList;
public InteriorResponse() {
}
public InteriorResponse(int startWeek, int endWeek, String pno12) {
super();
this.startWeek = startWeek;
this.endWeek = endWeek;
this.pno12 = pno12;
}
#XmlTransient
public int getStartWeek() {
return startWeek;
}
public void setStartWeek(int startWeek) {
this.startWeek = startWeek;
}
#XmlTransient
public int getEndWeek() {
return endWeek;
}
public void setEndWeek(int endWeek) {
this.endWeek = endWeek;
}
#XmlTransient
public String getPno12() {
return pno12;
}
public void setPno12(String pno12) {
this.pno12 = pno12;
}
#XmlTransient
public List<Feature> getFeatureList() {
return featureList;
}
public void setFeatureList(List<Feature> featureList) {
this.featureList = featureList;
}
#XmlTransient
public List<String> getOptionList() {
return optionList;
}
public void setOptionList(List<String> optionList) {
this.optionList = optionList;
}
#Override
public String toString() {
return "InteriorResponse{" + "sWeek=" + startWeek + ", eWeek=" + endWeek + ", pno12='" + pno12 + '\'' + ", featureList=" + featureList + ", optionList="
+ optionList + '}';
}
}
My version of Feature class:-
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
public class Feature {
#XmlElement(name = "Code")
private String code;
#XmlTransient
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#Override
public String toString() {
return "Feature{" + "code_='" + code + '\'' + '}';
}
}
Note that I don't need any extra wrapper class for FeatuerList and OptionList. It can be done by the JAXB annotation #XmlElementWrapper(name = "FeatureList"). Also, a very important lesson learned. We have to mark all the property's getter method as #XmlTransient. Otherwise, JAXB throws an exception 2 properties found with the same name. Because our class all properties is visible to the JAXB. So we have to mark one as #XmlTransient.
In my opion, it is a better solution than the accepted answer. I gave all the credit to Sambit. I hove this will help others.
im trying to develop a simple RESTful webservice client. Using java and the javax jersey+dependencies. My problem is when trying to convert from the XML the object comes in, it returns an empty object.
The test is a simple test. I whish to get the language with a specific id, from my test i can see that the XML im getting is the same as in a browser.
The code for the classes is as follows:
Language
package data;
import javax.xml.bind.annotation.*;
#XmlRootElement(name = "prestashop")
#XmlType
public class Language {
private int id;
private String name;
private String iso_code;
private String language_code;
private boolean active;
private boolean is_rtl;
private String date_format_lite;
private String date_format_full;
public Language() {
}
public Language(String name, String iso_code, String date_format_lite,
String date_format_full) {
this.name = name;
this.iso_code = iso_code;
this.date_format_lite = date_format_lite;
this.date_format_full = date_format_full;
}
public Language(int id, String name, String iso_code, String language_code,
boolean active, boolean is_rtl, String date_format_lite,
String date_format_full) {
this.id = id;
this.name = name;
this.iso_code = iso_code;
this.language_code = language_code;
this.active = active;
this.is_rtl = is_rtl;
this.date_format_lite = date_format_lite;
this.date_format_full = date_format_full;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIso_code() {
return iso_code;
}
public void setIso_code(String iso_code) {
this.iso_code = iso_code;
}
public String getLanguage_code() {
return language_code;
}
public void setLanguage_code(String language_code) {
this.language_code = language_code;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isIs_rtl() {
return is_rtl;
}
public void setIs_rtl(boolean is_rtl) {
this.is_rtl = is_rtl;
}
public String getDate_format_lite() {
return date_format_lite;
}
public void setDate_format_lite(String date_format_lite) {
this.date_format_lite = date_format_lite;
}
public String getDate_format_full() {
return this.date_format_full;
}
public void setDate_format_full(String date_format_full) {
this.date_format_full = date_format_full;
}
#Override
public String toString(){
return "Language ["
+ "id=" + id + ", "
+ "name=" + name + ", "
+ "iso_code=" + iso_code + ", "
+ "language_code=" + language_code + ", "
+ "active=" + active + ", "
+ "is_rtl=" + is_rtl + ", "
+ "date_format_lite=" + date_format_lite + ", "
+ "date_format_full=" + date_format_full+ ","
+ " ]";
}
}
Main
package webservicetest2;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import data.Language;
import java.net.URI;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import javax.xml.bind.JAXBException;
public class WebServiceTest2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws JAXBException {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new HTTPBasicAuthFilter("KEY", ""));
WebResource service = client.resource(getBaseURI());
System.out.println(service.path("languages")
.path("7")
.accept(MediaType.TEXT_XML)
.get(String.class));
Language language;
language = (Language) service.path("languages")
.path("7")
.accept(MediaType.TEXT_XML)
.get(Language.class);
System.out.println(language.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/api").build();
}
}
The output
run:
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<language>
<id><![CDATA[7]]></id>
<name><![CDATA[Danish]]></name>
<iso_code><![CDATA[da]]></iso_code>
<language_code><![CDATA[da]]></language_code>
<active><![CDATA[1]]></active>
<is_rtl><![CDATA[0]]></is_rtl>
<date_format_lite><![CDATA[Y-m-d]]></date_format_lite>
<date_format_full><![CDATA[Y-m-d H:i:s]]></date_format_full>
</language>
</prestashop>
Language [id=0, name=null, iso_code=null, language_code=null, active=false, is_rtl=false, date_format_lite=null, date_format_full=null, ]
BUILD SUCCESSFUL (total time: 0 seconds)
As you can see the XML im getting back has an object but the print of the object is an empty object. So something is wrong.
Sorry if simular question have been asked but havent been able to find any.
I want to serialize a object hierarchy including a list of objects which derive from the base class 'Thing'. This works fine, including deserialization - but XML-Simple insists in writing an attribute which specifies the actual used Java-class
when I create a xml file with the java code below, the content is like this:
<example1>
<things>
<fruit class="com.mumpitz.simplexmltest.Apple" id="17">
<sugar>212</sugar>
</fruit>
<fruit class="com.mumpitz.simplexmltest.Orange" id="25" weight="11.2"/>
</things>
</example1>
but this is not what I want.
I'd like to have
<example1>
<things>
<apple id="17">
<sugar>212</sugar>
</apple>
<orange id="25" weight="11.2"/>
</things>
</example1>
'apple' and 'orange' elements without a class attribute, not 'fruit' with such an attribute. Is this possible?
(The second xml complies to a existing schema; adding extra attributes is not an option)
Here's the code:
package com.mumpitz.simplexmltest;
import java.io.File;
import java.util.ArrayList;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
class Fruit {
#Attribute(name = "id")
protected final int id;
Fruit(
#Attribute(name = "id")
int id) {
this.id = id;
}
int getObjectId() {
return id;
}
}
#Root
class Apple extends Fruit {
private final int sugar;
#Element(type = Fruit.class)
public Apple(
#Attribute(name = "id")
int id,
#Element(name = "sugar")
int sugar) {
super(id);
this.sugar = sugar;
}
#Element(name = "sugar")
public int getSugar() {
return this.sugar;
}
#Override
public String toString() {
return "id: " + id + ", sugar: " + sugar;
}
}
#Root
class Orange extends Fruit {
#Attribute
public double weight;
public Orange(
#Attribute(name = "id")
int id) {
super(id);
}
#Override
public String toString() {
return "id: " + id + ", weight: " + weight;
}
}
#Root
public class Example1 {
#ElementList
public ArrayList<Fruit> things = new ArrayList<Fruit>();
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("things:\n");
for (int i=0; i<things.size(); i++) {
sb.append(" " + things.get(i).toString() + "\n");
}
return sb.toString();
}
//////////////////////////////////
static Example1 createDummy() {
Example1 d = new Example1();
d.things.add(new Apple(17, 212));
Orange or = new Orange(25);
or.weight = 11.2;
d.things.add(or);
return d;
}
static String msg;
static Example1 res;
static public String getMessage() {
String m = msg;
msg = null;
return m;
}
static public boolean write(String path) {
Serializer serializer = new Persister();
Example1 example = Example1.createDummy();
File result = new File(path);
try {
serializer.write(example, result);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
static public boolean read(String path) {
Serializer serializer = new Persister();
File source = new File(path);
try {
res = serializer.read(Example1.class, source);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
public static Object getResult() {
return res;
}
}
some hours later I found the solution. You simply have to
Read the manual
Use the #ElementListUnion annotation
package com.mumpitz.simplexmltest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
// the base class
#Element
class Thing {
static int count=0;
Thing() {
this.id = ++count;
}
#Attribute
protected int id;
public int getId() {
return id;
}
}
// first derived class
#Element
class Car extends Thing {
#Attribute
private String name;
Car(#Attribute(name="name") String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "ID: " + id + " Car: " + name;
}
}
// second derived class
#Element
class House extends Thing {
#Attribute
private int price;
House(#Attribute(name="price") int price) {
this.price = price;
}
public int getPrice() {
return this.price;
}
#Override
public String toString() {
return "ID: " + id + " House: " + price;
}
}
// a class with a list of base class instances
#Root(name="ListOfThings")
public class Example4 {
// specify the derived classes used in the list
#ElementListUnion({
#ElementList(entry="house", inline=true, type=House.class),
#ElementList(entry="car", inline=true, type=Car.class)
})
private ArrayList<Thing> list = new ArrayList<Thing>();
public void add(Thing t) {
list.add(t);
}
public List<Thing> getProperties() {
return list;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Example4 contains " + list.size() + " elements:\n");
for (Thing t : list) {
sb.append(" " + t.toString() + "\n");
}
return sb.toString();
}
//////////////////////////////////
// test code
//////////////////////////////////
static String msg;
static Example4 res;
static public String getMessage() {
String m = msg;
msg = null;
return m;
}
static private Example4 createDummy() {
Example4 d = new Example4();
d.add(new Car("Mercedes"));
d.add(new House(34000000));
d.add(new Car("VW"));
d.add(new House(230000));
return d;
}
//////////////////////////////////
// serialize / deserialize
//////////////////////////////////
static public boolean write(String path) {
Serializer serializer = new Persister();
File result = new File(path);
Example4 example = Example4.createDummy();
try {
serializer.write(example, result);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
static public boolean read(String path) {
Serializer serializer = new Persister();
File source = new File(path);
try {
res = serializer.read(Example4.class, source);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
public static Object getResult() {
return res;
}
}