XML unmarshalling to java objects - java

XML response
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
- <Film>
<film_id>1</film_id>
<title>ACADEMY DINOSAUR</title>
<description>xxx</description>
<length>86</length>
<image_id>1</image_id>
- <image>
<image_id>1</image_id>
<name>1.jpg</name>
<size>408307</size>
<type>.jpg</type>
<content>base64 byte</content>
</image>
</Film>
I have created pojo classes for Film and Image.
Film.java
public class Film {
private String film_id;
private String title;
private String description;
private String length;
private String image_id;
private Image image;
//setter and getter methods
}
Image.java
public class Image {
private int image_id;
private String name;
private int size;
private String type;
private byte[] content;
//setter and getter methods
}
Please help I am new to this and I should use JAXB.
SOLUTION:
I have added
#XmlRootElement(name = "film")
public class Film {
private int film_id;
private String title;
private String description;
private int length;
private int image_id;
private Image image;
}
on the getter method of Image, I have added #XMLElement(name="image").
On Image class I have added an annotation #XmlRootElement(name = "image"), which gives me what I wanted.

The only thing required to get your use case to work is to add an #XmlRootElement annotation on the Film class:
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="Film")
public class Film {
private String film_id;
private String title;
private String description;
private String length;
private String image_id;
private Image image;
}
The Other Part of Your Solution
on the getter method of Image, I have added #XMLElement(name="image").
On Image class I have added an annotation #XmlRootElement(name =
"image"), which gives me what I wanted.
Neither of these steps are required to map your particular use case.

Try converting your arrays to list on dublicating classes (worked for me)
As i see byte[] -> List < Byte>

Related

Why in my code do I have this inheritance problem? Create an object passing a specialized type instead of declared abstract super type

Working on a Java application I am finding the following problem related to inheritance.
I have the following situation:
1) I defined an abstract class named TrendFromExcelAbstract. This class contains some basic fields common to other classes which extend it and represent different tabs of an Excel file (but this is not important now):
public abstract class TrendFromExcelAbstract {
private Long id;
private String date;
private String time;
private String excelDocumentName;
private String excelDocumentSheet;
public TrendFromExcelAbstract() {
super();
}
public TrendFromExcelAbstract(Long id, String date, String time, String excelDocumentName,
String excelDocumentSheet) {
super();
this.id = id;
this.date = date;
this.time = time;
this.excelDocumentName = excelDocumentName;
this.excelDocumentSheet = excelDocumentSheet;
}
................................................................
................................................................
GETTER AND SETTER METHODS
................................................................
................................................................
}
Then I have a class named CompVibrAndTempDTO extending the previous abstract class:
public class CompVibrAndTempDTO extends TrendFromExcelAbstract {
// Temperature reading point
private String tempReadingPointA;
private String tempReadingPointB;
private String tempReadingPointC;
private String tempReadingPointD;
private String tempReadingPointE;
private String tempReadingPointF;
private String tempReadingPointG;
private String tempReadingPointH;
private String tempReadingPointI;
private String tempReadingPointJ;
private String tempReadingPointK;
private String tempReadingPointL;
private String tempReadingPointM;
private String tempReadingPointN;
private String tempReadingPointO;
private String tempReadingPointP;
// Vibration reading point
private String vibrReadingPointA;
private String vibrReadingPointB;
private String vibrReadingPointC;
private String vibrReadingPointD;
private String vibrReadingPointE;
private String vibrReadingPointF;
private String vibrReadingPointG;
private String vibrReadingPointH;
private String vibrReadingPointI;
private String vibrReadingPointJ;
private String vibrReadingPointK;
private String vibrReadingPointL;
public CompVibrAndTempDTO() {
super();
}
public CompVibrAndTempDTO(Long id, String date, String time, String excelDocumentName, String excelDocumentSheet,
String tempReadingPointA, String tempReadingPointB, String tempReadingPointC, String tempReadingPointD,
String tempReadingPointE, String tempReadingPointF, String tempReadingPointG, String tempReadingPointH,
String tempReadingPointI, String tempReadingPointJ, String tempReadingPointK, String tempReadingPointL,
String tempReadingPointM, String tempReadingPointN, String tempReadingPointO, String tempReadingPointP,
String vibrReadingPointA, String vibrReadingPointB, String vibrReadingPointC, String vibrReadingPointD,
String vibrReadingPointE, String vibrReadingPointF, String vibrReadingPointG, String vibrReadingPointH,
String vibrReadingPointI, String vibrReadingPointJ, String vibrReadingPointK, String vibrReadingPointL) {
........................................................................................................................
........................................................................................................................
........................................................................................................................
}
........................................................................................................................
........................................................................................................................
GETTER AND SETTER METHODS
........................................................................................................................
........................................................................................................................
}
Then I have another DTO class named ExcelTabGeneralInfoDTO like this:
public class ExcelTabGeneralInfoDTO {
private String excelDocumentName;
private String excelSheetName;
private List<TrendFromExcelAbstract> trendOfTabList;
public ExcelTabGeneralInfoDTO() {
super();
}
public ExcelTabGeneralInfoDTO(String excelDocumentName, String excelSheetName,
List<TrendFromExcelAbstract> trendOfTabList) {
super();
this.excelDocumentName = excelDocumentName;
this.excelSheetName = excelSheetName;
this.trendOfTabList = trendOfTabList;
}
..................................................................
..................................................................
GETTER AND SETTER METHODS
..................................................................
..................................................................
}
As you can see this class contains this list field:
private List<TrendFromExcelAbstract> trendOfTabList;
The idea is that this field represents a list of any objects that derive from TrendFromExcelAbstract
The problem is that in another class I am trying to do something like this:
public List<ExcelTabGeneralInfoDTO> getCompVibrAndTempTab() {
List<CompVibrAndTempDTO> tabTrendList = excelRepo.findCompVibrAndTempTab();
String excelDocumentName;
String excelSheetName;
if(tabTrendList.size() >=0 ) {
excelDocumentName = tabTrendList.get(0).getExcelDocumentName();
excelSheetName = tabTrendList.get(0).getExcelDocumentSheet();
}
ExcelTabGeneralInfoDTO result = new ExcelTabGeneralInfoDTO(excelDocumentName, excelSheetName, tabTrendList);
return result;
}
So basically at this line:
ExcelTabGeneralInfoDTO result = new ExcelTabGeneralInfoDTO(excelDocumentName, excelSheetName, tabTrendList);
I am trying to create a new ExcelTabGeneralInfoDTO, passing to it the tabTrendList list having type List.
I get the following error message:
Description Resource Path Location Type
The constructor ExcelTabGeneralInfoDTO(String, String, List<CompVibrAndTempDTO>) is undefined ExcelServiceImpl.java /energy-prg-be/src/main/java/com/springboot/excelapi/services line 425 Java Problem
Description Resource Path Location Type
Type mismatch: cannot convert from List<ExcelTabGeneralInfoDTO> to List<CompVibrAndTempDTO> ExcelResource.java /energy-prg-be/src/main/java/com/springboot/excelapi/resources line 167 Java Problem
My idea is that I can use the more general type (ExcelTabGeneralInfoDTO) and then pass the child type (CompVibrAndTempDTO). But it seems that my assumption is false. What is wrong? What am I missing? Why can't I do something like this? How can I fix it?
ExcelTabGeneralInfoDTO does not have a defined constructor for List<CompVibrAndTempDTO>, only for List<TrendFromExcelAbstract>. Try declaring tabTrendList as a List<TrendFromExcelAbstract> and see if it works.

JUNIT Test for partial update with java springboot mongodb

Hello I am new to JUnit test and Mockito and my question is how can I write a unit test for this custom partial update method in my customArticleRepository, which has no return parameter?
I have a POJO object named Article and I would like to partially update it. The REST endpoint PUT get a DTO Object Classification Mask with the specific updated value as request body, call the Service layer ArticleService, which call my CustomArticleRepository method.
this is my Article object
public class Article {
private String id;
#Field("_cls")
private String inheritance;
private String title;
private Date published;
private String content;
private String link;
private String summary;
private String description;
private Date updated;
private String primary;
private String[] secondary;
private String category;
private String[] categories;
private String person;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private Date deleted_date;
private Boolean is_new;
private Boolean edited;
private Aws aws;
this is my DTO Object
public class ClassificationMask {
private String id;
private String title;
private String content;
private String primary;
private String[] secondary;
private Float sentiment_positive;
private Float sentiment_negative;
private Float sentiment_neutral;
private Float sentiment_mixed;
private String category;
private String person;
private Boolean is_new;
private Datasource datasource;
and this is my partialupdate method in the repository
public void partialUpdateMask(String id, ClassificationMask articleUpdate) {
Query query = new Query(where("id").is(id));
Update update = new Update();
if(articleUpdate.getPrimary() !=null) { update.set("primary", articleUpdate.getPrimary()); }
if(articleUpdate.getSecondary() !=null){ update.set("secondary", articleUpdate.getSecondary());}
if(articleUpdate.getCategory() !=null){ update.set("category", articleUpdate.getCategory());}
if(articleUpdate.getPerson() !=null){ update.set("person",articleUpdate.getPerson());}
if(articleUpdate.getIs_new() !=null){ update.set("is_new",articleUpdate.getIs_new()); }
update.set("edited",true);
mongoTemplate.updateFirst(query,update ,Article.class);
}
Testing void method we could have:
Method that modifies the status of the object under test: so you can verify that the state of the sut is consistent with your aspectative
Method doesn't modify the status of the SUT but, for example, writes data on the DB so you can verify that your DAO is invoked
This is the second case and you can have something like this:
Mockito.verify(mongoTemplate).updateFirst(query, update, Article.class);
In this manner you're testing that
the method really calls updateFirst
the method calss updateFirst using the right parameters

Serializing multiple tiers of XML elements

Let's say I'm trying to create an XML document out of an object. Is this possible using JAXB annotations on a single Food class, or do I need to create inner classes for Cost and Flavor?
I know I can use #XmlElement or #XmlAttribute to set up immediate children of my root element. However, I'm not sure if/how to create the <cost> and <Flavor> tags as I show here.
<Food>
<cost amt=13.5 unit=USD/>
<Flavor spicy=5>It tastes good</Flavor>
</Food>
#XmlRootElement("Food")
public class Food {
private float amount;
private String units;
private String flavorType;
private STring flavorDescription;
}
Add a new Java class Cost:
public class Cost
{
#XmlAttribute
double amt;
#XmlAttribute
String unit;
}
And exdend class Food
#XmlRootElement
public class Food {
private float amount;
private String units;
private String flavorType;
private String flavorDescription;
private Cost cost;
...
you could also use something like this for Flavor class
public class Flavor {
private long spicy;
private String shortDesc;
#XmlValue
public String getShortDesc() {
return shortDesc;
}
public void setShortDesc(String shortDesc) {
this.shortDesc = shortDesc;
}
#XmlAttribute
public Long getSpicy() {
return spicy;
}
public void setSpicy(long spicy) {
this.spicy= spicy;
}
}

Jackson XML: nested field deserialization

I have the following xml
<MyPojo>
<name>Jason</name>
<age>25</age>
<meta>
<occupation>Engineer</occupation>
</meta>
</MyPojo>
I need to deserialize it to the following POJO:
public class MyPojo {
private String name;
private int age;
private String occupation;
}
The problem here is that occupation is wrapped within meta element
You need one more object:
public class MyPojo {
private String name;
private int age;
private Meta meta;
}
public class Meta{
private String occupation;
}
My idea is to replace occupation with an own class. Something like myMeta or whatever you want to call it(be aware in your case like the xml says: meta). This class should cotain the field occupation:
public class Meta
{
private String occupation;
}
After that you only have to add a new field of your new class e.g. myMeta to myPojo. Something like this:
public class MyPojo
{
private String name;
private int age;
private Meta meta;
}
this should avoid
that occupation is wrapped within meta element
Hope that helps!

json conversion with gson on java

I have json like following picture.
I have created 3 classes for this json.
First one is Main Class which is called KategoriResult
public class KategoriResult{
private String ErrorMessage;
private String ResultCode;
private List<KategoriItem> Payload;
..
..
getter - setter
..
Second KategoriItems
public class KategoriItem implements Serializable{
private int RowIdx;
private int Id;
private String Title;
private String Type;
private String WebUrl;
private List<ChildrenItem> Children;
private Boolean VideoItems;
..
..
getter - setter
..
and ChildrenItems
public class ChildrenItem implements Serializable{
private int RowIdx;
private int Id;
private String Title;
private String Type;
private String WebUrl;
private Boolean Children;
private Boolean VideoItems;
..
..
getter - setter
..
I am trying to convert the json above to java object with gson. I am getting following error : E/AndroidRuntime(1510): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 7729.
HOw can I fix this?
java:
private List ChildrenList;
json:
Children : []
May be you should rename "ChildrenList" <-> "Children". What setter name do you use?

Categories