JAXB This will cause infinitely deep XML - java

I'm writing a simple budgeting program that has a budget class with an array of category classes. Each category class can have child category classes. When I try to save the data to an XML file using JAXB, I get the error
com.sun.istack.internal.SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML
I have searched on the error and see it is caused by a parent child relationship where the parent references the child and the child references the parent. Most answers are to use #XMLTransient.
My problem is that my Category class does not reference either the budget parent nor the category parent if one exists.
I am new to JAXB, but not Java. I'm using this app as a learning experience for JAXB and also JavaFX.
Below are my Budget and Category classes.
package budget.model;
import java.time.LocalDate;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import budget.util.BudgetProperties.DayOfWeek;
import budget.util.LocalDateAdapter;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
#XmlRootElement(name = "budget")
public class Budget {
// default to Sunday
ObjectProperty<DayOfWeek> startOfWeek = new SimpleObjectProperty<DayOfWeek>(DayOfWeek.SUNDAY);
ObjectProperty<LocalDate> startDate = new SimpleObjectProperty<LocalDate>();
IntegerProperty daysBeyondWeek = new SimpleIntegerProperty(3);
IntegerProperty numberOfWeeks = new SimpleIntegerProperty();
ObservableList<Category> categories = FXCollections.observableArrayList();
// startOfWeek
public DayOfWeek getStartOfWeek() {
return this.startOfWeek.getValue();
}
public void setStartOfWeek(DayOfWeek startOfWeek) {
this.startOfWeek.set(startOfWeek);
}
public ObjectProperty<DayOfWeek> startOfWeekProperty() {
return this.startOfWeek;
}
// startDate
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getStartDate() {
return this.startDate.getValue();
}
public void setStartDate(LocalDate startDate){
this.startDate.set(startDate);
}
public ObjectProperty<LocalDate> startDateProperty() {
return this.startDate;
}
// daysBeyondWeek
public Integer getDaysBeyondWeek() {
return this.daysBeyondWeek.getValue();
}
public void setDaysBeyondWeek(Integer daysBeyondWeek) {
this.daysBeyondWeek.set(daysBeyondWeek);
}
public IntegerProperty daysBeyondWeekProperty() {
return this.daysBeyondWeek;
}
// numberOFWeeks
public Integer getNumberOfWeeks() {
return this.numberOfWeeks.getValue();
}
public void setNumberOfWeeks(Integer numberOfWeeks) {
this.numberOfWeeks.set(numberOfWeeks);
}
public IntegerProperty numberOfWeeksProperty() {
return numberOfWeeks;
}
// categories
public ObservableList<Category> getCategories () {
return categories;
}
public void setCategories(ObservableList<Category> categories) {
this.categories = categories;
}
public ObservableList<Category> categoriesProperty () {
return categories;
}
}
package budget.model;
import java.time.LocalDate;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import budget.util.BudgetProperties.RepeatFrequency;
import budget.util.LocalDateAdapter;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Category {
StringProperty name = new SimpleStringProperty("");
ObservableList<Category> children = FXCollections.observableArrayList();
StringProperty comments = new SimpleStringProperty("");
ObjectProperty<RepeatFrequency> repeatFrequency = new SimpleObjectProperty<RepeatFrequency>();
ObjectProperty<LocalDate> dueDate = new SimpleObjectProperty<LocalDate>();
DoubleProperty budgetAmount = new SimpleDoubleProperty();
DoubleProperty actualAmount = new SimpleDoubleProperty();
// name
public String getName() {
return name.getValue();
}
public void setName(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
// children
public ObservableList<Category> getChildren() {
return children;
}
public void setChildren(ObservableList<Category> children) {
this.children.setAll(children);
}
public void addChild(Category category) {
this.children.add(category);
}
// isParent
public Boolean isParent() {
// return this.parent.getValue();
if (children == null || children.isEmpty() || children.size() == 0) {
return false;
} else {
return true;
}
}
// comments
public String getComments() {
return comments.getValue();
}
public void setComments(String comments) {
this.comments.set(comments);
}
public StringProperty commentsProperty() {
return comments;
}
// repeatFrequency
public RepeatFrequency getRepeatFrequency() {
return this.repeatFrequency.getValue();
}
public void setRepeatFrequency(RepeatFrequency repeatFrequency) {
this.repeatFrequency.set(repeatFrequency);
}
public ObjectProperty<RepeatFrequency> repeatFrequencyProperty() {
return this.repeatFrequency;
}
// dueDate
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getDueDate() {
return this.dueDate.getValue();
}
public void setDueDate(LocalDate dueDate) {
this.dueDate.set(dueDate);
}
public ObjectProperty<LocalDate> dueDateProperty() {
return this.dueDate;
}
// budgetAmount
public Double getBudgetAmount() {
return this.budgetAmount.getValue();
}
public void setBudgetAmount(Double budgetAmount) {
this.budgetAmount.set(budgetAmount);
}
public DoubleProperty budgetAmountProperty() {
return this.budgetAmount;
}
// actualAmount
public Double getActualAmount() {
return this.actualAmount.getValue();
}
public void setActualAmount(Double actualAmount) {
this.actualAmount.set(actualAmount);
}
public DoubleProperty actualAmountProperty() {
return this.actualAmount;
}
}
There is another class that handles the marshalling. The function in this class is below
public void saveBudgetData(Budget budget) {
File file = new File(path + BUDGET_FILE);
try {
JAXBContext context = JAXBContext
.newInstance(Budget.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Marshalling and saving XML to the file.
m.marshal(budget, file);
} catch (Exception e) { // catches ANY exception
logger.error("exception: ", e);
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.showAndWait();
}
}
I understand that this is a recursive relationship between categories. Is this what it is complaining about? I did not see find this scenario in my searching.
Thanks.
Cleaned up Budget and Category classes
package budget.model;
import java.time.LocalDate;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import budget.util.BudgetProperties.DayOfWeek;
import budget.util.LocalDateAdapter;
#XmlRootElement(name = "budget")
public class BudgetNoFX {
// default to Sunday
DayOfWeek startOfWeek = DayOfWeek.SUNDAY;
// default to now
LocalDate startDate = LocalDate.now();
// number of days beyond week end to include in list of due bills
// default to 3
Integer daysBeyondWeek = new Integer(3);
Integer numberOfWeeks = new Integer(0);
ArrayList<CategoryNoFX> categories = new ArrayList<CategoryNoFX>();
// startOfWeek
public DayOfWeek getStartOfWeek() {
return this.startOfWeek;
}
public void setStartOfWeek(DayOfWeek startOfWeek) {
this.startOfWeek = startOfWeek;
}
// startDate
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getStartDate() {
return this.startDate;
}
public void setStartDate(LocalDate startDate){
this.startDate = startDate;
}
// daysBeyondWeek
public Integer getDaysBeyondWeek() {
return this.daysBeyondWeek;
}
public void setDaysBeyondWeek(Integer daysBeyondWeek) {
this.daysBeyondWeek = daysBeyondWeek;
}
// numberOFWeeks
public Integer getNumberOfWeeks() {
return this.numberOfWeeks;
}
public void setNumberOfWeeks(Integer numberOfWeeks) {
this.numberOfWeeks = numberOfWeeks;
}
// categories
public ArrayList<CategoryNoFX> getCategories () {
return categories;
}
public void setCategories(ArrayList<CategoryNoFX> categories) {
this.categories = categories;
}
}
package budget.model;
import java.time.LocalDate;
import java.util.ArrayList;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import budget.util.BudgetProperties.RepeatFrequency;
import budget.util.LocalDateAdapter;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class CategoryNoFX {
public static final String ROOT_CATEGORY = "ROOT";
String name = new String("");
ArrayList<CategoryNoFX> children = new ArrayList<CategoryNoFX>();
String comments = new String("");
// default to monthly
RepeatFrequency repeatFrequency = RepeatFrequency.MONTHLY;
LocalDate dueDate = LocalDate.now();
Double budgetAmount = new Double(0);
Double actualAmount = new Double(0);
// name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// children
public ArrayList<CategoryNoFX> getChildren() {
return children;
}
public void setChildren(ArrayList<CategoryNoFX> children) {
this.children = children;
}
public void addChild(CategoryNoFX category) {
this.children.add(category);
}
// isParent
public Boolean isParent() {
if (children == null || children.isEmpty() || children.size() == 0) {
return false;
} else {
return true;
}
}
// comments
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
// repeatFrequency
public RepeatFrequency getRepeatFrequency() {
return this.repeatFrequency;
}
public void setRepeatFrequency(RepeatFrequency repeatFrequency) {
this.repeatFrequency = repeatFrequency;
}
// dueDate
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getDueDate() {
return this.dueDate;
}
public void setDueDate(LocalDate dueDate) {
this.dueDate = dueDate;
}
// budgetAmount
public Double getBudgetAmount() {
return this.budgetAmount;
}
public void setBudgetAmount(Double budgetAmount) {
this.budgetAmount = budgetAmount;
}
// actualAmount
public Double getActualAmount() {
return this.actualAmount;
}
public void setActualAmount(Double actualAmount) {
this.actualAmount = actualAmount;
}
}
I updated the saveBudgetData function to use the new budget class
public void saveBudgetData(BudgetNoFX budget) {
File file = new File(path + BUDGET_FILE);
try {
JAXBContext context = JAXBContext
.newInstance(BudgetNoFX.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Marshalling and saving XML to the file.
m.marshal(budget, file);
} catch (Exception e) { // catches ANY exception
logger.error("exception: ", e);
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.showAndWait();
}
}

I'm a bit embarrassed. I know you have to be careful with recursion and that was my problem.
Before building the ui, I hardcoded some values - created a budget and added some categories. I should have posted that code. I had set one of the categories as a child to itself.
Category food = new Category();
food.setName("Food");
categories.add(food);
Category groceries = new Category();
groceries.setBudgetAmount(new Double(120));
groceries.setName("Groceries");
// groceries.setParentCategory("Food");
groceries.setRepeatFrequency(RepeatFrequency.WEEKLY);
food.addChild(food); <-- problem line
Once I fixed the offending line to
food.addChild(groceries);
it started working.
I found it by by commenting out the save funciton to XML and instead wrote out my budget object to the screen.
I had recently read this tutorial: http://code.makery.ch/library/javafx-8-tutorial/ and built another simple app. This is where the LocalDateAdapter class came from. In part 5, he explains about jaxb and lists. I've made some code changes to better handle my lists and I'm getting xml output that I'm happy with.
Thanks for taking the time to look at my code and help me out.
If I ever get this done, maybe I'll post the app/code to the Internet. I've never done that before and don't know the best place though.
Again, thanks.
Chris

Related

How I can to validate my Junit test with Gson parse

I'm using the Gson library and jakarta. Although I have been able to use the conversion in CarrinhoResource.java as below, my ClienteTest.java cannot use the String content (already in json) inside the cart. I cant run my test a just only message into my intellij is (Cannot resolve method 'fromJson(java.lang.String)').
Can someone help me?
Class CarrinhoResource.java
package br.com.alura.loja.resource;
import br.com.alura.loja.dao.CarrinhoDAO;
import br.com.alura.loja.modelo.Carrinho;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
#Path("/v1/carrinhos")
public class CarrinhoResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public String busca(){
Carrinho carrinho = new CarrinhoDAO().busca(1L);
return carrinho.toJson();
}
}
Carrinho.java
package br.com.alura.loja.modelo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gson.Gson;
public class Carrinho {
private List<Produto> produtos = new ArrayList<Produto>();
private String rua;
private String cidade;
private long id;
public Carrinho adiciona(Produto produto) {
produtos.add(produto);
return this;
}
public Carrinho para(String rua, String cidade) {
this.rua = rua;
this.cidade = cidade;
return this;
}
public Carrinho setId(long id) {
this.id = id;
return this;
}
public String getRua() {
return rua;
}
public void setRua(String rua) {
this.rua = rua;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public long getId() {
return id;
}
public void remove(long id) {
for (Iterator iterator = produtos.iterator(); iterator.hasNext();) {
Produto produto = (Produto) iterator.next();
if(produto.getId() == id) {
iterator.remove();
}
}
}
public void troca(Produto produto) {
remove(produto.getId());
adiciona(produto);
}
public void trocaQuantidade(Produto produto) {
for (Iterator iterator = produtos.iterator(); iterator.hasNext();) {
Produto p = (Produto) iterator.next();
if(p.getId() == produto.getId()) {
p.setQuantidade(produto.getQuantidade());
return;
}
}
}
public List<Produto> getProdutos() {
return produtos;
}
public String toJson() {
return new Gson().toJson(this);
}
}
ClienteTest.java
package br.com.alura.loja;
import br.com.alura.loja.modelo.Carrinho;
import com.google.gson.*;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import org.junit.Assert;
import org.junit.Test;
public class ClienteTest {
#Test
public void testaConexaoServidor() {
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8085");
String conteudo = target.path("/v1/carrinhos").request().get(String.class);
Carrinho carrinho = (Carrinho) new Gson().fromJson(conteudo); **//Cannot resolve method 'fromJson(java.lang.String)'/**
System.out.println(carrinho);
Assert.assertEquals("Rua Vergueiro, 3185", carrinho.getRua());
}
}
Carrinho carrinho = (Carrinho) new Gson().fromJson(conteudo); **//Cannot resolve method 'fromJson(java.lang.String)'/**
The reason for this is that there is no Gson.fromJson(String) method, see the Gson class documentation. For deserialization Gson needs to know which type you are expecting, so all fromJson methods have a second parameter representing the type.
You can simply change your code to:
Carrinho carrinho = new Gson().fromJson(conteudo, Carrinho.class);

Why can't the database still not save the data with my current TypeConverter?

I am stuck with implementing a TypeConverter to my Database. I have added the TypeConverters but it still keeps saying that it cannot figure out how to save the field into the database. Or maybe I have missed something? I was following this article to create TypeConverters (https://android.jlelse.eu/room-persistence-library-typeconverters-and-database-migration-3a7d68837d6c), which is with my knowledge so far a bit hard to understand.
Any help would be appreciated!
MyGame.java:
package com.riceplant.capstoneproject.room;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import com.riceplant.capstoneproject.data.Cover;
import com.riceplant.capstoneproject.data.Genre;
import com.riceplant.capstoneproject.data.Platform;
import com.riceplant.capstoneproject.data.ReleaseDate;
import com.riceplant.capstoneproject.data.Video;
import java.util.List;
#Entity(tableName = "game")
public class MyGame {
#PrimaryKey(autoGenerate = true)
private Integer mId;
private Cover mCover;
private String mName;
private Double mPopularity;
private String mSummary;
private List<Genre> mGenres;
private List<Platform> mPlatform;
private Double mRating;
private List<ReleaseDate> mReleaseDate;
private List<Video> mVideos;
#Ignore
public MyGame() {
}
public MyGame(Integer id,
Cover cover,
String name,
Double popularity,
String summary,
List<Genre> genres,
List<Platform> platform,
Double rating,
List<ReleaseDate> releaseDate,
List<Video> videos) {
mId = id;
mCover = cover;
mName = name;
mPopularity = popularity;
mSummary = summary;
mGenres = genres;
mPlatform = platform;
mRating = rating;
mReleaseDate = releaseDate;
mVideos = videos;
}
public Integer getId() {
return mId;
}
public void setId(Integer id) {
id = mId;
}
public Cover getCover() {
return mCover;
}
public void setCover(Cover cover) {
cover = mCover;
}
public String getName() {
return mName;
}
public void setName(String name) {
name = mName;
}
public Double getPopularity() {
return mPopularity;
}
public void setPopularity(Double popularity) {
popularity = mPopularity;
}
public String getSummary() {
return mSummary;
}
public void setSummary(String summary) {
summary = mSummary;
}
public List<Genre> getGenres() {
return mGenres;
}
public void setGenres(List<Genre> genres) {
genres = mGenres;
}
public List<Platform> getPlatform() {
return mPlatform;
}
public void setPlatform(List<Platform> platform) {
platform = mPlatform;
}
public Double getRating() {
return mRating;
}
public void setRating(Double rating) {
rating = mRating;
}
public List<ReleaseDate> getReleaseDate() {
return mReleaseDate;
}
public void setReleaseDate(List<ReleaseDate> releaseDate) {
releaseDate = mReleaseDate;
}
public List<Video> getVideos() {
return mVideos;
}
public void setVideos(List<Video> videos) {
videos = mVideos;
}
}
Converters.java
package com.riceplant.capstoneproject.room;
import androidx.room.TypeConverter;
import com.riceplant.capstoneproject.data.Cover;
import com.riceplant.capstoneproject.data.Genre;
import com.riceplant.capstoneproject.data.Platform;
import com.riceplant.capstoneproject.data.Video;
public class Converters {
#TypeConverter
public static Cover toCover(String value) {
return value == null ? null : new Cover();
}
#TypeConverter
public static String toString(Cover value) {
return value == null ? null : value.getUrl();
}
#TypeConverter
public static Genre toGenre(String value) {
return value == null ? null : new Genre();
}
#TypeConverter
public static String toString(Genre value) {
return value == null ? null : value.getName();
}
#TypeConverter
public static Platform toPlatform(String value) {
return value == null ? null : new Platform();
}
#TypeConverter
public static String toString(Platform value) {
return value == null ? null : value.getName();
}
#TypeConverter
public static Video toString(String value) {
return value == null ? null : new Video();
}
#TypeConverter
public static String toVideo(Video value) {
return value == null ? null : value.getVideoId();
}
}
GameRoomDatabase.java
package com.riceplant.capstoneproject.room;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
#Database(entities = {MyGame.class}, version = 3, exportSchema = false)
#TypeConverters({Converters.class})
public abstract class GameRoomDatabase extends RoomDatabase {
private static final String LOG_TAG = GameRoomDatabase.class.getSimpleName();
private static final Object LOCK = new Object();
private static final String DATABASE_NAME = "gameslist";
private static GameRoomDatabase sInstance;
public static GameRoomDatabase getInstance(Context context) {
if (sInstance == null) {
synchronized (LOCK) {
sInstance = Room.databaseBuilder(context.getApplicationContext(),
GameRoomDatabase.class, GameRoomDatabase.DATABASE_NAME)
.fallbackToDestructiveMigration()
.build();
}
}
return sInstance;
}
public abstract GameDao gameDao();
}
GameDao.java
package com.riceplant.capstoneproject.room;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
#Dao
public interface GameDao {
#Query("SELECT * FROM game ORDER BY mId")
LiveData<List<MyGame>> loadAllGames();
#Insert
void insertGame(MyGame myGame);
#Update(onConflict = OnConflictStrategy.REPLACE)
void updateGame(MyGame myGame);
#Delete
void deleteGame(MyGame myGame);
#Query("SELECT * FROM game WHERE mId = :id")
MyGame loadGameById(int id);
}
GameViewModel
package com.riceplant.capstoneproject.room;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class GameViewModel extends AndroidViewModel {
private LiveData<List<MyGame>> games;
public GameViewModel(#NonNull Application application) {
super(application);
GameRoomDatabase database = GameRoomDatabase.getInstance(this.getApplication());
games = database.gameDao().loadAllGames();
}
public LiveData<List<MyGame>> getGames() {
return games;
}
}
Your DB contains Lists of Genre, Platform, ReleaseDate and Video. SQLite supports column types of INTEGER, REAL, TEXT and BLOB. You must provide methods for conversion of your List types to/from String(TEXT) or one of the other supported SQLite types.
For example:
#TypeConverter
public static List<Genre> toGenreList(String value) {
// TODO conversion code
}
#TypeConverter
public static String toString(List<Genre> value) {
// TODO conversion code
}

Serializing an object to file creates blank object in file

I am trying to create an object that is then serialized and written to file but regardless of what I try, a blank object is always written to file instead.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class FileIO implements Serializable {
private static final long serialVersionUID = 1L;
private VIAModel viaModel1;
private VIAView viaView1 = new VIAView();
private VIAController viaContr = new VIAController();
public void setVIAModelFromFile() throws IOException, ClassNotFoundException, EOFException {
boolean endOfFile = false;
FileInputStream fstream = new FileInputStream("viaModel.ser");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
while (!endOfFile) {
try {
viaModel1 = (VIAModel) inputFile.readObject();
} catch (EOFException eof) {
endOfFile = true;
}
}
inputFile.close();
}
public void setToFile() throws IOException {
viaContr = viaView1.getController();
viaModel1.setEventList(viaContr.getVIAMod().getEventList());
System.out.println(viaModel1.getEventList().getListOfEvents());
FileOutputStream fstream = new FileOutputStream("viaModel.ser");
ObjectOutputStream outputFile = new ObjectOutputStream(fstream);
try {
outputFile.writeObject(viaModel1);
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException ioe) {
System.out.println("Error.");
ioe.printStackTrace();
}
}
public VIAModel getVIAModel() {
return viaModel1;
}
public void setVIAModel(VIAModel viamod) {
this.viaModel1 = viamod;
}
}
The object being written has serializable on all objects inside and objects unable to be serialized have been manually serialized. The system.out.print shows the object with the information entered in the program, but this information doesn't appear in the .ser file at all and so only a blank object is read later.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javafx.beans.property.SimpleStringProperty;
public class Events implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5596571541918537611L;
private transient SimpleStringProperty name = new SimpleStringProperty("");
private transient SimpleStringProperty date = new SimpleStringProperty("");
private transient SimpleStringProperty duration = new SimpleStringProperty("");
private transient SimpleStringProperty type = new SimpleStringProperty("");
private transient SimpleStringProperty location = new SimpleStringProperty("");
private transient SimpleStringProperty category = new SimpleStringProperty("");
// private Lecturer conductor;
private transient SimpleStringProperty price = new SimpleStringProperty("");
private transient SimpleStringProperty minPartic = new SimpleStringProperty("");
private transient SimpleStringProperty maxPartic = new SimpleStringProperty("");
private boolean isFinalized = false;
// ArrayList<Members> eventMembList = new ArrayList<>();
public Events(String name, String date, String duration, String type, String location, String category,
/* Lecturer conductor, */ String price, String minPartic, String maxPartic, boolean isFinalized) {
setName(name);
setDate(date);
setDuration(duration);
setType(type);
setLocation(location);
setCategory(category);
setPrice(price);
setMinPartic(minPartic);
setMaxPartic(maxPartic);
this.isFinalized = isFinalized;
}
public Events() {
this("","","","","","","","","",false);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getDate() {
return date.get();
}
public void setDate(String date) {
this.date.set(date);
}
public String getDuration() {
return duration.get();
}
public void setDuration(String duration) {
this.duration.set(duration);
}
public String getType() {
return type.get();
}
public void setType(String type) {
this.type.set(type);
}
public String getLocation() {
return location.get();
}
public void setLocation(String location) {
this.location.set(location);
}
public String getCategory() {
return category.get();
}
public void setCategory(String category) {
this.category.set(category);
}
public String getPrice() {
return price.get();
}
public void setPrice(String price) {
this.price.set(price);
}
public String getMinPartic() {
return minPartic.get();
}
public void setMinPartic(String minPartic) {
this.minPartic.set(minPartic);
}
public String getMaxPartic() {
return maxPartic.get();
}
public void setMaxPartic(String maxPartic) {
this.maxPartic.set(maxPartic);
}
public boolean isFinalized() {
return isFinalized;
}
public void setFinalized(boolean isFinalized) {
this.isFinalized = isFinalized;
}
public void finalizeEvent() {
this.isFinalized = true;
}
// public void addMemToEvent(Members member) {
// eventMembList.add(member);
// }
public String toString() {
return this.name + "\n" + this.date+ "\n" + this.duration+ "\n" + this.type+ "\n" + this.location+ "\n" + this.category+ "\n" + this.price+ "\n" + this.minPartic+ "\n" + this.maxPartic+ "\n" + this.isFinalized;
}
public void readExternal(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
name = new SimpleStringProperty((String) in.readObject());
date = new SimpleStringProperty((String) in.readObject());
duration = new SimpleStringProperty((String) in.readObject());
type = new SimpleStringProperty((String) in.readObject());
location = new SimpleStringProperty((String) in.readObject());
category = new SimpleStringProperty((String) in.readObject());
price = new SimpleStringProperty((String) in.readObject());
minPartic = new SimpleStringProperty((String) in.readObject());
maxPartic = new SimpleStringProperty((String) in.readObject());
}
public void writeExternal(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(name.get());
out.writeObject(date.get());
out.writeObject(duration.get());
out.writeObject(type.get());
out.writeObject(location.get());
out.writeObject(category.get());
out.writeObject(price.get());
out.writeObject(minPartic.get());
out.writeObject(maxPartic.get());
}
}
Changing SimpleStringProperty to String seems to work perfectly and eliminates all of the issues involved with serializing, which is something that I don't have the knowledge to correct.
in your below code you will end up reading only the last object make sure you are reading correct contents from input file. Did you tried populating a new VIAModel object and then writing it to the file
while (!endOfFile) {
try {
viaModel1 = (VIAModel) inputFile.readObject();
} catch (EOFException eof) {
endOfFile = true;
}
It is exactly as I said. You have
public class Events implements Serializable
and a whole series of transient fields, and also
public void readExternal(ObjectInputStream in)
and
public void writeExternal(ObjectOutputStream out)
These methods are never called. There is nothing in the Object Serialization Specification about either of these method signatures.
If you want this class to be serialized, you need to either remove transient throughout, if SimpleStringProperty is Serializable, and remove these methods, or make it extends Externalizable, and fix the resulting compilation errors.
What you can't do is just make up your own semantics and signatures and then wonder why Java doesn't implement them.

updating a record in a db - JSF JPA etc

i am wondering if you could help me
basically i have created a db, and it adds data to two pieces of data to the table, leaving the rest of the columns blank, what i want to do, is be able to update these records with some more data for the blank columns, how can i achieve this ?
this is my code atm, but i just get a null point error and don't know if im doing it right
This is the u.i.
<p>
Student Number : <!--More for me than anything -->
<h:inputText value="#{editMarkingBean.markSectionTwo.studentNumber}" />
</p>
this is where the student number is entered, this is what i want to update, the record that contains this student number (no way can there be more than one of the same username )
<p:spinner id="ajaxspinner80-100" value="#{editMarkingBean.markSectionTwo.markSectionTwo}"
stepFactor="1" min="80" max="100" disabled="#{formBean.number != 8}">
<p:ajax update="ajaxspinnervalue" process="#this" />
</p:spinner>
this is the value i want to add to the column markSectionTwo
the save button
<p:commandButton action="#{editMarkingBean.markSectionTwo}" value="#{bundle.buttonSave}" update=":growl" icon="ui-icon-disk"/>
the backing bean :
private MarkingService markingService;
#Inject
private MarkingFacade markingFacade;
public void markSectionTwo() {
this.markingFacade.edit(this.markSectionTwo);
this.setMessage("Mark Saved");
}
and this is the entity for the table creation
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String studentNumber,markingStage, markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour, markSectionFive, overalMark, plagorism, feedback, comments;
i get the error
WARNING: javax.el.PropertyNotFoundException: /lecturer/marking/marking-section-two.xhtml #109,82 value="#{editMarkingBean.markSectionTwo.markSectionTwo}": Target Unreachable, 'null' returned null
how can i update the records based on the student number ?
Thanks guys
EDIT
here is the complete editMarkingController class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sws.control;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import sws.business.MarkingService;
import sws.entities.Marking;
import sws.persistance.MarkingFacade;
/**
*
* #author Richard
*/
#Named(value = "editMarkingBean")
#ViewScoped
public class EditMarkingController {
private String searchString;
private String ordering;
private String criteria;
private String match;
private Date today;
private String caseMatch;
private int spinnerField;
private Marking markSectionOne;
private Marking studentNumber;
private Marking markSectionTwo;
private MarkingService markingService;
#Inject
private MarkingFacade markingFacade;
/*
public String markSectionOne() {
//supposing the data in markSectionOne is filled...
this.markingFacade.create(markSectionOne);
this.setMessage("Mark Saved");
//after saving...
markSectionOne = new Marking();
// now navigating to the next page
return "/lecturer/marking/marking-section-two";
}
*/
public void editMark() {
this.markingFacade.edit(this.markSectionTwo);
this.setMessage("Mark Saved");
}
public void markSectionTwo() {
this.markingFacade.edit(this.markSectionTwo);
this.setMessage("Mark Saved");
}
private void setMessage(String message) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(message, ""));
}
public Marking getMarkSectionTwo() {
return markSectionTwo;
}
public void setMarkSectionTwo(Marking markSectionTwo) {
this.markSectionTwo = markSectionTwo;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getOrdering() {
return ordering;
}
public void setOrdering(String ordering) {
this.ordering = ordering;
}
public String getCriteria() {
return criteria;
}
public void setCriteria(String criteria) {
this.criteria = criteria;
}
public String getMatch() {
return match;
}
public void setMatch(String match) {
this.match = match;
}
public Date getToday() {
return today;
}
public void setToday(Date today) {
this.today = today;
}
public String getCaseMatch() {
return caseMatch;
}
public void setCaseMatch(String caseMatch) {
this.caseMatch = caseMatch;
}
public int getSpinnerField() {
return spinnerField;
}
public void setSpinnerField(int spinnerField) {
this.spinnerField = spinnerField;
}
public Marking getMarkSectionOne() {
return markSectionOne;
}
public void setMarkSectionOne(Marking markSectionOne) {
this.markSectionOne = markSectionOne;
}
public Marking getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(Marking studentNumber) {
this.studentNumber = studentNumber;
}
public MarkingService getMarkingService() {
return markingService;
}
public void setMarkingService(MarkingService markingService) {
this.markingService = markingService;
}
public MarkingFacade getMarkingFacade() {
return markingFacade;
}
public void setMarkingFacade(MarkingFacade markingFacade) {
this.markingFacade = markingFacade;
}
}
the complete marking service
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Inject;
import sws.entities.Marking;
import sws.entities.ProjectIdea;
import sws.persistance.MarkingFacade;
import sws.persistance.PersonFacade;
/**
*
* #author Richard
*/
public class MarkingService {
#EJB
private MarkingFacade markingFacade;
public List<Marking> getAllMarks() {
return markingFacade.findAll();
}
}
and comeplte marking entity
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sws.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* #author Richard
*/
#Entity(name = "MARKING")
public class Marking implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String studentNumber,markingStage, markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour, markSectionFive, overalMark, plagorism, feedback, comments;
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public String getMarkingStage() {
return markingStage;
}
public void setMarkingStage(String markingStage) {
this.markingStage = markingStage;
}
public String getMarkingCompleted() {
return markingCompleted;
}
public void setMarkingCompleted(String markingCompleted) {
this.markingCompleted = markingCompleted;
}
public String getMarkSectionOne() {
return markSectionOne;
}
public void setMarkSectionOne(String markSectionOne) {
this.markSectionOne = markSectionOne;
}
public String getMarkSectionTwo() {
return markSectionTwo;
}
public void setMarkSectionTwo(String markSectionTwo) {
this.markSectionTwo = markSectionTwo;
}
public String getMarkSectionThree() {
return markSectionThree;
}
public void setMarkSectionThree(String markSectionThree) {
this.markSectionThree = markSectionThree;
}
public String getMarkSectionFour() {
return markSectionFour;
}
public void setMarkSectionFour(String markSectionFour) {
this.markSectionFour = markSectionFour;
}
public String getMarkSectionFive() {
return markSectionFive;
}
public void setMarkSectionFive(String markSectionFive) {
this.markSectionFive = markSectionFive;
}
public String getOveralMark() {
return overalMark;
}
public void setOveralMark(String overalMark) {
this.overalMark = overalMark;
}
public String getPlagorism() {
return plagorism;
}
public void setPlagorism(String plagorism) {
this.plagorism = plagorism;
}
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
this.feedback = feedback;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Marking)) {
return false;
}
Marking other = (Marking) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "sws.entities.Marking[ id=" + id + " ]";
}
public void setmarkSectionOne(String markSectionOne) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
EDIT 2:
i have added a postconstruct
#PostConstruct
public void markSectionTwo() {
this.markingFacade.edit(this.markSectionTwo);
markSectionTwo = new Marking();
this.setMessage("Mark Saved");
}
but now i get the error message http 500 error
javax.servlet.ServletException: WELD-000049 Unable to invoke public void sws.control.EditMarkingController.markSectionTwo() on sws.control.EditMarkingController#44de1491
root cause
org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke public void sws.control.EditMarkingController.markSectionTwo() on sws.control.EditMarkingController#44de1491
root cause
java.lang.reflect.InvocationTargetException
root cause
javax.ejb.EJBException
root cause
java.lang.IllegalArgumentException: Object: null is not a known entity type.
when i try to load the page
EDIT 3
i have fixed that issue, but now i am only able to add the record, what i am trying to do is merge the records, so if the studentNumber is the same as already in the table then update the markSectionTwo to this value rather than creating a new row in the db for it
private Marking markSectionTwo;
private MarkingService markingService;
#Inject
private MarkingFacade markingFacade;
#PostConstruct
public void init() {
this.markSectionTwo = new Marking();
}
public String markSectionTwo() {
//supposing the data in markSectionOne is filled...
//markSectionOne.setMarkSectionOne("markSectionOne");
//markSectionTwo.setMarkSectionTwo("markSectionTwo");
this.markingFacade.edit(markSectionTwo);
this.setMessage("Mark Saved");
//after saving...
markSectionTwo = new Marking();
this.setMessage("Mark Saved");
// now navigating to the next page
return "/lecturer/marking/marking-section-two";
}
private void setMessage(String message) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(message, ""));
}
your error message
javax.el.PropertyNotFoundException (...) #{editMarkingBean.markSectionTwo.markSectionTwo}"
basically says that you must have
a managed bean called editMarkingBean
an object in your managed bean called markSectionTwo with proper getter and setter
an attribute in your object markSectionTwo called markSectionTwo with proper getter and setter
so what EL is trying to call is
editMarkingBean.getMarkSectionTwo().getMarkSectionTwo()
please check all your classes and, if possible, post all the relevant parts in your question, such as classes names (all of them), managed bean scope annotations, getters and setters and attributes.

Using user id with other model classes

I am using the play-authenticate plugin in my play-framework project. I want to be able to use the user ID (of the user currently logged in) from the User.java model class of the plugin.
#Id
public Long id;
I want to do this so that when users are creating entries in a separate model class I can store the user who has created these entries. Is there functionality in place to access this information or would I need to write an additional method in the User class to return the active user?
package controllers;
import java.text.SimpleDateFormat;
import java.util.Date;
import models.*;
import models.User;
import play.Routes;
import play.data.Form;
import play.mvc.*;
import play.mvc.Http.Response;
import play.mvc.Http.Session;
import providers.MyUsernamePasswordAuthProvider;
import providers.MyUsernamePasswordAuthProvider.MyLogin;
import providers.MyUsernamePasswordAuthProvider.MySignup;
import play.data.*;
import views.html.*;
import play.*;
import be.objectify.deadbolt.actions.Restrict;
import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider;
public class Application extends Controller {
/*Part of the Play-Authenticate authentication plugin for the Play Framework.*/
public static final String FLASH_MESSAGE_KEY = "message";
public static final String FLASH_ERROR_KEY = "error";
public static final String USER_ROLE = "user";
public static User getLocalUser(final Session session) {
final User localUser = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session));
return localUser;
}
/*Source: https://github.com/joscha/play-authenticate*/
#Restrict(Application.USER_ROLE)
public static Result restricted() {
final User localUser = getLocalUser(session());
return ok(journeyManagement.render(localUser));
}
/*Source: https://github.com/joscha/play-authenticate*/
#Restrict(Application.USER_ROLE)
public static Result profile() {
final User localUser = getLocalUser(session());
return ok(profile.render(localUser));
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result login() {
return ok(login.render(MyUsernamePasswordAuthProvider.LOGIN_FORM));
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result doLogin() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MyLogin> filledForm = MyUsernamePasswordAuthProvider.LOGIN_FORM
.bindFromRequest();
if (filledForm.hasErrors()) {
// User did not fill everything properly
return badRequest(login.render(filledForm));
} else {
// Everything was filled
return UsernamePasswordAuthProvider.handleLogin(ctx());
}
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result signup() {
return ok(signup.render(MyUsernamePasswordAuthProvider.SIGNUP_FORM));
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result jsRoutes() {
return ok(
Routes.javascriptRouter("jsRoutes",
controllers.routes.javascript.Signup.forgotPassword()))
.as("text/javascript");
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result doSignup() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MySignup> filledForm = MyUsernamePasswordAuthProvider.SIGNUP_FORM
.bindFromRequest();
if (filledForm.hasErrors()) {
// User did not fill everything properly
return badRequest(signup.render(filledForm));
} else {
// Everything was filled
// do something with your part of the form before handling the user
// signup
return UsernamePasswordAuthProvider.handleSignup(ctx());
}
}
/*Source: https://github.com/joscha/play-authenticate*/
public static String formatTimestamp(final long t) {
return new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").format(new Date(t));
}
}
Update:
package models;
import play.mvc.Http.Session;
import controllers.*;
import java.util.*;
import play.db.ebean.*;
import play.data.validation.Constraints.*;
import javax.persistence.*;
import play.data.format.*;
import com.avaje.ebean.*;
import java.text.*;
#Entity
public class Journey extends Model {
public SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("hh:mm");
public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
#Id
public Long id;
#Required
public String start_loc;
#Required
public String end_loc;
#Required
public String participant_type;
#Required
public String date = simpleDateFormat.format(new Date());
#Required
public String time = simpleTimeFormat.format(new Date());
#ManyToOne
public User createUser;
#ManyToOne
public User modifyUser;
public static Finder<Long,Journey> find = new Finder(
Long.class, Journey.class
);
public static List<Journey> all() {
return find.all();
}
public static void create(Journey journey) {
journey.save();
}
public static void delete(Long id) {
find.ref(id).delete();
}
public static List<Journey> searchByAddress(String address) {
return find.where().ilike("start_loc", "%"+address+"%").findList();
}
public void save() {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o) {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}
}
You don't need to write it manualy, for an example if you have a Book.java model you can add field for an example updatedBy to identify who was editing record last time, what's more you can override Model's methods save() and update(Object o) to make sure, that these fields will be always updated without additional effort.
#Entity
public class Book extends Model {
#Id
public Integer id;
#ManyToOne
public User createUser;
#ManyToOne
public User modifyUser;
public void save() {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o) {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}
// other fields/methods
}

Categories