I have class-Composite:
public class CompositeText implements ComponentText {
private TypeComponent type;
private String value;
private final List<ComponentText> childComponents;
private CompositeText() {
childComponents = new ArrayList<>();
}
public CompositeText(String value, TypeComponent typeComponent) {
this.value = value;
this.type = typeComponent;
childComponents = new ArrayList<>();
}
#Override
public void add(ComponentText componentText) {
childComponents.add(componentText);
}
#Override
public void remove(ComponentText componentText) {
childComponents.remove(componentText);
}
#Override
public TypeComponent getComponentType() {
return this.type;
}
#Override
public ComponentText getChild(int index) {
return childComponents.get(index);
}
#Override
public int getCountChildElements() {
return childComponents.size();
}
#Override
public int getCountAllElements() {
return childComponents.stream()
.mapToInt(ComponentText::getCountAllElements)
.sum();
}
#Override
public String toString() {
return null;
}
}
I created classes that perform the same action - parsing, parsing text into paragraphs, into sentences, into tokens, into symbols.
public class IntoParagraphParser implements ActionParser {
// call IntoSentenceParser
}
public class IntoSentenceParser implements ActionParser {
// call IntoLexemeParser
}
public class IntoLexemeParser implements ActionParser {
// call IntoSymbolParser
}
public class IntoSymbolParser implements ActionParser {
}
All data is stored in List <ComponentText> childComponents in class-Composite - CompositeText.
How to properly create a method so that it prints all the data that is inside the composite?
I think this will be the method toString() in CompositeText.
Class IntoParagraphParser look:
public class IntoParagraphParser implements ActionParser {
private static final String PARAGRAPH_SPLIT_REGEX = "(?m)(?=^\\s{4})";
private static final IntoParagraphParser paragraphParser = new IntoParagraphParser();
private static final IntoSentenceParser sentenceParser = IntoSentenceParser.getInstance();
private IntoParagraphParser() {
}
public static IntoParagraphParser getInstance() {
return paragraphParser;
}
public ComponentText parse(String text) throws TextException {
ComponentText oneParagraph;
ComponentText componentParagraph = new CompositeText(text, TypeComponent.PARAGRAPH);
String[] arrayParagraph = text.split(PARAGRAPH_SPLIT_REGEX);
for(String element: arrayParagraph) {
oneParagraph = new CompositeText(element, TypeComponent.PARAGRAPH);
oneParagraph.add(sentenceParser.parse(element));
componentParagraph.add(oneParagraph);
}
return componentParagraph;
}
}
Need #Override the method toString() in CompositeText like this:
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (ComponentText component : childComponents) {
builder.append(component.toString());
}
return builder.toString();
}
But how to write this code correctly with Stream API?
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
childComponents.stream().map(...????
return builder.toString();
}
Related
For example I have two simple as possible classes, A and B
I want to take some action on objects of B, if some specific field of A object is changed I should do one thing, If some other field is changed I should do second thing, how can I do that with Lambda?
A:
public class A {
private int someField;
private String nextField;
public A(int someField, String nextField) {
this.someField = someField;
this.nextField = nextField;
}
public int getSomeField() {
return someField;
}
public void setSomeField(int someField) {
this.someField = someField;
}
public String getNextField() {
return nextField;
}
public void setNextField(String nextField) {
this.nextField = nextField;
}
}
B:
public class B {
private String someField;
public String getSomeField() {
return someField;
}
public void setSomeField(String someField) {
this.someField = someField;
}
public B(String someField) {
this.someField = someField;
}
}
Demo:
public class Demo {
public static <T> boolean isFieldChanged(T oldValue, T newValue) {
return !Objects.equals(oldValue, newValue);
}
public static void someActionOne(B test){
return;
}
public static void someActionTwo(B test){
return;
}
public static void main(String[] args) {
A oldData = new A(35, "old");
A clientData = new A(25, "ClientData");
Consumer<B> action = null;
if (isFieldChanged(oldData.getNextField(), clientData.getNextField())) {
action = Demo::someActionOne;
} else if (isFieldChanged(oldData.getSomeField(), clientData.getSomeField())) {
action = Demo::someActionTwo;
}
List<B> mockData = new ArrayList<>(Arrays.asList(new B("test1"), new B("test2")));
mockData.forEach(b -> action.accept(b));
}
}
How can I avoid compile error in that case?
To be effectively-final, a variable must not be changed after initialization.
If you want to use different actions, just initialize them twice:
public static void main(String[] args) {
A oldData = new A(35, "old");
A clientData = new A(25, "ClientData");
List<B> mockData = new ArrayList<>(Arrays.asList(new B("test1"), new B("test2")));
if (isFieldChanged(oldData.getNextField(), clientData.getNextField())) {
mockData.forEach(Demo::someActionOne);
} else if (isFieldChanged(oldData.getSomeField(), clientData.getSomeField())) {
mockData.forEach(Demo::someActionTwo);
}
}
I am doing a liferay project which use ejb at back end. so my ejb method looks like this:-
#Override
public List<RmisPaymentDetailsDto> getEpaymentDetails(String ebpCode) {
Query q = entityManager.createQuery("select s from EpaymentBo s where s.ebpCode=:ebpcode")
.setParameter("ebpcode",ebpCode);
#SuppressWarnings("unchecked")
List<ProductBo> list = q.getResultList();
Iterator<ProductBo> i = list.iterator();
List<RmisPaymentDetailsDto> rList = new ArrayList<RmisPaymentDetailsDto>();
while(i.hasNext()){
EpaymentBo ep =(EpaymentBo) i.next();
RmisPaymentDetailsDto dto = new RmisPaymentDetailsDto();
dto.setAdvertisementcode(ep.getAdvertisementcode());
dto.setAmount(ep.getAmount());
dto.setStudentmasterid(ep.getStudentmasterid());
dto.setEbpgendate(ep.getEbp_gen_date());
dto.setEbpcode(ep.getEbpCode());
dto.setPaymentstatus(ep.getPaymentstatus());
dto.setCandidatenameinnepali(ep.getCandidatenameinnepali());
rList.add(dto);
}
return rList;
}
the above method successfully fetches data from database and sets it to my RmisPaymentDetailsDto.
like this:-
now i am calling same method from my liferay controlller.
PreExaminationRemote preRef = (PreExaminationRemote) jndiContext
.lookup("PreExamination/remote");
List<RmisPaymentDetailsDto> rDto = preRef.getEpaymentDetails(ebpCode);
I am wondering how my one property(candidatenameinnepali) is lost as i return same dto from my ejb.
My dto looks like this:-
public class RmisPaymentDetailsDto implements Serializable {
private static final long serialVersionUID = 1L;
private String advertisementcode;
private String ebpcode;
private String amount;
private String studentmasterid;
private Date ebpgendate;
private String paymentstatus;
private String candidatenameinnepali;
public String getCandidatenameinnepali() {
return candidatenameinnepali;
}
public void setCandidatenameinnepali(String candidatenameinnepali) {
this.candidatenameinnepali = candidatenameinnepali;
}
public String getAdvertisementcode() {
return advertisementcode;
}
public void setAdvertisementcode(String advertisementcode) {
this.advertisementcode = advertisementcode;
}
public String getEbpcode() {
return ebpcode;
}
public void setEbpcode(String ebpcode) {
this.ebpcode = ebpcode;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getStudentmasterid() {
return studentmasterid;
}
public void setStudentmasterid(String studentmasterid) {
this.studentmasterid = studentmasterid;
}
public Date getEbpgendate() {
return ebpgendate;
}
public void setEbpgendate(Date ebpgendate) {
this.ebpgendate = ebpgendate;
}
public String getPaymentstatus() {
return paymentstatus;
}
public void setPaymentstatus(String paymentstatus) {
this.paymentstatus = paymentstatus;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
I'm trying to store a coordnates (array of double) using Realm-java,but I'm not able to do it.
Here is an example of json that I'm trying to parse:
{"_id":"597cd98b3af0b6315576d717",
"comarca":"string",
"font":null,
"imatge":"string",
"location":{
"coordinates":[41.64642,1.1393],
"type":"Point"
},
"marca":"string",
"municipi":"string",
"publisher":"string",
"recursurl":"string",
"tematica":"string",
"titol":"string"
}
My global object code is like that
public class Images extends RealmObject implements Serializable {
#PrimaryKey
private String _id;
private String recursurl;
private String titol;
private String municipi;
private String comarca;
private String marca;
private String imatge;
#Nullable
private Location location;
private String tematica;
private String font;
private String parentRoute;
public Location getLocation() {return location;}
public void setLocation(Location location) {this.location = location;}
public String getParentRoute() {
return parentRoute;
}
public void setParentRoute(String parentRoute) {
this.parentRoute = parentRoute;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getFont() {
return font;
}
public void setFont(String font) {
this.font = font;
}
public String getRecursurl() {
return recursurl;
}
public void setRecursurl(String recursurl) {
this.recursurl = recursurl;
}
public String getTitol() {
return titol;
}
public void setTitol(String titol) {
this.titol = titol;
}
public String getMunicipi() {
return municipi;
}
public void setMunicipi(String municipi) {
this.municipi = municipi;
}
public String getComarca() {
return comarca;
}
public void setComarca(String comarca) {
this.comarca = comarca;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getImatge() {
return imatge;
}
public void setImatge(String imatge) {
this.imatge = imatge;
}
public String getTematica() {
return tematica;
}
public void setTematica(String tematica) {
this.tematica = tematica;
}
And Location is a composite of type and a realmlist
Location.java
public class Location extends RealmObject implements Serializable {
private String type;
private RealmList<RealmDoubleObject> coordinates;
public Location() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RealmList<RealmDoubleObject> getCoordinates() {
return coordinates;
}
public void setCoordinates(RealmList<RealmDoubleObject> coordinates) {
this.coordinates = coordinates;
}
}
RealmDoubleObject.java
public class RealmDoubleObject extends RealmObject implements Serializable{
private Double value;
public RealmDoubleObject() {
}
public Double getDoublevalue() {
return value;
}
public void setDoublevalue(Double value) {
this.value = value;
}
}
The error is com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at path $[0].location.coordinates[0] but I'm not able to figure out why this number is not "fitting" by RealmDoubleObject.
For those that not familiar with realm RealmList doesn't work and you have to build your own realm object.
Thank you. I hope to find some Realm experts here!
SOLVED:
using Gson deserializer it can be done
First we have to initialize the gson object like this
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
#Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.registerTypeAdapter(new TypeToken<RealmList<RealmDoubleObject>>() {}.getType(), new TypeAdapter<RealmList<RealmDoubleObject>>() {
#Override
public void write(JsonWriter out, RealmList<RealmDoubleObject> value) throws IOException {
// Ignore
}
#Override
public RealmList<RealmDoubleObject> read(JsonReader in) throws IOException {
RealmList<RealmDoubleObject> list = new RealmList<RealmDoubleObject>();
in.beginArray();
while (in.hasNext()) {
Double valor = in.nextDouble();
list.add(new RealmDoubleObject(valor));
}
in.endArray();
return list;
}
})
.create();
And then we have to put some other constructor method
public RealmDoubleObject(double v) {
this.value = v;
}
and this is all.
Thanks for the help #EpicPandaForce
When i am trying Parce this json data with GSON. I am unable to get JsonArray in side of JsonObject. Below is my code, every suggestion will get appriciated.
JSON DATA FROM SERVER :
{
"GetJobDetails": {
"MaxAmount": 0,
"CreatorId": 1,
"JobImages": [
{
"ImagePath": "http://192.168.1.108:8088/Uploads/6e660c0c-4a2b- 42dc-ad97-82cc3efe87a0.jpg",
"JobImageId": 1
},
{
"ImagePath": "http://192.168.1.108:8088/Uploads/ccf1087d-9f7e-4c21-bc61-8aa3fd924e05.jpg",
"JobImageId": 2
},
{
"ImagePath": "http://192.168.1.108:8088/Uploads/4333e8b6-0079-457f-a225-fd7900ea81b1.jpg",
"JobImageId": 3
}
],
}
}
In ACTIVITY :
Gson gson = new Gson();
String response = new String(mresponce);
JobDetails jobDetails= gson.fromJson(response, JobDetails .class);
Log.e("JobDetails ",""+jobDetails.getJobImagesList());
this log prints allways null even when i have images list there in my data.
MODEL CLASS :
public class JobDetails implements Parcelable {
private int MaxAmount;
private int CreatorId;
private List<JobImage> JobImages;
public JobDetails() {
}
public JobDetails(Parcel parcel) {
this.MaxAmount = parcel.readInt();
this.CreatorId= parcel.readInt();
this.JobImages = new ArrayList<JobImage>();
parcel.readTypedList(JobImages, JobImage.CREATOR);
}
// Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.MaxAmount);
dest.writeInt(this.CreatorId);
dest.writeList(this.JobImages);
// TODO: Not Parceling AddressList
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public JobDetails createFromParcel(Parcel in) {
return new JobDetails(in);
}
public JobDetails[] newArray(int size) {
return new JobDetails[size];
}
};
public List<JobImage> getJobImagesList() {
return JobImages;
}
public void setJobImagesList(List<JobImage> jobImages) {
JobImages = jobImages;
}
public int getMaxAmount() {
return MaxAmount;
}
public void setMaxAmount(int maxAmount) {
MaxAmount= maxAmount;
}
}
ANOTHER MODEL CLASS FOR JOBIMAGE:
public class JobImage implements Parcelable {
private String ImagePath;
private int JobImageId;
JobImage(){
}
public JobImage(Parcel in) {
this.ImagePath = in.readString();
this.JobImageId = in.readInt();
}
// Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.ImagePath);
dest.writeInt(this.JobImageId);
// TODO: Not Parceling AddressList
}
public static final Creator CREATOR = new Creator() {
public JobImage createFromParcel(Parcel in) {
return new JobImage(in);
}
public JobImage[] newArray(int size) {
return new JobImage[size];
}
};
public String getImagePath() {
return ImagePath;
}
public void setImagePath(String imagePath) {
ImagePath = imagePath;
}
public int getJobImageId() {
return JobImageId;
}
public void setJobImageId(int jobImageId) {
JobImageId = jobImageId;
}
}
Please help me to find what i am doing wrong in this :
Your top-level JSON object is not a JobDetails object, it is an object that has JobDetails member name GetJobDetails. You need to handle this level of your JSON. You can do it with a custom TypeAdapter, or perhaps easier, just make a container object and deserialize it.
class JobDetailContainer {
private JobDetails GetJobDetails;
public JobDetails getJobDetails() {
return GetJobDetails;
}
}
then use --
Gson gson = new Gson();
String response = new String(mresponce);
GetJobDetails getJobDetails= gson.fromJson(response, GetJobDetails.class);
Log.e("JobDetails ",""+getJobDetails.getJobDetails().getJobImagesList());
Agreed with #iagreen ...I should handel top level json object too..this is what i have done after doing some R&D
public class GetJobDetails {
public GetJobDetailsResult getGetJobDetailsResult() {
return GetJobDetailsResult;
}
public void setGetJobDetailsResult(GetJobDetailsResult GetJobDetailsResult) {
this.GetJobDetailsResult = GetJobDetailsResult;
}
}
For Inner Json :
public class GetJobDetailsResult {
private Integer MaxAmount;
private Integer CreatorTotJobPosted;
private List<JobImage> JobImages = new ArrayList<JobImage>();
public Integer getMaxAmount() {
return MaxAmount;
}
public void setMaxAmount(Integer MaxAmount) {
this.MaxAmount = MaxAmount;
}
public Integer getCreatorTotJobPosted() {
return CreatorTotJobPosted;
}
public void setCreatorTotJobPosted(Integer CreatorTotJobPosted) {
this.CreatorTotJobPosted = CreatorTotJobPosted;
}
public List<JobImage> getJobImages() {
return JobImages;
}
public void setJobImages(List<JobImage> JobImages) {
this.JobImages = JobImages;
}
}
Finally For To Hold JobImages
public class JobImage {
private String ImagePath;
private Integer JobImageId;
public String getImagePath() {
return ImagePath;
}
public void setImagePath(String ImagePath) {
this.ImagePath = ImagePath;
}
public Integer getJobImageId() {
return JobImageId;
}
public void setJobImageId(Integer JobImageId) {
this.JobImageId = JobImageId;
}
}
Final Step :
Gson gson = new Gson();
String response = new String(jsonObjectresponce.toString());
GetJobDetails getJobDetails = gson.fromJson(response, GetJobDetails.class);
GetJobDetailsResult result = getJobDetails.getGetJobDetailsResult();
// now result object contains my json data.
I am working in an android application I want to sort a List of Objects with an Object Property. I have sorted it successfully but when I sort it all the List with that object changes the value to same as the sorted value
Please look into ma code :
SortedSet<Caseload> removeDuplicateClientName = new TreeSet<Caseload>(
new Comparator<Caseload>() {
#Override
public int compare(Caseload caseload0, Caseload caseload1) {
return caseload0.ClientName.compareTo(caseload1.ClientName);
}
});
// Getting the list of values from web service
mLISTCaseloadsHeads = parsedXML.getCaseLoadValues("get_Caseload_ClientServiceGroupID", param);
List<Caseload> newBackUp=mLISTCaseloadsHeads ;
Iterator<Caseload> iterator = mCaseloadsHeads.iterator();
while (iterator.hasNext()) {
removeDuplicateClientName.add(iterator.next());
}
mCaseloadsHeads.clear();
mCaseloadsHeads.addAll(removeDuplicateClientName);
The List newBackUp also changes the value to the same as sorted List
Caseload class:
public class Caseload implements Comparable<Caseload> {
public int BusClientLogID;
public int ClientID;
public int ClientStatus;
public int ClientServiceGroup_ClientSiteTherapyID;
public String ClientName;
public String TimeArrive;
public String TimeDepart;
public String SignOutTime;
public String SignInTime;
public String ServiceCompletedCount;
public Boolean ShowFooter = false;
public int getBusClientLogID() {
return BusClientLogID;
}
public void setBusClientLogID(int busClientLogID) {
BusClientLogID = busClientLogID;
}
public int getClientID() {
return ClientID;
}
public void setClientID(int clientID) {
ClientID = clientID;
}
public int getClientStatus() {
return ClientStatus;
}
public void setClientStatus(int clientStatus) {
ClientStatus = clientStatus;
}
public int getClientServiceGroup_ClientSiteTherapyID() {
return ClientServiceGroup_ClientSiteTherapyID;
}
public void setClientServiceGroup_ClientSiteTherapyID(
int clientServiceGroup_ClientSiteTherapyID) {
ClientServiceGroup_ClientSiteTherapyID = clientServiceGroup_ClientSiteTherapyID;
}
public String getClientName() {
return ClientName;
}
public void setClientName(String clientName) {
ClientName = clientName;
}
public String getTimeArrive() {
return TimeArrive;
}
public void setTimeArrive(String timeArrive) {
TimeArrive = timeArrive;
}
public String getTimeDepart() {
return TimeDepart;
}
public void setTimeDepart(String timeDepart) {
TimeDepart = timeDepart;
}
public String getSignOutTime() {
return SignOutTime;
}
public void setSignOutTime(String signOutTime) {
SignOutTime = signOutTime;
}
public String getSignInTime() {
return SignInTime;
}
public void setSignInTime(String signInTime) {
SignInTime = signInTime;
}
public String getServiceCompletedCount() {
return ServiceCompletedCount;
}
public void setServiceCompletedCount(String serviceCompletedCount) {
ServiceCompletedCount = serviceCompletedCount;
}
#Override
public int compareTo(Caseload compareCaseload) {
int busClientLogID = ((Caseload) compareCaseload).getBusClientLogID();
return busClientLogID - this.BusClientLogID;
}
}
Please give me a solution.
I doubt the return statement associated with your compare function in the comparator.
You should go by this approach to get the right ordering :
#Override
public int compare(YourClass lhs, YourClass rhs) {
YourClass p1 = (YourClass) lhs;
YourClass p2 = (YourClass) rhs;
int first = p1.ClientName; //use your getter if you want
int second = p2.ClientName;
if (second < first) {
return 1;
}
else if (second > first) {
return -1;
}
else {
return 0;
}
}
If you go by this approach I guess you will get the required ordering after sort.
Edit:
Now I have got the issue, you are using a reference of the original list in newBackup and its not a new list that is why this is happening, use this and you are good to go.
List<Caseload> newBackUp=new ArrayList<Caseload>(mLISTCaseloadsHeads);