TableView content not showing [duplicate] - java

This question already has answers here:
Javafx tableview not showing data in all columns
(3 answers)
Closed 4 years ago.
I have a table view which I have populated with information, however while I can select the rows which hold data, the text is not visible. Using table.getSelectionModel().getSelectedItem(); I can confirm that the table has indeed elements inside but the text does not show up.
I have a Socket communication in my programm where the server send the client an ArrayList of elements that the Client needs to display in the TableView.
Server side:
private void acceptedConnection(Socket client, Connection con){
try(ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream())){
System.out.println("receiving request");
String table = ois.readUTF();
System.out.println("Preparing statement");
PreparedStatement getTableContent = con.prepareStatement("SELECT * from " + table);
System.out.println("Fetching results");
ResultSet tableContentRs = getTableContent.executeQuery();
Builder builder = null;
switch (table){
case "blog_user": builder = new UserBuilder();break;
}
assert builder != null;
ArrayList tableContent = builder.buildArrayList(tableContentRs);
System.out.println("Sending results");
oos.writeObject(tableContent);
oos.flush();
System.out.println("Results sent");
}catch (IOException | SQLException e){
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client side:
public void loadTableContent(){
try (Socket client = new Socket(InetAddress.getLocalHost(), 667);
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(client.getInputStream())) {
System.out.println("Sending request");
String selectedTable = databaseTableComboBox.getSelectionModel().getSelectedItem();
oos.writeUTF(selectedTable);
oos.flush();
table.getColumns().clear();
table.getItems().clear();
ArrayList data = null;
Builder builder = null;
switch (selectedTable){
case "blog_user": builder = new UserBuilder();data = (ArrayList<User>)ois.readObject();break;
}
assert builder != null;
builder.setColumns(table);
table.getItems().addAll(data);
table.refresh();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
The UserBuilder:
public class UserBuilder implements Builder {
#Override
public ArrayList buildArrayList(ResultSet set) throws SQLException {
ArrayList<User> users = new ArrayList<>();
while (set.next()) users.add(new User(set.getInt(1), set.getString(2), set.getString(3)));
return users;
}
#Override
public void setColumns(TableView table) {
TableColumn<User, String> idCol = new TableColumn<>("ID");
TableColumn<User, String> nameCol = new TableColumn<>("Name");
TableColumn<User, String> pwdCol = new TableColumn<>("Passwort");
idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
nameCol.setCellValueFactory(new PropertyValueFactory<>("username"));
pwdCol.setCellValueFactory(new PropertyValueFactory<>("pwd"));
table.getColumns().addAll(idCol, nameCol, pwdCol);
}
}
And the User:
public class User implements Serializable{
private int id;
private String username;
private String pwd;
public User(int id, String username, String pwd) {
this.id = id;
this.username = username;
this.pwd = pwd;
}
#Override
public String toString() {
return id + " " + username + " " + pwd;
}
}
The interesting thing is that it already worked once but then I added the same mechanism I had for User and UserBuilder for other classes (so e.g. Admin and AdminBuilder) and suddenly the text did not show up in the TableView anymore.
Any and all help is greatly appreciated.

Your User class needs getter methods. The PropertyValueFactory needs to access these fields.
public class User {
private final int id;
private final String username;
private final String pwd;
public User(int id, String username, String pwd) {
this.id = id;
this.username = username;
this.pwd = pwd;
}
#Override
public String toString() {
return id + " " + username + " " + pwd;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPwd() {
return pwd;
}
}

Related

How to make ObjectInputStream read all objects from file in java?

I have a file which is storing objects and I have a *getAll() method which needs to return the List<Secretary>. But, I only see single object being printed in console.
I searched for the problem and tried 3 ways but it did not work.
The insert method for inserting object in file is:
#Override
public Secretary insert(Secretary t) {
try {
System.out.println("insert called");
FileOutputStream file = new FileOutputStream
(filename,true);
ObjectOutputStream out = new ObjectOutputStream
(file);
Method for serialization of object
out.writeObject(t);
out.close();
file.close();
return t;
}
catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
I have declared append mode as true as, my file was being replaced by new object when saving.
So,i need to fetch all object from file and need to assign to a list.I tried:
public class SecretaryDaoImpl implements SecretaryDAO{
private String filename = "secretary.txt";
private Secretary sec=null;
#Override
public List<Secretary> getAll() {
//Method 1
try {
Reading the object from a file
FileInputStream file = new FileInputStream
(filename);
ObjectInputStream in = new ObjectInputStream
(file);
List<Secretary> secList=new ArrayList<>();
Method for deserialization of object
secList.add((Secretary)in.readObject());
in.close();
file.close();
System.out.println("Object has been deserialized\n"
+ "Data after Deserialization.");
System.out.println("secList is" +secList);
return secList;
}
catch (IOException ex) {
System.out.println("Secreatary file not found");
return null;
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" +
" is caught");
}
return null;
//Method 2
List<Secretary> secList=new ArrayList<>();
ObjectInputStream objectinputstream = null;
try {
FileInputStream streamIn = new FileInputStream(filename);
objectinputstream = new ObjectInputStream(streamIn);
List<Secretary> readCase = (List<Secretary>) objectinputstream.readObject();
for(Secretary s:readCase){
secList.add(s);
}
System.out.println("seclist is" + secList);
return secList;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
try {
objectinputstream.close();
} catch (IOException ex) {
Logger.getLogger(SecretaryDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Method 3
try{
File file = new File(filename);
List<Secretary> list = new ArrayList<>();
if (file.exists()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
list.add((Secretary) ois.readObject());
}
}
System.out.println("getall is"+list);
}
catch(Exception e){
}
return null;
}
}
I have commented out my code but here while posting in stackoverflow I have uncommented all the codes.
My Secretary.java is :
package com.npsc.entity;
import java.io.Serializable;
/**
*
* #author Ashwin
*/
public class Secretary implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
private int id;
private String userName;
private String password;
private Branch branch;
public String getUserName() {
return userName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Secretary(String userName, String password) {
this.userName = userName;
this.password = password;
}
public Branch getBranch() {
return branch;
}
public void setBranch(Branch branch) {
this.branch = branch;
}
#Override
public String toString() {
return "Secretary{" + "id=" + id + ", userName=" + userName + ", password=" + password + ", branch=" + branch + '}';
}
}
While performing insert operation,my txt file saving objects is:
But,I am unable to read all the object and add in list.Where I am facing the problem?
You will need to store in the file, the number of Secretary objects to read back. You can then determine how many entities to read, and thus repopulate your list.
Something like:
List<Secretary> list;
private void persistList(ObjectOutputStream out) {
out.writeInt(list.size());
for (Secretary sec : list) {
out.writeObject(sec);
}
}
And then to read:
private List<Secretary> readFromStream(ObjectInputStream in) {
int numObjects = in.readInt();
List<Secretary> result = new ArrayList<>(numObjects);
for (int i = 0; i < numObjects; i++) {
result.add((Secretary)in.readObject());
}
return result;
}
This is just a sketch of the technique (and ignores error handling, stream opening/closing etc.); the main thing is to integrate the idea of recording the size of the list, then reading that many Secretaries into your existing code.
Write a List<Secretary> to file and read same back, then you will have all.
write (Secretary s) {
read List<Secretary> currentList ;
currentList.add(s)
write List<Secretary>
}

Hyperledger Fabric Java SDK Event Hub Exception when trying to initialize channel

I'm trying to use the Hyperledger Fabric Java SDK to invoke chaincode transactions but I'm getting the following error in channel.initialize():
Exception in thread "main" org.hyperledger.fabric.sdk.exception.TransactionException: org.hyperledger.fabric.sdk.exception.EventHubException: org.hyperledger.fabric.sdk.exception.CryptoException: Could not sign the message using private key
at org.hyperledger.fabric.sdk.Channel.initialize(Channel.java:1158)
at HLFJavaClient.getChannel(HLFJavaClient.java:231)
at HLFJavaClient.main(HLFJavaClient.java:84)
Caused by: org.hyperledger.fabric.sdk.exception.EventHubException: org.hyperledger.fabric.sdk.exception.CryptoException: Could not sign the message using private key
at org.hyperledger.fabric.sdk.EventHub.connect(EventHub.java:322)
at org.hyperledger.fabric.sdk.EventHub.connect(EventHub.java:200)
at org.hyperledger.fabric.sdk.Channel.initialize(Channel.java:1127)
... 2 more
Caused by: org.hyperledger.fabric.sdk.exception.CryptoException: Could not sign the message using private key
at org.hyperledger.fabric.sdk.security.CryptoPrimitives.ecdsaSignToBytes(CryptoPrimitives.java:747)
at org.hyperledger.fabric.sdk.security.CryptoPrimitives.sign(CryptoPrimitives.java:757)
at org.hyperledger.fabric.sdk.identity.X509SigningIdentity.sign(X509SigningIdentity.java:23)
at org.hyperledger.fabric.sdk.transaction.TransactionContext.sign(TransactionContext.java:180)
at org.hyperledger.fabric.sdk.transaction.TransactionContext.signByteString(TransactionContext.java:184)
at org.hyperledger.fabric.sdk.EventHub.blockListen(EventHub.java:389)
at org.hyperledger.fabric.sdk.EventHub.connect(EventHub.java:320)
... 4 more
Caused by: java.security.InvalidKeyException: cannot identify EC private key: java.lang.NullPointerException
at org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil.generatePrivateKeyParameter(Unknown Source)
at org.bouncycastle.jcajce.provider.asymmetric.ec.SignatureSpi.engineInitSign(Unknown Source)
at java.security.Signature$Delegate.engineInitSign(Signature.java:1177)
at java.security.Signature.initSign(Signature.java:530)
at org.hyperledger.fabric.sdk.security.CryptoPrimitives.ecdsaSignToBytes(CryptoPrimitives.java:729)
... 10 more
My network is running with 4 peers (peer0.org1.mydomain.com, peer0.org2..., peer0.org3... and peer0.org4...) and one orderer (orderer.mydomain.com).
Java SDK Client code:
public class HLFJavaClient {
public static final String HLF_USER_NAME = "User1#org1.mydomain.com";
public static final String HLF_CLIENT_ORG = "Org1";
public static final String HLF_CLIENT_MSPID = "Org1MSP";
public static final String HLF_CLIENT_CRT_PATH = "../crypto-config/peerOrganizations/org1.mydomain.com/users/User1#org1.mydomain.com/msp/signcerts/User1#org1.mydomain.com-cert.pem";
public static final String HLF_CLIENT_KEY_PATH = "../crypto-config/peerOrganizations/org1.mydomain.com/users/User1#org1.mydomain.com/msp/keystore/User1#org1.mydomain.com-priv.pem";
public static final String HLF_CHANNEL_NAME = "mychannel";
public static final String HLF_CHAINCODE_NAME = "pkicc";
private static final Logger log = Logger.getLogger(HLFJavaClient.class);
public static void main(String[] args) throws Exception {
AppUser appUser = getUser(HLF_CLIENT_CRT_PATH, HLF_CLIENT_KEY_PATH, HLF_USER_NAME);
HFClient client = getHfClient();
client.setUserContext(appUser);
Channel channel = getChannel(client);
addProperty(client, new String[] {"1","w"});
}
static void addProperty(HFClient client, String[] property) throws ProposalException, InvalidArgumentException {
Channel channel = client.getChannel(HLF_CHANNEL_NAME);
TransactionProposalRequest tpr = client.newTransactionProposalRequest();
ChaincodeID CCId = ChaincodeID.newBuilder().setName(HLF_CHAINCODE_NAME).build();
tpr.setChaincodeID(CCId);
tpr.setFcn("createWallet");
tpr.setArgs(property);
Collection<ProposalResponse> res = channel.sendTransactionProposal(tpr);
for (ProposalResponse pres : res) {
String stringResponse = "Response from endorser is: " + pres.getChaincodeActionResponseStatus();
log.info(stringResponse);
System.out.println(stringResponse);
}
channel.sendTransaction(res);
System.out.println("Transaction sent.");
}
static Channel getChannel(HFClient client) throws InvalidArgumentException, TransactionException {
Channel channel = client.newChannel(HLF_CHANNEL_NAME);
class PeerOrgPort {
public String org;
public int port;
public PeerOrgPort(String org, int port) {
this.org = org;
this.port = port;
}
}
PeerOrgPort[] peers = new PeerOrgPort[] {
new PeerOrgPort("1", 7051),
new PeerOrgPort("2", 8051),
new PeerOrgPort("3", 9051),
new PeerOrgPort("4", 10051),
};
for (int i = 0; i < peers.length; i++) {
File tlsCrt = Paths.get("../crypto-config/peerOrganizations/org" + peers[i].org + ".mydomain.com/tlsca", "tlsca.org" + peers[i].org + ".mydomain.com-cert.pem").toFile();
if (!tlsCrt.exists())
throw new RuntimeException("Missing TLS cert files");
Properties secPeerProperties = new Properties();
secPeerProperties.setProperty("hostnameOverride", "peer0.org" + peers[i].org + ".mydomain.com");
secPeerProperties.setProperty("sslProvider", "openSSL");
secPeerProperties.setProperty("negotiationType", "TLS");
secPeerProperties.setProperty("pemFile", tlsCrt.getAbsolutePath());
Peer peer = client.newPeer("peer0.org" + peers[i].org + ".mydomain.com", "grpcs://localhost:" + peers[i].port, secPeerProperties);
channel.addPeer(peer);
if (peers[i].org.equals("1")) {
EventHub eventHub = client.newEventHub("eventhub01", "grpcs://localhost:7053", secPeerProperties);
channel.addEventHub(eventHub);
}
}
File tlsOrdCrt = Paths.get("../crypto-config/ordererOrganizations/mydomain.com/tlsca", "tlsca.mydomain.com-cert.pem").toFile();
if (!tlsOrdCrt.exists())
throw new RuntimeException("Missing TLS cert files");
Properties secOrdererProperties = new Properties();
secOrdererProperties.setProperty("hostnameOverride", "orderer.mydomain.com");
secOrdererProperties.setProperty("sslProvider", "openSSL");
secOrdererProperties.setProperty("negotiationType", "TLS");
secOrdererProperties.setProperty("pemFile", tlsOrdCrt.getAbsolutePath());
Orderer orderer = client.newOrderer("orderer.mydomain.com", "grpcs://localhost:7050", secOrdererProperties);
channel.addOrderer(orderer);
channel.initialize();
return channel;
}
static HFClient getHfClient() throws Exception {
CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
HFClient client = HFClient.createNewInstance();
client.setCryptoSuite(cryptoSuite);
return client;
}
static AppUser getUser(String certPath, String keyPath, String userId) throws Exception {
AppUser appUser = null;//tryDeserialize(userId);
if (appUser == null) {
appUser = new AppUser(userId, HLF_CLIENT_ORG, HLF_CLIENT_MSPID, certPath, keyPath);
}
return appUser;
}
AppUser:
public class AppUser implements User, Serializable {
private static final long serializationId = 1L;
private static final long serialVersionUID = -6287264119837208213L;
private String name;
private Set<String> roles;
private String account;
private String affiliation;
private Enrollment enrollment;
private String mspId;
public AppUser() {
// no-arg constructor
}
public AppUser(String name, String affiliation, String mspId, String certPath, String keyPath) {
this.name = name;
this.affiliation = affiliation;
this.enrollment = getEnrollmentFromCertPath(certPath, keyPath);
this.mspId = mspId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getAffiliation() {
return affiliation;
}
public void setAffiliation(String affiliation) {
this.affiliation = affiliation;
}
public Enrollment getEnrollment() {
return enrollment;
}
public void setEnrollment(Enrollment enrollment) {
this.enrollment = enrollment;
}
public String getMspId() {
return mspId;
}
public void setMspId(String mspId) {
this.mspId = mspId;
}
#Override
public String toString() {
return "AppUser{" +
"name='" + name + '\'' +
"\n, roles=" + roles +
"\n, account='" + account + '\'' +
"\n, affiliation='" + affiliation + '\'' +
"\n, enrollment=" + enrollment +
"\n, mspId='" + mspId + '\'' +
'}';
}
private Enrollment getEnrollmentFromCertPath(final String certPath, final String keyPath) {
return new Enrollment() {
public PrivateKey getKey() {
try {
return loadPrivateKey(Paths.get(keyPath));
} catch (Exception e) {
return null;
}
}
public String getCert() {
try {
return new String(Files.readAllBytes(Paths.get(certPath)));
} catch (Exception e) {
return "";
}
}
};
}
private static PrivateKey loadPrivateKey(Path fileName) throws IOException, GeneralSecurityException {
PrivateKey key = null;
InputStream is = null;
BufferedReader br = null;
try {
is = new FileInputStream(fileName.toString());
br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
boolean inKey = false;
for (String line = br.readLine(); line != null; line = br.readLine()) {
if (!inKey) {
if (line.startsWith("-----BEGIN ") && line.endsWith(" PRIVATE KEY-----")) {
inKey = true;
}
continue;
} else {
if (line.startsWith("-----END ") && line.endsWith(" PRIVATE KEY-----")) {
inKey = false;
break;
}
builder.append(line);
}
}
byte[] encoded = DatatypeConverter.parseBase64Binary(builder.toString());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("ECDSA", "BC");
key = kf.generatePrivate(keySpec);
} finally {
br.close();
is.close();
}
return key;
}
}
What am I doing wrong?
Thank you

Insert record to database from a server/client GUI java

Hi i am struggling to get my database to receive a username and ip address from a client instance connecting to a server.
It is a bidding system that initially just lets multiple individual instances of the client bid on 2 items, now I need to add the name (user prompted to enter upon loading client instance) and their ip address to my database.
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null; //null pointer exception fix
Statement statement = null;
String inserSql = null;
Connection sqlLink = null;
final int PORT = 1239;
Socket client = null;
ClientHandler handler = null;
Scanner getTime;
try {
/**
* This piece of code has errors or you maybe did the error
* when copy/paste your code.
* Fixed the DriverManager connection code
*/
sqlLink = DriverManager.getConnection(
"correct info already here);
} catch (SQLException e) {
System.out.println("* Cannot connect to database! *");
System.exit(1);
}
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException ioEx) {
System.out.println("Unable to set up port!");
System.exit(1);
}
System.out.println("\nUp and running\n");
String currentTime = null;
getTime = new Scanner(System.in);
System.out.println("\nSet time for Ball");
currentTime = getTime.nextLine();
Items BallItem = new Items("Ball", currentTime, "Ball");
System.out.println("\nSet time for Plate");
currentTime = getTime.nextLine();
Items PlateItem = new Items("Plate", currentTime, "Plate");
Bidder bidder = new Bidder(null);
BallItem.start();
PlateItem.start();
Users user = new Users(BallItem, PlateItem);
ArrayList<ClientHandler> userList =
new ArrayList<ClientHandler>();
//add new array for the clients details as stated
ArrayList<String> bidders = new ArrayList<String>();
do {
client = serverSocket.accept();//
System.out.println("Enter username ");//
//takes in bidders name (1.1 and 2.1)
bidders.add(getTime.nextLine());
bidders.add(client.getInetAddress().toString());
//takes in next bidder's ip address to string like in tips (2.2)
Bidder userBidding = new Bidder(bidders);
System.out.println("\nUser" + (user.getUsers() + 1));
user.addUsers(userList, client, handler);
System.out.println(userBidding.returnUsers());
bidder.insert(statement, statement);
}
while (true);
}
}
class Items extends Thread {
private String name, description, timeUp, userBidding = "";
private boolean newBid = true;
private double topBid = 0;
private Calendar start = Calendar.getInstance();
private int date = start.get(Calendar.DATE); //gets the dates
private int month = start.get(Calendar.MONTH);
private int year = start.get(Calendar.YEAR);
private Calendar deadline = Calendar.getInstance();
//time file supplied to help etc
private Calendar now = Calendar.getInstance();
public Items(String newName, String newTimeString,
String newDescription) throws IOException {
String timeString, hourString, minString;
name = newName;
description = newDescription;
timeUp = newTimeString;
timeString = newTimeString;
hourString = timeString.substring(0, 2);
int hour = Integer.parseInt(hourString);
minString = timeString.substring(3, 5);
int minute = Integer.parseInt(minString);
deadline.set(year, month, date, hour, minute, 0); //setting time
}
public void run() {
while (now.before(deadline)) {
System.out.println(name + " " + getDateTime(now));
try {
Thread.sleep(5000); //increased to check server notifications easier
} catch (InterruptedException intEx) {
}
now = Calendar.getInstance();
}
System.out.println("\nDeadline! Times up!");
newBid = false;
}
class Bidder {
private static ArrayList<String> users;
private static Users user = new Users(null, null);
public Bidder(ArrayList<String> newUserList) {
users = newUserList;
}
public ArrayList<String> returnUsers()//return users as in question
{
return users;
}
public static String returnIP()//return ip as in question
{
return users.get(user.getUsers() + 1);
}
static void insert(Statement insert, Statement statement) {
Users user = new Users(null, null);
try {
String insertSql = "INSERT INTO Usernames(id, Name, ipAddress) VALUES (1"
+ users.get(user.getUsers()) + "," + returnIP() + ")";
System.out.println(users.get(user.getUsers()));
statement.executeUpdate(insertSql);
} catch (SQLException sqlEx) {
System.out.println("* Cannot execute insert! *");
sqlEx.printStackTrace();
System.exit(1);
}
}
//remove user as stated in question
public synchronized void RemoveUser(Socket client, int clientUser) {
int index = 0;
for (final String newString : users) {
if (users.indexOf(user.getUsers()) == clientUser) {
try {
client.close();
Thread.currentThread().isInterrupted();
users.remove(index);
} catch (final IOException e) {
System.out.println("Try to leave again!");
System.exit(1);
}
}
index++;
}
}
}
class Users {
private ArrayList<ClientHandler> userList;
private Items Ball;
private Items Plate;
public Users(Items newItem1, Items newItem2) {
Ball = newItem1;
Plate = newItem2;
userList = null;
}
public synchronized int getUsers() {
int totalUsers = 0;
if (userList != null)
for (ClientHandler handler : userList)
totalUsers++;
return totalUsers;
}
}// <-- miss this close brace

Where to implement onSave and onLoad functions to create serializable file

I've created these two functions and added them into an action listener within a button . The aim is to create a serialized file and write what is in the Jlist to the file. When the program is closed , the jlist should be populated with what is in the serialized file. For some reason it isn't working. Can anyone see what is wrong?
Here is the code:
JButton btnAdd = new JButton("Add"); // Setting what is written on the button
btnAdd.addActionListener(new ActionListener() { // implementing an action listener
public void actionPerformed(ActionEvent arg0) {
patientname = textField.getText(); // Getting the patient name from the textfield
patientaddress = textField_1.getText();
patientphone = textField_2.getText();
textField.setText(""); // Setting the textfield to be blank so that the user can input there name address etc..
textField_1.setText("");
textField_2.setText("");
patientid = patientid + 1;//Implementing the id to add 1 every time another id is added
Patient patient = new Patient(patientname, patientaddress, patientphone, patientid); // Populating the array list patientlist with the users input
patientList.add(patient); // Adding the patient's details to the patientlist
patientListModel.addElement(patient); // adds the patient's details to the list model
}
public void onSave(List<Patient> PatientList) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File("PatientList.ser")));
out.writeObject(PatientList);
out.flush();
}
catch (IOException e) {
// handle exception
}
finally {
if (out != null) {
try {
out.close();
}
catch (IOException e) {
// handle exception
}
}
}
}
public List<Patient> onLoad() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(new File("PatientList.ser")));
return (List<Patient>) in.readObject();
}
catch (IOException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
// handle exception
}
}
}
return null;
}
});
btnAdd.setBounds(0, 86, 65, 23);
contentPane.add(btnAdd);
/////////////////
Here is my patient class :
public class Patient {
public String patientName;
public String patientAddress;
public String patientPhone;
public int patientID;
public Patient(String patientname, String patientaddress, String patientphone,int patientid){
patientName = patientname;
patientAddress = patientaddress;
patientPhone = patientphone;
patientID = patientid;
}
public String setName(String patientname){
return patientName = patientname;
}
public String getName(){
return patientName;
}
public String setAddress(String patientaddress){
return patientAddress = patientaddress;
}
public String getAddress(){
return patientAddress;
}
public String setPhoneNum(String patientphone){
return patientPhone = patientphone;
}
public String getPhoneNum(){
return patientPhone;
}
public int setID(int patientid){
return patientID = patientid;
}
public int getID(){
return patientID;
}
public String toString() { // Printing the patient's details to the scroll pane
return "Patient Name: " + patientName + ", PatientAddress: "
+ patientAddress + ", PatientPhone: " + patientPhone
+ ", patientID: " + patientID +"" ;
}
}

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