I have the implemented the below and I have not tested it yet with large amount of data.
public class Main {
public static void main(String[] args) {
CombinedData combinedData = new CombinedData();
List<String> nameList = Arrays.asList("x1", "x3", "x2");
nameList.parallelStream().forEach(name -> {
populateDetails(name, combinedData);
});
}
static void log(String str) {
System.out.println(str);
}
static void populateDetails(String name, CombinedData combinedData) {
if (combinedData.getOrg() == null) {
combinedData.setOrg(MyUtil.getOrg(name));
}
if (combinedData.getRawData() != null) {
combinedData.setRawData(combinedData.getRawData() + name);
}
combinedData.addToDetails(new Details(name, MyUtil.getAdd(name)));
}
}
class CombinedData {
private String org;
private List<Details> details;
private String rawData;
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public void addToDetails(Details details) {
this.details.add(details);
}
public List<Details> getDetails() {
return details;
}
public void setDetails(List<Details> details) {
this.details = details;
}
public String getRawData() {
return rawData;
}
public void setRawData(String rawData) {
this.rawData = rawData;
}
}
class Details {
private String name;
private String address;
public Details(
String name,
String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
If you check the line 13 and 16 I need to add the org to combined response only once and I have added the check there and also I need to append the name to the rawData. My question is that since I'm using parallel stream how would that behave.
Im sure there might be a scenario that when threads are in parallel thing might break.
How can I go ahead and handle that scenario?
Related
This api works for inserting and updating but everytim I update the image dissapears so I am trying to say orElse if image not exist set image to existing image any advice pls
#RequestMapping(value = "/updateBank", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<Bank> updateBank(
#RequestPart("bank") #Valid Bank bank,
#RequestPart("file") #Valid Optional<MultipartFile> image) throws IOException {
// routine to update a bank including image
image.ifPresent(pic ->
{
try {
bank.setImage(new Binary(BsonBinarySubType.BINARY, pic.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
});
Bank result = bankRepository.save(bank);
return ResponseEntity.ok().body(result);
}
#Document(collection = "mst_Bank")
public class Bank {
#Id
private String id;
private String name;
private String address;
private String country;
private String region;
private String city;
private String swiftCode;
private String routeCode;
private Binary flag;
private Binary image;
public Bank(String name, String address, String country, String region, String city, String swiftCode,
String routeCode) {
this.name = name;
this.address = address;
this.country = country;
this.region = region;
this.city = city;
this.swiftCode = swiftCode;
this.routeCode = routeCode;
}
public Bank() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSwiftCode() {
return swiftCode;
}
public void setSwiftCode(String swiftCode) {
this.swiftCode = swiftCode;
}
public String getRouteCode() {
return routeCode;
}
public void setRouteCode(String routeCode) {
this.routeCode = routeCode;
}
public Binary getImage() {
return image;
}
public void setImage(Binary image) {
this.image = image;
}
}
/No Point of this
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details./
Use Something like this
#RequestMapping(value = "/updateEntity", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<Entity> updateEntity(#RequestPart("entity") #Valid Entity entity, #RequestPart("file") #Valid Optional<MultipartFile> image) throws IOException {
// routine to update a entity including image
byte[] imageData = null;
if (image.isPresent() && image.get() != null)
imageData = image.get().getBytes();
if (imageData == null && entity.getId() != null) {
Optional<Entity> readEntity = entityRepository.findById(entity.getId());
if (readEntity.get() != null)
imageData = readEntity.get().getImage().getData();
}
if (imageData != null) {
entity.setImage(new Binary(BsonBinarySubType.BINARY, imageData));
}
Entity result = entityRepository.save(entity);
return ResponseEntity.ok().body(result);
}
This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 5 years ago.
I have status like "In consultation","Waiting in Queue". all the data coming from json API and add all that data into array list using Pojo class.then how to sort this array list by Consultation status.
Patient Class:
public class Patient_Get_Set implements Serializable {
private String fullName;
private String age;
private String waitTime;
private String sex;
private String patientID;
private String gender;
private String dateOfBirth;
private String phoneNo;
private String Diagnosis;
private String Email;
private String token_id;
private String priority;
private String consultation_status;
private String case_number;
public String getCase_number() {
return case_number;
}
public void setCase_number(String case_number) {
this.case_number = case_number;
}
public String getConsultation_status() {
return consultation_status;
}
public void setConsultation_status(String consultation_status) {
this.consultation_status = consultation_status;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getToken_id() {
return token_id;
}
public void setToken_id(String token_id) {
this.token_id = token_id;
}
public String getConsultationstatus() {
return consultationstatus;
}
public void setConsultationstatus(String consultationstatus) {
this.consultationstatus = consultationstatus;
}
private String consultationstatus;
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getVisitorType() {
return visitorType;
}
public void setVisitorType(String visitorType) {
this.visitorType = visitorType;
}
private String visitorType;
public String getDiagnosis() {
return Diagnosis;
}
public void setDiagnosis(String diagnosis) {
Diagnosis = diagnosis;
}
private String patientJsonArray;
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setAge(String age) {
this.age = age;
}
public void setWaitTime(String waitTime) {
this.waitTime = waitTime;
}
public String getFullName() {
return fullName;
}
public String getAge() {
return age;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
public String getWaitTime() {
return waitTime;
}
public void setPatientID(String patientID) {
this.patientID = patientID;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getPhoneNo() {
return phoneNo;
}
public String getPatientID() {
return patientID;
}
public void setPatientJsonArray(String patientJsonArray) {
this.patientJsonArray = patientJsonArray;
}
public String getPatientJsonArray() {
return patientJsonArray;
}
public String getGender() {
return gender;
}
}
Here is code what you can use for your custom need -
Collections.sort(list, new Comparator<Patient_Get_Set>() {
#Override
public int compare(final Patient_Get_Set object1, final Patient_Get_Set object2) {
List<String> statusList = new ArrayList();
statusList.add("consultation");statusList.add("queue"); statusList.add("waiting");
return new Integer(statusList.indexOf(object1.getConsultation_status())).compareTo(new Integer(statusList.indexOf(object2.getConsultation_status())));
}
});
add elements in statusList in same order in which order you want pojo class to be sorted.
You can use Collections to sort your array list objects.
for example your list as below.
ArrayList<Patient> list = new ArrayList<Patient>();
Then you can sort list using below code.
Collections.sort(list, new Comparator<Patient>() {
#Override
public int compare(final Patient object1, final Patient object2) {
return object1.getConsultation_status().compareTo(object2.getConsultation_status());
}
});
OR
If you are using Java version 1.8 then you can sort list using below code.
list.stream()
.sorted((object1, object2) -> object1.getConsultation_status().compareTo(object2.getConsultation_status()));
import static java.util.Comparator.comparing;
Collections.sort(list, comparing(MyObject::getStartDate));
compare data with comparing in java8 follow http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html
My json API returns multiple network values, My website displays the first value only, where as my pojo reset for upcoming values and sets itself for last value received, I am trying to change my pojo file in such a way that if the values are already set it reject's or should not accept another pair. I am a newbee in json and jackson so please go easy if I ask more questions about your answer and I am trying to compare the data from json against data from live site.
I have tried this.name = name == null ? this.name : throw_(); but it's not solving the problem.
Example of the pojo -
#JsonIgnoreProperties(ignoreUnknown = true)
public class Networks{
private String banner;
private String description;
private boolean is_locked;
private String logo;
private String name;
private String network_analytics;
private Number network_id;
private String slug;
private String thumbnail_url;
private String url;
public String getBanner(){
return this.banner;
}
public void setBanner(String banner){
this.banner = banner;
}
public String getDescription(){
return this.description;
}
public void setDescription(String description){
this.description = description;
}
public boolean getIs_locked(){
return this.is_locked;
}
public void setIs_locked(boolean is_locked){
this.is_locked = is_locked;
}
public String getLogo(){
return this.logo;
}
public void setLogo(String logo){
this.logo = logo;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name == null ? this.name : throw_();
}
public String getNetwork_analytics(){
return this.network_analytics;
}
public void setNetwork_analytics(String network_analytics){
this.network_analytics = network_analytics;
}
public Number getNetwork_id(){
return this.network_id;
}
public void setNetwork_id(Number network_id){
this.network_id = network_id;
}
public String getSlug(){
return this.slug;
}
public void setSlug(String slug){
this.slug = slug;
}
public String getThumbnail_url(){
return this.thumbnail_url;
}
public void setThumbnail_url(String thumbnail_url){
this.thumbnail_url = thumbnail_url;
}
public String getUrl(){
return this.url;
}
public void setUrl(String url){
this.url = url;
}
public String throw_() {
throw new RuntimeException("Network name is already set, second network not allowed");
}
}
main Pojo class -
#JsonIgnoreProperties(ignoreUnknown = true)
public class JsonGen{
private String _type;
private List cast;
private Common_sense_data common_sense_data;
private String common_sense_id;
private List crew;
private String description;
private Number franchise_id;
private List genres;
private String guid;
#JsonProperty("image")
private Images images;
private boolean is_locked;
private boolean is_mobile;
private boolean is_parental_locked;
private String kind;
private List<String> mobile_networks;
private String most_recent_full_episode_added_date;
private String name;
private List<Networks> networks;
private List<String> platforms;
private List ratings;
private String release_date;
private List season_filters;
private String slug;
private String tms_id;
public JsonGen(){
System.out.println("in JsonGen");
networks = new ArrayList<Networks>();
}
public String get_type(){
return this._type;
}
public void set_type(String _type){
this._type = _type;
}
public List getCast(){
return this.cast;
}
public void setCast(List cast){
this.cast = cast;
}
public Common_sense_data getCommon_sense_data(){
return this.common_sense_data;
}
public void setCommon_sense_data(Common_sense_data common_sense_data){
this.common_sense_data = common_sense_data;
}
public String getCommon_sense_id(){
return this.common_sense_id;
}
public void setCommon_sense_id(String common_sense_id){
this.common_sense_id = common_sense_id;
}
public List getCrew(){
return this.crew;
}
public void setCrew(List crew){
this.crew = crew;
}
public String getDescription(){
return this.description;
}
public void setDescription(String description){
this.description = description;
}
public Number getFranchise_id(){
return this.franchise_id;
}
public void setFranchise_id(Number franchise_id){
this.franchise_id = franchise_id;
}
public List getGenres(){
return this.genres;
}
public void setGenres(List genres){
this.genres = genres;
}
public String getGuid(){
return this.guid;
}
public void setGuid(String guid){
this.guid = guid;
}
public Images getImages(){
return this.images;
}
public void setImages(Images images){
this.images = images;
}
public boolean getIs_locked(){
return this.is_locked;
}
public void setIs_locked(boolean is_locked){
this.is_locked = is_locked;
}
public boolean getIs_mobile(){
return this.is_mobile;
}
public void setIs_mobile(boolean is_mobile){
this.is_mobile = is_mobile;
}
public boolean getIs_parental_locked(){
return this.is_parental_locked;
}
public void setIs_parental_locked(boolean is_parental_locked){
this.is_parental_locked = is_parental_locked;
}
public String getKind(){
return this.kind;
}
public void setKind(String kind){
this.kind = kind;
}
public List<String> getMobile_networks(){
return this.mobile_networks;
}
public void setMobile_networks(List<String> mobile_networks){
this.mobile_networks = mobile_networks;
}
public String getMost_recent_full_episode_added_date(){
return this.most_recent_full_episode_added_date;
}
public void setMost_recent_full_episode_added_date(String most_recent_full_episode_added_date){
this.most_recent_full_episode_added_date = most_recent_full_episode_added_date;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public List getNetworks(){
return this.networks;
}
public void setNetworks(List networks){
System.out.println("in Set NW"+networks);
//System.out.println("in IF NW is null");
this.networks.addAll(networks);
//else {
//System.out.println("in ELse NW is not null");
//throw_();
//}
//this.networks = networks;
}
public List<String> getPlatforms(){
return this.platforms;
}
public void setPlatforms(List<String> platforms){
this.platforms = platforms;
}
public List getRatings(){
return this.ratings;
}
public void setRatings(List ratings){
this.ratings = ratings;
}
public String getRelease_date(){
return this.release_date;
}
public void setRelease_date(String release_date){
this.release_date = release_date;
}
public List getSeason_filters(){
return this.season_filters;
}
public void setSeason_filters(List season_filters){
this.season_filters = season_filters;
}
public String getSlug(){
return this.slug;
}
public void setSlug(String slug){
this.slug = slug;
}
public String getTms_id(){
return this.tms_id;
}
public void setTms_id(String tms_id){
this.tms_id = tms_id;
}
public String throw_() {
System.out.println("Network name is already set, second network not allowed");
throw new RuntimeException("Network name is already set, second network not allowed");
}
}
I have changed my JsonGen code for network list to -
public void setNetworks(List networks) {
Networks.add(networks);
this.networks = networks.subList(0, 1);
}
it adds all the list and the sub-list gives you the first value.
Thanks for voting down the question it really helped my morale.
Well so I'm trying to parse a bit of JSon. I succeeded to parse:
Member.json:
{"member":{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"peter#adress.com "}}
but what if I need to parse:
{"Members":[{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"peter#adress.com"},{"id":645231,"name":"Bill","profileIconId":123,"age":56,"email":"bill#adress.com"}]}
Ofcourse I searched the web, I think, I need to use "List<>" here private List<memberProfile> member;but how do I "get" this from my main class??
I used this to parse the first string:
memeberClass.java
public class memberClass {
private memberProfile member;
public memberProfile getMember() {
return member;
}
public class memberProfile{
int id;
String name;
int profileIconId;
int age;
String email;
//Getter
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getProfileIconId() {
return profileIconId;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
}
memberToJava.java
public class memberToJava {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("...Member.json"));
//convert the json string back to object
memberClass memberObj = gson.fromJson(br, memberClass.class);
System.out.println("Id: " + memberObj.getMember().getId());
System.out.println("Namw: " + memberObj.getMember().getName());
System.out.println("ProfileIconId: " + memberObj.getMember().getProfileIconId());
System.out.println("Age: " + memberObj.getMember().getAge());
System.out.println("Email: " + memberObj.getMember().getEmail());
} catch (IOException e) {
e.printStackTrace();
}
}
}
see below code
MemberClass.java
import java.util.List;
public class MemberClass {
private List<MemberProfile> member;
public List<MemberProfile> getMember() {
return member;
}
public void setMember(List<MemberProfile> member) {
this.member = member;
}
public class MemberProfile {
int id;
String name;
int profileIconId;
int age;
String email;
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 int getProfileIconId() {
return profileIconId;
}
public void setProfileIconId(int profileIconId) {
this.profileIconId = profileIconId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
}
Main Class
import com.google.gson.Gson;
public class MemTest {
public static void main(String[] args) {
String json = "{'member':[{'id':585897,'name':'PhPeter','profileIconId':691,'age':99,'email':'peter#adress.com'},{'id':645231,'name':'Bill','profileIconId':123,'age':56,'email':'bill#adress.com'}]}";
MemberClass memberClass = new Gson().fromJson(json, MemberClass.class);
System.out.println(new Gson().toJson(memberClass));
}
}
Output
{"member":[{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"\u0027peter#adress.com\u0027"},{"id":645231,"name":"Bill","profileIconId":123,"age":56}]}
Hi I made some changes to your application and it seems to work now ! You where quite close alls you need is a wrapper for the array.
public class memberWrapper {
private List<memberClass> Members;
public List<memberClass> getMembers() {
return Members;
}
public void setMembers(List<memberClass> members) {
this.Members = members;
}
}
Then I changed youir original class a little:
public class memberClass {
int id;
String name;
int profileIconId;
int age;
String email;
//Getter
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getProfileIconId() {
return profileIconId;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
and then in the main:
BufferedReader br = new BufferedReader(new FileReader("stuff.json"));
//convert the json string back to object
memberWrapper memberObj = gson.fromJson(br, memberWrapper.class);
System.out.println("Id: " + memberObj.getMembers().get(0).getId());
It should work now the important thing when dealing with JSOn is to just make sure the key matches the name of your variables.
In the java, commons beanutils, try to set property 'address' and 'creditCardList' to object, but it gave me error :
java.lang.NoSuchMethodException: Property 'address' has no setter method in class 'class com.dao.Student'
but I have this method there. The code is here:
public class Main {
public static void main(String[] args) {
Object student = new Student("John");
Object address = new Address("NJ");
try {
PropertyUtils.setProperty(student, "address", address);
//----------
List list = new ArrayList();
Object creditCard = new CreditCard();
list.add(creditCard);
PropertyUtils.setProperty(student, "creditCardList", list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private Address address;
private List<CreditCard> creditCardList;
public Student(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<CreditCard> getCreditCardList() {
return creditCardList;
}
public void setCreditCardList(List<CreditCard> creditCardList) {
this.creditCardList = creditCardList;
}
}
class Address {
private String name;
public Address(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class CreditCard{
private String cardName;
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
}
Your class Student should be a public class , try making it public and rerun your code.
I moved Student to a own file and made it public, that worked fine :)