Am I serializing/deserializing correctly? - java

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

Why don't you delete the file in "serializeQuotes()" before writing the object. That way you will be sure, that there will be only one object there.
private void serializeQuotes(){
FileOutputStream fos;
File file = new File(Constants.FILENAME);
if (file.exists()) file.delete();
try {
fos = openFileOutput(file, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotes);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
Or if you do not want to delete file every time, use some kind of iteration when reading obejcts from it.

Related

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

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

Hibernate does not save in DB using DAO object generated by visual-paradigm

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?

Accessing Java Class/function from CFML script

I want to access some Java class and function from within a CFML script (I'm total noob in Java):
<cfscript>
passwordutils = createObject("java","coldfusion.util.PasswordUtils");
newPass = passwordutils.encryptPassword("p455w0rd");
</cfscript>
<cfoutput>#newPass#</cfoutput>
Getting the following error:
The Java class I want to use is the one below (in coldfusion.util.PasswordUtils):
package coldfusion.util;
import coldfusion.archivedeploy.ArchiveDeployServiceImpl;
import coldfusion.flex.FlexAssemblerService;
import coldfusion.log.CFLogs;
import coldfusion.log.Logger;
import coldfusion.lucene.SolrServiceImpl;
import coldfusion.mail.MailSpooler;
import coldfusion.monitor.MonitoringServiceImpl;
import coldfusion.runtime.ApplicationException;
import coldfusion.runtime.CFPage;
import coldfusion.runtime.RuntimeServiceImpl;
import coldfusion.runtime.Struct;
import coldfusion.scheduling.CronServiceImpl;
import coldfusion.security.SecurityManager;
import coldfusion.security.SecurityUtils;
import coldfusion.server.SecurityService;
import coldfusion.server.ServiceException;
import coldfusion.server.ServiceFactory;
import coldfusion.server.ServiceRuntimeException;
import coldfusion.sql.Executive;
import coldfusion.tagext.io.FileUtils;
import coldfusion.wddx.Base64Encoder;
import coldfusion.xml.rpc.XmlRpcServiceImpl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.Properties;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class PasswordUtils
extends Observable
{
private static final char PADCHAR = '#';
private static final String DESALGORITHM = "DESede";
private static final String AES_CBC_PKCS5_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String SEEDFILE = "seed.properties";
private static final String BASEENCODING = "Base64";
public static final String SEED = "seed";
public static final String ALGORITHM = "algorithm";
public static final String CURRENT_ALGORITHM = "AES/CBC/PKCS5Padding";
public static final int FORAES_START_MAJOR_VERSION = 9;
public static final int FORAES_START_MINOR_VERSION = 5;
private static String ROOTDIR;
private static String SEEDFILEPATH;
private static PasswordUtils instance = null;
private String seedValue;
private Properties seedProperties;
private static File seedFileObj;
public static PasswordUtils getInstance(String rootDir)
throws ServiceException
{
if (instance == null)
{
ROOTDIR = rootDir;
SEEDFILEPATH = ROOTDIR + File.separatorChar + "lib" + File.separatorChar + "seed.properties";
instance = new PasswordUtils();
}
return instance;
}
public static PasswordUtils getInstance()
{
return instance;
}
private PasswordUtils()
throws ServiceException
{
this.seedProperties = new Properties();
loadSeed();
}
private void loadSeed()
throws ServiceException
{
seedFileObj = new File(SEEDFILEPATH);
FileInputStream finput = null;
try
{
finput = new FileInputStream(seedFileObj);
this.seedProperties.load(finput);
try
{
finput.close();
}
catch (Throwable t) {}
seed = this.seedProperties.getProperty("seed");
}
catch (Throwable t)
{
if (seedFileObj.exists()) {
throw new ServiceException(t);
}
}
finally
{
try
{
finput.close();
}
catch (Throwable t) {}
}
String seed;
String algoValue = this.seedProperties.getProperty("algorithm");
if ((seed != null) && (algoValue != null) && (seed.length() > 0) && (algoValue.length() > 0))
{
this.seedValue = seed;
if (!algoValue.equalsIgnoreCase("AES/CBC/PKCS5Padding")) {
throw new SeedException();
}
}
else
{
throw new SeedException();
}
}
public void setSeed(String seedVal)
throws Exception
{
if (seedVal != null)
{
String digest = SecurityUtils.hash(seedVal, "SHA-256", "", "");
seedVal = digest.substring(0, 16);
}
else
{
throw new RuntimeException("Seed cannot be null");
}
if (seedVal.equals(this.seedValue)) {
return;
}
this.seedValue = seedVal;
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
PasswordUtils.this.seedProperties.setProperty("seed", PasswordUtils.this.seedValue);
PasswordUtils.this.storeSeedProperties();
return null;
}
});
setChanged();
notifyObservers(this.seedValue);
}
public synchronized void addObserver(Observer o)
{
if (o == null) {
throw new NullPointerException();
}
if ((!(o instanceof RuntimeServiceImpl)) && (!(o instanceof SolrServiceImpl)) && (!(o instanceof SecurityManager)) && (!(o instanceof Executive)) && (!(o instanceof FlexAssemblerService)) && (!(o instanceof CronServiceImpl)) && (!(o instanceof MonitoringServiceImpl)) && (!(o instanceof MailSpooler)) && (!(o instanceof XmlRpcServiceImpl)) && (!(o instanceof ArchiveDeployServiceImpl))) {
throw new SeedException();
}
super.addObserver(o);
o.update(instance, this.seedValue);
}
public static String reEncryptWithNewSeed(String encryptedStr, String oldSeed, String newSeed, String oldAlgoValue, int majorVersion, int minorVersion)
{
return reEncryptWithNewSeed(encryptedStr, oldSeed, newSeed, false, oldAlgoValue, majorVersion, minorVersion);
}
public static String reEncryptWithNewSeed(String encryptedStr, String oldSeed, String newSeed, boolean noEncodingForDecryption, String oldAlgoValue, int majorVersion, int minorVersion)
{
if ((encryptedStr == null) || ((encryptedStr != null) && (encryptedStr.equals("")))) {
return encryptedStr;
}
if (majorVersion == 0)
{
PasswordUtils tmp31_28 = instance;tmp31_28.getClass();throw new SeedException(tmp31_28);
}
if (isAESS(majorVersion, minorVersion))
{
if ((oldAlgoValue != null) && (oldAlgoValue.length() > 0))
{
if ((oldAlgoValue.equalsIgnoreCase("AES/CBC/PKCS5Padding")) && (oldSeed.equals(newSeed))) {
return encryptedStr;
}
if (oldAlgoValue.equalsIgnoreCase("AES/CBC/PKCS5Padding")) {
return encryptWithAES_CBC_PKCS5(decryptWithAES_CBC_PKCS5(encryptedStr, oldSeed), newSeed);
}
}
else
{
PasswordUtils tmp110_107 = instance;tmp110_107.getClass();throw new SeedException(tmp110_107);
}
}
else {
return encryptWithAES_CBC_PKCS5(decryptWith3DES(encryptedStr, oldSeed, noEncodingForDecryption), newSeed);
}
return encryptedStr;
}
public static String reEncryptForSM(String encryptedStr, String oldSeed, String newSeed)
{
if ((encryptedStr == null) || ((encryptedStr != null) && (encryptedStr.equals("")))) {
return encryptedStr;
}
if ((oldSeed != null) && (oldSeed.equals(newSeed))) {
return encryptedStr;
}
return encryptWith3DES(decryptWithAES_CBC_PKCS5(encryptedStr, oldSeed), newSeed);
}
public static String reEncryptWithNewSeed(String encryptedStr, String oldSeed, String newSeed)
{
if ((encryptedStr == null) || ((encryptedStr != null) && (encryptedStr.equals("")))) {
return encryptedStr;
}
if ((oldSeed != null) && (oldSeed.equals(newSeed))) {
return encryptedStr;
}
return encryptWithAES_CBC_PKCS5(decryptWithAES_CBC_PKCS5(encryptedStr, oldSeed), newSeed);
}
public static String decryptPassword(String encryptedPassword, String seedval, String algoValue)
{
if ((encryptedPassword == null) || ((encryptedPassword != null) && (encryptedPassword.equals("")))) {
return encryptedPassword;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
String pwd = null;
if ((algoValue != null) && (algoValue.length() > 0)) {
if (algoValue.equalsIgnoreCase("AES/CBC/PKCS5Padding"))
{
pwd = decryptWithAES_CBC_PKCS5(encryptedPassword, seedval);
}
else
{
CFLogs.SERVER_LOG.error("Unknown Algorithm Specified."); PasswordUtils
tmp79_76 = instance;tmp79_76.getClass();throw new UnknownAlgorithmException(tmp79_76);
}
}
return pwd;
}
public static String decryptPassword(String encryptedPassword, String seedval)
{
if ((encryptedPassword == null) || ((encryptedPassword != null) && (encryptedPassword.equals("")))) {
return encryptedPassword;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
String pwd = null;
pwd = decryptWithAES_CBC_PKCS5(encryptedPassword, seedval);
return pwd;
}
public static String encryptPassword(String p, String seedval)
{
if ((p == null) || ((p != null) && (p.equals("")))) {
return p;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
return encryptWithAES_CBC_PKCS5(p, seedval);
}
public static String encryptWith3DES(String p, String seedval)
{
String secKey = CFPage.generate3DesKey(seedval);
return CFPage.Encrypt(p, secKey, "DESede", "Base64");
}
private static String decryptWith3DES(String encryptedPassword, String seedval, boolean noEncodingForDecryption)
{
String secKey = CFPage.generate3DesKey(seedval);
String pwd;
String pwd;
if (noEncodingForDecryption) {
pwd = CFPage.Decrypt(encryptedPassword, secKey, "DESede");
} else {
pwd = CFPage.Decrypt(encryptedPassword, secKey, "DESede", "Base64");
}
return pwd;
}
private static String decryptWithAES_CBC_PKCS5(String encryptedPassword, String seedval)
{
String secKey = generateAesKey(seedval);
return CFPage.Decrypt(encryptedPassword, secKey, "AES/CBC/PKCS5Padding", "Base64");
}
private static String decryptWithAES_CBC_PKCS5(String encryptedPassword, String seedval, String enc)
{
String secKey = generateAesKey(seedval);
if ((enc != null) && (enc.length() > 0)) {
return CFPage.Decrypt(encryptedPassword, secKey, "AES/CBC/PKCS5Padding", enc);
}
return CFPage.Decrypt(encryptedPassword, secKey, "AES/CBC/PKCS5Padding", "Base64");
}
private static String encryptWithAES_CBC_PKCS5(String p, String seedval)
{
String secKey = generateAesKey(seedval);
return CFPage.Encrypt(p, secKey, "AES/CBC/PKCS5Padding", "Base64");
}
private static String encryptWithAES_CBC_PKCS5(String p, String seedval, String enc)
{
String secKey = generateAesKey(seedval);
if ((enc != null) && (enc.length() > 0)) {
return CFPage.Encrypt(p, secKey, "AES/CBC/PKCS5Padding", enc);
}
return CFPage.Encrypt(p, secKey, "AES/CBC/PKCS5Padding", "Base64");
}
private static String generateAesKey(String seed)
{
if ((seed == null) || ((seed != null) && (seed.length() == 0)))
{
PasswordUtils tmp22_19 = instance;tmp22_19.getClass();throw new SeedException(tmp22_19);
}
byte[] seedBytes = null;
try
{
seedBytes = seed.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
seedBytes = seed.getBytes();
}
int seedLen = seedBytes.length;
seedBytes = Arrays.copyOf(seedBytes, 16);
if (seedLen < 16) {
for (int i = seedLen; i < 16; i++) {
seedBytes[i] = 35;
}
}
SecretKey secretKey = new SecretKeySpec(seedBytes, "AES");
return Base64Encoder.encode(secretKey.getEncoded());
}
private final void storeSeedProperties()
{
FileOutputStream foutput = null;
try
{
foutput = new FileOutputStream(SEEDFILEPATH);
this.seedProperties.store(foutput, null);
if (foutput != null) {
try
{
foutput.close();
}
catch (Exception e)
{
CFLogs.SERVER_LOG.error(e);
}
}
try
{
FileUtils.setUnixModes(SEEDFILEPATH, 600);
}
catch (Exception e)
{
CFLogs.SERVER_LOG.error(e);
}
}
catch (Exception ex)
{
throw new ServiceRuntimeException(ex);
}
finally
{
if (foutput != null) {
try
{
foutput.close();
}
catch (Exception e)
{
CFLogs.SERVER_LOG.error(e);
}
}
}
}
public static FastHashtable loadSeedForMigration(String filePath)
throws ServiceException
{
ServiceFactory.getSecurityService().authenticateAdmin();
FastHashtable struct = Struct.StructNew();
Properties props = new Properties();
if (filePath == null) {
return struct;
}
File seedFile = new File(filePath);
if ((seedFile != null) && (!seedFile.exists())) {
return struct;
}
try
{
if ((seedFileObj != null) && (seedFile != null) && (seedFileObj.getCanonicalPath().equalsIgnoreCase(seedFile.getCanonicalPath()))) {
return struct;
}
}
catch (IOException e)
{
CFLogs.SERVER_LOG.error(e);
}
FileInputStream finput = null;
try
{
finput = new FileInputStream(seedFile);
props.load(finput);
try
{
finput.close();
}
catch (Throwable t)
{
CFLogs.SERVER_LOG.error(t);
}
if (props == null) {
return struct;
}
}
catch (Throwable t) {}finally
{
try
{
finput.close();
}
catch (Throwable t)
{
CFLogs.SERVER_LOG.error(t);
}
}
String seed = props.getProperty("seed");
String algoValue = props.getProperty("algorithm");
if ((seed != null) && (seed.length() > 0)) {
struct.put("seed", seed);
}
if ((algoValue != null) && (algoValue.length() > 0)) {
struct.put("algorithm", algoValue);
}
return struct;
}
public static boolean isAESS(int majorVersion, int minorVersion)
{
if ((majorVersion > 9) || ((majorVersion == 9) && (minorVersion == 5))) {
return true;
}
return false;
}
public static String encryptWithEncoding(String p, String seedval, String enc)
{
if ((p == null) || ((p != null) && (p.equals("")))) {
return p;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
return encryptWithAES_CBC_PKCS5(p, seedval, enc);
}
public static String decryptWithEncoding(String encryptedPassword, String seedval, String enc)
{
if ((encryptedPassword == null) || ((encryptedPassword != null) && (encryptedPassword.equals("")))) {
return encryptedPassword;
}
if (seedval == null) {
throw new RuntimeException("Seed passed for encryption in null.");
}
String pwd = null;
pwd = decryptWithAES_CBC_PKCS5(encryptedPassword, seedval, enc);
return pwd;
}
public class SeedException
extends ApplicationException
{
private static final long serialVersionUID = 1L;
public SeedException() {}
}
public class UnknownAlgorithmException
extends ApplicationException
{
private static final long serialVersionUID = 1L;
public UnknownAlgorithmException() {}
}
}
public static String encryptPassword(String p, String seedval)
I think you forgot the seedval argument. Does this work?
newPass = passwordutils.encryptPassword("p455w0rd","thisisnotaseed");

java.io.StreamCorruptedException: invalid type code: 4C - replicationstream tomcat

I have following code
The function writes objects to the replicationstream provided by tomcat. IF the object is not serializable then I am trying to write "Misssing value".
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeInt(getType());
out.writeInt(getAction());
out.writeUTF(getName());
out.writeBoolean(getValue()!=null);
try
{
out.writeObject(getValue());
}
catch (Exception e)
{
System.out.println("Missing Value");
}
}
Following code reads object. Similar to read if the object is not serializable I try to read again to get read "Missing Value"
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
this.type = in.readInt();
this.action = in.readInt();
this.name = in.readUTF();
boolean hasValue=in.readBoolean();
try{
this.value = in.readObject();
}
catch(Exception er)
{
System.out.println("Missing Value");
}
}
I am getting following error, and I am not quite sure what does it mean. Both of the functions are being called for multiple times. First the writeExternal function is called for all the objects and then the readExternal.
java.io.StreamCorruptedException: invalid type code: 4C
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2480)
at java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2515)
at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2587)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2792)
at java.io.ObjectInputStream.readInt(ObjectInputStream.java:967)
EDIT
*Here is the code*
public class DeltaRequest
implements Externalizable
{
private LinkedList actions = new LinkedList();
private LinkedList actionPool = new LinkedList();
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
AttributeInfo info = null;
if (this.actionPool.size() > 0) {
info = (AttributeInfo)this.actionPool.removeFirst();
info.readExternal(in);
this.actions.addLast(info);
}
}
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeUTF(getSessionId());
out.writeBoolean(this.recordAllActions);
out.writeInt(getSize());
for (int i = 0; i < getSize(); i++) {
AttributeInfo info = (AttributeInfo)this.actions.get(i);
info.writeExternal(out);
}
}
protected byte[] serialize()
throws IOException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
writeExternal(oos);
oos.flush();
oos.close();
return bos.toByteArray();
}
private static class AttributeInfo implements Externalizable {
private String name = null;
private Object value = null;
private int action;
private int type;
public AttributeInfo() {
}
public AttributeInfo(int type, int action, String name, Object value) {
init(type, action, name, value);
}
public void init(int type, int action, String name, Object value)
{
this.name = name;
this.value = value;
this.action = action;
this.type = type;
}
public int getType() {
return this.type;
}
public int getAction() {
return this.action;
}
public Object getValue() {
return this.value;
}
public int hashCode() {
return this.name.hashCode();
}
public String getName() {
return this.name;
}
public void recycle() {
this.name = null;
this.value = null;
this.type = -1;
this.action = -1;
}
public boolean equals(Object o) {
if (!(o instanceof AttributeInfo)) return false;
AttributeInfo other = (AttributeInfo)o;
return other.getName().equals(getName());
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
this.type = in.readInt();
this.action = in.readInt();
this.name = in.readUTF();
boolean hasValue=in.readBoolean();
try{
this.value = in.readObject();
}
catch(Exception er)
{
out.writeObject("Value Missing");
}
}
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeInt(getType());
out.writeInt(getAction());
out.writeUTF(getName());
out.writeBoolean(getValue()!=null);
try
{
out.writeObject(getValue());
}
catch (Exception e)
{
out.writeObject("Value Missing");
}
}
public String toString()
{
StringBuffer buf = new StringBuffer("AttributeInfo[type=");
buf.append(getType()).append(", action=").append(getAction());
buf.append(", name=").append(getName()).append(", value=").append(getValue());
buf.append(", addr=").append(super.toString()).append("]");
return buf.toString();
}
}
}
Code:
This is how the above function are called.
protected DeltaRequest deserializeDeltaRequest(DeltaSession objbb, byte[] data)
throws ClassNotFoundException, IOException
{
try
{
objbb.lock();
ReplicationStream ois = getReplicationStream(data);
objbb.getDeltaRequest().readExternal(ois);
ois.close();
return objbb.getDeltaRequest();
} finally {
objbb.unlock();
}
}
protected byte[] serializeDeltaRequest(DeltaSession objbb, DeltaRequest objAA)
throws IOException
{
try
{
objbb.lock();
return objAA.serialize();
} finally {
objbb.unlock();
}
}
DeltaManager
public class DeltaManager extends ClusterManagerBase
{
public Session createSession(String sessionId)
{
return createSession(sessionId, true);
}
public Session createSession(String sessionId, boolean distribute)
{
if ((this.maxActiveSessions >= 0) && (this.sessions.size() >= this.maxActiveSessions)) {
this.rejectedSessions += 1;
throw new IllegalStateException(sm.getString("deltaManager.createSession.ise"));
}
DeltaSession session = (DeltaSession)super.createSession(sessionId);
if (distribute) {
sendCreateSession(session.getId(), session);
}
if (log.isDebugEnabled())
log.debug(sm.getString("deltaManager.createSession.newSession", session.getId(), new Integer(this.sessions.size())));
return session;
}
protected void sendCreateSession(String sessionId, DeltaSession session)
{
if (this.cluster.getMembers().length > 0) {
SessionMessage msg = new SessionMessageImpl(getName(), 1, null, sessionId, sessionId + "-" + System.currentTimeMillis());
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.sendMessage.newSession", this.name, sessionId));
msg.setTimestamp(session.getCreationTime());
this.counterSend_EVT_SESSION_CREATED += 1L;
send(msg);
}
}
protected DeltaRequest deserializeDeltaRequest(DeltaSession session, byte[] data)
throws ClassNotFoundException, IOException
{
try
{
session.lock();
ReplicationStream ois = getReplicationStream(data);
session.getDeltaRequest().readExternal(ois);
ois.close();
return session.getDeltaRequest();
} finally {
session.unlock();
}
}
protected byte[] serializeDeltaRequest(DeltaSession session, DeltaRequest deltaRequest)
throws IOException
{
try
{
session.lock();
return deltaRequest.serialize();
} finally {
session.unlock();
}
}
protected void deserializeSessions(byte[] data)
throws ClassNotFoundException, IOException
{
ClassLoader originalLoader = Thread.currentThread().getContextClassLoader();
ObjectInputStream ois = null;
try
{
ois = getReplicationStream(data);
Integer count = (Integer)ois.readObject();
int n = count.intValue();
for (int i = 0; i < n; i++) {
DeltaSession session = (DeltaSession)createEmptySession();
session.readObjectData(ois);
session.setManager(this);
session.setValid(true);
session.setPrimarySession(false);
session.access();
session.setAccessCount(0);
session.resetDeltaRequest();
if (findSession(session.getIdInternal()) == null) {
this.sessionCounter += 1;
} else {
this.sessionReplaceCounter += 1L;
if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.loading.existing.session", session.getIdInternal()));
}
add(session);
}
} catch (ClassNotFoundException e) {
log.error(sm.getString("deltaManager.loading.cnfe", e), e);
throw e;
} catch (IOException e) {
log.error(sm.getString("deltaManager.loading.ioe", e), e);
throw e;
}
finally {
try {
if (ois != null) ois.close();
}
catch (IOException f)
{
}
ois = null;
if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader);
}
}
protected byte[] serializeSessions(Session[] currentSessions)
throws IOException
{
ByteArrayOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
fos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
oos.writeObject(new Integer(currentSessions.length));
for (int i = 0; i < currentSessions.length; i++) {
((DeltaSession)currentSessions[i]).writeObjectData(oos);
}
oos.flush();
} catch (IOException e) {
log.error(sm.getString("deltaManager.unloading.ioe", e), e);
throw e;
} finally {
if (oos != null) {
try {
oos.close();
}
catch (IOException f) {
}
oos = null;
}
}
return fos.toByteArray();
}
public void start()
throws LifecycleException
{
if (!this.initialized) init();
if (this.started) {
return;
}
this.started = true;
this.lifecycle.fireLifecycleEvent("start", null);
generateSessionId();
try
{
Cluster cluster = getCluster();
if (cluster == null) {
Container context = getContainer();
if ((context != null) && ((context instanceof Context))) {
Container host = context.getParent();
if ((host != null) && ((host instanceof Host))) {
cluster = host.getCluster();
if ((cluster != null) && ((cluster instanceof CatalinaCluster))) {
setCluster((CatalinaCluster)cluster);
} else {
Container engine = host.getParent();
if ((engine != null) && ((engine instanceof Engine))) {
cluster = engine.getCluster();
if ((cluster != null) && ((cluster instanceof CatalinaCluster)))
setCluster((CatalinaCluster)cluster);
}
else {
cluster = null;
}
}
}
}
}
if (cluster == null) {
log.error(sm.getString("deltaManager.noCluster", getName()));
return;
}
if (log.isInfoEnabled()) {
String type = "unknown";
if ((cluster.getContainer() instanceof Host))
type = "Host";
else if ((cluster.getContainer() instanceof Engine)) {
type = "Engine";
}
log.info(sm.getString("deltaManager.registerCluster", getName(), type, cluster.getClusterName()));
}
if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.startClustering", getName()));
cluster.registerManager(this);
getAllClusterSessions();
}
catch (Throwable t) {
log.error(sm.getString("deltaManager.managerLoad"), t);
}
}
public synchronized void getAllClusterSessions()
{
if ((this.cluster != null) && (this.cluster.getMembers().length > 0)) {
long beforeSendTime = System.currentTimeMillis();
Member mbr = findSessionMasterMember();
if (mbr == null) {
return;
}
SessionMessage msg = new SessionMessageImpl(getName(), 4, null, "GET-ALL", "GET-ALL-" + getName());
this.stateTransferCreateSendTime = beforeSendTime;
this.counterSend_EVT_GET_ALL_SESSIONS += 1L;
this.stateTransfered = false;
try
{
synchronized (this.receivedMessageQueue) {
this.receiverQueue = true;
}
this.cluster.send(msg, mbr);
if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.waitForSessionState", getName(), mbr, Integer.valueOf(getStateTransferTimeout())));
waitForSendAllSessions(beforeSendTime);
} finally {
synchronized (this.receivedMessageQueue) {
for (Iterator iter = this.receivedMessageQueue.iterator(); iter.hasNext(); ) {
SessionMessage smsg = (SessionMessage)iter.next();
if (!this.stateTimestampDrop) {
messageReceived(smsg, smsg.getAddress() != null ? smsg.getAddress() : null);
}
else if ((smsg.getEventType() != 4) && (smsg.getTimestamp() >= this.stateTransferCreateSendTime))
{
messageReceived(smsg, smsg.getAddress() != null ? smsg.getAddress() : null);
}
else if (log.isWarnEnabled()) {
log.warn(sm.getString("deltaManager.dropMessage", getName(), smsg.getEventTypeString(), new Date(this.stateTransferCreateSendTime), new Date(smsg.getTimestamp())));
}
}
this.receivedMessageQueue.clear();
this.receiverQueue = false;
}
}
}
else if (log.isInfoEnabled()) { log.info(sm.getString("deltaManager.noMembers", getName())); }
}
protected void registerSessionAtReplicationValve(DeltaSession session)
{
if ((this.replicationValve == null) &&
((this.container instanceof StandardContext)) && (((StandardContext)this.container).getCrossContext())) {
Cluster cluster = getCluster();
if ((cluster != null) && ((cluster instanceof CatalinaCluster))) {
Valve[] valves = ((CatalinaCluster)cluster).getValves();
if ((valves != null) && (valves.length > 0)) {
for (int i = 0; (this.replicationValve == null) && (i < valves.length); i++) {
if ((valves[i] instanceof ReplicationValve)) this.replicationValve = ((ReplicationValve)valves[i]);
}
if ((this.replicationValve == null) && (log.isDebugEnabled())) {
log.debug("no ReplicationValve found for CrossContext Support");
}
}
}
}
if (this.replicationValve != null)
this.replicationValve.registerReplicationSession(session);
}
protected Member findSessionMasterMember()
{
Member mbr = null;
Member[] mbrs = this.cluster.getMembers();
if (mbrs.length != 0) mbr = mbrs[0];
if ((mbr == null) && (log.isWarnEnabled())) log.warn(sm.getString("deltaManager.noMasterMember", getName(), ""));
if ((mbr != null) && (log.isDebugEnabled())) log.warn(sm.getString("deltaManager.foundMasterMember", getName(), mbr));
return mbr;
}
public void messageDataReceived(ClusterMessage cmsg)
{
if ((cmsg != null) && ((cmsg instanceof SessionMessage))) {
SessionMessage msg = (SessionMessage)cmsg;
switch (msg.getEventType()) {
case 1:
case 2:
case 3:
case 4:
case 13:
synchronized (this.receivedMessageQueue) {
if (this.receiverQueue) {
this.receivedMessageQueue.add(msg);
return;
}
}
break;
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12: } messageReceived(msg, msg.getAddress() != null ? msg.getAddress() : null);
}
}
public ClusterMessage requestCompleted(String sessionId)
{
return requestCompleted(sessionId, false);
}
public ClusterMessage requestCompleted(String sessionId, boolean expires)
{
DeltaSession session = null;
try {
session = (DeltaSession)findSession(sessionId);
DeltaRequest deltaRequest = session.getDeltaRequest();
session.lock();
msg = null;
boolean isDeltaRequest = false;
synchronized (deltaRequest) {
isDeltaRequest = deltaRequest.getSize() > 0;
if (isDeltaRequest) {
this.counterSend_EVT_SESSION_DELTA += 1L;
byte[] data = serializeDeltaRequest(session, deltaRequest);
msg = new SessionMessageImpl(getName(), 13, data, sessionId, sessionId + "-" + System.currentTimeMillis());
session.resetDeltaRequest();
}
}
if (!isDeltaRequest) {
if ((!expires) && (!session.isPrimarySession())) {
this.counterSend_EVT_SESSION_ACCESSED += 1L;
msg = new SessionMessageImpl(getName(), 3, null, sessionId, sessionId + "-" + System.currentTimeMillis());
if (log.isDebugEnabled()) {
log.debug(sm.getString("deltaManager.createMessage.accessChangePrimary", getName(), sessionId));
}
}
}
else if (log.isDebugEnabled()) {
log.debug(sm.getString("deltaManager.createMessage.delta", getName(), sessionId));
}
if (!expires)
session.setPrimarySession(true);
long replDelta;
if ((!expires) && (msg == null)) {
replDelta = System.currentTimeMillis() - session.getLastTimeReplicated();
if (replDelta > getMaxInactiveInterval() * 1000) {
this.counterSend_EVT_SESSION_ACCESSED += 1L;
msg = new SessionMessageImpl(getName(), 3, null, sessionId, sessionId + "-" + System.currentTimeMillis());
if (log.isDebugEnabled()) {
log.debug(sm.getString("deltaManager.createMessage.access", getName(), sessionId));
}
}
}
if (msg != null) {
session.setLastTimeReplicated(System.currentTimeMillis());
msg.setTimestamp(session.getLastTimeReplicated());
}
return msg;
}
catch (IOException x)
{
SessionMessage msg;
log.error(sm.getString("deltaManager.createMessage.unableCreateDeltaRequest", sessionId), x);
return null;
} finally {
if (session != null) session.unlock();
}
}
protected void messageReceived(SessionMessage msg, Member sender)
{
if ((doDomainReplication()) && (!checkSenderDomain(msg, sender))) {
return;
}
ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
try
{
ClassLoader[] loaders = getClassLoaders();
if ((loaders != null) && (loaders.length > 0)) Thread.currentThread().setContextClassLoader(loaders[0]);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.eventType", getName(), msg.getEventTypeString(), sender));
switch (msg.getEventType()) {
case 4:
handleGET_ALL_SESSIONS(msg, sender);
break;
case 12:
handleALL_SESSION_DATA(msg, sender);
break;
case 14:
handleALL_SESSION_TRANSFERCOMPLETE(msg, sender);
break;
case 1:
handleSESSION_CREATED(msg, sender);
break;
case 2:
handleSESSION_EXPIRED(msg, sender);
break;
case 3:
handleSESSION_ACCESSED(msg, sender);
break;
case 13:
handleSESSION_DELTA(msg, sender);
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
}
} catch (Exception x) { log.error(sm.getString("deltaManager.receiveMessage.error", getName()), x);
} finally {
Thread.currentThread().setContextClassLoader(contextLoader);
}
}
protected void handleALL_SESSION_TRANSFERCOMPLETE(SessionMessage msg, Member sender)
{
this.counterReceive_EVT_ALL_SESSION_TRANSFERCOMPLETE += 1;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.transfercomplete", getName(), sender.getHost(), new Integer(sender.getPort())));
this.stateTransferCreateSendTime = msg.getTimestamp();
this.stateTransfered = true;
}
protected void handleSESSION_DELTA(SessionMessage msg, Member sender)
throws IOException, ClassNotFoundException
{
this.counterReceive_EVT_SESSION_DELTA += 1L;
byte[] delta = msg.getSession();
DeltaSession session = (DeltaSession)findSession(msg.getSessionID());
if (session != null) {
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.delta", getName(), msg.getSessionID())); try
{
session.lock();
DeltaRequest dreq = deserializeDeltaRequest(session, delta);
dreq.execute(session, this.notifyListenersOnReplication);
session.setPrimarySession(false);
} finally {
session.unlock();
}
}
}
protected void handleSESSION_CREATED(SessionMessage msg, Member sender)
{
this.counterReceive_EVT_SESSION_CREATED += 1L;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.createNewSession", getName(), msg.getSessionID()));
DeltaSession session = (DeltaSession)createEmptySession();
session.setManager(this);
session.setValid(true);
session.setPrimarySession(false);
session.setCreationTime(msg.getTimestamp());
session.setMaxInactiveInterval(getMaxInactiveInterval());
session.access();
if (this.notifySessionListenersOnReplication) {
session.setId(msg.getSessionID());
} else {
session.setIdInternal(msg.getSessionID());
add(session);
}
session.resetDeltaRequest();
session.endAccess();
}
protected void handleALL_SESSION_DATA(SessionMessage msg, Member sender)
throws ClassNotFoundException, IOException
{
this.counterReceive_EVT_ALL_SESSION_DATA += 1L;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataBegin", getName()));
byte[] data = msg.getSession();
deserializeSessions(data);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataAfter", getName()));
}
protected void handleGET_ALL_SESSIONS(SessionMessage msg, Member sender)
throws IOException
{
this.counterReceive_EVT_GET_ALL_SESSIONS += 1L;
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingBegin", getName()));
Session[] currentSessions = findSessions();
long findSessionTimestamp = System.currentTimeMillis();
if (isSendAllSessions()) {
sendSessions(sender, currentSessions, findSessionTimestamp);
}
else {
int len = currentSessions.length < getSendAllSessionsSize() ? currentSessions.length : getSendAllSessionsSize();
Session[] sendSessions = new Session[len];
for (int i = 0; i < currentSessions.length; i += getSendAllSessionsSize()) {
len = i + getSendAllSessionsSize() > currentSessions.length ? currentSessions.length - i : getSendAllSessionsSize();
System.arraycopy(currentSessions, i, sendSessions, 0, len);
sendSessions(sender, sendSessions, findSessionTimestamp);
if (getSendAllSessionsWaitTime() > 0)
try {
Thread.sleep(getSendAllSessionsWaitTime());
}
catch (Exception sleep)
{
}
}
}
SessionMessage newmsg = new SessionMessageImpl(this.name, 14, null, "SESSION-STATE-TRANSFERED", "SESSION-STATE-TRANSFERED" + getName());
newmsg.setTimestamp(findSessionTimestamp);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionTransfered", getName()));
this.counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE += 1;
this.cluster.send(newmsg, sender);
}
protected void sendSessions(Member sender, Session[] currentSessions, long sendTimestamp)
throws IOException
{
byte[] data = serializeSessions(currentSessions);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingAfter", getName()));
SessionMessage newmsg = new SessionMessageImpl(this.name, 12, data, "SESSION-STATE", "SESSION-STATE-" + getName());
newmsg.setTimestamp(sendTimestamp);
if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionData", getName()));
this.counterSend_EVT_ALL_SESSION_DATA += 1L;
this.cluster.send(newmsg, sender);
}
}
The problem here is that you are calling
this.writeExternal(oos);
instead of
oos.writeObject(this);
so the ObjectOutputStream never gets the chance to write the object preamble.
Similarly, you must call
Object o = ois.readObject();
rather than
Object o = this.readExternal(ois);
Re your non-serializable object, you should write a special object. At the moment you are treating every possible exception as just a missing object, when it could be a huge number of other things.

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

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

Categories

Resources