I'm trying to create an implementation of TransformList that maintains a list of distinct values off a source list. However, I'm a little puzzled on how the implementation should add the distinct values to my hashmap and distinct list that are contained internally. I think my ListChangeListener.change should work though. But how do I intercept any new or removed distinct values and add/remove them to the distinct map and list?
public class DistinctList<E> extends TransformationList<E,E> {
private final ObservableList<E> distinctList = FXCollections.observableArrayList();
private final ConcurrentHashMap<E,E> distinctValues = new ConcurrentHashMap<>();
private final ObservableList<E> source;
public DistinctList(ObservableList<E> source) {
super(source);
this.source = source;
source.stream().filter(s -> attemptAdd(s)).forEach(s -> distinctList.add(s));
}
private boolean attemptAdd(E e) {
final boolean result = distinctValues.putIfAbsent(e,e) == null;
if (result) {
distinctList.add(e);
}
return result;
}
private boolean attemptRemove(E e) {
final boolean result = distinctValues.remove(e, e);
if (result) {
distinctList.remove(e);
}
return result;
}
#Override
protected void sourceChanged(ListChangeListener.Change<? extends E> c) {
fireChange(new ListChangeListener.Change<E>(this) {
#Override
public boolean wasAdded() {
if (c.getAddedSubList().stream().filter(v -> distinctValues.contains(v) == false).findAny().isPresent()) {
return true;
}
else {
return false;
}
}
#Override
public boolean wasRemoved() {
if (c.getRemoved().stream().filter(v -> !source.contains(v)).findAny().isPresent()) {
return true;
}
else {
return false;
}
}
#Override
public boolean wasPermutated() {
return false;
}
#Override
protected int[] getPermutation() {
throw new AssertionError("getPermutation() not implemented");
}
#Override
public List<E> getRemoved() {
return c.getRemoved().stream().filter(v -> !source.contains(v)).collect(Collectors.toList());
}
#Override
public int getFrom() {
return 0;
}
#Override
public int getTo() {
return 0;
}
#Override
public boolean next() {
return c.next();
}
#Override
public void reset() {
c.reset();
}
});
}
#Override
public int getSourceIndex(int index) {
return IntStream.range(0,source.size()).filter(i -> source.get(i).equals(this.get(i))).findAny().orElse(-1);
}
#Override
public E get(int index) {
return distinctList.get(index);
}
#Override
public int size() {
return distinctList.size();
}
}
UPDATE
I kept working with this and I think I figured out where to interact source changes with the distinct value map and list. But when my source list removes a value (and other values with same hashcode/equals still exists), it wrongly removes the value from the distinct values. What am I doing wrong?
public class DistinctList<E> extends TransformationList<E,E> {
private final ObservableList<E> distinctList = FXCollections.observableArrayList();
private final ConcurrentHashMap<E,E> distinctValues = new ConcurrentHashMap<>();
private final ObservableList<E> source;
public DistinctList(ObservableList<E> source) {
super(source);
this.source = source;
source.stream().forEach(s -> attemptAdd(s));
}
private boolean attemptAdd(E e) {
final boolean result = distinctValues.putIfAbsent(e,e) == null;
if (result) {
distinctList.add(e);
}
return result;
}
private boolean attemptRemove(E e) {
final boolean result = distinctValues.remove(e, e);
if (result) {
distinctList.remove(e);
}
return result;
}
#Override
protected void sourceChanged(ListChangeListener.Change<? extends E> c) {
ListChangeListener.Change<E> change = new ListChangeListener.Change<E>(this) {
#Override
public boolean wasAdded() {
if (c.getAddedSubList().stream().filter(v -> source.contains(v)).findAny().isPresent()) {
return true;
}
else {
return false;
}
}
#Override
public boolean wasRemoved() {
if (c.getRemoved().stream().filter(v -> source.contains(v) == false).findAny().isPresent()) {
return true;
}
else {
return false;
}
}
#Override
public boolean wasPermutated() {
return false;
}
#Override
protected int[] getPermutation() {
throw new AssertionError("getPermutation() not implemented");
}
#Override
public List<E> getRemoved() {
return c.getRemoved().stream().filter(v -> source.contains(v) == false)
.collect(Collectors.toList());
}
#Override
public int getFrom() {
return 0;
}
#Override
public int getTo() {
return 0;
}
#Override
public boolean next() {
return c.next();
}
#Override
public void reset() {
c.reset();
}
};
while (c.next()) {
if (c.wasAdded()) {
c.getAddedSubList().stream().filter(v -> !distinctValues.containsKey(v)).peek(a -> System.out.println("ADDING FROM MAP " + a)).forEach(a -> attemptAdd(a));
}
if (c.wasRemoved()) {
c.getRemoved().stream().filter(v -> distinctValues.containsKey(v)).peek(a -> System.out.println("REMOVING FROM MAP " + a)).forEach(a -> attemptRemove(a));
}
}
fireChange(change);
}
#Override
public int getSourceIndex(int index) {
return IntStream.range(0,source.size()).filter(i -> source.get(i).equals(this.get(i))).findAny().orElse(-1);
}
#Override
public E get(int index) {
return distinctList.get(index);
}
#Override
public int size() {
return distinctList.size();
}
}
I think I got it. Let me know if I'm missing anything.
public class DistinctList<E> extends TransformationList<E,E> {
private final ObservableList<E> distinctList = FXCollections.observableArrayList();
private final ConcurrentHashMap<E,E> distinctValues = new ConcurrentHashMap<>();
private final ObservableList<E> source;
public DistinctList(ObservableList<E> source) {
super(source);
this.source = source;
source.stream().forEach(s -> attemptAdd(s));
}
private boolean attemptAdd(E e) {
final boolean result = distinctValues.putIfAbsent(e,e) == null;
if (result) {
distinctList.add(e);
}
return result;
}
private boolean attemptRemove(E e) {
final boolean result = distinctValues.remove(e, e);
if (result) {
distinctList.remove(e);
}
return result;
}
#Override
protected void sourceChanged(ListChangeListener.Change<? extends E> c) {
while (c.next()) {
ListChangeListener.Change<E> change = new ListChangeListener.Change<E>(this) {
#Override
public boolean wasAdded() {
if (c.getAddedSubList().stream().filter(v -> distinctValues.contains(v) == false).findAny().isPresent()) {
return true;
} else {
return false;
}
}
#Override
public List<E> getAddedSubList() {
return c.getAddedSubList().stream().filter(v -> distinctValues.contains(v) == false).collect(Collectors.toList());
}
#Override
public boolean wasRemoved() {
if (c.getRemoved().stream().filter(v -> source.contains(v) == false).findAny().isPresent()) {
return true;
} else {
return false;
}
}
#Override
public boolean wasPermutated() {
return false;
}
#Override
protected int[] getPermutation() {
throw new AssertionError("getPermutation() not implemented");
}
#Override
public List<E> getRemoved() {
return c.getRemoved().stream().filter(v -> source.contains(v) == false)
.collect(Collectors.toList());
}
#Override
public int getFrom() {
return 0;
}
#Override
public int getTo() {
return 0;
}
#Override
public boolean next() {
return c.next();
}
#Override
public void reset() {
c.reset();
}
};
if (change.wasAdded()) {
change.getAddedSubList().stream().filter(v -> !distinctValues.containsKey(v)).peek(a -> System.out.println("ADDING FROM MAP " + a)).forEach(a -> attemptAdd(a));
}
if (change.wasRemoved()) {
change.getRemoved().stream().filter(v -> distinctValues.containsKey(v)).peek(a -> System.out.println("REMOVING FROM MAP " + a)).forEach(a -> attemptRemove(a));
}
fireChange(change);
}
}
#Override
public int getSourceIndex(int index) {
return IntStream.range(0,source.size()).filter(i -> source.get(i).equals(this.get(i))).findAny().orElse(-1);
}
#Override
public E get(int index) {
return distinctList.get(index);
}
#Override
public int size() {
return distinctList.size();
}
}
Related
I have tough problem with my project. Its hard to explain. I have two different model but, I should compare these two model. Should I make a new model for this two models?
Here is Cart.java. There is Voyage.java as a Model. This class differentiate if type_voyage not equals each other. I have another model named Bus.java. I should compare if it equals together with model.
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
ArrayList<Voyage> list = Lists.newArrayList(Collections2.filter(voyages, new Predicate<Voyage>() {
#Override
public boolean apply(Voyage voyage) {
return !voyage.getType_voyage().equals(type_voyage);
}
}));
return list.size() > 0 ? true : false;
}
Bus.java
public class Bus {
private static Bus instance;
private String BROADCAST_TAG = "com.bss.hepsi.bus";
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<BusPassenger> busPasengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_bus;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
boolean isExpanded;
boolean isShowProgress;
public Bus() {
}
public static synchronized Bus getInstance() {
if (instance == null) {
instance = new Bus();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public boolean isExpanded() {
return this.isExpanded;
}
public void setExpanded(boolean expanded) {
this.isExpanded = expanded;
}
public boolean isShowProgress() {
return this.isShowProgress;
}
public void setShowProgress(boolean showProgress) {
this.isShowProgress = showProgress;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_bus() {
return type_bus;
}
public void setType_voyage(String type_bus) {
this.type_bus = type_bus;
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
if (resultReturn.length()<1){
busReturnIsEmpty();}
else{
busReturnIsNotEmpty();
}
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(600 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
private void sendVoyagesArrayBroadcast(String target, JSONArray resultArray) {
Intent intent = new Intent();
intent.setAction(BROADCAST_TAG + target);
intent.putExtra("data", resultArray.toString());
context.sendBroadcast(intent);
}
public static Bus setJsonToClass(JSONObject jsonObject, int direction, String owner) {
Bus bus = new Gson().fromJson(String.valueOf(jsonObject), Bus.class);
bus.setDirection(direction);
bus.setType_voyage(owner);
bus.setDepartureTime(bus.departure_time);
bus.setArrivalTime(bus.arrival_time);
for (Leg leg :
bus.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
bus.type = owner;
return bus;
}
Voyage.java
public class Voyage {
private static Voyage instance;
//private static String url="http://78.186.57.167:3000/";
//private static String url="http://10.0.0.27:1337/";
/////public static final String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///bunu kaldırdım static oldugu için
private String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///onun yerine bunu koydum
//private static String url="http://185.122.203.104:3002/";
// private static String url="http://10.0.0.25:1337/";
public int checkCart; // Result activity'de veri gelip gelmediğini kontrol edip kullanıcıyı uyarmak için
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<FlightPassenger> flightPassengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_voyage;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
public Voyage() {
}
public static synchronized Voyage getInstance() {
if (instance == null) {
instance = new Voyage();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
/*public static String getUrl() {
return url;
}*/
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_voyage() {
return type_voyage;
}
public void setType_voyage(String type_voyage) {
this.type_voyage = type_voyage;
}
public void searchFlightVoyages(Context context) {
this.context = context;
cancelRequest("flight/search", context);
Map<String, String> header = prepareVoyageSearchHeaderForFlight();
sendRequest("flight/search", header);
}
public void searchTrainVoyages(Context context) {
this.context = context;
cancelRequest("train/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("train/search", header);
}
public void searchBoatVoyages(Context context) {
this.context = context;
cancelRequest("seaway/boat/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/boat/search", header);
}
public void searchFerryVoyages(Context context) {
this.context = context;
cancelRequest("seaway/ferry/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/ferry/search", header);
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("AAAA" + owner, response);
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
// servisten gelen cevap not_available ise
//// owner
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
// servisten gösterilebilecek bir sonuç geldiyse
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
// checkCart=0;
// sendCheckCart();
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("AAAA" + owner, String.valueOf(error.getCause()));
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setTag(owner);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
public static Voyage setJsonToClass(JSONObject jsonObject, int direction, String owner) {
//Log.e("jsonobj", String.valueOf(jsonObject));
Voyage voyage = new Gson().fromJson(String.valueOf(jsonObject), Voyage.class);
voyage.setDirection(direction);
voyage.setType_voyage(owner);
voyage.setDepartureTime(voyage.departure_time);
voyage.setArrivalTime(voyage.arrival_time);
for (Leg leg :
voyage.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
voyage.type = owner;
return voyage;
}
When you remove all the code from your question that is superfluous, it makes the problem more obvious.
First I simplified your comparison method:
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
for(Voyage voyage : voyages) {
if(!type_voyage.equals(voyage.getType_voyage()) {
return true;
}
}
}
Then created an interface
interface Voyage {
String getType_voyage();
}
Bus.java
public class Bus implements Voyage {
...
private String type_voyage;
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
And changed Voyage.java to Ferry.java
public class Ferry implements Voyage {
...
private String type_voyage;
...
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
You may want to look at creating some more classes so that your 'model' classes are not doing to much / have so many responsibilities.
I am trying to sort the category arraylist with Collections.sort method but have no luck with it.
Here is my code:
public class Categories implements Parcelable {
private ArrayList<Category> category;
private Recent recent;
public ArrayList<Category> getCategories() {
return this.category;
}
public void setCategory(ArrayList<Category> category) {
this.category = category;
}
public Recent getRecent() {
return this.recent;
}
public void setRecent(Recent recent) {
this.recent = recent;
}
protected Categories(Parcel in) {
if (in.readByte() == 0x01) {
category = new ArrayList<Category>();
in.readList(category, Category.class.getClassLoader());
} else {
category = null;
}
recent = (Recent) in.readValue(Recent.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (category == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(category);
}
dest.writeValue(recent);
}
public static final Parcelable.Creator<Categories> CREATOR = new Parcelable.Creator<Categories>() {
#Override
public Categories createFromParcel(Parcel in) {
return new Categories(in);
}
#Override
public Categories[] newArray(int size) {
return new Categories[size];
}
};
}
You can also use custom comparator:
public class CategoriesComparator implements Comparator<Category> {
#Override
public int compare(Category category1, Category category2) {
return category1.getSomeProperty().compareTo(category2.getSomeProperty());
}
}
When you want to compare call this:
Collections.sort(yourListCategories, new CategoriesComparator());
Hope it helps!
Collections.sort(yourListHere,new Comparator<Categories>() {
#Override
public int compare(Categories lhs, Categories rhs) {
//your sort logic here
return 0;
}
});
Hope this helps.
Code below counts files with certain name. TypeCount is then some number (four for example).
File dir = new File(Environment.getExternalStorageDirectory().toString(), "/AppDir/" );
File[] files=dir.listFiles();
int typeCount = 0;
String type = "dog";
for (int i=0; i<files.length; i++) {
File file = files[i];
String filepath = file.getPath();
if(filepath.contains(type)){
typeCount = typeCount + 1;
}
}
In this code I want to put every path (File) in the List<File>. But when I set typeCount to size of the List I get always zero instead.
File dir = new File(Environment.getExternalStorageDirectory().toString(), "/AppDir/" );
File dir = new File(Environment.getExternalStorageDirectory().toString(), "/AppDir/" );
File[] files=dir.listFiles();
int typeCount = 0;
String typeype = "dog";
List<File> myList;
myList = new List<File>() {
#Override
public void add(int i, File file) {
}
#Override
public boolean add(File file) {
return false;
}
#Override
public boolean addAll(int i, Collection<? extends File> collection) {
return false;
}
#Override
public boolean addAll(Collection<? extends File> collection) {
return false;
}
#Override
public void clear() {
}
#Override
public boolean contains(Object o) {
return false;
}
#Override
public boolean containsAll(Collection<?> collection) {
return false;
}
#Override
public File get(int i) {
return null;
}
#Override
public int indexOf(Object o) {
return 0;
}
#Override
public boolean isEmpty() {
return false;
}
#NonNull
#Override
public Iterator<File> iterator() {
return null;
}
#Override
public int lastIndexOf(Object o) {
return 0;
}
#Override
public ListIterator<File> listIterator() {
return null;
}
#NonNull
#Override
public ListIterator<File> listIterator(int i) {
return null;
}
#Override
public File remove(int i) {
return null;
}
#Override
public boolean remove(Object o) {
return false;
}
#Override
public boolean removeAll(Collection<?> collection) {
return false;
}
#Override
public boolean retainAll(Collection<?> collection) {
return false;
}
#Override
public File set(int i, File file) {
return null;
}
#Override
public int size() {
return 0;
}
#NonNull
#Override
public List<File> subList(int i, int i1) {
return null;
}
#NonNull
#Override
public Object[] toArray() {
return new Object[0];
}
#NonNull
#Override
public <T> T[] toArray(T[] ts) {
return null;
}
};
for (int i=0; i<files.length; i++){
File file = files[i];
String filepath = file.getPath();
if(filepath.contains(type)){
myList.add(file);
}
}
typeCount = myList.size();
What is wrong here?
(And a little off topic - Is path written correctly? I'm not sure about it.)
This method size() will always print 0 because your own List implementation has a wrong returning statement:
#Override
public int size() {
return 0; // Oops!
}
Another thing too, you don't really insert anything in your List because of this:
#Override
public boolean add(File file) {
return false; // Hum...
}
Your methods aren't completed yet to execute the same tasks as a normal List. You better should use ArrayList<File> or List<File> which will have all the right methods and won't require hard work from you. Don't reinvent the wheel ;)
Finally, the path are right declared, but you should test if the files are presents in the folder before executing the code. Something as follows:
File[] files = dir.listFiles();
if (files.length > 0) {
// loop and add to a list
}
in my code i need a ConcurrentLinkedDeque but i want to bind this Deque biiderectional to a TableView in JavaFX or at least the size of the Deque to a PieChart, whats the common way to do something like this. Is there something like a ObservableConcurrentLinkedDeque i could use instead of the ConcurrentLinkedDeque and bind directly to a TableView?
There is no such implementation in the JavaFX library.
Note that it really doesn't make sense to implement a concurrent collection of any kind for use as a backing list for a TableView (or any other JavaFX node that is bound to its state). Once you use this as the backing data for a UI node, it can only be accessed from the JavaFX thread, so making it thread safe is redundant. So you are reduced to asking for an observable list that is also a Deque.
To do this, you could subclass ModifiableObservableListBase, delegating it to a LinkedList, and implement Deque, also delegating those methods to the LinkedList. You just need to be careful to fire changes when you call Deque methods that modify the list. So something like:
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import javafx.collections.ModifiableObservableListBase;
public class ObservableLinkedList<T> extends ModifiableObservableListBase<T> implements Deque<T> {
private final LinkedList<T> list = new LinkedList<>();
#Override
public void addFirst(T e) {
list.addFirst(e);
beginChange();
nextAdd(0, 1);
++modCount ;
endChange();
}
#Override
public void addLast(T e) {
list.addLast(e);
int size = list.size();
beginChange();
nextAdd(size-1, size);
++modCount ;
endChange();
}
#Override
public boolean offerFirst(T e) {
addFirst(e);
return true ;
}
#Override
public boolean offerLast(T e) {
addLast(e);
return true ;
}
#Override
public T removeFirst() {
T old = list.removeFirst() ;
beginChange();
nextRemove(0, old);
++modCount ;
endChange();
return old ;
}
#Override
public T removeLast() {
T old = list.removeLast() ;
beginChange();
nextRemove(list.size(), old);
++modCount ;
endChange();
return old ;
}
#Override
public T pollFirst() {
T result = list.pollFirst();
if (result != null) {
beginChange();
nextRemove(0, result);
++modCount ;
endChange();
}
return result ;
}
#Override
public T pollLast() {
T result = list.pollLast();
if (result != null) {
beginChange();
nextRemove(list.size(), result);
++modCount ;
endChange();
}
return result ;
}
#Override
public T getFirst() {
return list.getFirst() ;
}
#Override
public T getLast() {
return list.getLast() ;
}
#Override
public T peekFirst() {
return list.peekFirst() ;
}
#Override
public T peekLast() {
return list.peekLast() ;
}
#Override
public boolean removeFirstOccurrence(Object o) {
// not efficient: maybe a more efficient way, but we need the index...
int index = list.indexOf(o);
if (index > -1) {
remove(index);
return true ;
} else {
return false ;
}
}
#Override
public boolean removeLastOccurrence(Object o) {
// not efficient: maybe a more efficient way, but we need the index...
int index = list.lastIndexOf(o);
if (index > -1) {
remove(index);
return true ;
} else {
return false ;
}
}
#Override
public boolean offer(T e) {
return offerLast(e);
}
#Override
public T remove() {
return removeFirst();
}
#Override
public T poll() {
return pollFirst();
}
#Override
public T element() {
return getFirst();
}
#Override
public T peek() {
return peekFirst();
}
#Override
public void push(T e) {
addFirst(e);
}
#Override
public T pop() {
return removeFirst();
}
#Override
public Iterator<T> descendingIterator() {
return list.descendingIterator();
}
#Override
public T get(int index) {
return list.get(index);
}
#Override
public int size() {
return list.size();
}
#Override
protected void doAdd(int index, T element) {
list.add(index, element);
}
#Override
protected T doSet(int index, T element) {
return list.set(index, element);
}
#Override
protected T doRemove(int index) {
return list.remove(index);
}
}
Usage example:
ObservableLinkedList<String> list = new ObservableLinkedList<>();
list.addListener((Change<? extends String> c) -> {
while (c.next()) {
if (c.wasAdded()) {
System.out.println("Added from "+c.getFrom()+" to "+c.getTo()+" "+c.getAddedSubList());
}
if (c.wasRemoved()) {
System.out.println("Removed from "+c.getFrom() + " to "+c.getTo()+" "+c.getRemoved());
}
if (c.wasUpdated()) {
System.out.println("Updated");
}
if (c.wasPermutated()) {
System.out.println("Permutated");
}
}
});
list.addAll("Two", "Three", "Four");
list.offerFirst("One");
list.offer("Five");
System.out.println(list.pollFirst());
System.out.println(list.pollLast());
I have created three entity classes whose relation is defined as follows:
Screen -----> has many ConfigurableRows
ConfigurableRows -----> Has many Seats.
When i am trying to persist the Screen Class object no table is getting creating.
I am attaching my entity classes here.
public class Screen {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int screenid;
private String screenName;
#OneToMany(targetEntity=ConfigurableRow.class, mappedBy="screenid", fetch=FetchType.LAZY,cascade= CascadeType.ALL)
private List<ConfigurableRow> rows;
public Screen(){
rows = new ArrayList<ConfigurableRow>(10);
}
public Screen(int rowSize){
rows = new ArrayList<ConfigurableRow>(rowSize);
}
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public int getScreenid() {
return screenid;
}
public void setScreenid(int screenid) {
this.screenid = screenid;
}
public List<ConfigurableRow> getRows() {
return rows;
}
public void setRows(List<ConfigurableRow> rows) {
this.rows = rows;
}
}
public class ConfigurableRow implements List<Seat>, IConfigureRow , IRow {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int rowId;
private int numberOfSeats;
private String rowName;
private String screenName;
private int screenid;
#ElementCollection
List<Seat> seats;
public ConfigurableRow(){
this.numberOfSeats = 10;
this.rowName = "Default";
this.screenName = "Default";
this.seats = new ArrayList<>(numberOfSeats);
}
public ConfigurableRow(int numberOfSeats,String screenName , String rowName){
this.numberOfSeats = numberOfSeats;
this.rowName = rowName;
this.screenName = screenName;
this.seats = new ArrayList<Seat>(numberOfSeats);
}
public int getRowId() {
return rowId;
}
#ManyToOne(targetEntity = Screen.class,fetch = FetchType.LAZY,cascade = CascadeType.ALL)
#JoinColumn (name="screenid",referencedColumnName="screenid",nullable=false,unique=false)
public int getScreenid() {
return screenid;
}
public void setScreenid(int screenid) {
this.screenid = screenid;
}
public List<Seat> getSeats() {
return seats;
}
public void setSeats(List<Seat> seats) {
this.seats = seats;
}
public String getRowName() {
return rowName;
}
public String getScreenName() {
return screenName;
}
#Override
public boolean add(Seat e) {
return seats.add(e);
}
#Override
public boolean addAll(Collection<? extends Seat> c) {
if(c.size() >= numberOfSeats){
throw new IllegalArgumentException("Seat Limit Exceeds!!!!!");
}
else {
return addAll(c);
}
}
#Override
public void clear() {
seats.clear();
}
#Override
public boolean contains(Object o) {
return seats.contains(o);
}
#Override
public boolean containsAll(Collection<?> c) {
return seats.containsAll(c);
}
#Override
public boolean isEmpty() {
return seats.isEmpty();
}
#Override
public Iterator<Seat> iterator() {
return seats.iterator();
}
#Override
public boolean remove(Object o) {
return seats.remove(o);
}
#Override
public boolean removeAll(Collection<?> c) {
return seats.removeAll(c);
}
#Override
public boolean retainAll(Collection<?> c) {
return seats.removeAll(c);
}
#Override
public int size() {
return seats.size();
}
#Override
public Object[] toArray() {
return seats.toArray();
}
#Override
public <T> T[] toArray(T[] a) {
return seats.toArray(a);
}
#Override
public boolean addSeat(Seat seat) {
if(seats.size() >= numberOfSeats){
throw new IllegalArgumentException("Seat Limit Exceeds!!!!!");
} else{
return add(seat);
}
}
#Override
public boolean addSeat(Seat seat, int seatNumber) {
if(seats.size() >= numberOfSeats){
throw new IllegalArgumentException("Seat Limit Exceeds!!!!!");
} else{
add(seatNumber,seat);
return true;
}
}
#Override
public boolean addAll(int index, Collection<? extends Seat> c) {
if(seats.size() + c.size() > numberOfSeats){
throw new IllegalArgumentException();
}
else {
return seats.addAll(index, c);
}
}
#Override
public Seat get(int index) {
return seats.get(index);
}
#Override
public Seat set(int index, Seat element) {
return seats.set(index, element);
}
#Override
public void add(int index, Seat element) {
seats.add(index, element);
}
#Override
public Seat remove(int index) {
return seats.remove(index);
}
#Override
public int indexOf(Object o) {
return seats.indexOf(o);
}
#Override
public int lastIndexOf(Object o) {
return seats.lastIndexOf(o);
}
#Override
public ListIterator<Seat> listIterator() {
return seats.listIterator();
}
#Override
public ListIterator<Seat> listIterator(int index) {
return seats.listIterator(index);
}
#Override
public List<Seat> subList(int fromIndex, int toIndex) {
return seats.subList(fromIndex, toIndex);
}
public int getNumberOfSeats() {
return numberOfSeats;
}
public void setNumberOfSeats(int numberOfSeats) {
this.numberOfSeats = numberOfSeats;
}
public List<Seat> getRowSet() {
return seats;
}
public void setRowSet(List<Seat> rowSet) {
this.seats = rowSet;
}
}
public class Seat implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8083252956190536785L;
/*#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int seatid;*/
private int seatNumber;
private SeatType seatType;
public int getSeatNumber() {
return seatNumber;
}
public void setSeatNumber(int seatNumber) {
this.seatNumber = seatNumber;
}
public SeatType getSeatType() {
return seatType;
}
public void setSeatType(SeatType seatType) {
this.seatType = seatType;
}
}
I am new to hibernate. Kindly let me know what I am doing wrong here.
My Tables are getting created now . But with out any values. Hence foreign key violation error is coming.
I think that is a OneToMany bidirectional relationship so
in the class ConfigurableRow you have to add an object from Screen class with annotation #ManyToOne
#ManyToOne
private Screen screen
i think you should put the onetomany annotation before your getrows() method.
#OneToMany(targetEntity=ConfigurableRow.class, mappedBy="screenid", fetch=FetchType.LAZY,cascade= CascadeType.ALL)
public List<ConfigurableRow> getRows() {
return rows;
}