Using JAXB with an XML file with many of the same elements - java

I am working on creating a Java class to map an XML file that has multiple same elements. The following XML is an example of what the file looks like:
<TrackBroadcast>
<DateTime>some date</DateTime>
<From>from someone</From>
<To>to someone</To>
<Classification>some type of classification</Classification>
<Command>some type of command</Command>
<MsgId>some id</MsgId>
<Barge attribute1="???" attribute2="???" attribute3="" etc/> --->The Barge.java class explains the attributes
<Barge attribute1="???" attribute2="???" attribute3="" etc/> --->The Barge.java class explains the attributes
<Barge attribute1="???" attribute2="???" attribute3="" etc/> --->The Barge.java class explains the attributes
<Barge attribute1="???" attribute2="???" attribute3="" etc/> --->The Barge.java class explains the attributes
</TrackBroadcast>
My JAXB class can read in the DateTime, From, To, Classification, Command, and MsgId elements but it cannot read in the Barge elements. I have two classes to try to encapsulate the XML but I know I doing something wrong. The two classes are:
#XmlRootElement(name="TrackBroadcast")
public class TrackBroadcast {
String dataTime;
String from;
String to;
String classification;
String command;
String msgId;
List<Barge> barge = new ArrayList<Barge>();
public String getDataTime() {
return dataTime;
}
#XmlElement(name="DateTime")
public void setDataTime(String dataTime) {
this.dataTime = dataTime;
}
public String getFrom() {
return from;
}
#XmlElement(name="From")
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
#XmlElement(name="To")
public void setTo(String to) {
this.to = to;
}
public String getClassification() {
return classification;
}
#XmlElement(name="Classification")
public void setClassification(String classification) {
this.classification = classification;
}
public String getCommand() {
return command;
}
#XmlElement(name="Command")
public void setCommand(String command) {
this.command = command;
}
public String getMsgId() {
return msgId;
}
#XmlElement(name="MsgId")
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public List<Barge> getBarge() {
return barge;
}
public void setBarge(List<Barge> barge) {
this.barge = barge;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TrackBroadcast other = (TrackBroadcast) obj;
if ((this.dataTime == null) ? (other.dataTime != null) : !this.dataTime.equals(other.dataTime)) {
return false;
}
if ((this.from == null) ? (other.from != null) : !this.from.equals(other.from)) {
return false;
}
if ((this.to == null) ? (other.to != null) : !this.to.equals(other.to)) {
return false;
}
if ((this.command == null) ? (other.command != null) : !this.command.equals(other.command)) {
return false;
}
if ((this.msgId == null) ? (other.msgId != null) : !this.msgId.equals(other.msgId)) {
return false;
}
if (this.barge != other.barge && (this.barge == null || !this.barge.equals(other.barge))) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 7;
hash = 43 * hash + (this.dataTime != null ? this.dataTime.hashCode() : 0);
hash = 43 * hash + (this.from != null ? this.from.hashCode() : 0);
hash = 43 * hash + (this.to != null ? this.to.hashCode() : 0);
hash = 43 * hash + (this.classification != null ? this.classification.hashCode() : 0);
hash = 43 * hash + (this.command != null ? this.command.hashCode() : 0);
hash = 43 * hash + (this.msgId != null ? this.msgId.hashCode() : 0);
hash = 43 * hash + (this.barge != null ? this.barge.hashCode() : 0);
for(int i=0; i<barge.size(); i++){
Barge b = barge.get(i);
System.out.println(b.toString());
}
return hash;
}
#Override
public String toString() {
return "TrackBroadcast{" + "dataTime=" + dataTime + ", from=" + from + ", to=" + to + ", classification=" + classification + ", command=" + command + ", msgId=" + msgId + ", barge=" + barge + '}';
}
}
and
#XmlRootElement(name="Barge")
public class Barge {
String misleBargeVesselId;
String bargeName;
String towingVesselName;
String nonVesselName;
String towingVesselPhoneNo;
String towingVesselCompany;
String positionDate;
double latitude;
double longitude;
String waterwayAbbr;
double waterwayMileMarker;
String bargeDirection;
String bargeCdcType;
double bargeCdcQuantity;
String bargeCdcMeasureUnit;
String bargeLoadStatus;
String nextEta;
public String getMisleBargeVesselId() {
return misleBargeVesselId;
}
#XmlAttribute(name="MISLE_Barge_Vessel_Id")
public void setMisleBargeVesselId(String misleBargeVesselId) {
this.misleBargeVesselId = misleBargeVesselId;
}
public String getBargeName() {
return bargeName;
}
#XmlAttribute(name="Barge_Name")
public void setBargeName(String bargeName) {
this.bargeName = bargeName;
}
public String getTowingVesselName() {
return towingVesselName;
}
#XmlAttribute(name="Towing_Vessel_Name")
public void setTowingVesselName(String towingVesselName) {
this.towingVesselName = towingVesselName;
}
public String getNonVesselName() {
return nonVesselName;
}
#XmlAttribute(name="Non_Vessel_Name")
public void setNonVesselName(String nonVesselName) {
this.nonVesselName = nonVesselName;
}
public String getTowingVesselPhoneNo() {
return towingVesselPhoneNo;
}
#XmlAttribute(name="Towing_Vessel_Phone_No")
public void setTowingVesselPhoneNo(String towingVesselPhoneNo) {
this.towingVesselPhoneNo = towingVesselPhoneNo;
}
public String getTowingVesselCompany() {
return towingVesselCompany;
}
#XmlAttribute(name="Towing_Vessel_Company")
public void setTowingVesselCompany(String towingVesselCompany) {
this.towingVesselCompany = towingVesselCompany;
}
public String getPositionDate() {
return positionDate;
}
#XmlAttribute(name="Position_Date")
public void setPositionDate(String positionDate) {
this.positionDate = positionDate;
}
public double getLatitude() {
return latitude;
}
#XmlAttribute(name="Latitude")
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
#XmlAttribute(name="Longitude")
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getWaterwayAbbr() {
return waterwayAbbr;
}
#XmlAttribute(name="Waterway_Abbr")
public void setWaterwayAbbr(String waterwayAbbr) {
this.waterwayAbbr = waterwayAbbr;
}
public double getWaterwayMileMarker() {
return waterwayMileMarker;
}
#XmlAttribute(name="Waterway_Mile_Marker")
public void setWaterwayMileMarker(double waerwayMileMarker) {
this.waterwayMileMarker = waerwayMileMarker;
}
public String getBargeDirection() {
return bargeDirection;
}
#XmlAttribute(name="Barge_Direction")
public void setBargeDirection(String bargeDirection) {
this.bargeDirection = bargeDirection;
}
public String getBargeCdcType() {
return bargeCdcType;
}
#XmlAttribute(name="Barge_CDC_Type")
public void setBargeCdcType(String bargeCdcType) {
this.bargeCdcType = bargeCdcType;
}
public double getBargeCdcQuantity() {
return bargeCdcQuantity;
}
#XmlAttribute(name="Barge_CDC_Quantity")
public void setBargeCdcQuantity(double bargeCdcQuantity) {
this.bargeCdcQuantity = bargeCdcQuantity;
}
public String getBargeCdcMeasureUnit() {
return bargeCdcMeasureUnit;
}
#XmlAttribute(name="Barge_CDC_Measure_Unit")
public void setBargeCdcMeasureUnit(String bargeCdcMeasureUnit) {
this.bargeCdcMeasureUnit = bargeCdcMeasureUnit;
}
public String getBargeLoadStatus() {
return bargeLoadStatus;
}
#XmlAttribute(name="Barge_Load_Status")
public void setBargeLoadStatus(String bargeLoadStatus) {
this.bargeLoadStatus = bargeLoadStatus;
}
public String getNextEta() {
return nextEta;
}
#XmlAttribute(name="Next_ETA")
public void setNextEta(String nextEta) {
this.nextEta = nextEta;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Barge other = (Barge) obj;
if ((this.misleBargeVesselId == null) ? (other.misleBargeVesselId != null) : !this.misleBargeVesselId.equals(other.misleBargeVesselId)) {
return false;
}
if ((this.bargeName == null) ? (other.bargeName != null) : !this.bargeName.equals(other.bargeName)) {
return false;
}
if ((this.towingVesselName == null) ? (other.towingVesselName != null) : !this.towingVesselName.equals(other.towingVesselName)) {
return false;
}
if ((this.nonVesselName == null) ? (other.nonVesselName != null) : !this.nonVesselName.equals(other.nonVesselName)) {
return false;
}
if ((this.towingVesselPhoneNo == null) ? (other.towingVesselPhoneNo != null) : !this.towingVesselPhoneNo.equals(other.towingVesselPhoneNo)) {
return false;
}
if ((this.towingVesselCompany == null) ? (other.towingVesselCompany != null) : !this.towingVesselCompany.equals(other.towingVesselCompany)) {
return false;
}
if ((this.positionDate == null) ? (other.positionDate != null) : !this.positionDate.equals(other.positionDate)) {
return false;
}
if (Double.doubleToLongBits(this.latitude) != Double.doubleToLongBits(other.latitude)) {
return false;
}
if (Double.doubleToLongBits(this.longitude) != Double.doubleToLongBits(other.longitude)) {
return false;
}
if ((this.waterwayAbbr == null) ? (other.waterwayAbbr != null) : !this.waterwayAbbr.equals(other.waterwayAbbr)) {
return false;
}
if (Double.doubleToLongBits(this.waterwayMileMarker) != Double.doubleToLongBits(other.waterwayMileMarker)) {
return false;
}
if ((this.bargeDirection == null) ? (other.bargeDirection != null) : !this.bargeDirection.equals(other.bargeDirection)) {
return false;
}
if ((this.bargeCdcType == null) ? (other.bargeCdcType != null) : !this.bargeCdcType.equals(other.bargeCdcType)) {
return false;
}
if (Double.doubleToLongBits(this.bargeCdcQuantity) != Double.doubleToLongBits(other.bargeCdcQuantity)) {
return false;
}
if ((this.bargeCdcMeasureUnit == null) ? (other.bargeCdcMeasureUnit != null) : !this.bargeCdcMeasureUnit.equals(other.bargeCdcMeasureUnit)) {
return false;
}
if ((this.bargeLoadStatus == null) ? (other.bargeLoadStatus != null) : !this.bargeLoadStatus.equals(other.bargeLoadStatus)) {
return false;
}
if ((this.nextEta == null) ? (other.nextEta != null) : !this.nextEta.equals(other.nextEta)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + (this.misleBargeVesselId != null ? this.misleBargeVesselId.hashCode() : 0);
hash = 17 * hash + (this.bargeName != null ? this.bargeName.hashCode() : 0);
hash = 17 * hash + (this.towingVesselName != null ? this.towingVesselName.hashCode() : 0);
hash = 17 * hash + (this.nonVesselName != null ? this.nonVesselName.hashCode() : 0);
hash = 17 * hash + (this.towingVesselPhoneNo != null ? this.towingVesselPhoneNo.hashCode() : 0);
hash = 17 * hash + (this.towingVesselCompany != null ? this.towingVesselCompany.hashCode() : 0);
hash = 17 * hash + (this.positionDate != null ? this.positionDate.hashCode() : 0);
hash = 17 * hash + (int) (Double.doubleToLongBits(this.latitude) ^ (Double.doubleToLongBits(this.latitude) >>> 32));
hash = 17 * hash + (int) (Double.doubleToLongBits(this.longitude) ^ (Double.doubleToLongBits(this.longitude) >>> 32));
hash = 17 * hash + (this.waterwayAbbr != null ? this.waterwayAbbr.hashCode() : 0);
hash = 17 * hash + (int) (Double.doubleToLongBits(this.waterwayMileMarker) ^ (Double.doubleToLongBits(this.waterwayMileMarker) >>> 32));
hash = 17 * hash + (this.bargeDirection != null ? this.bargeDirection.hashCode() : 0);
hash = 17 * hash + (this.bargeCdcType != null ? this.bargeCdcType.hashCode() : 0);
hash = 17 * hash + (int) (Double.doubleToLongBits(this.bargeCdcQuantity) ^ (Double.doubleToLongBits(this.bargeCdcQuantity) >>> 32));
hash = 17 * hash + (this.bargeCdcMeasureUnit != null ? this.bargeCdcMeasureUnit.hashCode() : 0);
hash = 17 * hash + (this.bargeLoadStatus != null ? this.bargeLoadStatus.hashCode() : 0);
hash = 17 * hash + (this.nextEta != null ? this.nextEta.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "Barge{" + "misleBargeVesselId=" + misleBargeVesselId + ", bargeName=" + bargeName + ", towingVesselName=" + towingVesselName + ", nonVesselName=" + nonVesselName + ", towingVesselPhoneNo=" + towingVesselPhoneNo + ", towingVesselCompany=" + towingVesselCompany + ", positionDate=" + positionDate + ", latitude=" + latitude + ", longitude=" + longitude + ", waterwayAbbr=" + waterwayAbbr + ", waerwayMileMarker=" + waterwayMileMarker + ", bargeDirection=" + bargeDirection + ", bargeCdcType=" + bargeCdcType + ", bargeCdcQuantity=" + bargeCdcQuantity + ", bargeCdcMeasureUnit=" + bargeCdcMeasureUnit + ", bargeLoadStatus=" + bargeLoadStatus + ", nextEta=" + nextEta + '}';
}
}
When I unmarshall the file I can get everything in the TrackBroadcast except for the Barges. I'm new to JAXB and was wondering if anyone could see what I might be doing wrong or if anyone could nudge me in the right direction.

You should just need to add #XmlElement(name="Barge") as by the JAXB (JSR-222) default naming rules JAXB implementations will look for elements with the name barge instead of Barge:
#XmlElement(name="Barge")
public List<Barge> getBarge() {
return barge;
}
For More Information
http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html

Just define JAXB #XmlElement annotation with preferred name over required field setter. Also I think that generating classes from XML Schema is a much better option than manually ensuring mapping contract.

Related

Execute command line equivalent to Runtime.getRuntime().exec(cmd); in JNI C

I was developing an app which had requirement to implement root detection logic, so by researching I found some detection logic in JAVA and had implemented following class.
class RootDetection {
public boolean isDeviceRooted() {
return checkForBinary("su") || checkForBinary("busybox") || checkForMaliciousPaths() || checkSUonPath()
|| detectRootManagementApps() || detectPotentiallyDangerousApps() || detectRootCloakingApps()
|| checkForDangerousProps() || checkForRWPaths()
|| detectTestKeys() || checkSuExists();
}
private boolean detectTestKeys() {
String buildTags = android.os.Build.TAGS;
String buildFinger = Build.FINGERPRINT;
String product = Build.PRODUCT;
String hardware = Build.HARDWARE;
String display = Build.DISPLAY;
System.out.println("Java: build: " + buildTags + "\nFingerprint: " + buildFinger + "\n Product: " + product + "\n Hardware: " + hardware + "\nDisplay: " + display);
return (buildTags != null) && (buildTags.contains("test-keys") || buildFinger.contains("genric.*test-keys") || product.contains("generic") || product.contains("sdk") || hardware.contains("goldfish") || display.contains(".*test-keys"));
}
private boolean detectRootManagementApps() {
return detectRootManagementApps(null);
}
private boolean detectRootManagementApps(String[] additionalRootManagementApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownRootAppsPackages));
if (additionalRootManagementApps != null && additionalRootManagementApps.length > 0) {
packages.addAll(Arrays.asList(additionalRootManagementApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean detectPotentiallyDangerousApps() {
return detectPotentiallyDangerousApps(null);
}
private boolean detectPotentiallyDangerousApps(String[] additionalDangerousApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownDangerousAppsPackages));
if (additionalDangerousApps != null && additionalDangerousApps.length > 0) {
packages.addAll(Arrays.asList(additionalDangerousApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean detectRootCloakingApps() {
return detectRootCloakingApps(null);
}
private boolean detectRootCloakingApps(String[] additionalRootCloakingApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownRootCloakingPackages));
if (additionalRootCloakingApps != null && additionalRootCloakingApps.length > 0) {
packages.addAll(Arrays.asList(additionalRootCloakingApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean checkForBinary(String filename) {
for (String path : suPaths) {
String completePath = path + filename;
File f = new File(completePath);
boolean fileExists = f.exists();
if (fileExists) {
return true;
}
}
return false;
}
private boolean checkForMaliciousPaths() {
for (String path : maliciousPaths) {
File f = new File(path);
boolean fileExists = f.exists();
if (fileExists) {
return true;
}
}
return false;
}
private static boolean checkSUonPath() {
for (String pathDir : System.getenv("PATH").split(":")) {
if (new File(pathDir, "su").exists()) {
return true;
}
}
return false;
}
private String[] propsReader() {
InputStream inputstream = null;
try {
inputstream = Runtime.getRuntime().exec("getprop").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String propval = "";
try {
propval = new Scanner(inputstream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
}
return propval.split("\n");
}
private String[] mountReader() {
InputStream inputstream = null;
try {
inputstream = Runtime.getRuntime().exec("mount").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
if (inputstream == null) return null;
String propval = "";
try {
propval = new Scanner(inputstream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
e.printStackTrace();
}
return propval.split("\n");
}
private boolean isAnyPackageFromListInstalled(List<String> packages) {
PackageManager pm = activity.getPackageManager();
for (String packageName : packages) {
try {
pm.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
}
return false;
}
private boolean checkForDangerousProps() {
final Map<String, String> dangerousProps = new HashMap<>();
dangerousProps.put("ro.debuggable", "1");
dangerousProps.put("ro.secure", "0");
String[] lines = propsReader();
for (String line : lines) {
for (String key : dangerousProps.keySet()) {
if (line.contains(key)) {
String badValue = dangerousProps.get(key);
badValue = "[" + badValue + "]";
if (line.contains(badValue)) {
return true;
}
}
}
}
return false;
}
private boolean checkForRWPaths() {
String[] lines = mountReader();
for (String line : lines) {
String[] args = line.split(" ");
if (args.length < 4) {
continue;
}
String mountPoint = args[1];
String mountOptions = args[3];
for (String pathToCheck : pathsThatShouldNotBeWrtiable) {
if (mountPoint.equalsIgnoreCase(pathToCheck)) {
for (String option : mountOptions.split(",")) {
if (option.equalsIgnoreCase("rw")) {
return true;
}
}
}
}
}
return false;
}
private boolean checkSuExists() {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[]{"which", "su"});
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
return in.readLine() != null;
} catch (Throwable t) {
return false;
} finally {
if (process != null) process.destroy();
}
}
}
but now to increase security I want to do this root detection logic in native C++ JNI code. I managed to migrate package detection code to JNI C but am not able to find anything regarding these 3 functions
checkForDangerousProps(),checkForRWPaths(),checkSuExists()
these 3 use Runtime.getRuntime().exec which am not able to find. can someone help me in converting this 3 logics to JNI C one from above code? Help would be really appreciated.
Pls guys help.

Usage of synchronized with ConcurrentHashMap compound operations(contains+get+put)

Can you please read through below code and help to let me know if i need to use synchronized keyword with the concurrent hash map in this example?
The main problem is i dont understand when a synchronized keyword needs to be used in compound operations in a concurrent hash map.can someone please help
import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
class Pair {
public final Integer x;
public final Integer y;
public Pair(Integer x, Integer y) {
this.x = x;
this.y = y;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.hashCode());
result = prime * result + ((y == null) ? 0 : y.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (x == null) {
if (other.x != null)
return false;
} else if (!x.equals(other.x))
return false;
if (y == null) {
if (other.y != null)
return false;
} else if (!y.equals(other.y))
return false;
return true;
}
}
class Order{
int clOrdId;
int origClOrdId;
String symbol;
int qty;
double price;
#Override
public String toString() {
return "Order [clOrdId=" + clOrdId + ", origClOrdId=" + origClOrdId + ", symbol=" + symbol + ", qty=" + qty
+ ", price=" + price + ", side=" + side + "]";
}
char side;
Order(int clOrdId,String symbol,int qty,double price,char side){
this.clOrdId=clOrdId;
this.symbol=symbol;
this.qty=qty;
this.price=price;
this.side=side;
}
Order(int clOrdId,int origClOrdId,String symbol,int qty,double price,char side){
this.clOrdId=clOrdId;
this.origClOrdId=origClOrdId;
this.symbol=symbol;
this.qty=qty;
this.price=price;
this.side=side;
}
}
class Message {
int sessionId;
Order order;
Message(int sessionId, Order order) {
this.sessionId = sessionId;
this.order = order;
}
#Override
public String toString() {
return "Message [sessionId=" + sessionId + ", order=" + order + "]";
}
}
/*
* Different clients can submit different messages 1. Each message has a
* sessionId and a string msg 2. Each of the messages on a particular session
* need to be processed sequentially
*/
public class Concurrency {
private Map<Integer, BlockingDeque<Runnable>> pendingTasks = new ConcurrentHashMap<>();
private Map<Pair,Order> orderMap = new ConcurrentHashMap<>();
private ExecutorService executorService = Executors.newFixedThreadPool(13);
public void submitMsg(final Message msg) {
submitTask(msg, () -> {
if(msg.order.origClOrdId==0){
print("Received new order msg " + msg);
sleep(1000);
}else{
Pair key = new Pair(msg.sessionId,msg.order.origClOrdId);
if(orderMap.containsKey(key)){
if(isOnlyAggressivePriceMod(msg, key) ){
print("Aggressive price modification "+ msg);
}else if(isOnlyQtyModUp(msg, key)){
print(" Quantity modification up only for "+ msg);
}else if(isOnlyQtyDown(msg, key)){
print(" Quantity modification down only for "+ msg);
}
}
}
orderMap.put(new Pair(msg.sessionId,msg.order.clOrdId), msg.order);
});
}
private boolean isOnlyQtyDown(final Message msg, Pair key) {
return msg.order.qty<orderMap.get(key).qty && Double.compare(msg.order.price,orderMap.get(key).price)==0;
}
private boolean isOnlyQtyModUp(final Message msg, Pair key) {
return msg.order.qty>orderMap.get(key).qty && Double.compare(msg.order.price,orderMap.get(key).price)==0;
}
private boolean isOnlyAggressivePriceMod(final Message msg, Pair key) {
return ((Double.compare(msg.order.price,orderMap.get(key).price)>0 && msg.order.side=='B') ||
(Double.compare(msg.order.price,orderMap.get(key).price)<0 && msg.order.side=='S')) && Double.compare(msg.order.qty,orderMap.get(key).qty)==0;
}
private void sleep(int time){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void print(String msg){
System.out.println(msg);
}
private void submitTask(final Message msg, Runnable task) {
synchronized(pendingTasks){
if (pendingTasks.containsKey(msg.sessionId)) {
pendingTasks.get(msg.sessionId).add(task);
return;
}
}
BlockingDeque<Runnable> pendingTasksPerSession = new LinkedBlockingDeque<Runnable>();
pendingTasksPerSession.push(task);
pendingTasks.put(msg.sessionId, pendingTasksPerSession);
executorService.submit(new SynchronizedTask(msg, task));
}
public class SynchronizedTask implements Runnable {
Message msg;
Runnable task;
public SynchronizedTask(Message msg, Runnable task) {
this.msg = msg;
this.task = task;
}
public void run() {
task.run();
BlockingDeque<Runnable> pendingTasksForSession = pendingTasks.get(msg.sessionId);
if (!pendingTasksForSession.remove(task)) {
return;
}
if (!pendingTasksForSession.isEmpty())
executorService.submit(new SynchronizedTask(msg, pendingTasksForSession.getFirst()));
}
}
public static void main(String args[]) {
Concurrency c = new Concurrency();
for(int i =1;i<10;i++){
c.submitMsg(new Message(i, new Order(10,"0001.HK",2000*i,200+i,'B')));
c.submitMsg(new Message(i, new Order(11,10,"0001.HK",1000*i,200+i,'B')));
c.submitMsg(new Message(i, new Order(12,11,"0001.HK",2000*i,201+i,'B')));
}
for(int i =1;i<10;i++){
c.submitMsg(new Message(i, new Order(10,"0001.HK",2000*i,200+i,'S')));
c.submitMsg(new Message(i, new Order(11,10,"0001.HK",1000*i,200+i,'S')));
c.submitMsg(new Message(i, new Order(12,11,"0001.HK",2000*i,201+i,'S')));
}
}
}

Syntax error on token "(", Type expected after this token

So I've run into some errors during this code, error is down where the keys are so
first but of code is where the error is, it's saying Syntax error on token "(" Type expected after this token, before I had string without the <> and then keys was underlined and the error was different... so not sure what to do.
Here is where the syntax error is:
for (<String> key : keys) {
Object out = map.get(key);
out = saveObject(out, field, cs, path + "." + key, depth);
subCS.set(key, out);
The whole file:
package me.kalo121;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.util.Vector;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public abstract class ConfigObject
{
protected void onLoad(ConfigurationSection cs)
throws Exception
{
for (Field field : getClass().getDeclaredFields()) {
String path = field.getName().replaceAll("_", ".");
if (!doSkip(field))
{
if (cs.isSet(path))
field.set(this, loadObject(field, cs, path));
else
cs.set(path, saveObject(field.get(this), field, cs, path));
}
}
}
protected void onSave(ConfigurationSection cs) throws Exception {
for (Field field : getClass().getDeclaredFields()) {
String path = field.getName().replaceAll("_", ".");
if (!doSkip(field))
{
cs.set(path, saveObject(field.get(this), field, cs, path));
}
}
}
protected Object loadObject(Field field, ConfigurationSection cs, String path) throws Exception {
return loadObject(field, cs, path, 0);
}
protected Object saveObject(Object obj, Field field, ConfigurationSection cs, String path) throws Exception {
return saveObject(obj, field, cs, path, 0);
}
protected Object loadObject(Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
#SuppressWarnings("rawtypes")
Class clazz = getClassAtDepth(field.getGenericType(), depth);
if ((ConfigObject.class.isAssignableFrom(clazz)) && (isConfigurationSection(cs.get(path))))
return getConfigObject(clazz, cs.getConfigurationSection(path));
if ((Location.class.isAssignableFrom(clazz)) && (isJSON(cs.get(path))))
return getLocation((String)cs.get(path));
if ((Vector.class.isAssignableFrom(clazz)) && (isJSON(cs.get(path))))
return getVector((String)cs.get(path));
if ((Map.class.isAssignableFrom(clazz)) && (isConfigurationSection(cs.get(path))))
return getMap(field, cs.getConfigurationSection(path), path, depth);
if ((clazz.isEnum()) && (isString(cs.get(path))))
return getEnum(clazz, (String)cs.get(path));
if ((List.class.isAssignableFrom(clazz)) && (isConfigurationSection(cs.get(path)))) {
#SuppressWarnings("rawtypes")
Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1);
if ((ConfigObject.class.isAssignableFrom(subClazz)) || (Location.class.isAssignableFrom(subClazz)) || (Vector.class.isAssignableFrom(subClazz)) ||
(Map.class.isAssignableFrom(subClazz)) || (List.class.isAssignableFrom(subClazz)) || (subClazz.isEnum())) {
return getList(field, cs.getConfigurationSection(path), path, depth);
}
return cs.get(path);
}
return cs.get(path);
}
#SuppressWarnings("rawtypes")
protected Object saveObject(Object obj, Field field, ConfigurationSection cs, String path, int depth)
throws Exception
{
#SuppressWarnings("rawtypes")
Class clazz = getClassAtDepth(field.getGenericType(), depth);
if ((ConfigObject.class.isAssignableFrom(clazz)) && (isConfigObject(obj)))
return getConfigObject((ConfigObject)obj, path, cs);
if ((Location.class.isAssignableFrom(clazz)) && (isLocation(obj)))
return getLocation((Location)obj);
if ((Vector.class.isAssignableFrom(clazz)) && (isVector(obj)))
return getVector((Vector)obj);
if ((Map.class.isAssignableFrom(clazz)) && (isMap(obj)))
return getMap((Map)obj, field, cs, path, depth);
if ((clazz.isEnum()) && (isEnum(clazz, obj)))
return getEnum((Enum)obj);
if ((List.class.isAssignableFrom(clazz)) && (isList(obj))) {
Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1);
if ((ConfigObject.class.isAssignableFrom(subClazz)) || (Location.class.isAssignableFrom(subClazz)) || (Vector.class.isAssignableFrom(subClazz)) ||
(Map.class.isAssignableFrom(subClazz)) || (List.class.isAssignableFrom(subClazz)) || (subClazz.isEnum())) {
return getList((List)obj, field, cs, path, depth);
}
return obj;
}
return obj;
}
#SuppressWarnings("rawtypes")
protected Class getClassAtDepth(Type type, int depth)
throws Exception
{
if (depth <= 0) {
String className = type.toString();
if ((className.length() >= 6) && (className.substring(0, 6).equalsIgnoreCase("class "))) {
className = className.substring(6);
}
if (className.indexOf("<") >= 0)
className = className.substring(0, className.indexOf("<"));
try
{
return Class.forName(className);
}
catch (ClassNotFoundException ex) {
if (className.equalsIgnoreCase("byte")) return Byte.class;
if (className.equalsIgnoreCase("short")) return Short.class;
if (className.equalsIgnoreCase("int")) return Integer.class;
if (className.equalsIgnoreCase("long")) return Long.class;
if (className.equalsIgnoreCase("float")) return Float.class;
if (className.equalsIgnoreCase("double")) return Double.class;
if (className.equalsIgnoreCase("char")) return Character.class;
if (className.equalsIgnoreCase("boolean")) return Boolean.class;
throw ex;
}
}
depth--;
ParameterizedType pType = (ParameterizedType)type;
Type[] typeArgs = pType.getActualTypeArguments();
return getClassAtDepth(typeArgs[(typeArgs.length - 1)], depth);
}
protected boolean isString(Object obj) {
if ((obj instanceof String)) {
return true;
}
return false;
}
protected boolean isConfigurationSection(Object o) {
try {
return (ConfigurationSection)o != null; } catch (Exception e) {
}
return false;
}
protected boolean isJSON(Object obj)
{
try {
if ((obj instanceof String)) {
String str = (String)obj;
if (str.startsWith("{")) {
return new JSONParser().parse(str) != null;
}
}
return false; } catch (Exception e) {
}
return false;
}
protected boolean isConfigObject(Object obj)
{
try {
return (ConfigObject)obj != null; } catch (Exception e) {
}
return false;
}
protected boolean isLocation(Object obj)
{
try {
return (Location)obj != null; } catch (Exception e) {
}
return false;
}
protected boolean isVector(Object obj)
{
try {
return (Vector)obj != null; } catch (Exception e) {
}
return false;
}
#SuppressWarnings("rawtypes")
protected boolean isMap(Object obj)
{
try
{
return (Map)obj != null; } catch (Exception e) {
}
return false;
}
#SuppressWarnings("rawtypes")
protected boolean isList(Object obj)
{
try
{
return (List)obj != null; } catch (Exception e) {
}
return false;
}
protected boolean isEnum(#SuppressWarnings("rawtypes") Class clazz, Object obj)
{
if (!clazz.isEnum()) return false;
for (Object constant : clazz.getEnumConstants()) {
if (constant.equals(obj)) {
return true;
}
}
return false;
}
protected ConfigObject getConfigObject(#SuppressWarnings("rawtypes") Class clazz, ConfigurationSection cs)
throws Exception
{
ConfigObject obj = (ConfigObject)clazz.newInstance();
obj.onLoad(cs);
return obj;
}
protected Location getLocation(String json) throws Exception {
JSONObject data = (JSONObject)new JSONParser().parse(json);
World world = Bukkit.getWorld((String)data.get("world"));
double x = Double.parseDouble((String)data.get("x"));
double y = Double.parseDouble((String)data.get("y"));
double z = Double.parseDouble((String)data.get("z"));
float pitch = Float.parseFloat((String)data.get("pitch"));
float yaw = Float.parseFloat((String)data.get("yaw"));
Location loc = new Location(world, x, y, z);
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc;
}
protected Vector getVector(String json) throws Exception {
JSONObject data = (JSONObject)new JSONParser().parse(json);
double x = Double.parseDouble((String)data.get("x"));
double y = Double.parseDouble((String)data.get("y"));
double z = Double.parseDouble((String)data.get("z"));
return new Vector(x, y, z);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
protected Map getMap(Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
depth++;
Set keys = cs.getKeys(false);
Map map = new HashMap();
if ((keys != null) && (keys.size() > 0)) {
for (<String> key : keys) {
Object in = cs.get(key);
in = loadObject(field, cs, key, depth);
map.put(key, in);
}
}
return map;
}
protected List<String> getList(Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
depth++;
int listSize = cs.getKeys(false).size();
String key = path;
if (key.lastIndexOf(".") >= 0) {
key = key.substring(key.lastIndexOf("."));
}
List<String> list = new ArrayList<String>();
if (listSize > 0) {
int loaded = 0;
int i = 0;
while (loaded < listSize) {
if (cs.isSet(key + i)) {
Object in = cs.get(key + i);
in = loadObject(field, cs, key + i, depth);
list.add((String) in);
loaded++;
}
i++;
if (i > listSize * 3) loaded = listSize;
}
}
return list;
}
#SuppressWarnings("rawtypes")
protected Enum getEnum(Class clazz, String string) throws Exception
{
if (!clazz.isEnum()) throw new Exception("Class " + clazz.getName() + " is not an enum.");
for (Object constant : clazz.getEnumConstants()) {
if (((Enum)constant).toString().equals(string)) {
return (Enum)constant;
}
}
throw new Exception("String " + string + " not a valid enum constant for " + clazz.getName());
}
protected ConfigurationSection getConfigObject(ConfigObject obj, String path, ConfigurationSection cs)
throws Exception
{
ConfigurationSection subCS = cs.createSection(path);
obj.onSave(subCS);
return subCS;
}
protected String getLocation(Location loc) {
String ret = "{";
ret = ret + "\"world\":\"" + loc.getWorld().getName() + "\"";
ret = ret + ",\"x\":\"" + loc.getX() + "\"";
ret = ret + ",\"y\":\"" + loc.getY() + "\"";
ret = ret + ",\"z\":\"" + loc.getZ() + "\"";
ret = ret + ",\"pitch\":\"" + loc.getPitch() + "\"";
ret = ret + ",\"yaw\":\"" + loc.getYaw() + "\"";
ret = ret + "}";
if (!isJSON(ret)) return getLocationJSON(loc); try
{
getLocation(ret);
} catch (Exception ex) {
return getLocationJSON(loc);
}
return ret;
}
#SuppressWarnings("unchecked")
protected String getLocationJSON(Location loc)
{
JSONObject data = new JSONObject();
data.put("world", loc.getWorld().getName());
data.put("x", String.valueOf(loc.getX()));
data.put("y", String.valueOf(loc.getY()));
data.put("z", String.valueOf(loc.getZ()));
data.put("pitch", String.valueOf(loc.getPitch()));
data.put("yaw", String.valueOf(loc.getYaw()));
return data.toJSONString();
}
protected String getVector(Vector vec) {
String ret = "{";
ret = ret + "\"x\":\"" + vec.getX() + "\"";
ret = ret + ",\"y\":\"" + vec.getY() + "\"";
ret = ret + ",\"z\":\"" + vec.getZ() + "\"";
ret = ret + "}";
if (!isJSON(ret)) return getVectorJSON(vec); try
{
getVector(ret);
} catch (Exception ex) {
return getVectorJSON(vec);
}
return ret;
}
#SuppressWarnings("unchecked")
protected String getVectorJSON(Vector vec)
{
JSONObject data = new JSONObject();
data.put("x", String.valueOf(vec.getX()));
data.put("y", String.valueOf(vec.getY()));
data.put("z", String.valueOf(vec.getZ()));
return data.toJSONString();
}
protected ConfigurationSection getMap(#SuppressWarnings("rawtypes") Map map, Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
depth++;
ConfigurationSection subCS = cs.createSection(path);
#SuppressWarnings("rawtypes")
Set keys = map.keySet();
if ((keys != null) && (keys.size() > 0)) {
for (<String> key : keys) {
Object out = map.get(key);
out = saveObject(out, field, cs, path + "." + key, depth);
subCS.set(key, out);
}
}
return subCS;
}
protected ConfigurationSection getList(#SuppressWarnings("rawtypes") List list, Field field, ConfigurationSection cs, String path, int depth) throws Exception
{
depth++;
ConfigurationSection subCS = cs.createSection(path);
String key = path;
if (key.lastIndexOf(".") >= 0) {
key = key.substring(key.lastIndexOf("."));
}
if ((list != null) && (list.size() > 0)) {
for (int i = 0; i < list.size(); i++) {
Object out = list.get(i);
out = saveObject(out, field, cs, path + "." + key + (i + 1), depth);
subCS.set(key + (i + 1), out);
}
}
return subCS;
}
protected String getEnum(#SuppressWarnings("rawtypes") Enum enumObj)
{
return enumObj.toString();
}
protected boolean doSkip(Field field)
{
return (Modifier.isTransient(field.getModifiers())) || (Modifier.isStatic(field.getModifiers())) || (Modifier.isFinal(field.getModifiers())) ||
(Modifier.isPrivate(field.getModifiers()));
}
}
for (<String> key : keys) { is invalid syntax. The reason for (String key : keys) { didn't work either is that the type of your keys variable is the raw Set, which means you can only iterate over it with for (Object key : keys) {.
If you change Set keys = cs.getKeys(false); to
Set<String> keys = cs.getKeys(false); (assuming this Set contains only Strings), the following with work :
for (String key : keys) {

Refactor the existing code :- put a portion of a code in a method and use that method

The existing fillModel method is as below
#Override
protected void fillModel(final Model model,
final List<FacebookChannelConfig> items) {
final Map<FacebookChannelConfig, Boolean> defaultConfigMap = Maps
.newHashMapWithExpectedSize(items.size());
for (FacebookChannelConfig channelConfig : items) {
if (configRepository.getDefault() != null
&& configRepository.getDefault().getId().toString()
.equals(channelConfig.getId().toString())) {
defaultConfigMap.put(channelConfig, Boolean.TRUE);
} else {
defaultConfigMap.put(channelConfig, Boolean.FALSE);
}
if (channelConfig.getOwner().getId().getId() != userContext
.getOrganization().getId().getId()) {
channelConfig.setName(channelConfig.getName() + "("
+ channelConfig.getOwner().getName() + ")");
}
}
model.addAttribute("isDefault", defaultConfigMap);
}
I have added the following code from above fillModel to *idDefault* method as above.
if (configRepository.getDefault() != null
&& configRepository.getDefault().getId().toString()
.equals(channelConfig.getId().toString())) {
defaultConfigMap.put(channelConfig, Boolean.TRUE);
} else {
defaultConfigMap.put(channelConfig, Boolean.FALSE);
}
I have the isDefault method which returns boolean values as below
private boolean isDefault(final List<FacebookChannelConfig> config) {
if (configRepository.getDefault() != null
&& configRepository.getDefault().getId().toString()
.equals(config.get(0).toString())) {
return true;
}
return false;
}
The above method isDefault is being used inside fillModel method as below
protected void fillModel(final Model model,
final List<FacebookChannelConfig> items) {
final Map<FacebookChannelConfig, Boolean> defaultConfigMap = Maps
.newHashMapWithExpectedSize(items.size());
for (FacebookChannelConfig channelConfig : items) {
defaultConfigMap.put(channelConfig, isDefault(items));
if (channelConfig.getOwner().getId().getId() != userContext.getOrganization().getId().getId()) {
channelConfig.setName(
channelConfig.getName() + "("
+ channelConfig.getOwner().getName()
+ ")");
}
}
model.addAttribute("isDefault", defaultConfigMap);
}
The above usage of defaultConfigMap.put(channelConfig, isDefault(items)); is not correct.
Pleas suggest
You use List where you wanted the element:
Maybe this could work:
private boolean isDefault(final FacebookChannelConfig channelConfig) {
if (configRepository.getDefault() != null
&& configRepository.getDefault().getId().toString()
.equals(channelConfig.getId().toString())) {
return true;
}
return false;
}
and use:
defaultConfigMap.put(channelConfig, isDefault(channelConfig));

Am I serializing/deserializing correctly?

For some reason when I deserialize my quotes ArrayList, I don't get the right object back. I want to make sure that whenever I read/write my object, it will always be the same object.
Serialization code:
private void serializeQuotes(){
FileOutputStream fos;
try {
fos = openFileOutput(Constants.FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotes);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void deserializeQuotes(){
try{
FileInputStream fis = openFileInput(Constants.FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
quotes = (ArrayList<Quote>) ois.readObject();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
Here is my Quote object
package org.stocktwits.model;
import java.io.Serializable;
public class Quote implements Serializable {
private static final long serialVersionUID = 1L;
public String symbol;
public String name;
public String change;
public String percentChange;
public String open;
public String daysHigh;
public String daysLow;
public String volume;
public String peRatio;
public String marketCapitalization;
public String yearHigh;
public String yearLow;
public String lastTradePriceOnly;
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getChange() {
return change;
}
public void setChange(String change) {
this.change = change;
}
public String getPercentChange() {
return percentChange;
}
public void setPercentChange(String percentChange) {
this.percentChange = percentChange;
}
public String getOpen() {
return open;
}
public void setOpen(String open) {
this.open = open;
}
public String getDaysHigh() {
return daysHigh;
}
public void setDaysHigh(String daysHigh) {
this.daysHigh = daysHigh;
}
public String getDaysLow() {
return daysLow;
}
public void setDaysLow(String daysLow) {
this.daysLow = daysLow;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getPeRatio() {
return peRatio;
}
public void setPeRatio(String peRatio) {
this.peRatio = peRatio;
}
public String getMarketCapitalization() {
return marketCapitalization;
}
public void setMarketCapitilization(String marketCapitalization) {
this.marketCapitalization = marketCapitalization;
}
public String getYearHigh() {
return yearHigh;
}
public void setYearHigh(String yearHigh) {
this.yearHigh = yearHigh;
}
public String getYearLow() {
return yearLow;
}
public void setYearLow(String yearLow) {
this.yearLow = yearLow;
}
public String getLastTradePriceOnly() {
return lastTradePriceOnly;
}
public void setLastTradePriceOnly(String lastTradePriceOnly) {
this.lastTradePriceOnly = lastTradePriceOnly;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((change == null) ? 0 : change.hashCode());
result = prime * result
+ ((daysHigh == null) ? 0 : daysHigh.hashCode());
result = prime * result + ((daysLow == null) ? 0 : daysLow.hashCode());
result = prime
* result
+ ((lastTradePriceOnly == null) ? 0 : lastTradePriceOnly
.hashCode());
result = prime
* result
+ ((marketCapitalization == null) ? 0 : marketCapitalization
.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((open == null) ? 0 : open.hashCode());
result = prime * result + ((peRatio == null) ? 0 : peRatio.hashCode());
result = prime * result
+ ((percentChange == null) ? 0 : percentChange.hashCode());
result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
result = prime * result + ((volume == null) ? 0 : volume.hashCode());
result = prime * result
+ ((yearHigh == null) ? 0 : yearHigh.hashCode());
result = prime * result + ((yearLow == null) ? 0 : yearLow.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Quote other = (Quote) obj;
if (change == null) {
if (other.change != null)
return false;
} else if (!change.equals(other.change))
return false;
if (daysHigh == null) {
if (other.daysHigh != null)
return false;
} else if (!daysHigh.equals(other.daysHigh))
return false;
if (daysLow == null) {
if (other.daysLow != null)
return false;
} else if (!daysLow.equals(other.daysLow))
return false;
if (lastTradePriceOnly == null) {
if (other.lastTradePriceOnly != null)
return false;
} else if (!lastTradePriceOnly.equals(other.lastTradePriceOnly))
return false;
if (marketCapitalization == null) {
if (other.marketCapitalization != null)
return false;
} else if (!marketCapitalization.equals(other.marketCapitalization))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (open == null) {
if (other.open != null)
return false;
} else if (!open.equals(other.open))
return false;
if (peRatio == null) {
if (other.peRatio != null)
return false;
} else if (!peRatio.equals(other.peRatio))
return false;
if (percentChange == null) {
if (other.percentChange != null)
return false;
} else if (!percentChange.equals(other.percentChange))
return false;
if (symbol == null) {
if (other.symbol != null)
return false;
} else if (!symbol.equals(other.symbol))
return false;
if (volume == null) {
if (other.volume != null)
return false;
} else if (!volume.equals(other.volume))
return false;
if (yearHigh == null) {
if (other.yearHigh != null)
return false;
} else if (!yearHigh.equals(other.yearHigh))
return false;
if (yearLow == null) {
if (other.yearLow != null)
return false;
} else if (!yearLow.equals(other.yearLow))
return false;
return true;
}
}
Why don't you delete the file in "serializeQuotes()" before writing the object. That way you will be sure, that there will be only one object there.
private void serializeQuotes(){
FileOutputStream fos;
File file = new File(Constants.FILENAME);
if (file.exists()) file.delete();
try {
fos = openFileOutput(file, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotes);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
Or if you do not want to delete file every time, use some kind of iteration when reading obejcts from it.

Categories

Resources