I have two classes , utilisateur ( means user in french ) and Envellope ( wich means envelope ), so i have many classes to organize sending and receiving objects to/from two classes in localhost !
I want to print the result in the screen after sending and receiving.
I conclude that it's not deserializing and the output of toString is a kind of hashcode like this #14ae5a5
Envellope class:
public class Envellope<T> implements Serializable{
private static final long serialVersionUID = -5653473013975445298L;
public String todo;
public T thing;
public Envellope() {
}
public Envellope(String todo, T thing) {
this.todo = todo;
this.thing = thing;
}
}
Utilisateur class:
public class utilisateur implements Serializable{
private static final long serialVersionUID = -5429001491604482315L;
public String login;
public String mdp;
public utilisateur(String l,String m){
login=l;
mdp=m;
}
public utilisateur(){}
}
and there is the main (Client):
public static void main(String[] args) {
try {
Socket socket=new Socket("localhost",4444);
StreamObject so=new StreamObject(socket);
Envellope<utilisateur> toSend=new Envellope<utilisateur>("Authenticate",new utilisateur("addou","ismail"));
so.send(toSend);//sending to ServerSocket
Envellope<utilisateur> env=(Envellope<utilisateur>) so.receive();//receiving from server
System.out.println(env.todo+" Object: "+env.thing);
} catch (IOException ex) {
Logger.getLogger(Aaa.class.getName()).log(Level.SEVERE, null, ex);
}
}
I didn't write here the other classes, because i think it works , but if you need it just tell me !
StreamObject class:
public class StreamObject extends IOS{
private ObjectOutputStream oos;
private ObjectInputStream ois;
public StreamObject(Socket s) throws IOException{
super();
super.os=s.getOutputStream();
super.is=s.getInputStream();
oos=new ObjectOutputStream(os);
ois=new ObjectInputStream(is);
}
And IOS class is just inputStream and OutputStream !
public void send(Object object) {
try {
oos.writeObject(object);
} catch (IOException e) {
System.out.print("Erreur receive socket: ");
System.err.print("IOException ");
System.out.println(e.getMessage());
}
}
public Object receive() {
try {
return ois.readObject();
} catch (ClassNotFoundException e) {
System.out.print("Erreur receive socket: ");
System.err.print("ClassNotFoundException ");
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.print("Erreur receive socket: ");
System.err.print("IOException ");
System.out.println(e.getMessage());
}
return null;
}
}
Your utilisateur class does not override toString, so it uses the default implementation, which returns the class name and hash code.
Add something like this to utilisateur:
#Override
public String toString() {
return "login="+login+" & mdp="+mdp;
}
Related
I have been struggling to create a serializing method that serializes all my already existing objects. This is what I have done:
my class:
public class Test implements Serializable{
ArrayList<TheOtherClass> obj = new ArrayList<>();
public static void main(String[] args) {
Test test = new Test();
test.addTest("This", "Is", "Some");
test.addTest("Text", "As", "Example");
test.saveAllArrays();
}
// omitted code down here.
public void addTest(String some, String random, String text) {
obj.add(new TheOtherClass(some, random, text));
}
public void saveTest(Object obj) throws IOException{
ObjectOutputStream save = new ObjectOutputStream(new FileOutputStream("SaveFile.bin"));
save.writeObject(obj);
}
public void saveAllArrays(){
for(TheOtherClass all : obj){
try {
saveTest(all);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
my object class:
public class TheOtherClass implements Serializable{
private String some;
private String random;
private String savedText;
Getter and setter methods are omitted.
Here is a complete example. Hopefully it will get you moving.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Test implements Serializable {
private static final String FILE = "SaveFile.bin";
private List<Item> itemList = new ArrayList<>();
public class Item implements Serializable {
private String first;
private String second;
private String last;
public Item(String first, String second, String last) {
this.first = first;
this.second = second;
this.last = last;
}
#Override
public String toString() {
return first + ", " + second + ", " + last;
}
}
public static void main(String args[]) {
Test test = new Test();
if(args.length > 0) {
try {
test.loadItemList();
System.out.println("loaded");
test.printList();
} catch (IOException | ClassNotFoundException e) {
System.out.println(e.getMessage());
}
} else {
test.addItem("1", "2", "done");
test.addItem("Text", "As", "Example");
try {
test.saveItemList();
System.out.println("saved");
test.printList();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
private void printList() {
itemList.forEach(System.out::println);
}
private void addItem(String first, String second, String last) {
itemList.add(new Item(first, second, last));
}
private void loadItemList() throws IOException, ClassNotFoundException {
InputStream inputStream = new FileInputStream(FILE);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
itemList = (List<Item>) objectInputStream.readObject();
}
private void saveItemList() throws IOException {
OutputStream outputStream = new FileOutputStream(FILE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(itemList);
}
}
At present you're creating a new file per serialized object, so you lose all but the last one. There is no need to serialize multiple objects at all, or iterate over the array list. Just save it directly, and deserialize it directly too.
I've reasearched a lot of websites and I couldn't find answear. I'm trying to write to .txt file my ArrayList which constains class objects. Every time I try to do it I`m getting exception. With reading is the same problem. Here is my code:
public static void write()
{
try
{
FileOutputStream out = new FileOutputStream("clients.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(lista);
oout.close();
}
catch(Exception ioe)
{
System.out.println("writing Error!");
welcome();
}
}
public static void read()
{
try
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("clients.txt"));
lista = (List<Client>) ois.readObject();
}
catch (ClassNotFoundException ex)
{
System.out.println("Koniec pliku");
}
catch(IOException ioe)
{
System.out.println("Error!");
welcome();
}
}
I guess you're looking for the Serializable interface of Java. In order to save objects you're class have to implement it.
The question is: What execatly do you want to save? The content of the list so that you can save it in a file and load it afterwards?
This simple example works for me (for the scenario I mention above):
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public User(String name, int ag) {
this.name = name;
this.age = age;
}
#Override
public String toString() {
return (this.name + ' ' + this.age);
}
}
public class Main {
private static List<User> l;
public static void main(String[] args) {
l = new ArrayList<User>();
user1 = new User("John", 22);
user2 = new User("Jo", 33);
l.add(user1);
l.add(user2);
write();
}
public static void write() {
try {
FileOutputStream fos = new FileOutputStream("testout.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(l);
oos.close();
} catch (Exception ioe) {
System.out.println("writing Error!");
}
}
}
Ok I have changed a bit (not each function just the read and write functionality) and this work.
Link to Code.
One important thing is that the Scanner class is not serializable. Therefore, you have to make it static for example.
I have a server that contains an ArrayList in " ServerInfo " and when I try to take from ClientRMI an element of the ArrayList(in ServerInfo) for example adf.getSGM ( 0 ).incrementCount( ) ;
"count" does not increase it's as if every time I call it instantiates a new class SGM
in a few words I want to interact from ClientRMI with ArrayList that is on ServerInfo (SORRY FOR ENGLISH)
Hear are the classes :
SERVER
public class ServerRMI {
public static void main(String[] args) {
Registry registry = null;
String name = "ServerInfo";
try {
System.out.println("Init RMI");
ServerInfoInterface sir = ServerInfo.getInstance();
ServerInfoInterface stub = (ServerInfoInterface) UnicastRemoteObject.exportObject(sir, 0);
registry = LocateRegistry.createRegistry(9000);
registry.bind(name, stub);
System.out.println("RMI OK");
System.out.println("Init SGM...");
for(int i=0;i<3;i++){
ServerInfo.getInstance().addSGM(new SGM());
}
System.out.println("Init SGM OK");
} catch (Exception e) {
System.out.println("RMI Error"+e.toString());
registry = null;
}
}
}
public class ServerInfo implements ServerInfoInterface{
private ArrayList<SGM> sgmHandler = new ArrayList<SGM>();
// Singleton pattern
private static ServerInfo instance;
// Singleton pattern
public static ServerInfo getInstance() {
if (instance == null){
System.out.println("ServerInfo new instance");
instance = new ServerInfo();
}
return instance;
}
#Override
public synchronized void addSGM(SGM sgm) throws RemoteException {
sgmHandler.add(sgm);
}
#Override
public synchronized SGM getSGM(int i) throws RemoteException {
return sgmHandler.get(i);
}
}
public interface ServerInfoInterface extends Remote{
public void addSGM(SGM sgm) throws RemoteException;
public SGM getSGM(int i) throws RemoteException;
}
public class SGM implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4756606091542270097L;
private int count=0;
public void incrementCount(){
count++;
}
public void decrementCount(){
count--;
}
public int getCount(){
return count;
}
}
CLIENT
public class ClientRMI {
private ServerInfoInterface sgmInterface;
public void startServer() {
String name = "ServerInfo";
Registry registry;
try {
registry = LocateRegistry.getRegistry(9000);
try {
sgmInterface = (ServerInfoInterface) registry.lookup(name);
sgmInterface.getSGM(0).incrementCount();
System.out.println(sgmInterface.getSGM(0).getCount()); // always 0
} catch (AccessException e) {
System.out.println("RIM AccessException"+ e.toString());
} catch (RemoteException e) {
System.out.println("RIM RemoteException"+ e.toString());
} catch (NotBoundException e) {
System.out.println("RIM NotBoundException"+ e.toString());
}
} catch (RemoteException e) {
System.out.println("RIM RemoteException registry"+ e.toString());
}
}
}
You're creating an SGM at the server, passing it via Serialization to the client, incrementing its count at the client, and then expecting that count to be magically increased at the server.
It can't work.
You will have to make SGM a remote object, with its own remote interface, or else provide a remote method in the original remote interface to increment the count of a GSM, specified by index.
I´ve been reading that the static fields are not serialized but, after testing it, I saw that´s not true.
The static modifier even overrides the transient modifier and makes the field serializable.
I write one example from a book that shows that a static transient field is serialized.
import java.io.*;
class USPresident implements Serializable {
private static final long serialVersionUID = 1L;
#Override
public String toString() {
return "US President [name=" + name
+ ", period=" + period + ", term=" + term + "]";
}
public USPresident(String name, String period, String term) {
this.name = name;
this.period = period;
this.term = term;
}
private String name;
private String period;
private static transient String term;
}
class TransientSerialization {
public static void main(String[] args) {
USPresident usPresident = new USPresident("Barack Obama", "2009 to --", "56th term");
System.out.println(usPresident);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("USPresident.data"))) {
oos.writeObject(usPresident);
} catch (IOException ioe) {
// ignore
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("USPresident.data"))) {
Object obj = ois.readObject();
if (obj != null && obj instanceof USPresident) {
USPresident presidentOfUS = (USPresident) obj;
System.out.println(presidentOfUS);
}
} catch (IOException ioe) {
// ignore
} catch (ClassNotFoundException e) {
// ignore
}
}
}
Is wrong the general concept that static fields are not serialized? Is it just a recommendation?
Why the transient modifier doen't take effect with static ?
note: I understand that initialize a static field in a constructor is an odd code, but the compiler let me do it and it's just in order to understand static fields serialization.
This has nothing to do with serialization but due to the fact that you are setting the static field when you create your usPresident variable. This sets the field for the class of that JVM. Try reading in the serialized president in a different program and see that the transient field is not serialized.
As an aside: consider not ignoring your exceptions.
For example, refactored, your code could look like this:
class USPresident implements Serializable {
private static final long serialVersionUID = 1L;
#Override
public String toString() {
return "US President [name=" + name + ", period=" + period + ", term="
+ term + "]";
}
public USPresident(String name, String period, String term) {
this.name = name;
this.period = period;
this.term = term;
}
private String name;
private String period;
private static transient String term;
}
class TransientSerialization {
public static void main(String[] args) {
serializePresident();
deserializePresident();
}
private static void deserializePresident() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(
"USPresident.data"));
Object obj = ois.readObject();
if (obj != null && obj instanceof USPresident) {
USPresident presidentOfUS = (USPresident) obj;
System.out.println(presidentOfUS);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void serializePresident() {
USPresident usPresident = new USPresident("Barack Obama", "2009 to --",
"56th term");
System.out.println(usPresident);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("USPresident.data"));
oos.writeObject(usPresident);
oos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The second time your run it, change the main method to:
public static void main(String[] args) {
// serializePresident();
deserializePresident();
}
And see what comes up.
For me, the first run returns:
US President [name=Barack Obama, period=2009 to --, term=56th term]
US President [name=Barack Obama, period=2009 to --, term=56th term]
and the second run returns:
US President [name=Barack Obama, period=2009 to --, term=null]
I have the server project that I have seperated into 6 different classes:
ServerConnectionManager - is class is ment to be the hub for all other classes
Connection - This object is the created whenever a client connects and also starts a Thread
ServerListner - This is the Thread class that listens to input from the user
ServerSender - This is the class that sends messages to one or more users
ServerInformation - this class contains two list one of chat persons and one of connections this class also allows you to search through the list to find a specefic person and or connection
ChatPerson - This object is to contain the username of each person who connects to the server
As you no-doubt have guessed by now this is a server for a chat program!
My question to you is:
I want to use the Design patteren (Mediator) on this project and therefore the ServerConnectionManager contains all the key methods that each of the classes use. for example adding a connection to the connection list in the ServerInformation class.
But since the ServerInformation class cannot be called an object seeing as it only have alot of methods (functions) and no real purpose other than storing and searching Data would it be a good idea to make it static? or should i stick to the plan and make everything go through the ServerConnectionManager?
Here is a sample of my code:
ServerConnectionManager
public class ServerConnectionManager {
private static ServerSocket server;
private static Socket connection;
private static ServerInformation ai = new ServerInformation();
private static boolean connected = false;
private static final int portNumber = 7070;
private static int backLog = 100;
/**
* This method launches the server (and the application)!
* #param args
*/
public static void main(String[] args){
startServer();
waitForConnection();
}
/**
*This method sets the serverSocket to portNumber and also adds the backLog.
*/
private static void startServer() {
try {
server = new ServerSocket(portNumber, backLog);
connected = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* This method waits for a connection aslong as the serverSocket is connected.
* When a new client connects it creates an Object of the connection and starts the individual procedure.
*/
private static void waitForConnection() {
while (connected) {
try {
connection = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection c = new Connection(connection);
addConnection(c);
waitForConnection();
}
}
public static void closeMe(Socket con) {
for (Connection conn : ai.getConnectionList()) {
if (conn.getConnection() == con) {
ai.getList().remove(ai.getList().indexOf(ai.getChatPersonByConnection(con)));
ai.getConnectionList().remove(conn);
System.out.println(ai.getList());
System.out.println(ai.getConnectionList());
conn.close();
break;
}
}
}
public static void addConnection(Connection con){
ai.addToConnectionList(con);
}
public static void addChatPerson(ChatPerson p){
ai.add(p);
System.out.println(ai.getList());
}
}
Connection
public class Connection{
private Socket connection;
public Connection(Socket connection){
this.connection = connection;
ServerListner cl = new ServerListner(Connection.this);
cl.start();
}
public Socket getConnection(){
return this.connection;
}
public void close() {
try {
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ServerListner
public class ServerListner extends Thread {
private Socket connection;
private BufferedReader br;
private ChatPerson person;
private Connection con;
private ServerInformation ai = new ServerInformation();
private ServerSender sender = new ServerSender();
public ServerListner(Connection con){
this.con = con;
connection = con.getConnection();
try {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Socket getConnection(){
return this.connection;
}
public void run(){
System.out.println(con.getConnection().isConnected());
try {
String inString;
while ((inString = br.readLine()) != null) {
if (inString.equalsIgnoreCase("Disconnect")) {
System.out.println(inString);
break;
}else {
processInput(inString);
}
}
ServerConnectionManager.closeMe(connection);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void processInput(String input){
if (input.equalsIgnoreCase("Connect")) {
sender.sendMessageToConnection(this.connection, "Accepted");
}
if (input.equalsIgnoreCase("UserInformation")) {
try {
String username = br.readLine();
person = new ChatPerson(username, connection);
ServerConnectionManager.addChatPerson(person);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (input.equalsIgnoreCase("SearchByCon")) {
String name = ai.searchByConnection(connection);
System.out.println(name);
}
}
}
ServerSender
public class ServerSender {
private PrintWriter pw;
private ServerInformation ai = new ServerInformation();
public void addToList(){
}
public void sendToAll(String message){
for (Connection c : ai.getConnectionList()) {
try {
pw = new PrintWriter(c.getConnection().getOutputStream());
pw.print(message);
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
*
* #param con
* #param message
*/
/*
* Note - Denne metode gør også at jeg kan hviske til folk!:)
*/
public void sendMessageToConnection(Socket con, String message){
try {
PrintWriter print = new PrintWriter(con.getOutputStream());
print.println(message);
print.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ServerInformation
public class ServerInformation{
private ArrayList<Connection> connectedClients = new ArrayList<Connection>();
private ArrayList<ChatPerson> list = new ArrayList<ChatPerson>();
public ArrayList<Connection> getConnectionList(){
return connectedClients;
}
public void addToConnectionList(Connection con){
connectedClients.add(con);
}
public String searchByConnection(Socket myConnection){
for (ChatPerson p : list) {
if (p.getConnection() == myConnection) {
return p.getName();
}
}
/*
* If none found!
*/
return null;
}
public ChatPerson getChatPersonByConnection(Socket myConnection){
for (ChatPerson p : list) {
if (p.getConnection() == myConnection) {
return p;
}
}
return null;
}
public void add(ChatPerson p){
list.add(p);
}
public void removeByName(String name){
for (ChatPerson p : list) {
if (p.getName().equalsIgnoreCase(name)) {
list.remove(p);
}
}
}
public String searchList(String name){
for (ChatPerson p : list) {
if (p.getName().equalsIgnoreCase(name)) {
return p.getName();
}
}
return null;
}
public ArrayList<ChatPerson>getList(){
return list;
}
}
ChatPerson
public class ChatPerson {
private String chatName;
private Socket connection;
/*
* This is for furture development
* private Integer adminLevel;
*/
public ChatPerson(String name, Socket connection){
this.chatName = name;
this.connection = connection;
}
public void setName(String name){
this.chatName = name;
}
public String getName(){
return chatName;
}
public String toString(){
return "Username: "+chatName;
}
public Socket getConnection(){
return connection;
}
}
Thank you in advance, by the way since i am a student it would be nice if you had time to rate my code aswell and come with suggestions on how i can improve (if there are any :))
You probably meant class with only static methods, not static class. Static inner classes are something different (you can google it).
Advantages of having non-static methods in your manager:
You can easily mock them with frameworks like Mockito during testing.
You can pull them up to some interface during refactoring of your code.
Using static methods is not object-oriented-programming as such method invocations are not associated with any instance (object) of your class.