We are running hazelcast 2.5 as a cluster to replicate objects through applications. There are, at the moment, one producer and 3 consumers. The updates from the writer go as high as 10000 per minute and the consumers read every second searching for updates in the clustered map.The writer is a java native application running under a Debian 8 server with java 7. The hazelcast server is on the same machine as the producer but on an independent application. All the consumers are tomcat 7 apps running under a Debian 8 machine with java 7. The problem we are facing is that in average about 4 percent of the data clustered is reaching the consumer´s end garbled in the shared map. The code for the producer is the following :
Long imei;
Integer clase;
HazelCastobjGpsData datoGps;
HazelCastobjTelemetria datoTelemetria;
Set<HazelCastpkQueue> keys = HazelCast.tmpQueue.keySet();
for (Iterator<HazelCastpkQueue> i = keys.iterator(); i.hasNext();) {
HazelCastpkQueue current = i.next();
clase = current.getClase();
imei = current.getImei();
if (clase == CLASE_GPS) // GPS
{
try {
HazelCast.clienteHC.getLock(imei).lock();
datoGps = (HazelCastobjGpsData) HazelCast.tmpQueue
.remove(current);
HazelCast.instMapGPS.put(current.getImei(), datoGps);
HazelCast.instQueue.put(new HazelCastpkQueue(imei,
CLASE_GPS), CLASE_GPS);
} catch (Throwable t) {
System.out.println("Error HazelCast Gps Update: " + imei
+ " :" + t.getMessage());
if (!HazelCast.clienteHC.isActive()) {
System.out.println("Hazelcast no activo");
}
} finally {
HazelCast.clienteHC.getLock(imei).unlock();
}
} else // Telemetria
{
try {
HazelCast.clienteHC.getLock(imei).lock();
datoTelemetria = (HazelCastobjTelemetria) HazelCast.tmpQueue
.remove(current);
HazelCast.instMapTelemetria.put(new HazelCastpkQueue(imei,
clase), datoTelemetria);
HazelCast.instQueue.put(new HazelCastpkQueue(imei, clase),
clase);
} catch (Throwable t) {
System.out.println("Error HazelCast Telemetria Update: "
+ imei + " :" + t.getMessage());
if (!HazelCast.clienteHC.isActive()) {
System.out.println("Hazelcast no activo");
}
} finally {
HazelCast.clienteHC.getLock(imei).unlock();
}
}
}
Where HazelCastobjGpsData datoGps; is the object to be rescued by the consumers and HazelCast.instMapGPS.put(current.getImei(), datoGps); is the map with problems. It has a long as a key.
The code for the server is the following:
public class HazelServer {
#SuppressWarnings("unused")
private static ConcurrentMap<Long,HazelCastobjGpsData> instMapGPS;
#SuppressWarnings("unused")
private static ConcurrentMap<HazelCastpkQueue,HazelCastobjTelemetria> instMapTelemetria;
#SuppressWarnings("unused")
private static ConcurrentMap<HazelCastpkQueue,Integer> instQueue;
#SuppressWarnings("unused")
private static BlockingQueue<HazelCastpkTisPanicoQueue> tisPanicQueue;
public static void main(final String[] args) {
System.out.println("HazelCast Server init 03/03/2015");
init();
System.out.println("OK");
}
private static void init() {
try {
HazelcastInstance hcServer = Hazelcast.newHazelcastInstance(null);
instMapGPS = hcServer.getMap("gps");
instMapTelemetria = hcServer.getMap("telemetria");
instQueue = hcServer.getMap("colagpstele");
tisPanicQueue = hcServer.getQueue("cola_panico_tis");
} catch (Throwable t) {
System.out.println("Error al tratar de obtener mapas: " + t.getMessage());
}
}
}
The consumers code is the following
public static void fetchHazelCast() {
try {
if (GetHazelCast.isHazelcastActive()) {
double errores = 0;
double count=0;
Set<HazelCastpkQueue> keys = GetHazelCast.hcQueue.keySet();
for (final Iterator<HazelCastpkQueue> i = keys.iterator(); i.hasNext();) {
HazelCastpkQueue currentKey = i.next();
if (currentKey.getClase() == CLASE_GPS) // GPS Base
{
if(Realtime.newGPS(GetHazelCast.hcGPS.get(currentKey.getImei()))){
errores++;
}
count++;
} else // Telemetria
{
Realtime.newTelemetria(GetHazelCast.hcTelemetria.get(currentKey));
}
//count++;
GetHazelCast.hcQueue.remove(currentKey);
currentKey = null;
}
/*ReqInit.logger.warn("Errores "+(double)errores);
ReqInit.logger.warn("Cantidad "+(double)count);
ReqInit.logger.warn("Porcentaje "+(double) ((((double)errores)*100.0f)/(double)count));*/
if(count>0){
double promedio = (double) ((((double)errores)*100.0f)/(double)count);
CloudWatchSubmit.sendMetric("metricasreq", "errores", errores);
CloudWatchSubmit.sendMetric("metricasreq", "cantidad", count);
CloudWatchSubmit.sendMetric("metricasreq", "erroresporcentaje", promedio);
}
keys = null;
} else {
System.out.println("Hazelcast no activo...");
GetHazelCast.contectarHZRealTime();
}
} catch (Exception e) {
e.printStackTrace();
}
}
note that the consumer only takes out the data that has been updated recently, this is done because there is a map whith keys that are been updated, once the data is out thar key is removed from that map.
The following is the code of the object
public class HazelCastobjGpsData implements DataSerializable {
private static final long serialVersionUID = 1L;
private Calendar utc;
private Calendar lastupdate;
private String now = "n/a";
private double latitud = 0.0, longitud = 0.0, altitud = 0.0,
velocidad = 0.0, cog = 0.0, nsat = 4.0, hdop = 2.0, adc1 = -200,
adc2 = -200, adc3 = -200, adc4 = -200, bateria = -1;
private int ignicion, io1 = -1, io2 = -1, io3 = -1, io4 = -1, power = -1,
antirobo = -1, panico = -1;
private long imei = 0L, driverId = -1;
private boolean valid = true;
private long odometro = -1L;
private long horometro = -1L;
private String ip = "N/A";
private long ibutton2 = -1;
private long ibutton3 = -1;
private long ibutton4 = -1;
private long odometroInterno = -1L;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
private double anterior_lat = 0.0;
private double anterior_lon = 0.0;
private double anterior_sog = 0;
private double anterior_cog = 0;
private double anterior_ignicion = 0;
private long anterior_odometro = 0;
private long anterior_horometro = 0;
private long delta_time = 0;
private double delta_dist = 0;
private long trailerId = -1L;
private long tripTime = 0L;
private long horometroInterno = 0L;
public long getHorometroInterno() {
return horometroInterno;
}
public void setHorometroInterno(long horometroInterno) {
this.horometroInterno = horometroInterno;
}
public void setAnterior(HazelCastobjGpsData anterior) {
this.setDelta_dist(Math.round((new Geo(this.latitud, this.longitud)
.distanceKM(new Geo(anterior.getLatitud(), anterior
.getLongitud()))) * 1000));
this.setDelta_time((this.getUTC().getTimeInMillis() - anterior.getUTC()
.getTimeInMillis()) / 1000);
this.setAnterior_cog(anterior.getCOG());
this.setAnterior_sog(anterior.getVelocidad());
this.setAnterior_lat(anterior.getLatitud());
this.setAnterior_lon(anterior.getLongitud());
this.setAnterior_ignicion(anterior.getIgnicion());
}
private boolean fromDB = false;
private int evento = 0; // Por tiempo, curva u otro
public Calendar getUTC() {
return utc;
}
public String getNow() {
return now;
}
public double getLatitud() {
return latitud;
}
public double getLongitud() {
return longitud;
}
public double getAltitud() {
return altitud;
}
public double getVelocidad() {
return velocidad;
}
public double getCOG() {
return cog;
}
public String getCOGtoString() {
String txtDireccion = "";
if ((this.cog >= 0) && (this.cog <= 5)) {
txtDireccion = "Norte";
} else if ((this.cog > 5) && (this.cog <= 85)) {
txtDireccion = "Noreste (NorOriente)";
}
else if ((this.cog > 85) && (this.cog <= 95)) {
txtDireccion = "Este (Oriente)";
} else if ((this.cog > 95) && (this.cog <= 175)) {
txtDireccion = "Sureste (SurOriente)";
}
else if ((this.cog > 175) && (this.cog <= 185)) {
txtDireccion = "Sur";
}
else if ((this.cog > 185) && (this.cog <= 265)) {
txtDireccion = "Suroeste (SurPoniente)";
} else if ((this.cog > 265) && (this.cog <= 275)) {
txtDireccion = "Oeste (Poniente)";
} else if ((this.cog > 275) && (this.cog <= 355)) {
txtDireccion = "Noroeste (NorPoniente)";
}
else if ((this.cog > 355) && (this.cog <= 360)) {
txtDireccion = "Norte";
}
return txtDireccion;
}
public double getNsat() {
return nsat;
}
public double getHdop() {
return hdop;
}
public double getAdc1() {
return adc1;
}
public double getAdc2() {
return adc2;
}
public double getBateria() {
return bateria;
}
public int getIgnicion() {
return ignicion;
}
public int getIo(int index) {
int io_array[] = { 0, this.io1, this.io2, this.io3, this.io4,this.panico };
return io_array[index];
}
public int getIo1() {
return io1;
}
public int getIo2() {
return io2;
}
public int getIo3() {
return io3;
}
public int getIo4() {
return io4;
}
public int getPower() {
return power;
}
public long getHorometro() {
return horometro;
}
public long getOdometro() {
return odometro;
}
public int getEvento() {
return evento;
}
public int getAntirobo() {
return antirobo;
}
public int getPanico() {
return panico;
}
public long getImei() {
return imei;
}
public long getDriverId() {
return driverId;
}
public boolean isValid() {
return valid;
}
public Calendar getLastupdate() {
return lastupdate;
}
public void setLastupdate(Calendar lastupdate) {
this.lastupdate = lastupdate;
}
public HazelCastobjGpsData() {
}
public HazelCastobjGpsData(final GpsData original) {
this.imei = original.getImei();
this.driverId = original.getDriverId();
this.panico = original.getPanico();
this.antirobo = original.getAntirobo();
this.ignicion = original.getIgnicion();
this.now = original.getNow();
this.ip = original.getIpaddress();
if (original.getDriverIdArray() != null
&& original.getDriverIdArray().length == 4) {
this.ibutton2 = original.getDriverIdArray()[1];
this.ibutton3 = original.getDriverIdArray()[2];
this.ibutton4 = original.getDriverIdArray()[3];
} else {
this.ibutton2 = -1;
this.ibutton3 = -1;
this.ibutton4 = -1;
}
if (original.getTimeCalendar() == null || !original.isFullProcessed()
|| original.isOnlyStatus()) {
this.valid = false;
Calendar fecha_gps = Calendar.getInstance(TimeZone
.getTimeZone("UTC"));
fecha_gps.setTimeInMillis(0);
this.utc = fecha_gps;
this.lastupdate = original.getLastUpdate();
} else {
this.utc = original.getTimeCalendar();
this.latitud = original.getLatitud();
this.longitud = original.getLongitud();
this.altitud = original.getAltitud();
this.velocidad = original.getVelocidad();
this.cog = original.getCOG();
this.nsat = original.getNSAT();
this.io1 = original.getIo1();
this.io2 = original.getIo2();
this.io3 = original.getIo3();
this.io4 = original.getIo4();
this.hdop = original.getHdop();
this.adc1 = original.getAdc();
this.adc2 = original.getAdc2();
this.power = original.getPower();
this.bateria = original.getBateria();
this.odometro = original.getOdometro();
this.horometro = original.getHorometro();
this.evento = original.getEvento();
this.setTrailerId(original.getTrailerId());
this.setTripTime(original.getTripTime());
this.setHorometroInterno(original.getHorometroInterno());
}
}
// Para INIT por BD
public HazelCastobjGpsData(final boolean fromDB, final long imei,
final String registro, final Calendar utc,
final Calendar lastupdate, final long driverid,
final double latitud, final double longitud, final double altitud,
final double velocidad, final double cog, final double nsat,
final double hdop, final double adc1, final double adc2,
final double adc3, final double adc4, final double bateria,
final int ignicion, final int io1, final int io2, final int io3,
final int io4, final int power, final int antirobo,
final int panico, final long odometro, final long horometro,
final int evento) {
this.imei = imei;
this.driverId = driverid;
this.panico = panico;
this.antirobo = antirobo;
this.ignicion = ignicion;
this.now = registro;
this.utc = utc;
this.lastupdate = lastupdate;
this.latitud = latitud;
this.longitud = longitud;
this.altitud = altitud;
this.velocidad = velocidad;
this.cog = cog;
this.nsat = nsat;
this.io1 = io1;
this.io2 = io2;
this.io3 = io3;
this.io4 = io4;
this.hdop = hdop;
this.adc1 = adc1;
this.adc2 = adc2;
this.adc3 = adc3;
this.adc4 = adc4;
this.power = power;
this.bateria = bateria;
this.horometro = horometro;
this.odometro = odometro;
this.setFromDB(fromDB);
}
#Override
public void readData(final DataInput arg0) throws IOException {
this.utc = Calendar.getInstance();
try {
this.utc.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.parse(arg0.readUTF()));
} catch (ParseException e) {
ReqInit.logger.fatal(e.getMessage(), e);
}
this.lastupdate = Calendar.getInstance();
try {
this.lastupdate.setTime(new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS").parse(arg0.readUTF()));
} catch (ParseException e) {
ReqInit.logger.fatal(e.getMessage(), e);
}
this.now = arg0.readUTF();
this.latitud = arg0.readDouble();
this.longitud = arg0.readDouble();
this.altitud = arg0.readDouble();
this.velocidad = arg0.readDouble();
this.cog = arg0.readDouble();
this.nsat = arg0.readDouble();
this.hdop = arg0.readDouble();
this.adc1 = arg0.readDouble();
this.adc2 = arg0.readDouble();
this.adc3 = arg0.readDouble();
this.adc4 = arg0.readDouble();
this.bateria = arg0.readDouble();
this.ignicion = arg0.readInt();
this.io1 = arg0.readInt();
this.io2 = arg0.readInt();
this.io3 = arg0.readInt();
this.io4 = arg0.readInt();
this.power = arg0.readInt();
this.antirobo = arg0.readInt();
this.panico = arg0.readInt();
this.imei = arg0.readLong();
this.driverId = arg0.readLong();
this.valid = arg0.readBoolean();
this.odometro = arg0.readLong();
this.horometro = arg0.readLong();
this.evento = arg0.readInt();
this.ip = arg0.readUTF();
this.trailerId = arg0.readLong();
this.tripTime = arg0.readLong();
this.horometroInterno = arg0.readLong();
this.ibutton2 = arg0.readLong();
this.ibutton3 = arg0.readLong();
this.ibutton4 = arg0.readLong();
this.odometroInterno = arg0.readLong();
}
#Override
public void writeData(final DataOutput arg0) throws IOException {
arg0.writeUTF(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(utc.getTime()));
arg0.writeUTF(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(lastupdate.getTime()));
arg0.writeUTF(now);
arg0.writeDouble(latitud);
arg0.writeDouble(longitud);
arg0.writeDouble(altitud);
arg0.writeDouble(velocidad);
arg0.writeDouble(cog);
arg0.writeDouble(nsat);
arg0.writeDouble(hdop);
arg0.writeDouble(adc1);
arg0.writeDouble(adc2);
arg0.writeDouble(adc3);
arg0.writeDouble(adc4);
arg0.writeDouble(bateria);
arg0.writeInt(ignicion);
arg0.writeInt(io1);
arg0.writeInt(io2);
arg0.writeInt(io3);
arg0.writeInt(io4);
arg0.writeInt(power);
arg0.writeInt(antirobo);
arg0.writeInt(panico);
arg0.writeLong(imei);
arg0.writeLong(driverId);
arg0.writeBoolean(valid);
arg0.writeLong(odometro);
arg0.writeLong(horometro);
arg0.writeInt(evento);
arg0.writeUTF(ip);
arg0.writeLong(trailerId);
arg0.writeLong(tripTime);
arg0.writeLong(horometroInterno);
arg0.writeLong(ibutton2);
arg0.writeLong(ibutton3);
arg0.writeLong(ibutton4);
arg0.writeLong(odometroInterno);
}
public boolean isFromDB() {
return fromDB;
}
public void setFromDB(boolean fromDB) {
this.fromDB = fromDB;
}
public long getDeltaTime() {
return delta_time;
}
private void setDelta_time(long delta_time) {
this.delta_time = delta_time;
}
public double getAnteriorSog() {
return anterior_sog;
}
private void setAnterior_sog(double anterior_sog) {
this.anterior_sog = anterior_sog;
}
public double getAnterior_lon() {
return anterior_lon;
}
private void setAnterior_lon(double anterior_lon) {
this.anterior_lon = anterior_lon;
}
public double getAnterior_lat() {
return anterior_lat;
}
private void setAnterior_lat(double anterior_lat) {
this.anterior_lat = anterior_lat;
}
public double getAnteriorCog() {
return anterior_cog;
}
private void setAnterior_cog(double anterior_cog) {
this.anterior_cog = anterior_cog;
}
public double getAnteriorIgnicion() {
return anterior_ignicion;
}
private void setAnterior_ignicion(double anterior_ignicion) {
this.anterior_ignicion = anterior_ignicion;
}
public double getDeltaDist() {
return delta_dist;
}
private void setDelta_dist(double delta_dist) {
this.delta_dist = delta_dist;
}
public long getAnterior_odometro() {
return anterior_odometro;
}
public long getAnterior_horometro() {
return anterior_horometro;
}
public double getAdc3() {
return adc3;
}
public void setAdc3(double adc3) {
this.adc3 = adc3;
}
public double getAdc4() {
return adc4;
}
public void setAdc4(double adc4) {
this.adc4 = adc4;
}
public long getTrailerId() {
return trailerId;
}
public void setTrailerId(long trailerId) {
this.trailerId = trailerId;
}
public long getTripTime() {
return tripTime;
}
public void setTripTime(long tripTime) {
this.tripTime = tripTime;
}
public long getIbutton2() {
return ibutton2;
}
public void setIbutton2(long ibutton2) {
this.ibutton2 = ibutton2;
}
public long getIbutton3() {
return ibutton3;
}
public void setIbutton3(long ibutton3) {
this.ibutton3 = ibutton3;
}
public long getIbutton4() {
return ibutton4;
}
public void setIbutton4(long ibutton4) {
this.ibutton4 = ibutton4;
}
public long getOdometroInterno() {
return odometroInterno;
}
public void setOdometroInterno(long odometroInterno) {
this.odometroInterno = odometroInterno;
}
}
We are aware that we are using and older version of hazelcast but upgrade it is not an option yet, we want to know if there is a code issue first. Could you please help me to find the issue ?
Related
I have an arraylist of object type:
public static ArrayList crimes = new ArrayList();
The CityCrime.java has the following:
public class CityCrime {
//Instance variables
private String city;
private String state;
private int population;
private int murder;
private int robbery;
private int assault;
private int burglary;
private int larceny;
private int motorTheft;
public int totalCrimes;
public static void main(String[] args) {
}
public int getTotalCrimes() {
return totalCrimes;
}
public void setTotalCrimes(int murder, int robbery, int assault, int burglary, int larceny, int motorTheft) {
this.totalCrimes = murder + robbery + assault + burglary + larceny + motorTheft;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
if(state.equalsIgnoreCase("ALABAMA")) {
this.state = "AL";
}
else if(state.equalsIgnoreCase("ALASKA")) {
this.state = "AK";
}
else if(state.equalsIgnoreCase("ARIZONA")) {
this.state = "AR";
}
//etc
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getMurder() {
return murder;
}
public void setMurder(int murder) {
this.murder = murder;
}
public int getRobbery() {
return robbery;
}
public void setRobbery(int robbery) {
this.robbery = robbery;
}
public int getAssault() {
return assault;
}
public void setAssault(int assault) {
this.assault = assault;
}
public int getBurglary() {
return burglary;
}
public void setBurglary(int burglary) {
this.burglary = burglary;
}
public int getLarceny() {
return larceny;
}
public void setLarceny(int larceny) {
this.larceny = larceny;
}
public int getMotorTheft() {
return motorTheft;
}
public void setMotorTheft(int motorTheft) {
this.motorTheft = motorTheft;
}
public static void showAllMurderDetails() {
for (CityCrime crime : StartApp.crimes) {
System.out.println("Crime: City= " + crime.getCity() + ", Murder= " + crime.getMurder());
}
System.out.println();
}
public static int showAllViolentCrimes() {
int total = 0;
for(CityCrime crime : StartApp.crimes) {
total=total+crime.getMurder();
total=total+crime.getRobbery();
total=total+crime.getAssault();
}
System.out.println("Total of violent crimes: " + total);
return total;
}
public static int getPossessionCrimes() {
int total=0;
for (CityCrime crime : StartApp.crimes) {
total = total + crime.getBurglary();
total = total + crime.getLarceny();
total = total + crime.getMotorTheft();
}
System.out.println("Total of possession crimes: " + total);
return total;
}
}
The CityCrime ArrayList gets popular from another csv file:
public static void readCrimeData() {
File file = new File("crimeUSA.csv");
FileReader fileReader;
BufferedReader bufferedReader;
String crimeInfo;
String[] stats;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
crimeInfo = bufferedReader.readLine();
crimeInfo = bufferedReader.readLine();
do {
CityCrime crime = new CityCrime(); // Default constructor
stats = crimeInfo.split(",");
{
if (stats[0] != null) {
crime.setCity(stats[0]);
}
if (stats[1] != null) {
crime.setState(stats[1]);
}
if (stats[2] != null) {
if (Integer.parseInt(stats[2]) >= 0) {
crime.setPopulation(Integer.parseInt(stats[2]));
}
}
if (stats[3] != null) {
if (Integer.parseInt(stats[3]) >= 0) {
crime.setMurder(Integer.parseInt(stats[3]));
}
}
if (stats[4] != null) {
if (Integer.parseInt(stats[4]) >= 0) {
crime.setRobbery(Integer.parseInt(stats[4]));
}
}
if (stats[5] != null) {
if (Integer.parseInt(stats[5]) >= 0) {
crime.setAssault(Integer.parseInt(stats[5]));
}
}
if (stats[6] != null) {
if (Integer.parseInt(stats[6]) >= 0) {
crime.setBurglary(Integer.parseInt(stats[6]));
}
}
if (stats[7] != null) {
if (Integer.parseInt(stats[7]) >= 0) {
crime.setLarceny(Integer.parseInt(stats[7]));
}
}
if (stats[8] != null) {
if (Integer.parseInt(stats[8]) >= 0) {
crime.setMotorTheft(Integer.parseInt(stats[8]));
}
}
crime.setTotalCrimes(Integer.parseInt(stats[3]), Integer.parseInt(stats[4]), Integer.parseInt(stats[5]), Integer.parseInt(stats[6]), Integer.parseInt(stats[7]), Integer.parseInt(stats[8]));
}
crimes.add(crime);
System.out.println(crime);
crimeInfo = bufferedReader.readLine();
} while (crimeInfo != null);
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I want to sort the array list and output to the csv file the list of robberies in descending order with the corresponding city. So far I have got the following, but I am stuck and not sure if going in the right direction. I'm relatively new to Java as you can probably tell so would appreciate it in as simple terms as can be:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
FileWriter fileWriter = new FileWriter(csvFile);
ArrayList<Integer> robberyRates = new ArrayList();
for(CityCrime crime : crimes) {
robberyRates.add(crime.getRobbery());
}
Collections.sort(robberyRates);
}
The desired output will be for example:
Robbery,City
23511,New York
15863,Chicago
14353,Los Angeles
11371,Houston
10971,Philadelphia
etc…
Your help is appreciated. I have searched any page I can find on Google, but all I see from other example is writing to the csv from a set String ArrayList where they know the number of lines etc. Thankyou
You can try something like this:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
try(FileWriter fileWriter = new FileWriter(csvFile)) { // try-with-resources to be sure that fileWriter will be closed at end
StringBuilder stringBuilder = new StringBuilder(); // Betther than String for multiple concatenation
crimes.sort(Comparator.comparingInt(CityCrime::getRobbery).reversed()); // I want to compare according to getRobbery, as Int, in reversed order
stringBuilder.append("Robbery")
.append(',')
.append("City")
.append(System.lineSeparator()); // To get new line character according to OS
for (final var crime : crimes)
stringBuilder.append(crime.getRobbery())
.append(',')
.append(crime.getCity())
.append(System.lineSeparator());
fileWriter.write(stringBuilder.toString());
}
}
If you are stuck because you can't figure out how to write a list, convert your list into a String and print the String instead.
I commented the piece of code, if you have any questions, don't hesitate.
Another solution is to use specific CSV parser library, OpenCSV for example.
It makes it easier to read and write CSV file.
Here a tutorial about OpenCSV:
https://mkyong.com/java/how-to-read-and-parse-csv-file-in-java/
I would like to get the value of from context in a new [java simple class] by inspiring from the seconde generated [talend class] :
I couldn't get filepath value because TALEND CLASS seems a little bit difficult to me ^^
My new java class
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import sapphire.util.DataSet;
public class LHCM_FX {
public static void main(String[] args) {
// Trying to get filepath here from context as TALEND JAVA GENERATED CLASS DO
String filepath = "C:/Users/Administrator/Desktop/Test/";
System.out.println("xmldataset=" + parseFXFile(filepath+"0.txt").toXML());
}
public static DataSet parseFXFile(String filepath) {
// Something Codes Here
}
TALEND GENERATED CLASS where filepath is declared
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import routines.LHCM_FX_ROUTINE;
import routines.TalendString;
import routines.system.IPersistableRow;
import routines.system.ResumeUtil;
import routines.system.TDieException;
import sapphire.util.DataSet;
public class LHCM_FX {
public final Object obj = new Object();
private Object valueObject = null;
private static final String defaultCharset = Charset.defaultCharset().name();
private static final String utf8Charset = "UTF-8";
private Properties defaultProps = new Properties();
private LHCM_FX.ContextProperties context = new LHCM_FX.ContextProperties();
private final String jobVersion = "0.1";
private final String jobName = "LHCM_FX";
private final String projectName = "CETEMCO";
public Integer errorCode = null;
private String currentComponent = "";
private final Map<String, Long> start_Hash = new HashMap();
private final Map<String, Long> end_Hash = new HashMap();
private final Map<String, Boolean> ok_Hash = new HashMap();
private final Map<String, Object> globalMap = new HashMap();
public final List<String[]> globalBuffer = new ArrayList();
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final PrintStream errorMessagePS;
private Exception exception;
public String resuming_logs_dir_path;
public String resuming_checkpoint_path;
public String parent_part_launcher;
private String resumeEntryMethodName;
private boolean globalResumeTicket;
public boolean watch;
public Integer portStats;
public int portTraces;
public String clientHost;
public String defaultClientHost;
public String contextStr;
public String pid;
public String rootPid;
public String fatherPid;
public String fatherNode;
public long startTime;
public boolean isChildJob;
private boolean execStat;
private ThreadLocal threadLocal;
private Properties context_param;
public Map<String, Object> parentContextMap;
public String status;
ResumeUtil resumeUtil;
public LHCM_FX() {
this.errorMessagePS = new PrintStream(new BufferedOutputStream(this.baos));
this.exception = null;
this.resuming_logs_dir_path = null;
this.resuming_checkpoint_path = null;
this.parent_part_launcher = null;
this.resumeEntryMethodName = null;
this.globalResumeTicket = false;
this.watch = false;
this.portStats = null;
this.portTraces = 4334;
this.defaultClientHost = "localhost";
this.contextStr = "Default";
this.pid = "0";
this.rootPid = null;
this.fatherPid = null;
this.fatherNode = null;
this.startTime = 0L;
this.isChildJob = false;
this.execStat = true;
this.threadLocal = new ThreadLocal();
Map threadRunResultMap = new HashMap();
threadRunResultMap.put("errorCode", (Object)null);
threadRunResultMap.put("status", "");
this.threadLocal.set(threadRunResultMap);
this.context_param = new Properties();
this.parentContextMap = new HashMap();
this.status = "";
this.resumeUtil = null;
}
public Object getValueObject() {
return this.valueObject;
}
public void setValueObject(Object valueObject) {
this.valueObject = valueObject;
}
public LHCM_FX.ContextProperties getContext() {
return this.context;
}
public String getExceptionStackTrace() {
if ("failure".equals(this.getStatus())) {
this.errorMessagePS.flush();
return this.baos.toString();
} else {
return null;
}
}
public Exception getException() {
return "failure".equals(this.getStatus()) ? this.exception : null;
}
public void tJavaFlex_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tJavaFlex_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tLogRow_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tLogRow_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tLabVantageLIMSCIPostData_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tJavaFlex_1_onSubJobError(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.resumeUtil.addLog("SYSTEM_LOG", "NODE:" + errorComponent, "", String.valueOf(Thread.currentThread().getId()), "FATAL", "", exception.getMessage(), ResumeUtil.getExceptionStackTrace(exception), "");
}
public void tJavaFlex_1Process(Map<String, Object> globalMap) throws LHCM_FX.TalendException {
globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", 0);
boolean execStat = this.execStat;
String iterateId = "";
String currentComponent = "";
try {
String currentMethodName = (new Exception()).getStackTrace()[0].getMethodName();
boolean resumeIt = currentMethodName.equals(this.resumeEntryMethodName);
if (this.resumeEntryMethodName == null || resumeIt || this.globalResumeTicket) {
this.globalResumeTicket = true;
LHCM_FX.row1Struct row1 = new LHCM_FX.row1Struct();
this.ok_Hash.put("tLabVantageLIMSCIPostData_1", false);
this.start_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
currentComponent = "tLabVantageLIMSCIPostData_1";
int tos_count_tLabVantageLIMSCIPostData_1 = 0;
DataSet dsData_tLabVantageLIMSCIPostData_1 = new DataSet();
dsData_tLabVantageLIMSCIPostData_1.addColumn("sdcid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("keyid1", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("paramlistid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("variantid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("paramtype", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("instrumentfield", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("value", 0);
this.ok_Hash.put("tLogRow_1", false);
this.start_Hash.put("tLogRow_1", System.currentTimeMillis());
currentComponent = "tLogRow_1";
int tos_count_tLogRow_1 = 0;
this.ok_Hash.put("tJavaFlex_1", false);
this.start_Hash.put("tJavaFlex_1", System.currentTimeMillis());
currentComponent = "tJavaFlex_1";
int tos_count_tJavaFlex_1 = 0;
DataSet ds = LHCM_FX_ROUTINE.parseFXFile(this.context.filepath);
int i_tLabVantageLIMSCIPostData_1;
String keyid1;
String instrumentfield;
for(int i = 0; i < ds.getRowCount(); ++i) {
currentComponent = "tJavaFlex_1";
row1.sdcid = ds.getValue(i, "sdcid", "");
row1.keyid1 = ds.getValue(i, "keyid1", "");
row1.paramlistid = ds.getValue(i, "paramlistid", "");
row1.variantid = ds.getValue(i, "variantid", "");
row1.paramtype = ds.getValue(i, "paramtype", "");
row1.instrumentfield = ds.getValue(i, "instrumentfield", "");
row1.value = ds.getValue(i, "value", "");
++tos_count_tJavaFlex_1;
currentComponent = "tLogRow_1";
++tos_count_tLogRow_1;
currentComponent = "tLabVantageLIMSCIPostData_1";
i_tLabVantageLIMSCIPostData_1 = dsData_tLabVantageLIMSCIPostData_1.addRow();
keyid1 = "";
instrumentfield = "";
keyid1 = "sdcid";
instrumentfield = row1.sdcid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "keyid1";
instrumentfield = row1.keyid1;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "paramlistid";
instrumentfield = row1.paramlistid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "variantid";
instrumentfield = row1.variantid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "paramtype";
instrumentfield = row1.paramtype;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "instrumentfield";
instrumentfield = row1.instrumentfield;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "value";
instrumentfield = row1.value;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
++tos_count_tLabVantageLIMSCIPostData_1;
currentComponent = "tJavaFlex_1";
}
this.ok_Hash.put("tJavaFlex_1", true);
this.end_Hash.put("tJavaFlex_1", System.currentTimeMillis());
currentComponent = "tLogRow_1";
this.ok_Hash.put("tLogRow_1", true);
this.end_Hash.put("tLogRow_1", System.currentTimeMillis());
currentComponent = "tLabVantageLIMSCIPostData_1";
String sWarningMessages_tLabVantageLIMSCIPostData_1 = "";
if ("LIMS CI".equals("LIMS CI") && (!dsData_tLabVantageLIMSCIPostData_1.isValidColumn("sdcid") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("keyid1") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("instrumentfield") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("value"))) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + "Error : In 'LIMS CI' case, the columns sdcid, keyid1, instrumentfield and value are mandatory. Please change the component schema.";
}
if ("LIMS CI".equals("Protocol Provider") && (!dsData_tLabVantageLIMSCIPostData_1.isValidColumn("instrumentfield") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("value"))) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + "Error : In 'Protocol Provider' case, the columns instrumentfield and value are mandatory. Please change the component schema.";
}
if (sWarningMessages_tLabVantageLIMSCIPostData_1.equals("")) {
for(i_tLabVantageLIMSCIPostData_1 = 0; i_tLabVantageLIMSCIPostData_1 < dsData_tLabVantageLIMSCIPostData_1.getRowCount(); ++i_tLabVantageLIMSCIPostData_1) {
keyid1 = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, "keyid1", "null");
instrumentfield = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, "instrumentfield", "null");
if ((!"LIMS CI".equals("LIMS CI") || !keyid1.equals("null")) && !instrumentfield.equals("null")) {
for(int j_tLabVantageLIMSCIPostData_1 = 0; j_tLabVantageLIMSCIPostData_1 < dsData_tLabVantageLIMSCIPostData_1.getColumnCount(); ++j_tLabVantageLIMSCIPostData_1) {
String columnid = dsData_tLabVantageLIMSCIPostData_1.getColumnId(j_tLabVantageLIMSCIPostData_1);
String value = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, columnid, "nullvalue");
String message = "";
if ("LIMS CI".equals("LIMS CI") && (columnid.equals("sdcid") || columnid.equals("keyid1") || columnid.equals("instrumentfield")) && (value == null || value.equals("") || value.equals("nullvalue"))) {
message = "Error : Invalid value : The column '" + columnid + "' can not be empty or null.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
}
if ("LIMS CI".equals("Protocol Provider")) {
if (!columnid.equals("instrumentfield") && !columnid.equals("value")) {
message = "Error : Invalid column '" + columnid + "'. In 'Protocol Provider' case, only 'instrumentfield' and 'value' columns are accepted.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
} else if (columnid.equals("instrumentfield") && (value == null || value.equals("") || value.equals("nullvalue"))) {
message = "Error : Invalid value : The column '" + columnid + "' can not be empty or null.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
}
}
}
} else {
dsData_tLabVantageLIMSCIPostData_1.deleteRow(i_tLabVantageLIMSCIPostData_1);
--i_tLabVantageLIMSCIPostData_1;
}
}
}
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.equals("")) {
System.out.println("Invalid data ! You must solve the following problems : ");
System.out.println(sWarningMessages_tLabVantageLIMSCIPostData_1);
}
System.out.println("xmldataset=" + dsData_tLabVantageLIMSCIPostData_1.toXML());
globalMap.put("tLabVantageLIMSCIPostData_1_NB_LINE", dsData_tLabVantageLIMSCIPostData_1.getRowCount());
this.ok_Hash.put("tLabVantageLIMSCIPostData_1", true);
this.end_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
}
} catch (Exception var22) {
throw new LHCM_FX.TalendException(var22, currentComponent, globalMap, (LHCM_FX.TalendException)null);
} catch (Error var23) {
throw new Error(var23);
}
globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", 1);
}
public static void main(String[] args) {
LHCM_FX LHCM_FXClass = new LHCM_FX();
int exitCode = LHCM_FXClass.runJobInTOS(args);
System.exit(exitCode);
}
public String[][] runJob(String[] args) {
int exitCode = this.runJobInTOS(args);
String[][] bufferValue = new String[][]{{Integer.toString(exitCode)}};
return bufferValue;
}
public int runJobInTOS(String[] args) {
String lastStr = "";
boolean hasContextArg = false;
String[] var7 = args;
int var6 = args.length;
for(int var5 = 0; var5 < var6; ++var5) {
String arg = var7[var5];
if (arg.toLowerCase().contains("--context=")) {
hasContextArg = true;
} else if (arg.equalsIgnoreCase("--context_param")) {
lastStr = arg;
} else if (lastStr.equals("")) {
this.evalParam(arg);
} else {
this.evalParam(lastStr + " " + arg);
lastStr = "";
}
}
if (this.clientHost == null) {
this.clientHost = this.defaultClientHost;
}
if (this.pid == null || "0".equals(this.pid)) {
this.pid = TalendString.getAsciiRandomString(6);
}
if (this.rootPid == null) {
this.rootPid = this.pid;
}
if (this.fatherPid == null) {
this.fatherPid = this.pid;
} else {
this.isChildJob = true;
}
try {
InputStream inContext = LHCM_FX.class.getClassLoader().getResourceAsStream("cetemco/lhcm_fx_0_1/contexts/" + this.contextStr + ".properties");
if (inContext != null) {
this.defaultProps.load(inContext);
inContext.close();
this.context = new LHCM_FX.ContextProperties(this.defaultProps);
} else if (hasContextArg) {
System.err.println("Could not find the context " + this.contextStr);
}
if (!this.context_param.isEmpty()) {
this.context.putAll(this.context_param);
}
this.context.filepath = this.context.getProperty("filepath");
} catch (IOException var12) {
System.err.println("Could not load context " + this.contextStr);
var12.printStackTrace();
}
if (this.parentContextMap != null && !this.parentContextMap.isEmpty() && this.parentContextMap.containsKey("filepath")) {
this.context.filepath = (String)this.parentContextMap.get("filepath");
}
this.resumeEntryMethodName = ResumeUtil.getResumeEntryMethodName(this.resuming_checkpoint_path);
this.resumeUtil = new ResumeUtil(this.resuming_logs_dir_path, this.isChildJob, this.rootPid);
this.resumeUtil.initCommonInfo(this.pid, this.rootPid, this.fatherPid, "CETEMCO", "LHCM_FX", this.contextStr, "0.1");
this.resumeUtil.addLog("JOB_STARTED", "JOB:LHCM_FX", this.parent_part_launcher, String.valueOf(Thread.currentThread().getId()), "", "", "", "", ResumeUtil.convertToJsonText(this.context));
long startUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long endUsedMemory = 0L;
long end = 0L;
this.startTime = System.currentTimeMillis();
this.globalResumeTicket = true;
this.globalResumeTicket = false;
try {
this.errorCode = null;
this.tJavaFlex_1Process(this.globalMap);
this.status = "end";
} catch (LHCM_FX.TalendException var11) {
this.status = "failure";
var11.printStackTrace();
this.globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", -1);
}
this.globalResumeTicket = true;
end = System.currentTimeMillis();
if (this.watch) {
System.out.println(end - this.startTime + " milliseconds");
}
endUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
int returnCode = false;
int returnCode;
if (this.errorCode == null) {
returnCode = this.status != null && this.status.equals("failure") ? 1 : 0;
} else {
returnCode = this.errorCode;
}
this.resumeUtil.addLog("JOB_ENDED", "JOB:LHCM_FX", this.parent_part_launcher, String.valueOf(Thread.currentThread().getId()), "", "" + returnCode, "", "", "");
return returnCode;
}
private void evalParam(String arg) {
if (arg.startsWith("--resuming_logs_dir_path")) {
this.resuming_logs_dir_path = arg.substring(25);
} else if (arg.startsWith("--resuming_checkpoint_path")) {
this.resuming_checkpoint_path = arg.substring(27);
} else if (arg.startsWith("--parent_part_launcher")) {
this.parent_part_launcher = arg.substring(23);
} else if (arg.startsWith("--watch")) {
this.watch = true;
} else {
String keyValue;
if (arg.startsWith("--stat_port=")) {
keyValue = arg.substring(12);
if (keyValue != null && !keyValue.equals("null")) {
this.portStats = Integer.parseInt(keyValue);
}
} else if (arg.startsWith("--trace_port=")) {
this.portTraces = Integer.parseInt(arg.substring(13));
} else if (arg.startsWith("--client_host=")) {
this.clientHost = arg.substring(14);
} else if (arg.startsWith("--context=")) {
this.contextStr = arg.substring(10);
} else if (arg.startsWith("--father_pid=")) {
this.fatherPid = arg.substring(13);
} else if (arg.startsWith("--root_pid=")) {
this.rootPid = arg.substring(11);
} else if (arg.startsWith("--father_node=")) {
this.fatherNode = arg.substring(14);
} else if (arg.startsWith("--pid=")) {
this.pid = arg.substring(6);
} else if (arg.startsWith("--context_param")) {
keyValue = arg.substring(16);
int index = true;
int index;
if (keyValue != null && (index = keyValue.indexOf(61)) > -1) {
this.context_param.put(keyValue.substring(0, index), keyValue.substring(index + 1));
}
}
}
}
public Integer getErrorCode() {
return this.errorCode;
}
public String getStatus() {
return this.status;
}
public class ContextProperties extends Properties {
public String filepath;
public ContextProperties(Properties properties) {
super(properties);
}
public ContextProperties() {
}
public void synchronizeContext() {
if (this.filepath != null) {
this.setProperty("filepath", this.filepath.toString());
}
}
public String getFilepath() {
return this.filepath;
}
}
private class TalendException extends Exception {
private Map<String, Object> globalMap;
private Exception e;
private String currentComponent;
private TalendException(Exception e, String errorComponent, Map<String, Object> globalMap) {
this.globalMap = null;
this.e = null;
this.currentComponent = null;
this.currentComponent = errorComponent;
this.globalMap = globalMap;
this.e = e;
}
public void printStackTrace() {
if (!(this.e instanceof LHCM_FX.TalendException) && !(this.e instanceof TDieException)) {
this.globalMap.put(this.currentComponent + "_ERROR_MESSAGE", this.e.getMessage());
System.err.println("Exception in component " + this.currentComponent);
}
if (!(this.e instanceof TDieException)) {
if (this.e instanceof LHCM_FX.TalendException) {
this.e.printStackTrace();
} else {
this.e.printStackTrace();
this.e.printStackTrace(LHCM_FX.this.errorMessagePS);
LHCM_FX.this.exception = this.e;
}
}
if (!(this.e instanceof LHCM_FX.TalendException)) {
try {
Method[] var4;
int var3 = (var4 = this.getClass().getEnclosingClass().getMethods()).length;
for(int var2 = 0; var2 < var3; ++var2) {
Method m = var4[var2];
if (m.getName().compareTo(this.currentComponent + "_error") == 0) {
m.invoke(LHCM_FX.this, this.e, this.currentComponent, this.globalMap);
break;
}
}
boolean var10000 = this.e instanceof TDieException;
} catch (SecurityException var5) {
this.e.printStackTrace();
} catch (IllegalArgumentException var6) {
this.e.printStackTrace();
} catch (IllegalAccessException var7) {
this.e.printStackTrace();
} catch (InvocationTargetException var8) {
this.e.printStackTrace();
}
}
}
// ............. More More code
}
}
Thank you in advance,
My bad!
I have the parameter filepath inside args of my : MAIN (String[] args)
so filepath = args[4]
Im sorry and thanks anyway :)
I do not usually ask here.
I have a problem with the code I wrote down - I built a compression code - implementation of LZ77.
Everything works in code - when I use files that are based on ascii text in English.
When I use a bmp file - which works differently from a plain text file - I have a problem.
In a text file - I can write the character as it is - it works.
In the bmp file - when I try to compress it - I come across characters that are not English text letters - so I can not compress the file
That I'm trying to write a letter in English into a String builder it works - but in other characters - I can not write them inside the stringBuilder - as I try to write them - it performs null.
code:
main:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException
{
String inPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\Tiny24bit.bmp";
String outPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\encoded.txt";
String decompressedPath = "C:\\Users\\avraam\\Documents\\final-assignment\\LZ77\\decoded.bmp";
int windowSize = 512;
int lookaheadBufferSize = 200;
LZ77 compress = new LZ77(inPath,outPath,windowSize,lookaheadBufferSize);
compress.compress();
LZ77 decompress = new LZ77(outPath,decompressedPath,windowSize,lookaheadBufferSize);
decompress.decompress();
System.out.println("DONE!");
}
}
LZ77
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Writer;
import java.nio.file.Files;
import java.util.BitSet;
public class LZ77 {
private String inPath = null;
private String outPath = null;
private File inFile;
private File outFile;
private final int windowSize;
private final int lookaheadBufferSize;
private final int searchBufferSize;
private int nextByteIndex = 0;
private int nextBitIndex = 0;
private int currentSearchBufferSize = 0;
private int currentLookaheadBufferSize = 0;
private int appendToWindowBuffer = 0;
private byte[] source = null;
public LZ77(String inPath,String outPath,int windowSize,int lookaheadBufferSize) throws IOException
{
this.inPath = inPath;
this.outPath = outPath;
this.inFile = new File(inPath);
this.outFile = new File(outPath);
this.windowSize = windowSize;
this.lookaheadBufferSize = lookaheadBufferSize;
this.searchBufferSize = windowSize - lookaheadBufferSize;
this.source = Files.readAllBytes(inFile.toPath());
}
public void compress() throws IOException
{
StringBuilder dictionary = new StringBuilder();
bufferInitialize(dictionary);
StringBuilder compressed = new StringBuilder();
encode(dictionary,compressed);
addSizeBitsMod64(compressed);
//System.out.println(compressed);
writeFile(compressed);
}
public void bufferInitialize(StringBuilder dictionary)
{
for (int i = 0; i < lookaheadBufferSize; i++) {
if(source.length>nextByteIndex) {
dictionary.append((char)Byte.toUnsignedInt(source[nextByteIndex]));
nextByteIndex++;
currentLookaheadBufferSize++;
}
else
{
break;
}
}
}
public void encode(StringBuilder dictionary,StringBuilder compressed)
{
while(currentLookaheadBufferSize > 0)
{
Match match = findMatch(dictionary);
WriteMatch(compressed,match.offset,match.length,dictionary.charAt(currentSearchBufferSize + match.length));
appendToWindowBuffer = increaseBuffer(match.length);
appendBuffer(dictionary);
}
}
public Match findMatch(StringBuilder dictionary)
{
Match match= new Match(0,0, "");
String matchedString = null;
int offset;
int matchLookAheadIndex = currentSearchBufferSize;
if(!haveAnyMatch(dictionary))
{
}
else {
matchedString = "" + dictionary.charAt(matchLookAheadIndex);
offset = findMatchIndex(dictionary,matchedString);
while(offset != -1 && matchLookAheadIndex < dictionary.length() - 1)
{
match.SetLength(match.length + 1);
match.SetOffset(offset);
match.SetValue(matchedString);
matchLookAheadIndex++;
matchedString +=dictionary.charAt(matchLookAheadIndex);
offset = findMatchIndex(dictionary,matchedString);
}
}
return match;
}
public int findMatchIndex(StringBuilder dictionary,String value)
{
int stringLength = value.length();
String tmpMatch = null;
int offsetMatch;
for (int i = currentSearchBufferSize - 1; i >=0; i--)
{
tmpMatch = dictionary.substring(i, i +stringLength );
offsetMatch = currentSearchBufferSize - i;
if(tmpMatch.equals(value))
{
return offsetMatch;
}
}
return -1;
}
public boolean haveAnyMatch(StringBuilder dictionary)
{
if (currentSearchBufferSize == 0)
{
return false;
}
if(!isExistInSearchBuffer(dictionary,dictionary.charAt(currentSearchBufferSize)))
{
return false;
}
return true;
}
public boolean isExistInSearchBuffer(StringBuilder dictionary, char isCharAtDictionary)
{
for (int i = 0; i < currentSearchBufferSize; i++) {
if(dictionary.charAt(i) == isCharAtDictionary)
{
return true;
}
}
return false;
}
public int increaseBuffer(int matchLength)
{
return 1 + matchLength;
}
public int findBitSize(int decimalNumber) {
if(decimalNumber >= 256)
{
return 16;
}
else
{
return 8;
}
}
public void convertStringToBitSet(StringBuilder compressed,BitSet encodedBits)
{
for (int i = 0; i < compressed.length(); i++) {
if(compressed.charAt(i)==1)
{
encodedBits.set(i);
}
}
}
public BitSet ConvertToBits(StringBuilder compressed)
{
BitSet encodedBits = new BitSet(compressed.length());
int nextIndexOfOne = compressed.indexOf("1", 0);
while( nextIndexOfOne != -1)
{
encodedBits.set(nextIndexOfOne);
nextIndexOfOne++;
nextIndexOfOne = compressed.indexOf("1", nextIndexOfOne);
}
return encodedBits;
}
public void writeFile(StringBuilder compressed) throws IOException
{
BitSet encodedBits = new BitSet(compressed.length());
encodedBits = ConvertToBits(compressed);
FileOutputStream writer = new FileOutputStream(this.outPath);
ObjectOutputStream objectWriter = new ObjectOutputStream(writer);
objectWriter.writeObject(encodedBits);
objectWriter.close();
}
public void appendBuffer(StringBuilder dictionary)
{
for (int i = 0; i < appendToWindowBuffer && i < source.length; i++) {
if(ableDeleteChar(dictionary))
{
dictionary.deleteCharAt(0);
}
if(nextByteIndex<source.length)
{
char nextByte = (char)Byte.toUnsignedInt(source[nextByteIndex]);
dictionary.append(nextByte);
nextByteIndex++;
}
else
{
currentLookaheadBufferSize--;
}
if(currentSearchBufferSize < searchBufferSize)
{
currentSearchBufferSize++;
}
}
appendToWindowBuffer = 0;
}
public void WriteMatch(StringBuilder compressed,int offset, int length, char character)
{
/*int offsetBitSizeCheck, lengthBitSizeCheck;
offsetBitSizeCheck = findBitSize(offset);
lengthBitSizeCheck = findBitSize(length);
*/
String offsetInBits = writeInt(offset);
String LengthInBits = writeInt(length);
String characterInBits = writeChar(character);
String totalBits = offsetInBits + LengthInBits + characterInBits;
compressed.append(totalBits);
//compressed.append("<"+ offset + ","+ length +","+ character + ">");
System.out.print("<"+ offset + ","+ length +","+ character + ">");
}
public String writeInt(int decimalNumber)
{
int BitSizeCheck = findBitSize(decimalNumber);
StringBuilder binaryString = new StringBuilder();
binaryString.append(convertNumToBinaryString(decimalNumber));
while (binaryString.length() < BitSizeCheck)
{
binaryString.insert(0, "0");
}
if(BitSizeCheck == 8)
{
binaryString.insert(0, "0");
}
else
{
binaryString.insert(0, "1");
}
return binaryString.toString();
}
public String convertNumToBinaryString(int decimalNumber)
{
return Integer.toString(decimalNumber, 2);
}
public String writeChar(char character)
{
StringBuilder binaryString = new StringBuilder();
binaryString.append(convertNumToBinaryString((int)character));
while (binaryString.length() < 8)
{
binaryString.insert(0, "0");
}
return binaryString.toString();
}
public boolean ableDeleteChar(StringBuilder dictionary)
{
if(dictionary.length() == windowSize )
{
return true;
}
if(currentLookaheadBufferSize < lookaheadBufferSize)
{
if(currentSearchBufferSize == searchBufferSize)
{
return true;
}
}
return false;
}
public void addSizeBitsMod64(StringBuilder compressed)
{
int bitsLeft = compressed.length()%64;
String bitsLeftBinary = writeInt(bitsLeft);
compressed.insert(0, bitsLeftBinary);
}
public void decompress () throws ClassNotFoundException, IOException
{
BitSet source = readObjectFile();
//System.out.println(source.toString());
StringBuilder decompress = new StringBuilder ();
int bitSetLength = findLengthBitSet(source);
decode(decompress,bitSetLength,source);
writeDecode(decompress);
}
public BitSet readObjectFile() throws IOException, ClassNotFoundException
{
FileInputStream input = new FileInputStream(this.inPath);
ObjectInputStream objectInput = new ObjectInputStream(input);
BitSet restoredDataInBits = (BitSet) objectInput.readObject();
objectInput.close();
return restoredDataInBits;
}
public void decode(StringBuilder decompress, int bitSetLength,BitSet source)
{
System.out.println("decode: ");
System.out.println();
while(nextBitIndex < bitSetLength)
{
Match match = convertBitsToMatch(source);
//System.out.print("<"+ match.offset + ","+ match.length +","+ match.value + ">");
addDecode(decompress, match);
}
}
public void addDecode(StringBuilder decompress, Match match)
{
int RelativeOffset;
char decodeChar;
if(match.length == 0 && match.offset == 0)
{
decompress.append(match.value);
}
else
{
RelativeOffset = decompress.length() - match.offset;
System.out.println(RelativeOffset);
for (int i = 0; i < match.length; i++) {
decodeChar = decompress.charAt(RelativeOffset);
decompress.append(decodeChar);
RelativeOffset++;
}
decompress.append(match.value);
}
}
public Match convertBitsToMatch(BitSet source)
{
int offset;
int length;
char character;
if(source.get(nextBitIndex) == false)
{
nextBitIndex++;
offset = findOffsetLengthMatch(8,source);
}
else
{
nextBitIndex++;
offset = findOffsetLengthMatch(16,source);
}
if(source.get(nextBitIndex) == false)
{
nextBitIndex++;
length = findOffsetLengthMatch(8,source);
}
else
{
nextBitIndex++;
length = findOffsetLengthMatch(16,source);
}
character = findCharacterMatch(source);
//System.out.println("offset: " + offset + " length: " + length);
Match match = new Match(length,offset,""+character);
System.out.print("<"+ match.offset + ","+ match.length +","+ match.value + ">");
return match;
}
public int findOffsetLengthMatch(int index, BitSet source)
{
StringBuilder offsetLengthBinary = new StringBuilder();
for (int i = 0; i < index; i++) {
if(source.get(nextBitIndex) == false)
{
offsetLengthBinary.append('0');
nextBitIndex++;
}
else
{
offsetLengthBinary.append('1');
nextBitIndex++;
}
}
int offsetLengthDecimal = convertBinaryStringToDecimal(offsetLengthBinary);
//System.out.println("problem here: " + offsetLengthDecimal + " the binary is : " + offsetLengthBinary);
return offsetLengthDecimal;
}
public char findCharacterMatch(BitSet source)
{
StringBuilder charBinary = new StringBuilder();
for (int i = 0; i < 8; i++) {
if(source.get(nextBitIndex) == false)
{
charBinary.append('0');
nextBitIndex++;
}
else
{
charBinary.append('1');
nextBitIndex++;
}
}
char charDecimal = (char)convertBinaryStringToDecimal(charBinary);
return charDecimal;
}
public int findLengthBitSet(BitSet source)
{
StringBuilder lengthBinary = new StringBuilder();
for (int i = 0; i < 9; i++) {
if(source.get(i) == false)
{
lengthBinary.append('0');
nextBitIndex++;
}
else
{
lengthBinary.append('1');
nextBitIndex++;
}
}
int lengthModule = convertBinaryStringToDecimal(lengthBinary);
int lengthNotUsed = 64 - lengthModule;
int fullLength = source.size() - lengthNotUsed + 9 ;
return fullLength;
}
public int convertBinaryStringToDecimal(StringBuilder lengthBinary)
{
int length = Integer.parseInt(lengthBinary.toString(), 2);
//System.out.println("length: " + length + "lengthBinary: " + lengthBinary);
return length;
}
public void writeDecode (StringBuilder decompress) throws IOException
{
Writer write = new FileWriter(this.outFile);
write.write(decompress.toString());
write.close();
}
}
Match
public class Match {
protected int length;
protected int offset;
protected String value;
public Match(int length, int offset, String value)
{
this.length=length;
this.offset=offset;
this.value = value;
}
public void SetOffset(int offset) { this.offset = offset; }
public void SetLength(int length) { this.length = length; }
public void SetValue(String value) { this.value = value; }
public void AddValue(char value) { this.value += value; }
public void Reset()
{
this.offset = 0;
this.length = 0;
this.value = "";
}
}
I've a problem with hibernate. I'm trying to save an object into a relational db with hibernate using orm.jar library generated by visual-paradigm tool. The problem is that it does not work but the program does not give me exceptions.
I tried to change my code but the program catches an exception and does not work.
MAIN:
CoordinatorIntrusione c = CoordinatorIntrusione.getInstance();
c.avviaRilevamento();
c.notifyProximityBySerraID(1, 4);
ArrayList<Integer> prova = new ArrayList<Integer>();
prova.add(2);
prova.add(1);
prova.add(9);
c.notifyImageBySerraID(1, prova);
System.out.println("ecco");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
c.ripristinaRilevamento(1, "1");
COORDINATORINTRUSIONE:
public class CoordinatorIntrusione {
private volatile static CoordinatorIntrusione coordinator = null;
private ThreadGroup groupBLThread;
public int avviaRilevamento() {
int code = 0;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione[] colt = esm.getColtivazioniAttive();
if(colt.length==0) {
code=-1;
return code;
}
for(int i=0; i<colt.length; i++) {
EntitySerra serra = colt[i].getEntitySerra();
int id = serra.getId();
ControllerRilevaIntrusioneBL controller = new ControllerRilevaIntrusioneBL(id, groupBLThread, "worker"+i);
controller.start();
//System.out.println("ID :"+id);
}
return code;
}
public int negaID(int id, String matricola) {
//throw new UnsupportedOperationException();
int code = -1;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione coltivazione = esm.getColtivazioneBySerraID(id);
if(coltivazione == null) return code;
String matResp = coltivazione.getEntitySerra().getResponsabile().getMatricola();
if (!matricola.equals(matResp)) return code;
ControllerRilevaIntrusioneBL controller = this.searchWorkerForID(id);
if (controller == null) return code;
code = controller.negaID();
return code;
}
public int ripristinaRilevamento(int id, String matricola) {
//throw new UnsupportedOperationException();
int code = -1;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione coltivazione = esm.getColtivazioneBySerraID(id);
if(coltivazione == null) return code;
String matResp = coltivazione.getEntitySerra().getResponsabile().getMatricola();
if (!matricola.equals(matResp)) return code;
ControllerRilevaIntrusioneBL controller = this.searchWorkerForID(id);
if (controller == null) return code;
code = controller.ripristinaRilevamento();
return code;
}
public int confermaId(int id, String matricola) {
//throw new UnsupportedOperationException();
int code = -1;
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione coltivazione = esm.getColtivazioneBySerraID(id);
if(coltivazione == null) return code;
String matResp = coltivazione.getEntitySerra().getResponsabile().getMatricola();
if (!matricola.equals(matResp)) return code;
ControllerRilevaIntrusioneBL controller = this.searchWorkerForID(id);
if (controller == null) return code;
code = controller.confermaID();
return code;
// quindi se il code è negativo le matricole non combaciano, se positivo combaciano
}
protected ControllerRilevaIntrusioneBL searchWorkerForID(int idSerra) {
ControllerRilevaIntrusioneBL[] th = new ControllerRilevaIntrusioneBL[groupBLThread.activeCount()];
groupBLThread.enumerate(th);
int i=0;
while(i<th.length) {
if(th[i].getID() == idSerra) return th[i];
i++;
}
return null;
}
private CoordinatorIntrusione() {
groupBLThread = new ThreadGroup("workerCoordinator");
}
public void notifyProximityBySerraID(int idSerra, float value) {
ControllerRilevaIntrusioneBL thread = this.searchWorkerForID(idSerra);
thread.proximityValueArrived(value);
}
public void notifyImageBySerraID(int idSerra, ArrayList<Integer> img) {
ControllerRilevaIntrusioneBL thread = this.searchWorkerForID(idSerra);
thread.imgArrived(img);
}
public static CoordinatorIntrusione getInstance() {
if (coordinator == null) {
synchronized(CoordinatorIntrusione.class){ //Serve la sincronizzazione visto che è solo lettura
if(coordinator == null){
coordinator = new CoordinatorIntrusione();
}
}
}
return coordinator;
}
}
CONTROLLERRILEVAINTRUSIONEBL:
public class ControllerRilevaIntrusioneBL extends Thread{
private int id;
private float[] valoreProssimita;
private ArrayList<Integer> img;
private static final float criticalProxValue =5;
private Semaphore proxsem;
private Semaphore camsem;
private Semaphore ripristinasem;
private Semaphore waitsem ;
protected int rilevaVolti() {
//TODO with python script
//throw new UnsupportedOperationException();
return 0;
}
public synchronized int negaID() {
//throw new UnsupportedOperationException();
int code = 0;
if (waitsem.getQueueLength() > 0) {
waitsem.release();
code = 1;
}
else code = -1;
return code;
}
public synchronized int ripristinaRilevamento() {
//throw new UnsupportedOperationException();
int code = 0;
//System.out.println(ripristinasem.getQueueLength());
if (ripristinasem.getQueueLength() > 0) {
ripristinasem.release();
code = 1;
}
else code = -1;
//System.out.println(ripristinasem.getQueueLength());
return code;
}
public synchronized int confermaID() {
//throw new UnsupportedOperationException();
int code = 0;
if (waitsem.getQueueLength() > 0) {
waitsem.release();
code = 1;
}
else code = -1;
return code;
}
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
#Override
public void run() {
EntitySmartFarm esm = EntitySmartFarm.getInstance();
EntityColtivazione colt = esm.getColtivazioneBySerraID(id);
EntitySerra serra = colt.getEntitySerra();
EntitySensore proximity = serra.getSensoreProssimita();
EntitySensore camera = serra.getSensoreFotografico();
//ProxySerra proxyserra = ProxySerra.getInstance();
while (true) {
//MonitoraggioProssimità
//invio messaggio alla serra
try {
proxsem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
proximity.setValore(valoreProssimita);
if(valoreProssimita[0] < criticalProxValue){
// invio messaggio camera alla serra
try {
camsem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
float[] immagine = new float[img.size()];
int index = 0;
for (Integer value: img) {
immagine[index++] = value;
}
camera.setValore(immagine);
int ret = this.rilevaVolti();
if (ret == 0 || ret == -1) {
//New ProxyNotificationSystem
if (ret == 0) {
//ProxyNotificationSystem.inviosegnalazione();
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Rome"), Locale.ITALY);
Date today = calendar.getTime();
Date ora = calendar.getTime();
int[] array = img.stream().mapToInt(i -> i).toArray();
serra.addIntrusione(today, "Selvaggina", array, ora);
} else {
try {
waitsem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
//proxynotsys.nviosegnalazione();
}
System.out.println("Thread: "+this.id+" bloccato");
try {
ripristinasem.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread: "+this.id+" Sbloccato");
}
}
}
}
public ControllerRilevaIntrusioneBL(int id, ThreadGroup group, String threadName){
super(group,threadName);
this.id = id;
valoreProssimita = new float[1];
img = new ArrayList<Integer>();
proxsem = new Semaphore(0);
camsem = new Semaphore(0);
ripristinasem = new Semaphore(0);
waitsem = new Semaphore(0);
}
public void proximityValueArrived(float value) {
valoreProssimita[0]=value;
proxsem.release();
}
public void imgArrived(ArrayList<Integer> img) {
this.img=img;
camsem.release();
}
}
ENTITYSERRA (first "addIntrusione" method catches exception and does not work, second "addIntrusione" method does not catch but does not work anyway):
public class EntitySerra {
public EntitySerra() {
}
private java.util.Set this_getSet (int key) {
if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYEMPLOYERS) {
return ORM_entityEmployers;
}
else if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYSENSORES) {
return ORM_entitySensores;
}
else if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYINTRUSIONES) {
return ORM_entityIntrusiones;
}
else if (key == vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYLETTURAS) {
return ORM_entityLetturas;
}
return null;
}
org.orm.util.ORMAdapter _ormAdapter = new org.orm.util.AbstractORMAdapter() {
public java.util.Set getSet(int key) {
return this_getSet(key);
}
};
private int id;
private java.util.Set ORM_entityEmployers = new java.util.HashSet();
private java.util.Set ORM_entitySensores = new java.util.HashSet();
private java.util.Set ORM_entityIntrusiones = new java.util.HashSet();
private java.util.Set ORM_entityLetturas = new java.util.HashSet();
private void setId(int value) {
this.id = value;
}
public int getId() {
return id;
}
public int getORMID() {
return getId();
}
public void setORM_EntityEmployers(java.util.Set value) {
this.ORM_entityEmployers = value;
}
public java.util.Set getORM_EntityEmployers() {
return ORM_entityEmployers;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntityEmployerSetCollection entityEmployers = new vista_architetturale_gestoresmartfarm.entity2.EntityEmployerSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYEMPLOYERS, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public void setORM_EntitySensores(java.util.Set value) {
this.ORM_entitySensores = value;
}
public java.util.Set getORM_EntitySensores() {
return ORM_entitySensores;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntitySensoreSetCollection entitySensores = new vista_architetturale_gestoresmartfarm.entity2.EntitySensoreSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYSENSORES, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public void setORM_EntityIntrusiones(java.util.Set value) {
this.ORM_entityIntrusiones = value;
}
public java.util.Set getORM_EntityIntrusiones() {
return ORM_entityIntrusiones;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneSetCollection entityIntrusiones = new vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYINTRUSIONES, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public void setORM_EntityLetturas(java.util.Set value) {
this.ORM_entityLetturas = value;
}
public java.util.Set getORM_EntityLetturas() {
return ORM_entityLetturas;
}
public final vista_architetturale_gestoresmartfarm.entity2.EntityLetturaSetCollection entityLetturas = new vista_architetturale_gestoresmartfarm.entity2.EntityLetturaSetCollection(this, _ormAdapter, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_ENTITYSERRA_ENTITYLETTURAS, vista_architetturale_gestoresmartfarm.entity2.ORMConstants.KEY_MUL_ONE_TO_MANY);
public String getNotifyInformationResponsabile() {
//TODO: Implement Method
String recapito = null;
Iterator<EntityEmployer> it = ORM_entityEmployers.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntityEmployer empTemp = it.next();
if(empTemp.getTipo().equals("responsabile")){
trovato = true;
recapito = empTemp.getRecapito();
}
}
return recapito;
}
public void salvaLettura() {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public void salvaLettura2() {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public void addIntrusione(java.util.Date data, String tipo, int[] img, java.util.Date ora) {
//TODO: Implement Method
EntityIntrusione intrusione = new EntityIntrusione (data, ora, tipo, img);
//DA TESTARE IMPORTANTISSIMO
ORM_entityIntrusiones.add(intrusione);
try {
//EntitySerraDAO.save(this);
EntityIntrusioneDAO.save(intrusione);
} catch (PersistentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*public synchronized void addIntrusione(java.util.Date data, String tipo, int[] img, java.util.Date ora){
//TODO: Implement Method
EntityIntrusione intrusione = new EntityIntrusione (data,ora,tipo,img);
//DA TESTARE IMPORTANTISSIMO
this.ORM_entityIntrusiones.add(intrusione);
this.entityIntrusiones.add(intrusione);
try {
Stream<EntityIntrusione> stream = this.ORM_entityIntrusiones.stream();
// salva l'ultimo elem
EntityIntrusioneDAO.save(stream.reduce((a, b) -> b).orElse(null));
} catch (PersistentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
public EntitySerra(vista_architetturale_gestoresmartfarm.entity2.EntitySerraDAO serra) {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public String[] getNotifyInformationEmployers() {
//TODO: Implement Method
throw new UnsupportedOperationException();
}
public vista_architetturale_gestoresmartfarm.entity2.EntitySensore getSensoreProssimita() {
EntitySensore sensProssimita = null;
Iterator<EntitySensore> it = ORM_entitySensores.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntitySensore sensTemp = it.next();
if(sensTemp.getTipo().equals("prossimita")){
trovato = true;
sensProssimita = sensTemp;
}
}
return sensProssimita;
}
public vista_architetturale_gestoresmartfarm.entity2.EntitySensore getSensoreFotografico() {
EntitySensore sensFotocamera = null;
Iterator<EntitySensore> it = ORM_entitySensores.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntitySensore sensTemp = it.next();
if(sensTemp.getTipo().equals("cam")){
trovato = true;
sensFotocamera = sensTemp;
}
}
return sensFotocamera;
}
public vista_architetturale_gestoresmartfarm.entity2.EntityEmployer getResponsabile() {
//TODO: Implement Method
EntityEmployer responsabile = null;
Iterator<EntityEmployer> it = ORM_entityEmployers.iterator();
boolean trovato = false;
while(trovato == false && it.hasNext()){
EntityEmployer empTemp = it.next();
if(empTemp.getTipo().equals("responsabile")){
trovato = true;
responsabile = empTemp;
}
}
return responsabile;
}
public String toString() {
return String.valueOf(getId());
}
}
ENTITYINTRUSIONEDAO:
public class EntityIntrusioneDAO {
public static boolean save(vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione entityIntrusione) throws PersistentException {
try {
vista_architetturale_gestoresmartfarm.entity2.ProgettoPSSSAgosVersionPersistentManager.instance().saveObject(entityIntrusione);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
}
PERSISTENT MANAGER:
public class ProgettoPSSSAgosVersionPersistentManager extends PersistentManager {
private static PersistentManager _instance = null;
private static SessionType _sessionType = SessionType.THREAD_BASE;
private static int _timeToAlive = 60000;
private static JDBCConnectionSetting _connectionSetting = null;
private static Properties _extraProperties = null;
private static String _configurationFile = null;
private ProgettoPSSSAgosVersionPersistentManager() throws PersistentException {
super(_connectionSetting, _sessionType, _timeToAlive, new String[] {}, _extraProperties, _configurationFile);
setFlushMode(FlushMode.AUTO);
}
public String getProjectName() {
return PROJECT_NAME;
}
public static synchronized final PersistentManager instance() throws PersistentException {
if (_instance == null) {
_instance = new ProgettoPSSSAgosVersionPersistentManager();
}
return _instance;
}
public void disposePersistentManager() throws PersistentException {
_instance = null;
super.disposePersistentManager();
}
public static void setSessionType(SessionType sessionType) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set session type after create PersistentManager instance");
}
else {
_sessionType = sessionType;
}
}
public static void setAppBaseSessionTimeToAlive(int timeInMs) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set session time to alive after create PersistentManager instance");
}
else {
_timeToAlive = timeInMs;
}
}
public static void setJDBCConnectionSetting(JDBCConnectionSetting aConnectionSetting) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set connection setting after create PersistentManager instance");
}
else {
_connectionSetting = aConnectionSetting;
}
}
public static void setHibernateProperties(Properties aProperties) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set hibernate properties after create PersistentManager instance");
}
else {
_extraProperties = aProperties;
}
}
public static void setConfigurationFile(String aConfigurationFile) throws PersistentException {
if (_instance != null) {
throw new PersistentException("Cannot set configuration file after create PersistentManager instance");
}
else {
_configurationFile = aConfigurationFile;
}
}
public static void saveJDBCConnectionSetting() {
PersistentManager.saveJDBCConnectionSetting(PROJECT_NAME, _connectionSetting);
}
}
The exception caught is:
org.orm.PersistentException: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:598)
at org.orm.PersistentManager.saveObject(PersistentManager.java:326)
at vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneDAO.save(EntityIntrusioneDAO.java:304)
at vista_architetturale_gestoresmartfarm.entity2.EntitySerra.addIntrusione(EntitySerra.java:146)
at vista_architetturale_gestoresmartfarm.business_logic.ControllerRilevaIntrusioneBL.run(ControllerRilevaIntrusioneBL.java:139)
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:89)
at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready(AbstractEntityInsertAction.java:115)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:69)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:625)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:279)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:260)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:305)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:97)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:655)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:647)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:642)
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:596)
... 4 more
org.orm.PersistentException: org.orm.PersistentException: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneDAO.save(EntityIntrusioneDAO.java:309)
at vista_architetturale_gestoresmartfarm.entity2.EntitySerra.addIntrusione(EntitySerra.java:146)
at vista_architetturale_gestoresmartfarm.business_logic.ControllerRilevaIntrusioneBL.run(ControllerRilevaIntrusioneBL.java:139)
Caused by: org.orm.PersistentException: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:598)
at org.orm.PersistentManager.saveObject(PersistentManager.java:326)
at vista_architetturale_gestoresmartfarm.entity2.EntityIntrusioneDAO.save(EntityIntrusioneDAO.java:304)
... 2 more
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : vista_architetturale_gestoresmartfarm.entity2.EntityIntrusione._vista_architetturale_gestoresmartfarm.entity2.EntitySerra.ORM_EntityIntrusionesBackref
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:89)
at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready(AbstractEntityInsertAction.java:115)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:69)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:625)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:279)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:260)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:305)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:97)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:655)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:647)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:642)
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:596)
... 4 more
You can specify the Error Handling method when generating ORM code. May I know which option you selected?
Here is what I am trying to do. I have a number of threads which should all wait at a common point before they proceed, so obvious solution is to use CyclicBarrier. But I want to also compute the total time taken by the threads to execute. I defined the following utility method in class ConcurrentExecutionActionTimer.
public static long elapsedTimeUsingCyclicBarrier(Executor executor, int concurrency, final Runnable action) throws InterruptedException
{
final Runnable barrierAction = new Runnable() {
#Override
public void run() {
System.out.println("Condition of barrier is met.");
}
};
final
CyclicBarrier barrier = new CyclicBarrier(concurrency, barrierAction);
final CountDownLatch done = new CountDownLatch(concurrency);
for(int i=0; i<concurrency; i++ ){
executor.execute(new Runnable() {
#Override
public void run() {
try {
System.out.println("Waiting at barrier.");
barrier.await();
action.run();
//Cyclic barrier gets reset automatically. Again wait for them to finish.
barrier.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (BrokenBarrierException e) {
e.printStackTrace();
} finally {
done.countDown();
}
}
});
}
long startNanoTime = System.nanoTime();
done.await();
return System.nanoTime() - startNanoTime;
}
Then I called it up like:
public static void main(String[] args) {
//Executor is replacement for common thread idiom: (new Thread(r)).start() to e.execute(r)
ExecutorService executor = Executors.newFixedThreadPool(10);
Worker action = new Worker();
int concurrency = 5;
try {
long elapsedTime = ConcurrentExecutionActionTimer.elapsedTimeUsingCyclicBarrier(executor, concurrency, action);
double seconds = (double)elapsedTime / 1000000000.0;
System.out.println("Time Taken approximately: " + seconds + "seconds.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Here Worker is suppose my thread that does some work. For example:
class Worker implements Runnable {
#Override
public void run() {
System.out.println("Doing work.");
for(int i=0; i<20; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Finished.");
}
}
As I wanted to print the time taken I had to use CountDownLatch to make sure the control does not return back to main before all the threads are finished. Do we have any other way to make sure the same functionality?
You should use the same CyclicBarrier instance. The only difference is that you make the cyclic barrier count be #threads + 1. You can then use that barrier to calculate the time it took all of the threads to complete. The start time is calculated when the first barrier has been reached and the end time is calculated when the second barrier has been reached. This way you know approximately when all the threads have been started and when all of them have completed.
Therefore this:
long startNanoTime = System.nanoTime();
done.await();
return System.nanoTime() - startNanoTime;
becomes:
barrier.await()
long startNanoTime = System.nanoTime();
barrier.await();
return System.nanoTime() - startNanoTime;
import java.io.*;
import java.util.*;
import java.util.concurrent.CyclicBarrier;
class BusLine {
private String destination;
protected static int max_seat, checkpoint;
private ArrayList<Bus> BUSA = new ArrayList<Bus>();
private ArrayList<Bus> BUSC = new ArrayList<Bus>();
private ArrayList<Group> GROUP_A = new ArrayList<Group>();
private ArrayList<Group> GROUP_C = new ArrayList<Group>();
public BusLine(int ms, int cp, String d) {
max_seat = ms;
checkpoint = cp;
destination = d;
}
public String getDestination() {
return destination;
}
public void printAirportCheckpoint() {
System.out.println();
System.out.printf("%s >> %d airport-bound buses have been allocated.", Thread.currentThread().getName(), BUSA.size());
}
public void printCityCheckpoint() {
System.out.println();
System.out.printf("%s >> %d city-bound buses have been allocated.", Thread.currentThread().getName(), BUSC.size());
System.out.println();
System.out.println();
}
public void BusBoundA() {
int temp = 0;
for (int i = 0; i < BUSA.size(); i++) {
if (BUSA.get(i).getName().equals("A" + i)) {
temp++;
}
}
System.out.println();
System.out.printf("%s >> ==== Airport Bound ====", Thread.currentThread().getName());
System.out.println();
for (int i = 0; i < temp; i++) {
System.out.printf("%s >> %s : ", Thread.currentThread().getName(), "A" + i);
for (int j = 0; j < GROUP_A.size(); j++) {
if (GROUP_A.get(j).getBusname().equals("A" + i)) {
System.out.printf(" %-20s(%2d seats)", GROUP_A.get(j).getName(), GROUP_A.get(j).getSeat());
//System.out.printf(",");
}
} System.out.println();
}
}
public void BusBoundC() {
int temp = 0;
for (int i = 0; i < BUSC.size(); i++) {
if (BUSC.get(i).getName().equals("C" + i)) {
temp++;
}
}
System.out.println();
System.out.printf("%s >> ==== City Bound ====", Thread.currentThread().getName());
System.out.println();
for (int i = 0; i < temp; i++) {
System.out.printf("%s >> %s : ", Thread.currentThread().getName(), "C" + i);
for (int j = 0; j < GROUP_C.size(); j++) {
if (GROUP_C.get(j).getBusname().equals("C" + i)) {
System.out.printf(" %-20s(%2d seats)", GROUP_C.get(j).getName(), GROUP_C.get(j).getSeat());
//System.out.printf(",");
}
} System.out.println();
}
}
synchronized public void allocateBus(Data d) {
TicketCounter T = (TicketCounter) (Thread.currentThread());
while (d.getSeat() != 0) {
if ("A".equals(d.getDestination())) {
if (BUSA.size() == 0 || BUSA.get(BUSA.size() - 1).getAvailableSeat() == 0) {
BUSA.add(new Bus("A" + BUSA.size()));
}
if (d.getSeat() <= BUSA.get(BUSA.size() - 1).getAvailableSeat()) {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), d.getSeat(), BUSA.get(BUSA.size() - 1).getName());
GROUP_A.add(new Group(BUSA.get(BUSA.size() - 1).getName(), d.getName(), d.getSeat()));
BUSA.get(BUSA.size() - 1).Bookingseat(d.getSeat());
d.finishedBooking(d.getSeat());
} else {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), BUSA.get(BUSA.size() - 1).getAvailableSeat(), BUSA.get(BUSA.size() - 1).getName());
GROUP_A.add(new Group(BUSA.get(BUSA.size() - 1).getName(), d.getName(), BUSA.get(BUSA.size() - 1).getAvailableSeat()));
d.finishedBooking(BUSA.get(BUSA.size() - 1).getAvailableSeat());
BUSA.get(BUSA.size() - 1).Bookingseat(BUSA.get(BUSA.size() - 1).getAvailableSeat());
}
} else {
if (BUSC.size() == 0 || BUSC.get(BUSC.size() - 1).getAvailableSeat() == 0) {
BUSC.add(new Bus("C" + BUSC.size()));
}
if (d.getSeat() <= BUSC.get(BUSC.size() - 1).getAvailableSeat()) {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), d.getSeat(), BUSC.get(BUSC.size() - 1).getName());
GROUP_C.add(new Group(BUSC.get(BUSC.size() - 1).getName(), d.getName(), d.getSeat()));
BUSC.get(BUSC.size() - 1).Bookingseat(d.getSeat());
d.finishedBooking(d.getSeat());
} else {
System.out.printf("%s >> Transaction %2d : %-20s(%2d seats) bus %s\n", T.getName(), d.getTransaction(), d.getName(), BUSC.get(BUSC.size() - 1).getAvailableSeat(), BUSC.get(BUSC.size() - 1).getName());
GROUP_C.add(new Group(BUSC.get(BUSC.size() - 1).getName(), d.getName(), BUSC.get(BUSC.size() - 1).getAvailableSeat()));
d.finishedBooking(BUSC.get(BUSC.size() - 1).getAvailableSeat());
BUSC.get(BUSC.size() - 1).Bookingseat(BUSC.get(BUSC.size() - 1).getAvailableSeat());
}
}
}
}
}
class Group {
private String busname, name;
private int seat;
public Group(String n, String b, int s) {
busname = n;
name = b;
seat = s;
}
public String getName() { return name; }
public String getBusname() { return busname; }
public int getSeat() { return seat; }
}
class Bus {
private String Busname, group_name;
private int availableseat, seat;
public int getAvailableSeat() { return availableseat; }
public String getName() { return Busname; }
public void Bookingseat(int s) { availableseat -= s; }
public String getGroupname() { return group_name; }
public Bus(String n) {
availableseat = BusLine.max_seat;
Busname = n;
}
public Bus(String n, int s) {
group_name = n;
seat = s;
}
public Bus(String n, String gn, int s) {
Busname = n;
group_name = gn;
availableseat = s;
}
}
class Data {
private String name, destination;
private int seat, transaction, count = 0;
public int getCount() { return count; }
public int getTransaction() { return transaction; }
public String getName() { return name; }
public int getSeat() { return seat; }
public String getDestination() { return destination; }
public void finishedBooking(int s) { seat -= s; }
public Data(int t, String n, int s, String d) {
transaction = t;
name = n;
seat = s;
destination = d;
}
}
class TicketCounter extends Thread {
ArrayList<Data> transaction;
BusLine Airport, City;
private CyclicBarrier cfinish;
public void setCyclicBarrier(CyclicBarrier f) {
cfinish = f;
}
public TicketCounter(String n, ArrayList<Data> d, BusLine a, BusLine c) {
super(n);
transaction = d;
Airport = a;
City = c;
}
public void run() {
for (int i = 0; i < transaction.size(); i++) {
if (transaction.get(i).getTransaction() == BusLine.checkpoint) {
try {
cfinish.await();
cfinish.await();
} catch (Exception e) {}
}
if ("A".equals(transaction.get(i).getDestination())) {
Airport.allocateBus(transaction.get(i));
} else {
City.allocateBus(transaction.get(i));
}
}
}
}
class Userinput {
private ArrayList<Data> DATA1 = new ArrayList<Data>();
private ArrayList<Data> DATA2 = new ArrayList<Data>();
private ArrayList<Data> DATA3 = new ArrayList<Data>();
public Userinput() {}
public ArrayList<Data> getDATA1() { return DATA1; }
public ArrayList<Data> getDATA2() { return DATA2; }
public ArrayList<Data> getDATA3() { return DATA3; }
public void input() {
String infile[] = {"T1.txt", "T2.txt", "T3.txt"};
for (int i = 0; i < 3; i++) {
boolean opensuccess = false;
while (!opensuccess) {
try ( Scanner scanfile = new Scanner(new File(infile[i]));) {
while (scanfile.hasNext()) {
opensuccess = true;
String line = scanfile.nextLine();
String[] buf = line.split(",");
int transaction = Integer.parseInt(buf[0].trim());
String name = buf[1].trim();
int seat = Integer.parseInt(buf[2].trim());
String destination = buf[3].trim();
Data d = new Data(transaction, name, seat, destination);
switch (i) {
case 0: DATA1.add(d);
break;
case 1: DATA2.add(d);
break;
case 2: DATA3.add(d);
break;
}
}
} catch (FileNotFoundException e) {
System.out.println(e);
Scanner scan = new Scanner(System.in);
System.out.println("Enter new file name : ");
infile[i] = scan.nextLine();
}
}
}
}
}
public class Simulation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Thread Th = Thread.currentThread();
System.out.printf("%s >> Enter max seats = ", Th.getName());
System.out.println();
int max_seat = scan.nextInt();
System.out.printf("%s >> Enter checkpoints = ", Th.getName());
System.out.println();
int checkpoint = scan.nextInt();
Userinput U = new Userinput();
BusLine Airport = new BusLine(max_seat, checkpoint, "A");
BusLine City = new BusLine(max_seat, checkpoint, "C");
CyclicBarrier CB = new CyclicBarrier(4);
U.input();
TicketCounter[] T = {
new TicketCounter("T1", U.getDATA1(), Airport, City),
new TicketCounter("T2", U.getDATA2(), Airport, City),
new TicketCounter("T3", U.getDATA3(), Airport, City)};
for (int i = 0; i < 3; i++) {
T[i].setCyclicBarrier(CB);
T[i].start();
}
try {
CB.await();
Airport.printAirportCheckpoint();
City.printCityCheckpoint();
CB.await();
}catch (Exception e){}
for (int i = 0; i < 3; i++) {
try {
T[i].join();
} catch (Exception e) {
System.err.println(e);
}
}
Airport.BusBoundA();
City.BusBoundC();
}
}