Java Serialization not working how I expected - java

I am trying to serialize an ArrayList<Prescription> using an ObjectOutputStream
Here is the Prescription class:
import java.io.Serializable;
import java.util.Calendar;
public class Prescription implements Serializable {
private static final long serialVersionUID = 4432845389029948144L;
private String name;
private String dosage;
private int originalQuantity = 0;
private int quantityRemaining = 0;
private String prescribingPharmacy;
private long dateStarted = 0;
private boolean taken_AM = false;
private boolean taken_Noon = false;
private boolean taken_PM = false;
private boolean taken_Mon = false;
private boolean taken_Tue = false;
private boolean taken_Wed = false;
private boolean taken_Thu = false;
private boolean taken_Fri = false;
private boolean taken_Sat = false;
private boolean taken_Sun = false;
public Prescription(){
this.name = "Unknown";
}
public Prescription(String name, String dosage, int quantity, String pharmacy){
this.name = name;
this.dosage = dosage;
this.originalQuantity = quantity;
this.quantityRemaining = quantity;
this.prescribingPharmacy = pharmacy;
this.dateStarted = Calendar.getInstance().getTimeInMillis();
}
public void setTaken(boolean AM, boolean Noon, boolean PM){
this.taken_AM = AM;
this.taken_Noon = Noon;
this.taken_PM = PM;
}
public void setTaken(boolean Mon, boolean Tue, boolean Wed, boolean Thu,
boolean Fri, boolean Sat, boolean Sun){
this.taken_Mon = Mon;
this.taken_Tue = Tue;
this.taken_Wed = Wed;
this.taken_Thu = Thu;
this.taken_Fri = Fri;
this.taken_Sat = Sat;
this.taken_Sun = Sun;
}
public String getName(){
return this.name;
}
}
Yet, when I try to do this, I get a NotSerializableException on the Prescription class. This doesn't make any sense to me, as I am only using primitive data types and String.
Here is the function I am using to do the serialization:
public boolean saveToFile(){
try {
FileOutputStream fos = this.context.openFileOutput(LIST_SAVE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this.pList);
oos.close();
} catch(FileNotFoundException e){
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

The code:
public static void main(String[] args) {
try {
List<Prescription> d = new ArrayList<Prescription>();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("C:\\temp\\Prescription.dat")));
d.add(new Prescription());
oos.writeObject(d);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
works without any exceptions with the class you posted, so there's something you're not telling us :-)

Related

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?

Another serialization issue

I'm stuck trying to deserialize a list of Scores. I spent my entire day searching here but couldn't find a solution.. My code looks something like this:
public class Score implements Comparable<Score>, Serializable {
private String name;
private int score;
// .......
}
public class MySortedList<T> extends...implements...,Serializable {
private ArrayList<T> list;
// ....
}
public class ScoreManager {
private final String FILEPATH;
private final String FILENAME = "highscores.ser";
private MySortedList<Score> scoreList;
public ScoreManager() {
File workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
if ((scoreList = loadScores()) == null) {
scoreList = new MySortedList<Score>();
}
}
public void addScore(Score score) {
scoreList.add(score);
saveScores();
}
public MySortedList<Score> getScoreList() {
return scoreList;
}
private void saveScores() {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(scoreList);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MySortedList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MySortedList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The loadScores() method returns just an empty MySortedList everytime.
However program succesfully creates the highscores.ser file in the correct place and I have absolutely no errors. Score objects are added correctly to the MySortedList object.
Any ideas? Perhaps worth mentioning that this is a part of a bigger program made in Swing. the methods in the ScoreManager class is called when the player dies
only if it can help, this code is working for me:
class Score implements Comparable<Score>, Serializable{
private int point;
public Score(int point) {
this.point = point;
}
public int getPoint(){
return point;
}
#Override
public int compareTo(Score o) {
if (o.getPoint() == this.getPoint())
return 0;
return this.point < o.getPoint() ? - 1 : 1;
}
public String toString() {
return "points: " + point;
}
}
class MyList<T> implements Serializable {
private ArrayList<T> list = new ArrayList<>();
public void add(T e){
list.add(e);
}
public void show() {
System.out.println(list);
}
}
public class Main {
File workingFolder;
String FILEPATH;
private final String FILENAME = "highscores.ser";
MyList<Score> list = new MyList<>();
public static void main(String[] args) {
Main main = new Main();
main.createFolder();
main.addItems();
main.saveScores();
MyList<Score> tempList = main.loadScores();
tempList.show();
main.addMoreItems();
main.saveScores();
tempList = main.loadScores();
tempList.show();
}
private void addItems() {
Score sc = new Score(10);
list.add(sc);
}
private void addMoreItems() {
Score sc1 = new Score(20);
list.add(sc1);
Score sc2 = new Score(30);
list.add(sc2);
}
private void createFolder() {
workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
}
private void saveScores() {
System.out.println("before save: " + list);
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(list);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MyList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MyList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

Get information about a page using facebook4j

Is there a possibility to get the String of the page's information in the about section?
An Example: https://www.facebook.com/FacebookDevelopers
Here is the info: "Build, grow, and monetize your app with Facebook. https://developers.facebook.com/"
I found out that the Facebook graph api supports this by the Field about on a Page.
Thanks for help in advance!
Best regards,
Dominic
you can below snippet code for getting facebook page information in java :
private static final String FacebookURL_PAGES = "me/accounts?fields=access_token,category,id,perms,picture{url},can_post,is_published,cover,fan_count,is_verified,can_checkin,global_brand_page_name,link,country_page_likes,is_always_open,is_community_page,new_like_count,overall_star_rating,name";
public List<FacebookPageModel> getPages(String accessToken) throws FacebookException, JSONException {
JSONObject posts = getBatch(accessToken,FacebookURL_PAGES);
Gson g =new Gson();
System.out.println(posts);
JSONArray postsData = posts.getJSONArray("data");
System.out.println(g.toJson(postsData));
return getPageList(postsData);
}
private JSONObject getBatch(String accessToken, String url) throws FacebookException{
Gson g = new Gson();
Facebook facebook = getFacebook(accessToken);
BatchRequests<BatchRequest> batch = new BatchRequests<BatchRequest>();
batch.add(new BatchRequest(RequestMethod.GET, url));
List<BatchResponse> results = facebook.executeBatch(batch);
BatchResponse result2 = results.get(0);
System.out.println(g.toJson(result2.asJSONObject()));
return result2.asJSONObject();
}
private Facebook getFacebook(String accessToken){
if(accessToken == null){
System.out.println("Access Token null while request for Facebook Instance !");
return null;
}
Facebook facebook = new FacebookFactory().getInstance();
facebook.setOAuthAppId(appId, appSecret);
facebook.setOAuthPermissions("email,publish_stream, publish_actions");
facebook.setOAuthAccessToken(new AccessToken(accessToken, null));
return facebook;
}
private List<FacebookPageModel> getPageList(JSONArray pagesData) throws JSONException{
Gson g = new Gson();
List<FacebookPageModel> pages = new ArrayList<FacebookPageModel>();
SimpleDateFormat desiredFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = null;
for (int i = 0; i < pagesData.length(); i++) {
FacebookPageModel obj = new FacebookPageModel();
JSONObject page = pagesData.getJSONObject(i);
System.out.println(g.toJson(page));
try{
obj.setAccessToken(page.getString("access_token"));
}catch(Exception ee){
obj.setAccessToken(null);
}
try{
obj.setCategory(page.getString("category"));
}catch(Exception ee){
obj.setCategory(null);
}
try{
obj.setId(page.getString("id"));
}catch(Exception ee){
obj.setId(null);
}
try{
obj.setName(page.getString("name"));
}catch(Exception ee){
obj.setName(null);
}
try{
obj.setCanPost(page.getBoolean("can_post"));
}catch(Exception ee){
obj.setCanPost(false);
}
try{
JSONObject picture = page.getJSONObject("picture");
JSONObject pictureData = picture.getJSONObject("data");
obj.setPageProfilePic(pictureData.getString("url"));
}catch(Exception ee){
obj.setCanPost(false);
}
try{
obj.setPublished(page.getBoolean("is_published"));
}catch(Exception ee){
obj.setPublished(false);
}
try{
obj.setFanCount(page.getLong("fan_count"));
}catch(Exception ee){
obj.setFanCount(0L);
}
try{
obj.setVerified(page.getBoolean("is_verified"));
}catch(Exception ee){
obj.setVerified(false);
}
try{
obj.setCanCheckin(page.getBoolean("can_checkin"));
}catch(Exception ee){
obj.setCanCheckin(false);
}
try{
obj.setGlobalBranPageName(page.getString("global_brand_page_name"));
}catch(Exception ee){
obj.setGlobalBranPageName(null);
}
try{
obj.setPageLink(page.getString("link"));
}catch(Exception ee){
obj.setPageLink(null);
}
try{
obj.setNewLikeCount(page.getLong("new_like_count"));
}catch(Exception ee){
obj.setNewLikeCount(0L);
}
try{
obj.setOverallStarRating(page.getLong("overall_star_rating"));
}catch(Exception ee){
obj.setOverallStarRating(0L);
}
try{
obj.setOverallStarRating(page.getLong("overall_star_rating"));
}catch(Exception ee){
obj.setOverallStarRating(0L);
}
pages.add(obj);
}
System.out.println(g.toJson(pages));
return pages;
}
public class FacebookPageModel {
//access_token
private String accessToken;
//name
private String name;
//id
private String id;
//category
private String category;
// can_post
private boolean canPost;
private String pageProfilePic;
// is_published
private boolean isPublished;
// fan_count
private long fanCount;
// is_verified
private boolean isVerified;
// can_checkin
private boolean canCheckin;
// global_brand_page_name
private String globalBranPageName;
// link
private String pageLink;
// new_like_count
private long newLikeCount;
// overall_star_rating
private long overallStarRating;
public boolean isCanPost() {
return canPost;
}
public void setCanPost(boolean canPost) {
this.canPost = canPost;
}
public String getPageProfilePic() {
return pageProfilePic;
}
public void setPageProfilePic(String pageProfilePic) {
this.pageProfilePic = pageProfilePic;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public boolean isPublished() {
return isPublished;
}
public void setPublished(boolean isPublished) {
this.isPublished = isPublished;
}
public long getFanCount() {
return fanCount;
}
public void setFanCount(long fanCount) {
this.fanCount = fanCount;
}
public boolean isVerified() {
return isVerified;
}
public void setVerified(boolean isVerified) {
this.isVerified = isVerified;
}
public boolean isCanCheckin() {
return canCheckin;
}
public void setCanCheckin(boolean canCheckin) {
this.canCheckin = canCheckin;
}
public String getGlobalBranPageName() {
return globalBranPageName;
}
public void setGlobalBranPageName(String globalBranPageName) {
this.globalBranPageName = globalBranPageName;
}
public String getPageLink() {
return pageLink;
}
public void setPageLink(String pageLink) {
this.pageLink = pageLink;
}
public long getNewLikeCount() {
return newLikeCount;
}
public void setNewLikeCount(long newLikeCount) {
this.newLikeCount = newLikeCount;
}
public long getOverallStarRating() {
return overallStarRating;
}
public void setOverallStarRating(long overallStarRating) {
this.overallStarRating = overallStarRating;
}
}

Hadoop Writable for Date/Calendar

I'm looking to implement a custom hadoop Writable class where one of the fields is a time stamp. I can't seem to find a class in the hadoop libraries (e. g. a Writable for Date or Calendar) which would make this easy. I'm thinking of creating a custom writable using get/setTimeInMillis on Calendar, but I'm wondering if there is a better/built-in solution to this problem.
There is no Writable for a Calendar/Date in Hadoop. Considering that you can get the timeInMillis as a long from the Calendar object you can use the LongWritable to serialiaze a calendar object if and only if your application always uses the default UTC time zone (i.e. it's "agnostic" to time zones, it always assumes that timeInMillis represent an UTC time).
If you use another time zone or if your application needs to be able to interpret a timeInMillis with respect to various time zone, you'll have to write from scratch a default Writable implementation.
Here's a custom writable that I generated for you to illustrate a writable with three properties, one of which is a date. You can see that the data value is persisted as a long and that it's easy to convert a long to and from a Date. If having three properties is too much, I can just generate a writable with a date for you.
package com.lmx.writable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import com.eaio.uuid.UUID;
import org.apache.hadoop.io.*;
import org.apache.pig.ResourceSchema;
import org.apache.pig.ResourceSchema.ResourceFieldSchema;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataType;
import org.apache.pig.data.DefaultDataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MyCustomWritable implements Writable {
public static int PROPERTY_DATE = 0;
public static int PROPERTY_COUNT = 1;
public static int PROPERTY_NAME = 2;
private boolean[] changeFlag = new boolean[3];
private Date _date;
private int _count;
private String _name;
public MyCustomWritable() {
resetChangeFlags();
}
public MyCustomWritable(Date _date, int _count, String _name) {
resetChangeFlags();
setDate(_date);
setCount(_count);
setName(_name);
}
public MyCustomWritable(byte[] bytes) {
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
DataInput in = new DataInputStream(is);
try { readFields(in); } catch (IOException e) { }
resetChangeFlags();
}
public Date getDate() {
return _date;
}
public void setDate(Date value) {
_date = value;
changeFlag[PROPERTY_DATE] = true;
}
public int getCount() {
return _count;
}
public void setCount(int value) {
_count = value;
changeFlag[PROPERTY_COUNT] = true;
}
public String getName() {
return _name;
}
public void setName(String value) {
_name = value;
changeFlag[PROPERTY_NAME] = true;
}
public void readFields(DataInput in) throws IOException {
// Read Date _date
if (in.readBoolean()) {
_date = new Date(in.readLong());
changeFlag[PROPERTY_DATE] = true;
} else {
_date = null;
changeFlag[PROPERTY_DATE] = false;
}
// Read int _count
_count = in.readInt();
changeFlag[PROPERTY_COUNT] = true;
// Read String _name
if (in.readBoolean()) {
_name = Text.readString(in);
changeFlag[PROPERTY_NAME] = true;
} else {
_name = null;
changeFlag[PROPERTY_NAME] = false;
}
}
public void write(DataOutput out) throws IOException {
// Write Date _date
if (_date == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
out.writeLong(_date.getTime());
}
// Write int _count
out.writeInt(_count);
// Write String _name
if (_name == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
Text.writeString(out,_name);
}
}
public byte[] getBytes() throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(os);
write(out);
out.flush();
out.close();
return os.toByteArray();
}
public void resetChangeFlags() {
changeFlag[PROPERTY_DATE] = false;
changeFlag[PROPERTY_COUNT] = false;
changeFlag[PROPERTY_NAME] = false;
}
public boolean getChangeFlag(int i) {
return changeFlag[i];
}
public byte[] getDateAsBytes() throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(os);
// Write Date _date
if (_date == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
out.writeLong(_date.getTime());
}
out.flush();
out.close();
return os.toByteArray();
}
public byte[] getCountAsBytes() throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(os);
// Write int _count
out.writeInt(_count);
out.flush();
out.close();
return os.toByteArray();
}
public byte[] getNameAsBytes() throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(os);
// Write String _name
if (_name == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
Text.writeString(out,_name);
}
out.flush();
out.close();
return os.toByteArray();
}
public void setDateFromBytes(byte[] b) throws IOException {
ByteArrayInputStream is = new ByteArrayInputStream(b);
DataInput in = new DataInputStream(is);
int len;
// Read Date _date
if (in.readBoolean()) {
_date = new Date(in.readLong());
changeFlag[PROPERTY_DATE] = true;
} else {
_date = null;
changeFlag[PROPERTY_DATE] = false;
}
}
public void setCountFromBytes(byte[] b) throws IOException {
ByteArrayInputStream is = new ByteArrayInputStream(b);
DataInput in = new DataInputStream(is);
int len;
// Read int _count
_count = in.readInt();
changeFlag[PROPERTY_COUNT] = true;
}
public void setNameFromBytes(byte[] b) throws IOException {
ByteArrayInputStream is = new ByteArrayInputStream(b);
DataInput in = new DataInputStream(is);
int len;
// Read String _name
if (in.readBoolean()) {
_name = Text.readString(in);
changeFlag[PROPERTY_NAME] = true;
} else {
_name = null;
changeFlag[PROPERTY_NAME] = false;
}
}
public Tuple asTuple() throws ExecException {
Tuple tuple = TupleFactory.getInstance().newTuple(3);
if (getDate() == null) {
tuple.set(0, (Long) null);
} else {
tuple.set(0, new Long(getDate().getTime()));
}
tuple.set(1, new Integer(getCount()));
if (getName() == null) {
tuple.set(2, (String) null);
} else {
tuple.set(2, getName());
}
return tuple;
}
public static ResourceSchema getPigSchema() throws IOException {
ResourceSchema schema = new ResourceSchema();
ResourceFieldSchema fieldSchema[] = new ResourceFieldSchema[3];
ResourceSchema bagSchema;
ResourceFieldSchema bagField[];
fieldSchema[0] = new ResourceFieldSchema();
fieldSchema[0].setName("date");
fieldSchema[0].setType(DataType.LONG);
fieldSchema[1] = new ResourceFieldSchema();
fieldSchema[1].setName("count");
fieldSchema[1].setType(DataType.INTEGER);
fieldSchema[2] = new ResourceFieldSchema();
fieldSchema[2].setName("name");
fieldSchema[2].setType(DataType.CHARARRAY);
schema.setFields(fieldSchema);
return schema;
}
public static MyCustomWritable fromJson(String source) {
MyCustomWritable obj = null;
try {
JSONObject jsonObj = new JSONObject(source);
obj = fromJson(jsonObj);
} catch (JSONException e) {
System.out.println(e.toString());
}
return obj;
}
public static MyCustomWritable fromJson(JSONObject jsonObj) {
MyCustomWritable obj = new MyCustomWritable();
try {
if (jsonObj.has("date")) {
obj.setDate(new Date(jsonObj.getLong("date")));
}
if (jsonObj.has("count")) {
obj.setCount(jsonObj.getInt("count"));
}
if (jsonObj.has("name")) {
obj.setName(jsonObj.getString("name"));
}
} catch (JSONException e) {
System.out.println(e.toString());
obj = null;
}
return obj;
}
public JSONObject toJson() {
try {
JSONObject jsonObj = new JSONObject();
JSONArray jsonArray;
if (getDate() != null) {
jsonObj.put("date", getDate().getTime());
}
jsonObj.put("count", getCount());
if (getName() != null) {
jsonObj.put("name", getName());
}
return jsonObj;
} catch (JSONException e) { }
return null;
}
public String toJsonString() {
return toJson().toString();
}
}

Java: Serializing beginner problem :-(

I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.
package sotring;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.bcel.internal.generic.INEG;
public class storeing {
public static void storeMail(Message[] mail){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser"));
out.writeObject(mail);
out.flush();
out.close();
} catch (IOException e) {
}
}
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
for (int i=0; i< array.length;i++)
System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent());
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user1 = new User("User1", "geheim");
User user2 = new User("User2", "geheim");
Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar");
Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo");
Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) ");
Message [] mails = {email1, email2, email3};
storeMail(mails);
Message[] restored = getStoredMails();;
}
}
Here are the user and message class
public class Message implements Serializable{
static final long serialVersionUID = -1L;
private String receiver; //Empfänger
private String sender; //Absender
private String Betreff;
private String content;
private String timestamp;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Message (String receiver, String sender, String Betreff, String content) {
this.Betreff= Betreff;
this.receiver = receiver;
this.sender = sender;
this.content = content;
this.timestamp = getDateTime();
}
Message() { // Just for loaded msg
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getContent() {
return content;
}
public String getTime() {
return timestamp;
}
public void setContent(String content) {
this.content = content;
}
}
public class User implements Serializable{
static final long serialVersionUID = -1L;
private String username; //unique Username
private String ipadress; //changes everytime
private String password; //Password
private int unreadMsg; //Unread Messages
private static int usercount;
private boolean online;
public String getName(){
return username;
}
public boolean Status() {
return online;
}
public void setOnline() {
this.online = true;
}
public void setOffline() {
this.online = false;
}
User(String username,String password){
if (true){
this.username = username;
this.password = password;
usercount++;
} else System.out.print("Username not availiable");
}
public void changePassword(String newpassword){
password = newpassword;
}
public void setIP(String newip){
ipadress = newip;
}
public String getIP(){
if (ipadress.length() >= 7){
return ipadress;
} else return "ip address not set.";
}
public int getUnreadMsg() {
return unreadMsg;
}
}
Here is the exception:
exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type Message[]
at sotring.storeing.getStoredMails(storeing.java:22)
at sotring.storeing.main(storeing.java:57)
THANK YOU FOR YOUR HELP!!!!!!!!!!!
The catch clauses need to return something.
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null; //fix
}
If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.
Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.
On a different note, have you considered a third-party serializer library?
I'm using Simple right now for a project, and it seems to do stuff just fine with very little effort.
in the exception handling blocks of the getStoredMails method you do not return anything.
Suggested modification:
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null;
}
I modified the source. I added "return null" in exception and the for loop the output in the function. And the function gives me the right output but then throws it the exception.

Categories

Resources