I need to generate XML from java objects on Android. XML nodes must be in definite sequence.
Due XStream documentation order of XML nodes match object's fields define. There is no problems when I use java classes(String, Date...) as fields. But there is problem when I need serialize my objects as fields.
Here is my code:
final XStream x = new XStream();
x.autodetectAnnotations(true);
SecondEntity secondEntity = new SecondEntity();
secondEntity.setSecondaryDate(new Date());
secondEntity.setSecondaryString("Secondary String");
InnerEntity innerEntity = new InnerEntity();
innerEntity.setInnerDate(new Date());
innerEntity.setInnerString("Inner String");
SomeEntity someEntity = new SomeEntity();
someEntity.setInnerEntity(innerEntity);
someEntity.setSecondEntity(secondEntity);
someEntity.setSomeDate(new Date());
someEntity.setSomeString("Some string");
x.toXML(someEntity)
SomeEntity:
#XStreamAlias("SomeEntity")
public class SomeEntity {
#XStreamAlias("innerEntity")
private InnerEntity innerEntity;
#XStreamAlias("secondEntity")
private SecondEntity secondEntity;
#XStreamAlias("someString")
private String someString;
#XStreamAlias("someDate")
private Date someDate;
public InnerEntity getInnerEntity() {
return innerEntity;
}
public void setInnerEntity(InnerEntity innerEntity) {
this.innerEntity = innerEntity;
}
public SecondEntity getSecondEntity() {
return secondEntity;
}
public void setSecondEntity(SecondEntity secondEntity) {
this.secondEntity = secondEntity;
}
public String getSomeString() {
return someString;
}
public void setSomeString(String someString) {
this.someString = someString;
}
public Date getSomeDate() {
return someDate;
}
public void setSomeDate(Date someDate) {
this.someDate = someDate;
}
}
InnerEntity:
#XStreamAlias("InnerEntity")
public class InnerEntity {
#XStreamAlias("innerString")
private String innerString;
#XStreamAlias("innerDate")
private Date innerDate;
public String getInnerString() {
return innerString;
}
public void setInnerString(String innerString) {
this.innerString = innerString;
}
public Date getInnerDate() {
return innerDate;
}
public void setInnerDate(Date innerDate) {
this.innerDate = innerDate;
}
}
SecondEntity:
#XStreamAlias("SecondEntity")
public class SecondEntity {
#XStreamAlias("secondaryString")
private String secondaryString;
#XStreamAlias("secondaryDate")
private Date secondaryDate;
public String getSecondaryString() {
return secondaryString;
}
public void setSecondaryString(String secondaryString) {
this.secondaryString = secondaryString;
}
public Date getSecondaryDate() {
return secondaryDate;
}
public void setSecondaryDate(Date secondaryDate) {
this.secondaryDate = secondaryDate;
}
}
I get
<SomeEntity>
<innerEntity>
<innerDate>2013-02-28 18:04:24.184 UTC</innerDate>
<innerString>Inner String</innerString>
</innerEntity>
<secondEntity>
<secondaryDate>2013-02-28 18:04:24.183 UTC</secondaryDate>
<secondaryString>Secondary String</secondaryString>
</secondEntity>
<someDate>2013-02-28 18:04:24.184 UTC</someDate>
<someString>Some string</someString>
</SomeEntity>
When I need:
<SomeEntity>
<innerEntity>
<innerString>Inner String</innerString>
<innerDate>2013-02-28 18:04:24.184 UTC</innerDate>
</innerEntity>
<secondEntity>
<secondaryString>Secondary String</secondaryString>
<secondaryDate>2013-02-28 18:04:24.183 UTC</secondaryDate>
</secondEntity>
<someDate>2013-02-28 18:04:24.184 UTC</someDate>
<someString>Some string</someString>
</SomeEntity>
Please Implement this interface FieldKeySorter for InnerEntity and SecondEntity.
Related
When I use a distance API I get this response:
<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<Copyright>Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
<BrandLogoUri>http://dev.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
<StatusCode>200</StatusCode>
<StatusDescription>OK</StatusDescription>
<AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
<TraceId>df8ee9b6422846f0b97644c0a631deb8|DU00000D71|0.0.0.0|DU000005EC, DU00000480|Ref A: F00DC0285E97417B99490A8C98E65E31 Ref B: DB3EDGE1608 Ref C: 2020-06-09T18:53:54Z|Ref A: 69E0F633DF6448A89B2B904773DF19AB Ref B: DB3EDGE0807 Ref C: 2020-06-09T18:53:54Z</TraceId>
<ResourceSets>
<ResourceSet>
<EstimatedTotal>1</EstimatedTotal>
<Resources>
<Route>
<Id>v69,h1509963868,i0,a2,cen-US,dAAAAAAAAAAA1,y0,s1,m1,o1,t4,wWriswmZmQkBa9bnail0kQA2~BFnWzEBwiKgBBH_gASHtAT8A0~VHVuaXMsIFR1bmlzaWE1~~~~v11,w-Ki_XmFfQUC94xQdyYUlQA2~BFnWzEBYRLoBBH_gAc1znT4B0~U2ZheCwgVHVuaXNpYQ2~~~~v11,k1</Id>
<BoundingBox>
<SouthLatitude>34.74499</SouthLatitude>
<WestLongitude>10.18235</WestLongitude>
<NorthLatitude>36.800014</NorthLatitude>
<EastLongitude>10.76493</EastLongitude>
</BoundingBox>
<DistanceUnit>Kilometer</DistanceUnit>
<DurationUnit>Second</DurationUnit>
<TravelDistance>271.101</TravelDistance>
...
I want to get the value of TravelDistance.
If possible a full code because I have been trying with this for long time and no solution.
You can use XmlMapper of jackson to de/serialize your XML.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.8</version>
</dependency>
so you shall need to create an instance of it and deserialize as follows :
XmlMapper mapper = new XmlMapper();
Response value = xmlMapper.readValue("<Response>..</Response>", Response.class);
So you will need to create your object model that reflects your XML.
public class Response {
private String Copyright;
private String BrandLogoUri;
private String StatusCode;
private String StatusDescription;
private String AuthenticationResultCode;
private String TraceId;
ResourceSets ResourceSetsObject;
// Getter Methods
public String getCopyright() {
return Copyright;
}
public String getBrandLogoUri() {
return BrandLogoUri;
}
public String getStatusCode() {
return StatusCode;
}
public String getStatusDescription() {
return StatusDescription;
}
public String getAuthenticationResultCode() {
return AuthenticationResultCode;
}
public String getTraceId() {
return TraceId;
}
public ResourceSets getResourceSets() {
return ResourceSetsObject;
}
// Setter Methods
public void setCopyright(String Copyright) {
this.Copyright = Copyright;
}
public void setBrandLogoUri(String BrandLogoUri) {
this.BrandLogoUri = BrandLogoUri;
}
public void setStatusCode(String StatusCode) {
this.StatusCode = StatusCode;
}
public void setStatusDescription(String StatusDescription) {
this.StatusDescription = StatusDescription;
}
public void setAuthenticationResultCode(String AuthenticationResultCode) {
this.AuthenticationResultCode = AuthenticationResultCode;
}
public void setTraceId(String TraceId) {
this.TraceId = TraceId;
}
public void setResourceSets(ResourceSets ResourceSetsObject) {
this.ResourceSetsObject = ResourceSetsObject;
}
}
public class ResourceSets {
ResourceSet ResourceSetObject;
// Getter Methods
public ResourceSet getResourceSet() {
return ResourceSetObject;
}
// Setter Methods
public void setResourceSet(ResourceSet ResourceSetObject) {
this.ResourceSetObject = ResourceSetObject;
}
}
public class ResourceSet {
private String EstimatedTotal;
Resources ResourcesObject;
// Getter Methods
public String getEstimatedTotal() {
return EstimatedTotal;
}
public Resources getResources() {
return ResourcesObject;
}
// Setter Methods
public void setEstimatedTotal(String EstimatedTotal) {
this.EstimatedTotal = EstimatedTotal;
}
public void setResources(Resources ResourcesObject) {
this.ResourcesObject = ResourcesObject;
}
}
public class Resources {
Route RouteObject;
// Getter Methods
public Route getRoute() {
return RouteObject;
}
// Setter Methods
public void setRoute(Route RouteObject) {
this.RouteObject = RouteObject;
}
}
public class Route {
private String Id;
BoundingBox BoundingBoxObject;
private String DistanceUnit;
private String DurationUnit;
private String TravelDistance;
// Getter Methods
public String getId() {
return Id;
}
public BoundingBox getBoundingBox() {
return BoundingBoxObject;
}
public String getDistanceUnit() {
return DistanceUnit;
}
public String getDurationUnit() {
return DurationUnit;
}
public String getTravelDistance() {
return TravelDistance;
}
// Setter Methods
public void setId(String Id) {
this.Id = Id;
}
public void setBoundingBox(BoundingBox BoundingBoxObject) {
this.BoundingBoxObject = BoundingBoxObject;
}
public void setDistanceUnit(String DistanceUnit) {
this.DistanceUnit = DistanceUnit;
}
public void setDurationUnit(String DurationUnit) {
this.DurationUnit = DurationUnit;
}
public void setTravelDistance(String TravelDistance) {
this.TravelDistance = TravelDistance;
}
}
public class BoundingBox {
private String SouthLatitude;
private String WestLongitude;
private String NorthLatitude;
private String EastLongitude;
// Getter Methods
public String getSouthLatitude() {
return SouthLatitude;
}
public String getWestLongitude() {
return WestLongitude;
}
public String getNorthLatitude() {
return NorthLatitude;
}
public String getEastLongitude() {
return EastLongitude;
}
// Setter Methods
public void setSouthLatitude(String SouthLatitude) {
this.SouthLatitude = SouthLatitude;
}
public void setWestLongitude(String WestLongitude) {
this.WestLongitude = WestLongitude;
}
public void setNorthLatitude(String NorthLatitude) {
this.NorthLatitude = NorthLatitude;
}
public void setEastLongitude(String EastLongitude) {
this.EastLongitude = EastLongitude;
}
}
I'm using retrofit2 and Rxjava2 to insert/get information from mongodb and nodeJs server, for now, I receive all data as a string but I want to get hole collection Infos from my base so I need to convert string to JSON and get each information.
My code to receive data:
1- Service:
#POST("collect/get")
#FormUrlEncoded
Observable<String> getcollection(#Field("selector") String selector);
2-RetrofitClient:
if(instance == null){
instance = new Retrofit.Builder()
.baseUrl("http://transportor.ddns.net:3000/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()).build();
}
3- Recieve function
private void getallcollection(String selector) {
compositeDisposable.add(myServices.getcollection(selector)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>(){
#Override
public void accept(String s) throws Exception {
Log.d("infos",s);
}
}));
}
I'm already prepared Collection class:
public class col {
private String creator;
private String emailcol;
private String date_creation_col;
private String nom_col;
private String long_col;
private String lat_col;
private String tel_fix_col;
private String tel_mobile_col;
private String creatorcreator;
private String heure_matin_col;
private String heure_apresmatin_col;
private String type;
private String imagePath;
public col(String creator, String emailcol, String date_creation_col, String nom_col, String long_col, String lat_col, String tel_fix_col, String tel_mobile_col, String creatorcreator, String heure_matin_col, String heure_apresmatin_col, String type, String imagePath) {
this.creator = creator;
this.emailcol = emailcol;
this.date_creation_col = date_creation_col;
this.nom_col = nom_col;
this.long_col = long_col;
this.lat_col = lat_col;
this.tel_fix_col = tel_fix_col;
this.tel_mobile_col = tel_mobile_col;
this.creatorcreator = creatorcreator;
this.heure_matin_col = heure_matin_col;
this.heure_apresmatin_col = heure_apresmatin_col;
this.type = type;
this.imagePath = imagePath;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getEmailcol() {
return emailcol;
}
public void setEmailcol(String emailcol) {
this.emailcol = emailcol;
}
public String getDate_creation_col() {
return date_creation_col;
}
public void setDate_creation_col(String date_creation_col) {
this.date_creation_col = date_creation_col;
}
public String getNom_col() {
return nom_col;
}
public void setNom_col(String nom_col) {
this.nom_col = nom_col;
}
public String getLong_col() {
return long_col;
}
public void setLong_col(String long_col) {
this.long_col = long_col;
}
public String getLat_col() {
return lat_col;
}
public void setLat_col(String lat_col) {
this.lat_col = lat_col;
}
public String getTel_fix_col() {
return tel_fix_col;
}
public void setTel_fix_col(String tel_fix_col) {
this.tel_fix_col = tel_fix_col;
}
public String getTel_mobile_col() {
return tel_mobile_col;
}
public void setTel_mobile_col(String tel_mobile_col) {
this.tel_mobile_col = tel_mobile_col;
}
public String getCreatorcreator() {
return creatorcreator;
}
public void setCreatorcreator(String creatorcreator) {
this.creatorcreator = creatorcreator;
}
public String getHeure_matin_col() {
return heure_matin_col;
}
public void setHeure_matin_col(String heure_matin_col) {
this.heure_matin_col = heure_matin_col;
}
public String getHeure_apresmatin_col() {
return heure_apresmatin_col;
}
public void setHeure_apresmatin_col(String heure_apresmatin_col) {
this.heure_apresmatin_col = heure_apresmatin_col;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
Actually I received all data and console show me : [{"_id":"5e22074673c926147c3a73f5","date_creation_col":"17-01-2020","creator":"Alaeddine","emailcol":"amir#gmail.com","nom_col":"amir","long_col":"10.179326869547367","lat_col":"36.83353893150942","tel_fix_col":"123","tel_mobile_col":"1234","adress_col":"rue Paris mision 34","heure_matin_col":"7","heure_apresmatin_col":"5","type":"collection","imagePath":"mmmmmmmmmmmm"}]
I want to know how to extract for example creator from this Json.
You can use a third-party JSON parser, like Google GSON, as you're already developing for Android. Java does not seem to contain a built-in JSON parser.
See this answer.
I am trying to insert data in oracle DB using spring JPA repositories
I have a hash map which contains all the values which needs to be populated into DB,I am Iterating each value and setting into my Entity class
Basically I have a table which has a composite primary key(NotifiedToId).when I am setting the values ints throwing constraint violation exception.In my logs it is printing all correct values but its not getting inserted,
My Entity class:
#Embeddable
public class TbBamiNotifUserLogPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="NOTIFIED_TO_ID")
private String notifiedToId;
public TbBamiNotifUserLogPK() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getNotifiedToId() {
return this.notifiedToId;
}
public void setNotifiedToId(String notifiedToId) {
this.notifiedToId = notifiedToId;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof TbBamiNotifUserLogPK)) {
return false;
}
TbBamiNotifUserLogPK castOther = (TbBamiNotifUserLogPK)other;
return
this.notifRefNo.equals(castOther.notifRefNo)
&& this.notifiedToId.equals(castOther.notifiedToId);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.notifRefNo.hashCode();
hash = hash * prime + this.notifiedToId.hashCode();
return hash;
}
}
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="TB_BAMI_NOTIF_USER_LOG")
#NamedQuery(name="TbBamiNotifUserLog.findAll", query="SELECT t FROM TbBamiNotifUserLog t")
public class TbBamiNotifUserLog implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private TbBamiNotifUserLogPK id;
#Column(name="NOTIF_CAT")
private String notifCat;
#Column(name="NOTIFIED_TO_NAME")
private String notifiedToName;
#Column(name="NOTIFIED_TO_ROLE")
private String notifiedToRole;
public TbBamiNotifUserLog() {
}
public TbBamiNotifUserLogPK getId() {
return this.id;
}
public void setId(TbBamiNotifUserLogPK id) {
this.id = id;
}
public String getNotifCat() {
return this.notifCat;
}
public void setNotifCat(String notifCat) {
this.notifCat = notifCat;
}
public String getNotifiedToName() {
return this.notifiedToName;
}
public void setNotifiedToName(String notifiedToName) {
this.notifiedToName = notifiedToName;
}
public String getNotifiedToRole() {
return this.notifiedToRole;
}
public void setNotifiedToRole(String notifiedToRole) {
this.notifiedToRole = notifiedToRole;
}
}
#Entity
#Table(name="TB_BAMI_NOTIFICATION_LOG")
#NamedQuery(name="TbBamiNotificationLog.findAll", query="SELECT t FROM TbBamiNotificationLog t")
public class TbBamiNotificationLog implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="NOTIF_REF_NO")
private String notifRefNo;
#Column(name="\"ACTION\"")
private String action;
#Column(name="NOTIF_CONTENT")
private String notifContent;
#Column(name="NOTIF_TYPE")
private String notifType;
#Column(name="NOTIFIED_DATE_TIME")
private Timestamp notifiedDateTime;
private String refno;
#Column(name="\"VERSION\"")
private BigDecimal version;
public TbBamiNotificationLog() {
}
public String getNotifRefNo() {
return this.notifRefNo;
}
public void setNotifRefNo(String notifRefNo) {
this.notifRefNo = notifRefNo;
}
public String getAction() {
return this.action;
}
public void setAction(String action) {
this.action = action;
}
public String getNotifContent() {
return this.notifContent;
}
public void setNotifContent(String notifContent) {
this.notifContent = notifContent;
}
public String getNotifType() {
return this.notifType;
}
public void setNotifType(String notifType) {
this.notifType = notifType;
}
public Timestamp getNotifiedDateTime() {
return this.notifiedDateTime;
}
public void setNotifiedDateTime(Timestamp notifiedDateTime) {
this.notifiedDateTime = notifiedDateTime;
}
public String getRefno() {
return this.refno;
}
public void setRefno(String refno) {
this.refno = refno;
}
public BigDecimal getVersion() {
return this.version;
}
public void setVersion(BigDecimal version) {
this.version = version;
}
}
Business Logic:
for (Entry<String, PushNotificationDetails> entry : finalTemplate.entrySet()){
try{
notificationlog.setNotifRefNo("121323");
notificationlog.setRefno(refNum);
notificationlog.setVersion(new BigDecimal(1));
notificationlog.setAction(action);
LOGGER.debug("TEMPLATE TYPE"+entry.getValue().getTemplate_type());
LOGGER.debug("TEMPLATE"+entry.getValue().getTemplate());
notificationlog.setNotifType(entry.getValue().getTemplate_type());
notificationlog.setNotifContent(entry.getValue().getTemplate());
notificationlog.setNotifiedDateTime(notifiedDateTime);
tbBamiNotifyLogRepository.save(notificationlog);
LOGGER.debug("inside if block ::: ");
LOGGER.debug("USERID is: "+entry.getValue().getUserID());
LOGGER.debug("NOTIFCAT is: "+entry.getValue().getNotif_cat());
LOGGER.debug("NOTIFUSER is: "+entry.getValue().getUserName());
LOGGER.debug("NOTIFROLE is: "+entry.getKey());
tbBamiNotifUserLogPK.setNotifiedToId(entry.getValue().getUserID());
tbBamiNotifUserLogPK.setNotifRefNo("121323");
tbBamiNotifUserLog.setId(tbBamiNotifUserLogPK);
LOGGER.debug("GET is: "+tbBamiNotifUserLog.getId().getNotifiedToId());
tbBamiNotifUserLog.setNotifCat(entry.getValue().getNotif_cat());
tbBamiNotifUserLog.setNotifiedToName(entry.getValue().getUserName());
tbBamiNotifUserLog.setNotifiedToRole(entry.getKey());
tbBamiNotifyUserLogRepository.save(tbBamiNotifUserLog);
}
Try to add notificationlog = new TbBamiNotificationLog() in the beginning of your saving for. It could be possible when you try to save the second row but the instance is the same (with id provided during the first save).
Hi This is my Row Mapper class.
public class UserRowMapper implements RowMapper<UserData> {
#Override
public UserData mapRow(ResultSet resultSet, int line) throws SQLException {
UserData userData = new UserData();
try
{
userData.setUserID(resultSet.getString("User_ID"));
userData.setUserName(resultSet.getString("User_Name"));
userData.setUserPassword(resultSet.getString("User_Password"));
userData.setUserRole(resultSet.getString("User_Role"));
userData.setUserStatus(resultSet.getString("User_Status"));
userData.setUserLogStatus(resultSet.getString("UserLog_Status"));
userData.setUserAccountName(resultSet.getString("User_AccountName"));
userData.setUserAccountID(resultSet.getString("User_AccountID"));
userData.setUserEmailID(resultSet.getString("User_EmailID"));
userData.setUserPasswordStatus(resultSet.getString("User_Password_ExpiryStatus"));
userData.setUserIDStatus(resultSet.getString("User_ID_Status"));
userData.setAcatTenantID(resultSet.getLong("acatTenant_ID"));
userData.setUserRoleCode(resultSet.getLong("User_Role_Code"));
userData.setUserSkillSetCode(resultSet.getLong("User_SkillSet_Code"));
userData.setUserAccountCode(resultSet.getLong("User_Account_Code"));
return userData;
}
catch (EmptyResultDataAccessException e)
{
return null;
}
}
}
and this is my Model class.
public class UserData {
private String userID;
private String userPassword;
private String userRole;
private String userStatus;
private String userLogStatus;
private String userName;
private String userAccountName;
private String userAccountID;
private String userIDStatus;
private String userPasswordStatus;
private String userEmailID;
private String userAdminID;
private String deactivationComment;
private String reqPageID;
private String userSessionID;
private String reqFunctionalityID;
private long userAccountCode;
private long userRoleCode;
private long userSkillSetCode;
private long acatTenantID;
public long getUserAccountCode() {
return userAccountCode;
}
public void setUserAccountCode(long userAccountCode) {
this.userAccountCode = userAccountCode;
}
public long getUserRoleCode() {
return userRoleCode;
}
public void setUserRoleCode(long userRoleCode) {
this.userRoleCode = userRoleCode;
}
public long getUserSkillSetCode() {
return userSkillSetCode;
}
public void setUserSkillSetCode(long userSkillSetCode) {
this.userSkillSetCode = userSkillSetCode;
}
public long getAcatTenantID() {
return acatTenantID;
}
public void setAcatTenantID(long acatTenantID) {
this.acatTenantID = acatTenantID;
}
public String getReqFunctionalityID() {
return reqFunctionalityID;
}
public void setReqFunctionalityID(String reqFunctionalityID) {
this.reqFunctionalityID = reqFunctionalityID;
}
public String getReqPageID() {
return reqPageID;
}
public void setReqPageID(String reqPageID) {
this.reqPageID = reqPageID;
}
public String getUserSessionID() {
return userSessionID;
}
public void setUserSessionID(String userSessionID) {
this.userSessionID = userSessionID;
}
public String getUserAdminID() {
return userAdminID;
}
public void setUserAdminID(String userAdminID) {
this.userAdminID = userAdminID;
}
public String getDeactivationComment() {
return deactivationComment;
}
public void setDeactivationComment(String deactivationComment) {
this.deactivationComment = deactivationComment;
}
public String getUserIDStatus() {
return userIDStatus;
}
public void setUserIDStatus(String userIDStatus) {
this.userIDStatus = userIDStatus;
}
public String getUserPasswordStatus() {
return userPasswordStatus;
}
public void setUserPasswordStatus(String userPasswordStatus) {
this.userPasswordStatus = userPasswordStatus;
}
public String getUserEmailID() {
return userEmailID;
}
public void setUserEmailID(String userEmailID) {
this.userEmailID = userEmailID;
}
public String getUserAccountID() {
return userAccountID;
}
public void setUserAccountID(String userAccountID) {
this.userAccountID = userAccountID;
}
public String getUserAccountName() {
return userAccountName;
}
public void setUserAccountName(String userAccountName) {
this.userAccountName = userAccountName;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
public String getUserLogStatus() {
return userLogStatus;
}
public void setUserLogStatus(String userLogStatus) {
this.userLogStatus = userLogStatus;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
The above classes are my Row Mapper and Model class.i do not know how to write junit test class for Row Mapper class .please any one guide me how to write junit test for these classes.
Hi here is my Junit test code for above classes.
public class UserRowMapperTest {
UserRowMapper userRowMapper=null;
#Before
public void runBeforeEachTest(){
userRowMapper= new UserRowMapper();
}
#After
public void runAfterEachTest(){
userRowMapper=null;
}
#Test
public void testMapRow(){
userRowMapper.mapRow(resultSet, line);
}
}
From my point of view there is nothing to test here.
You should create unit tests only for the methods which have some business logic. I don't see the reason to test the methods which are using just getters and setters because in general they don't do anything.
However, if you want just to practice this is the advice what you could do for the unit test. First of all check some questions on how to write the unit tests because it feels like you don't understand what you need/want to achieve.
In general this is the sketch of what you want:
#Test
public void testMapRow(){
// SETUP SUT
UserRowMapper userRowMapper = new UserRowMapper()
// fill (prepare) in the Object that you want to pass to a method.
ResultSet resultSet = createResultSet();
// EXERCISE
UserData resultData = userRowMapper.mapRow(resultSet, line);
// VERIFY
Assert.assertEquals(expectedValue, resultData.getSomeValue())
}
p.s. By the way, there is no point in line parameter in this method because you don't use it.
And about the NullPointerException, please, have a look to quite popular question about it.
I want to use javax.ws.rs.core.Response to send and receive an Card entity object. But I don't know how to convert the contents back in to a Card object.
My testCreate() method should execute the create(Card card) method, receive back the json and convert it in to a card object. But I somehow always get type mismatches or it says that the getEntity() method can't be executed like this: response.getEntity(Card.class).
Does anybody know how I have to handle the response correctly so that I can convert the returned json entity in to a Card object again?
Here my CardResource method:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response create(Card card) {
Card c = dao.create(card);
if(c.equals(null)) {
return Response.status(Status.BAD_REQUEST).entity("Create failed!").build();
}
return Response.status(Status.OK)
.entity(c)
.type(MediaType.APPLICATION_JSON)
.build();
}
And here my CardResourceTests class
#Test
public void testCreate() {
boolean thrown = false;
CardResource resource = new CardResource();
Card c = new Card(1, "Cardname", "12345678", 1, 1,
"cardname.jpg", new Date(), new Date());
try {
Response result = resource.create(c);
System.out.println(result.getEntity(Card.class)); // not working!!!
if(result.getStatus() != 200) {
thrown = true;
}
} catch(Exception e) {
e.printStackTrace();
thrown = true;
}
assertEquals("Result", false, thrown);
}
And here my Card.class
#XmlRootElement
#PersistenceCapable(detachable="true")
public class Card {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
private Integer id;
#Persistent
private String name;
#Persistent
private String code;
#Persistent
private Integer cardProviderId;
#Persistent
private Integer codeTypeId;
#Persistent
private String picturePath;
#Persistent
private Boolean valid;
#Persistent
private Date mobCreationDate;
#Persistent
private Date mobModificationDate;
#Persistent
private Date creationDate;
#Persistent
private Date modificationDate;
public Card() {
this.setId(null);
this.setName(null);
this.setCode(null);
this.setCardProviderId(null);
this.setCodeTypeId(null);
this.setPicturePath(null);
this.setMobCreationDate(null);
this.setMobModificationDate(null);
this.setCreationDate(null);
this.setModificationDate(null);
}
public Card(Integer id, String name, String code, Integer cardProviderId,
Integer codeTypeId, String picturePath,
Date mobCreationDate, Date mobModificationDate) {
this.setId(id);
this.setName(name);
this.setCode(code);
this.setCardProviderId(cardProviderId);
this.setCodeTypeId(codeTypeId);
this.setPicturePath(picturePath);
this.setMobCreationDate(mobCreationDate);
this.setMobModificationDate(mobModificationDate);
this.setCreationDate(new Date());
this.setModificationDate(new Date());
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public Integer getCardProviderId() {
return cardProviderId;
}
public void setCardProviderId(Integer cardProviderId) {
this.cardProviderId = cardProviderId;
}
public void setCode(String code) {
this.code = code;
}
public Integer getCodeTypeId() {
return codeTypeId;
}
public void setCodeTypeId(Integer codeTypeId) {
this.codeTypeId = codeTypeId;
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
public Date getMobCreationDate() {
return mobCreationDate;
}
public void setMobCreationDate(Date mobCreationDate) {
this.mobCreationDate = mobCreationDate;
}
public Date getMobModificationDate() {
return mobModificationDate;
}
public void setMobModificationDate(Date mobModificationDate) {
this.mobModificationDate = mobModificationDate;
}
public Boolean getValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
}
And here my CardDAO class
public class CardDAO {
private final static Logger logger = Logger.getLogger(CardDAO.class.getName());
public Card create(Card card) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Card c = new Card(card.getId(), card.getName(), card.getCode(),
card.getCardProviderId(), card.getCodeTypeId(), card.getPicturePath(),
new Date(), new Date());
try {
pm.makePersistent(c);
} catch(Exception e) {
logger.severe("Create failed: " + e.getMessage());
return null;
} finally {
pm.close();
}
return c;
}
}
Is your Card class using #XmlRootElement and #XmlElement annotations to enable JAXB mapping JSON to/from POJO?
See example:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Book {
#XmlElement(name = "id")
String id;
//...
I am not sure that it is correct to call the annotated web-service method just like a simple method with params. Try to remove all annotations from your CardResource class and invoke this method simply like a class method.