I'm try to convert DemoEntity to DemoDto. And they have child attribute Collection<SubEntity> and Collection<SubDto>. Error happened when converting Collection<SubEntity>. If I don't add #JMap("subEntities"), JMapper would works well. Now I want that when converting DemoEntity, the Collection<SubEntity> could be converted together.
public class DemoEntity {
/** The id. */
private int id;
/** The code. */
private String code;
/** The date. */
private Date date;
private Collection<SubEntity> subEntities;
#JMapConversion(from = "date", to = "date")
public String convertDate(Date date) {
return date.toString();
}
public DemoEntity(int id, String code, Date date, Collection<SubEntity> subEntities) {
super();
this.id = id;
this.code = code;
this.date = date;
this.subEntities = subEntities;
}
...setter and getter...
}
public class DemoDto {
/** The id. */
#JMap
private Long id;
/** The code. */
#JMap
private String code;
/** The date. */
#JMap
private String date;
#JMap("subEntities")
private Collection<SubDto> subDtos;
... setter and getter...
}
The main method is below:
Collection<SubEntity> subEntities = new ArrayList<>();
for (int i = 1; i < 100; i++) {
SubEntity subEntity = new SubEntity(i, "C" + i, new Date());
subEntities.add(subEntity);
}
DemoEntity demoEntity = new DemoEntity(1, "D" + 1, new Date(), subEntities);
JMapperAPI api = new JMapperAPI();
MappedClass mappedClass = new MappedClass(SubDto.class);
api.add(mappedClass);
JMapper<DemoDto, DemoEntity> mapper = new JMapper<>(DemoDto.class, DemoEntity.class, api);
DemoDto demoDto = mapper.getDestination(demoEntity);
System.out.println(demoDto);
An exception happened, when covert DemoEntity.subEntities to DemoDto.subDtos
Exception in thread "main" com.googlecode.jmapper.exceptions.JMapperException: java.lang.NullPointerException
at com.googlecode.jmapper.config.JmapperLog.ERROR(JmapperLog.java:46)
at com.googlecode.jmapper.JMapper.<init>(JMapper.java:445)
at com.googlecode.jmapper.JMapper.<init>(JMapper.java:411)
at com.googlecode.jmapper.JMapper.<init>(JMapper.java:385)
at com.jmapper.JmapperDemo.main(JmapperDemo.java:35)
Caused by: java.lang.NullPointerException
at com.googlecode.jmapper.operations.complex.AComplexOperation.newInstance(AComplexOperation.java:107)
at com.googlecode.jmapper.operations.complex.AComplexOperation.newInstance(AComplexOperation.java:98)
at com.googlecode.jmapper.operations.recursive.MappedCollectionOperation.sharedCode(MappedCollectionOperation.java:64)
at com.googlecode.jmapper.operations.complex.AComplexOperation.sourceControl(AComplexOperation.java:156)
at com.googlecode.jmapper.operations.complex.AComplexOperation.genericFlow(AComplexOperation.java:133)
at com.googlecode.jmapper.operations.complex.AComplexOperation.write(AComplexOperation.java:89)
at com.googlecode.jmapper.generation.MapperConstructor.mapping(MapperConstructor.java:154)
at com.googlecode.jmapper.generation.MapperConstructor.wrappedMapping(MapperConstructor.java:123)
at com.googlecode.jmapper.generation.MapperConstructor.getMappings(MapperConstructor.java:89)
at com.googlecode.jmapper.generation.MapperGenerator.generateMapperClass(MapperGenerator.java:54)
at com.googlecode.jmapper.generation.MapperBuilder.generate(MapperBuilder.java:88)
at com.googlecode.jmapper.JMapper.createMapper(JMapper.java:458)
at com.googlecode.jmapper.JMapper.<init>(JMapper.java:440)
... 3 more
Besides, is there any method convert Collection<Entity> to Collection<Dto>
This is a case of recursive mapping, you need to map sub classes.
As you map DemoDTO with DemoEntity, you need to map SubDTO with SubEntity.
Related
I am not sure how to add entries into the Calendar properly. I want to populate base on input from the data base.
I have tried the following but am unsure how to set the dates and entries. I am getting the data and placing into an ObserverableList . In my case the database table is CalendarData
public class CalendarController<CalendarEvent> extends Application {
private RosterService rosterService = new RosterServiceImpl();
private ObservableList<CalendarData> calendarList = FXCollections.observableArrayList();
public ObservableList<CalendarData> getCalendarDataList() {
if (!calendarList.isEmpty())
calendarList.clear();
calendarList = FXCollections.observableList((List<CalendarData>) rosterService.listCalendarData());
return calendarList;
}
#Override
public void start(Stage primaryStage) throws Exception {
CalendarView calendarView = new CalendarView();
Calendar shifts = new Calendar("ShiftRoster");
shifts.setStyle(Style.STYLE1);
CalendarSource myCalendarSource = new CalendarSource("My Calendars");
// myCalendarSource.getCalendars().addAll(shifts, holidays);
calendarView.getCalendarSources().addAll(myCalendarSource);
calendarView.setRequestedTime(LocalTime.now());
getCalendarDataList();
for(CalendarData task : calendarList){
Entry<String> entry = new Entry<String>(task.getShiftType());
LocalDate date = task.getShiftDate();
shifts.addEntries(dates);
}
CalendarSource calendarSourceTasks = new CalendarSource("Shifts");
calendarSourceTasks.getCalendars().addAll(shifts);
calendarView.getCalendarSources().setAll(calendarSourceTasks);
Solved it by doing the following code:
CalendarView calendarView = new CalendarView();
Calendar shifts = new Calendar("ShiftRoster");
shifts.setStyle(Style.STYLE1);
ZoneId id = ZoneId.of("Australia/Brisbane");
getCalendarDataList();
for (CalendarData task : calendarList) {
Entry<String> dentistAppointment = new Entry<>(task.getEmployeename());
String startTime = task.getStartTIme();
String endTime = task.getEndTime();
LocalDate date = task.getShiftDate();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm:ss");
LocalTime start = LocalTime.parse(startTime, dtf);
LocalTime end = LocalTime.parse(endTime, dtf);
if (!start.isAfter(end)) {
dentistAppointment.setInterval(date);
dentistAppointment.setInterval(start, end);
shifts.addEntry(dentistAppointment);
}
if (!end.isAfter(start)) {
dentistAppointment.setInterval(date);
dentistAppointment.setInterval(date,start, date.plusDays(1),end);
shifts.addEntry(dentistAppointment);
}
}
CalendarSource calendarSourceTasks = new CalendarSource("Shifts");
calendarSourceTasks.getCalendars().addAll(shifts);
calendarView.getCalendarSources().setAll(calendarSourceTasks);
How do I access/get the string return values of a public static method that is nested in a public static class?
I want to display the string on a screen.
I've tried using private StringProperty variables to setDataString() the method return values as seen in the code snippet below.
The method named "byteToHex(buffer)" is the one whose return value I'm trying to access.
public static class SerialPortReader implements SerialPortEventListener
{
final public static char COMMA = ',';
final public static String COMMA_STR = ",";
final public static char ESCAPE_CHAR = '\\';
#Override
public void serialEvent(SerialPortEvent event)
{
if(event.isRXCHAR() && event.getEventValue() > 0)
{
try {
byte buffer[] = serialPort.readBytes();
byteToHex(buffer);
TransCeiveSerialData dataString = new TransCeiveSerialData();
dataString.setDataString(byteToHex(buffer));
/*
* wait some milliseconds before sending next data package to avoid data losses
*/
try {
Thread.sleep(100);
}catch(InterruptedException ie)
{
Logger.getLogger(TransCeiveSerialData.class.getName()).log(Level.SEVERE, null, ie);
}
}
catch(SerialPortException spe) {System.out.println("Error in port listener: " + spe);}
}
}
}
public static String byteToHex(byte x[])
{
StringBuffer retString = new StringBuffer();
for(int i = 0; i < x.length; ++i)
{
retString.append(Integer.toHexString(0x0100 + (x[i] & 0x00FF)).substring(1));
}
return retString.toString();
}
Using for exmaple System.out.println("Received data: " + instanceOfClass.getDataString()); in an external class to get the method's return string I get a "null". But I expect to get 31323334353637380d0a.
I've also tried binding the values but without any success.
Do you perhaps have any ideas how I can solve this problem? Your help will be very much appreciated.
Thanks a lot in advance!
AvJoe
I am trying to get a list of equipment IDs to show under one data structure, instead of a listing with the equipment name alongside each ID.
I'm trying to get it to show:
Site Equipment
Inlet P1
M&C-SP2500
329
Sick Maihak-MCS 100e
330
336
538
Inlet P2
etc....
The data is from MySQL query and using an ObservableList.
private ObservableList<Customer_EquipTree> equiptrees;
TreeItem<String> rootItem = new TreeItem<String>("Site Equipment");
rootItem.setExpanded(true);
for (Customer_EquipTree equiptree : equiptrees) {
TreeItem<String> equip = new TreeItem<String>(equiptree.getEquipment());
TreeItem<String> clID = new TreeItem<String>(equiptree.getclID().toString());
boolean found = false;
for (TreeItem<String> siteDes : rootItem.getChildren()) {
if (siteDes.getValue().contentEquals(equiptree.getSiteDesignation())) {
siteDes.getChildren().add(equip);
equip.getChildren().add(clID);
found = true;
break;
}
}
if (!found) {
TreeItem<String> siteDes = new TreeItem<String>(equiptree.getSiteDesignation());
rootItem.getChildren().add(siteDes);
siteDes.getChildren().add(equip);
equip.getChildren().add(clID);
locationTreeView.setRoot(rootItem);
}
}
This is how I have
public class Customer_EquipTree {
private String SiteDesignation;
private String Equipment;
private Integer Checklistid;
private Integer clID;
public Customer_EquipTree(String SiteDesignation, String Equipment, Integer Checklistid, Integer clID) {
this.SiteDesignation = SiteDesignation;
this.Equipment = Equipment;
this.Checklistid = Checklistid;
this.clID = clID;
}
public String getSiteDesignation() {
return SiteDesignation;
}
public void setSiteDesignation(String SiteDesignation) {
this.SiteDesignation = SiteDesignation;
}
public String getEquipment() {
return Equipment;
}
public void setEquipment(String Equipment) {
this.Equipment = Equipment;
}
public Integer getChecklistid() {
return Checklistid;
}
public void setChecklistid(Integer Checklistid) {
this.Checklistid = Checklistid;
}
public Integer getclID() {
return clID;
}
public void setclID(Integer clID) {
this.clID = clID;
}
#Override
public String toString() {
return SiteDesignation + " " + Equipment.toString();
}
}
It seems to me that your Customer_EquipTree is basically a tuple of site, equipment and id and there is one for every id. It looks you need to look for existing equipment the same way you look for existing sites.
You should create a helper method for this to avoid code duplication:
public static <T> TreeItem<T> findOrInsert(TreeItem<T> parent, T childValue) {
for (TreeItem<T> child : parent.getChildren()) {
if (child.getValue().equals(childValue)) {
return child;
}
}
TreeItem<T> result = new TreeItem<T>(childValue);
parent.getChildren().add(result);
return result;
}
for (Customer_EquipTree equiptree : equiptrees) {
TreeItem<String> siteDes = findOrInsert(rootItem, equiptree.getSiteDesignation());
TreeItem<String> equip = findOrInsert(siteDes, equiptree.getEquipment());
equip.getChildren().add(new TreeItem<>(equiptree.getclID().toString()));
}
BTW: using ORDER BY in your sql query would allow you to simplify the tree creation a bit, since you can be sure the items with matching site/equipment values occur next to each other in the ResultSet, e.g.
TreeItem<String> rootItem = new TreeItem<String>("Site Equipment");
try (Statement st = conn.createStatement()) {
ResultSet rs = st.executeQuery("SELECT siteDesignation, equipment, clID FROM Customer_EquipTree ORDER BY siteDesignation, equipment");
String currentSite = null;
String currentEquipment = null;
TreeItem<Sting> tiSite = null;
TreeItem<String> tiEquipment = null;
while (rs.next()) {
String site = rs.getString(1);
String equipment = rs.getString(2);
String id = rs.getString(3);
if (!site.equals(currentSite)) {
currentSite = site;
tiSite = new TreeItem<>(site);
rootItem.getChildren().add(tiSite);
currentEquipment = null; // equipment needs to be replaced too
}
if (!equipment.equals(currentEquipment)) {
currentEquipment = equipment;
tiEquipment = new TreeItem<>(equipment);
tiSite.getChildren().add(tiEquipment);
}
tiEquipment.getChildren().add(new TreeItem<>(id));
}
}
I have a class called Result (data that I want to show in my table) with several attributes.
public class Result
{
private final SimpleStringProperty object;
private List<SimpleStringProperty> listObject= new ArrayList<SimpleStringProperty>();
private final Util util = new Util();
public Result(String object, String[] listObject)
{
this.object= new SimpleStringProperty(object);
this.objectList= util.transformar(listObject);
}
public String getObject()
{
return this.object.get();
}
public void setObject(String object)
{
this.hash.set(hash);
}
public String[] getListObject()
{
return util.transformar2(this.listObject);
}
public void setListObject(String[] listObject)
{
this.listObject= transformar(listObject);
}
}
And I have my controller where I have an empty table and I add the columns and the objetcs Result. The controller has the attribute:
#FXML
private TableView tablaResultado;
The method were I do that is:
private List<TableColumn> load()
{
List<TableColumn> listColumn = new ArrayList<TableColumn>();
Object2 object2= new Object2();
List<Result> listaResultado = object2.getResultado();
ObservableList<Result> prueba = FXCollections
.observableArrayList(listaResultado);
TableColumn<Result, String> object= new TableColumn<Result, String>("object");
direccion.setCellValueFactory(
new PropertyValueFactory<Result, String>(
"object"));
listColumn.add(object);
List<TableColumn<Result, String>> listObject = new ArrayList<TableColumn<Result, String>>();
for (int i = 0; i < ((Result) listaResultado
.get(0)).getListObject().length; i++)
{
TableColumn<Result, String> columna = new TableColumn<Result, String>(
this.lenguaje.getProperty("listObject"+i);
columna.setCellValueFactory(
new PropertyValueFactory<Result, String>(
"listObject[" + i + "]"));
objectList.add(columna);
}
listColumn.addAll(objectList);
ObservableList<TableColumn<Result, String>> prueba2 = FXCollections
.observableArrayList(listObject);
this.tablaResultado.setItems(prueba);
this.tablaResultado.getColumns().addAll(object);
for (int i = 0; i < prueba2.size(); i++)
{
this.tablaResultado.getColumns().addAll(prueba2.get(i));
}
}
return listColumn ;
The result is the columns with their names and the data in the column object but the data in the columns listObject is empty. It has to be a list or something because I don't know the size of listObject.
If I change:
columna.setCellValueFactory(new PropertyValueFactory<Result, String ("listObject[" + i + "]"));
and I write:
columna.setCellValueFactory(new PropertyValueFactory<Result, String ("listObject"));
I got something like Ljava.lang.String;#bda3303 in that columns.
Do
final int index = i ;
columna.setCellValueFactory(cellData ->
new SimpleStringProperty(cellData.getValue().getListObject()[index]));
PropertyValueFactory does not "evaluate" an expression. It just tries to access a property of the table item. The default TableCells will use the toString method to get the text to display, which is why you get something like Ljava.lang.String;#bda3303 in the third version, see Java arrays printing out weird numbers, and text .
However you can write your own cellValueFactory:
public class Result
public StringProperty listObjectProperty(int index) {
return listObject.get(index);
}
final int columnIndex = i;
columna.setCellValueFactory(cellData -> cellData.getValue().listObjectProperty(columnIndex));
Alternatively simply create a ObservableValue<String> with a constant value for the column value:
final int columnIndex = i;
columna.setCellValueFactory(cellData -> Bindings.createStringBinding(() -> cellData.getValue().getListObject()[columnIndex]));
This is the code for the TableView:
TableView<KontaktPerson> tableKontaktPerson = new TableView<>();
TableColumn KontaktPersonFornavn = new TableColumn("Fornavn");
KontaktPersonFornavn.setCellValueFactory(new PropertyValueFactory<KontaktPerson, String>("fornavn"));
TableColumn KontaktPersonEtternavn = new TableColumn("Etternavn");
KontaktPersonEtternavn.setCellValueFactory(new PropertyValueFactory<KontaktPerson, String>("etternavn"));
TableColumn KontaktPersonNr = new TableColumn("Medlemsnummer");
KontaktPersonNr.setCellValueFactory(new PropertyValueFactory<KontaktPerson, Integer>("medlemsNr"));
tableKontaktPerson.getColumns().addAll(KontaktPersonFornavn,KontaktPersonEtternavn,KontaktPersonNr);
tableKontaktPerson.getSelectionModel().cellSelectionEnabledProperty();
tableKontaktPerson.setPrefSize(800, 300);
i wish to display the "fornavn","etternavn" and "medlemsNr" of that Object
Here is the "KontaktPerson" Class:
public class KontaktPerson extends Bruker implements Serializable {
private String fornavn, etternavn, telefon, epost;
private static int nestenr = 1000;
private int medlemsNr;
public KontaktPerson(String br, String pas, String fn, String en, String tlf, String ep) { // Tar in oppgitte Stirng verdier
super(br,pas);
fornavn = fn;
etternavn = en;
telefon = tlf;
epost = ep;
medlemsNr = ++nestenr;
}
}
For some reason i cant seem to get the "fornavn" and "etternavn" out, i just get the medlemsNr...