I have been studying Java networking for a while.
I am using ObjectInputStream and ObjectOutputStream for the I/O between sockets.
Is this possible to transfer a Entity or Model from server to client and vise versa?
How can I implement this? Am I suppose to implement the Entity or Model to Serializable?
Your response is highly appreciated.
I am not sure what sort of special thing you mean to denote by capital-E Entity and capital-M Model; these terms don't have any fixed, privileged meaning in Java (although they might with respect to a certain API or framework.) In general, if by these you just mean some specific Java objects, then yes, you can send any sort of objects this way, and yes, they would be required to implement Serializable. The only limitations would be if these objects contained members whose values wouldn't make sense on the other end of the pipe -- like file paths, etc.
Note that if you send one object, you'll end up sending every other object it holds a non-transient reference to, as well.
First of all... why sending an object through I/O stream? What's wrong with XML?
However, you can always send/receive an object through I/O stream as long as the sender can serialize the object and the receiver can deserialize the object. Hope it helps
You definitely need to look at one of these two libraries
Google gson: http://code.google.com/p/google-gson/
Converts Java object to JSON and back. advantage is that the object can be consumed or generated by Javascript. I have also used this for Java-Java RPC, but it gives you flexibility if you want to target browsers later
Google protocol buffers: http://code.google.com/apis/protocolbuffers/
This is what google uses for RPC. Implementations for Java, C, Python. If you need performance and the smallest size, this is the one to go with (The trade off is you can't look at the data easily to debug problems, like you can with gson, which generates plaint text JSON).
Related
dear stackoverflow community.
Currently, I am working on a project. This project shall have a server and clients connecting to it. Because of their simplicity, I'd like to use Java's integrated ServerSockets and Sockets.
In my project, data shall be sent from the client to the server and opposite.
My initial idea is to just send JSON and then parse it as receiver and get the data from that.
I'm a little unsure about that though, since JSON isn't something that's integrated into Java, but comes from Java script. Also, I'm currently using a Multithreaded-Socket-Server, so I have a ClientHandler Thread class. In that class, the messages were received, parsed and the "action" parameter was read out of the JSON and then I did a switch statement with multiple actions and their functions. I don't think that's a good way of doing that either.
So, my question is:
How can I do that better, and maybe do I have to use something else?
Thanks in advance.
It is true that JSON grew out of JavaScript, but it is a reasonable definition language on its own and I don't see any reason you shouldn't use it. There are libraries for parsing it so you don't have to.
Assuming your JSON structures are different for different purposes, and complex enough to need different classes to represent them, I like the idea of the JSON having a parameter that identifies the class to which it belongs, after which you can hand off parsing to a class that understands the designated output. Then a class can read the JSON, get the type, and some the specific parsing routine can go from there to an object created for the purpose.
I don't see anything wrong with an action string, either; it's served well enough for Swing and some other UIs, after all. Instead of branching out to a function, depending on complexity again, you could have action classes that all implemented an interface, and the action 'verb' could tell you which one (out of a map, say?) to get and execute the 'performAction()' method on or whatever you want to call it.
I don't know how clear this is from a quick description; would be willing to chat about it in an SO chat room if you care about it.
I've seen a lot of questions on how to Serialize POJO's in java using different frameworks, but I wanted to really understand the need of making our POJO's Serializable in the first place. You use JavaScript to handle the POJO objects or Spring or any other framework - why is it that we always have to make our POJO's Serializable ?
Is it something that has to be done on a GOOD PRACTICE or a BEST PRACTICE?
If it is not the case, what is the advantage that we would be able to leverage by Serializing POJO classes?
There are a couple of threads that discuss about this, but I'm not really satisfied with the explanation / answers!
Can anyone here, shed some light on this concept please?
You serialize POJO's when you usually need to:
Transmit them through some medium (Web Service, etc)
Store them on some medium. (This in turn devolves into how you are going to store them: XML, binary, etc).
You do not always have to serialize them, it depends on what ever it is you are doing.
For instance, if you have a web application with the concept of a User object, wherein a user has a user name, and maybe some preferences it might not make sense to make that class serializable. However, if you expose a web service through which 3rd parties can extract user information, then that class would need to be serializable so that it can be transmitted to said 3rd parties.
Serialization is needed when you have to convert the Object to byte Stream.
Byte Streaming is needed when you transmit the object with other applications or when you have to store that object.
So if you are using other formats like JSON for passing data, you won't need to serialize your objects.
I have a Java Server that sending the java serializable object to my client, and receive java serializable object for execution. If my client is also java written, which is nice, that allow me to do communication within any problems.
But now, I would like to extend my programme to not only java client, the client may be written in C, objective C, python or php. So, I would like to do something to "convent" to client request to a java object, and send back to Server. The convent process, I can use the JSON to receive, and construct a Java object to the Server, but I also need a layer that convert back the Java object to JSON to the client.
My Question is except make a JSON-Java Translation layer, is there any other ways to do so? Also, we can afford to change some code in server side, but we must use Java as our primary language for that. Any suggestions? Thanks.
I use Netty API for designing my protocol and it is quite quick to do so if you can understand a NIO-like Byte and Buffer API.
It is design to work with a concept of Encoder and Decoder that could fit your need, there are a lot of default implementation of Encoder and Decoder for zipping, using ssl...
The problem you have seems to looks like this one:
JBoss Netty with JSON
I don't know JSON very well but most of the time is could also be quick and easy to design your own protocol.
Do you need a generic Serialization process for any kind of Object or do you simply need to serialize some String and primitive types (Integer, Short, Float..etc)?
In the case of simple objects it is easy and a lot faster to do the wrapper by yourself.
If objects are quite simple, and I would guess this is the case, your need it to design your own "protocol" specification meaning how to turn each Object into a sequence of primitive types, String and arrays. Than it should be quite easy to write both the Encoder and the Decoder in each language.
Good luck
There are other libraries designed for this, like protocol buffers and thrift.
http://thrift.apache.org/
http://code.google.com/p/protobuf/
I'd like to create a web API of some kind (I don't have a preference for the protocol), where the server uses Java and the client uses PHP.
I want the request and response to both be objects (instances of classes, not JSON-style hashes). The objects' fields can be primitive types or other objects. I would define all the necessary classes in both the client and server code. PHP and Java have similar object models, so it shouldn't be hard to write corresponding classes in both languages.
To make this work, there would need to be some automated way to serialize an object on one side, and unserialize it on the other. It would need to know which PHP class maps to which Java class, and how to convert the fields. I could write something, but is there an existing protocol for transferring objects like this? Can this be done with SOAP?
Java and PHP objects are not interchangeable. You will have to define the object types on both ends, and the transfer protocol could be anything you like. Serialization and deserialization makes the whole process transparent. The transport medium could be JSON, XML, YAML, or anything else for that matter.
For a record-like objects:
{"_type":"MyCoolObjectType", "a":1, "b":2, "c":3"}
If you're wanting to write once and use everywhere, I'd recommend using the same language on both ends, otherwise you'll have to have a compiler that can translate between your choice languages.
A SOAP web service can handle the basic abstraction as long as the request/response is not very complex. You can create the classes in java and then get the API to export a WSDL for them.
You need to have them both serialize to the same string. The PHP format and Java format for serialization are different, and therefore incompatible. You need a common exchange format, and I recommend that you DON'T use PHP's. However, the functions to serialize in PHP are fairly simple, are contained in ext/standard/var.c file in the PHP source if you choose to use it..
See the following:
Unserialize in Java a serialized php object - A similar question to yours.
http://en.wikipedia.org/wiki/Serialization#Serialization_formats
http://en.wikipedia.org/wiki/XML
XML, API, CSV, SOAP! Understanding the Alphabet Soup of Data Exchange
From http://en.wikipedia.org/wiki/XML (emphasis mine):
Although the design of XML focuses on documents, it is widely used for the representation of arbitrary data structures, for example in web services.
What are the key points in checklist to be checked while implementing good serialization in java (I'm not really looking for , implements Serializable, write, readObject etc).
Instead , How to reduce the size of the object , Probably how to make the object in zip format and send over the network etc..
How to ensure the secure mode of transfer.
any others like this..
How to reduce the size of the object: new ObjectOutputStream(new GZipOutputStream(new BufferedOutputStream(out)). But this is a space-time tradeoff. You may find that it makes performance worse by adding latency.
How to ensure the secure mode of transfer: SSLSocket or an HTTPS URL.
Any others like this
Any others like what? You will need to be specific.
Do not use serialization to "persist" objects - this makes schema management (i.e. changing what constitutes a class's state) almost unworkable
Always declare a serialVersionUID field; otherwise you will not be able to add methods, or change the class in any way (even non-state-changing ones) without old versions of your code being unable to deserialize the objects (an IncompatibleClassVersionError will be thrown)
try and override readResolve if you are deserializing a logical "enum" instance of a class (typesafe enumeration pattern)
Make sure you are 100% happy with the name of the variables which make up the state of your class. Once you have serialized instances around, you cannot change the variable names
Do not implement Serializable unless you really have to
Do not make your interfaces Serializable - the implementation classes may be, but the interfaces should not be
Do not make serialization part of the way your library passes objects around, unless you are the only producer and consumer of the objects (e.g. server-GUI communication). Use a binary/wire protocol instead (e.g. protobuf)
To minimize what is sent over the wire, you could use swizzling. That is, perhaps you have a Product class; the serialized form might just be a unique int id field. All other methods could then be made to construct relevant state as required (perhaps as a database call, or call to some central service)
Make sure, if you are serializing out an object which contains some collection of elements as part of its state, that you synchronize on the collection. Otherwise you may find that someone modifies the collection as it is being serialized out, resulting in a ConcurrentModificationException
Probably how to make the object in zip format and send over the network etc..
Check out how the game developers for network games implement networking. They know, how to transmit data quickly. Have a look at e.g. http://code.google.com/p/kryonet/
How to ensure the secure mode of transfer. any others like this..
There are a lot of interpretations of secure mode. If you need reliability, use TCP otherwise UDP. If you need encryption use TLS otherwise rot13 may fit. If you need to ensure integrity, append a hash of the values to the message.
How to reduce the size of the object ,
Analyse your data and strip down the objects, so that you only have the necessary data in there. This is very context specific, as the best optimisation can be in the domain. E.g. you can check, if it is possible to send only deltas of the change.
It is an interesting question, but you have to be more specific about your goal or domain to get an answer that fits best.