Using Serialization

Serialization is a mechanism built into the core Java libraries for writing a graph of objects into a stream of data. This stream of data can then be programmatically manipulated, and a deep copy of the objects can be made by reversing the process. This reversal is often called deserialization.

Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

import java.io.*;

public class SerializeDemo
{

public static void main(String [] args)
{

Employee e = new Employee();
e.name = “Ramakrishna”;
e.address = “Hyderabad”;
e.SSN = 11122333;
e.number = 200113;

try
{

FileOutputStream fileOut =
new FileOutputStream(“employee.ser”);
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();

}catch(IOException i)
{
i.printStackTrace();
}
}
}

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:

import java.io.*;

public class DeserializeDemo
{

public static void main(String [] args)
{

Employee e = null;

try
{
FileInputStream fileIn =
new FileInputStream(“employee.ser”);
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;

}catch(ClassNotFoundException c)
{
System.out.println(.Employee class not found.);
c.printStackTrace();
return;
}

System.out.println(“Deserialized Employee…”);
System.out.println(“Name: ” + e.name);
System.out.println(“Address: ” + e.address);
System.out.println(“SSN: ” + e.SSN);
System.out.println(“Number: ” + e.number);
}
}

This would produce following result:

Deserialized Employee…
Name: Ramakrishna
Address:Hyderabad
SSN: 0
Number:200113


In particular, there are three main uses of serialization:

As a persistence mechanism
If the stream being used is FileOutputStream, then the data will automatically be written to a file.

As a copy mechanism
If the stream being used is ByteArrayOutputStream, then the data will be written to a byte array in memory. This byte array can then be used to create duplicates of the original objects.

As a communication mechanism
If the stream being used comes from a socket, then the data will automatically be sent over the wire to the receiving socket, at which point another program will decide what to do.

The important thing to note is that the use of serialization is independent of the serialization algorithm itself. If we have a serializable class, we can save it to a file or make a copy of it simply by changing the way we use the output of the serialization mechanism.

As you might expect, serialization is implemented using a pair of streams. Even though the code that underlies serialization is quite complex, the way you invoke it is designed to make serialization as transparent as possible to Java developers. To serialize an object, create an instance of ObjectOutputStream and call the writeObject( ) method; to read in a serialized object, create an instance of ObjectInputStream and call the readObject( ) object.

TIP: There are two versions of the serialization protocol currently defined: PROTOCOL_VERSION_1 and PROTOCOL_VERSION_2. If you send serialized data to a 1.1 (or earlier) JVM, you should probably use PROTOCOL_VERSION_1. The most common case of this involves applets. Most applets run in browsers over which the developer has no control. This means, in particular, that the JVM running the applet could be anything, from Java 1.0.2 through the latest JVM. Most servers, on the other hand, are written using JDK1.2.2 or later.[3] If you pass serialized objects between an applet and a server, you should specify the serialization protocol.

Explain Briefly about Serialization

Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, I referred to this process several times but delayed a detailed discussion until now. In this chapter, we drill down on the serialization mechanism; by the end of it, you will understand exactly how serialization works and how to use it efficiently within your applications.

What does it mean for the client to pass an instance of Money to the server? At a minimum, it means that the server is able to call public methods on the instance of Money. One way to do this would be to implicitly make Money into a server as well.[1] For example, imagine that the client sends the following two pieces of information whenever it passes an instance as an argument:

  • The type of the instance; in this case, Money.
  • A unique identifier for the object (i.e., a logical reference). For example, the address of the instance in memory.

The RMI runtime layer in the server can use this information to construct a stub for the instance of Money, so that whenever the Account server calls a method on what it thinks of as the instance of Money, the method call is relayed over the wire

Attempting to do things this way has three significant drawbacks:

  • You can’t access fields on the objects that have been passed as arguments.

Stubs work by implementing an interface. They implement the methods in the interface by simply relaying the method invocation across the network. That is, the stub methods take all their arguments and simply marshall them for transport across the wire. Accessing a public field is really just dereferencing a pointer–there is no method invocation and hence, there isn’t a method call to forward over the wire.

  • It can result in unacceptable performance due to network latency.

Even in our simple case, the instance of Account is going to need to call getCents( ) on the instance of Money. This means that a simple call to makeDeposit( ) really involves at least two distinct networked method calls: makeDeposit( ) from the client and getCents( ) from the server.

  • It makes the application much more vulnerable to partial failure.

Let’s say that the server is busy and doesn’t get around to handling the request for 30 seconds. If the client crashes in the interim, or if the network goes down, the server cannot process the request at all. Until all data has been requested and sent, the application is particularly vulnerable to partial failures.

This last point is an interesting one. Any time you have an application that requires a long-lasting and durable connection between client and server, you build in a point of failure. The longer the connection needs to last, or the higher the communication bandwidth the connection requires, the more likely the application is to occasionally break down.
TIP: The original design of the Web, with its stateless connections, serves as a good example of a distributed application that can tolerate almost any transient network failure. These three reasons imply that what is really needed is a way to copy objects and send them over the wire. That is, instead of turning arguments into implicit servers, arguments need to be completely copied so that no further network calls are needed to complete the remote method invocation. Put another way, we want the result of makeWithdrawal( ) to involve creating a copy of the instance of Money on the server side. The runtime structure should resemble

The desire to avoid unnecessary network dependencies has two significant consequences:

  • Once an object is duplicated, the two objects are completely independent of each other.

Any attempt to keep the copy and the original in sync would involve propagating changes over the network, entirely defeating the reason for making the copy in the first place.

  • The copying mechanism must create deep copies.

If the instance of Money references another instance, then copies must be made of both instances. Otherwise, when a method is called on the second object, the call must be relayed across the wire. Moreover, all the copies must be made immediately–we can’t wait until the second object is accessed to make the copy because the original might change in the meantime.

These two consequences have a very important third consequence:

  • If an object is sent twice, in separate method calls, two copies of the object will be created.

In addition to arguments to method calls, this holds for objects that are referenced by the arguments. If you pass object A, which has a reference to object C, and in another call you pass object B, which also has a reference to C, you will end up with two distinct copies of C on the receiving side.

GUI Examples Using Applets

/* Now the applet will have a GUI
These are elements to interact with the user.
In this example they will not perform any actions.
*/


import java.awt.*;
import java.applet.*;

public class GuiExample extends Applet
{


// A Button to click
Button okButton;

// A textField to get text input
TextField nameField;

// A group of radio buttons
// necessary to only allow one radio button to be selected at the same time

CheckboxGroup radioGroup;
// The radio buttons to be selected
Checkbox radio1;
Checkbox radio2;

// An independant selection box
Checkbox option;

public void init()
{

// Tell the applet not to use a layout manager.
setLayout(null);

// initialze the button and give it a text.
okButton = new Button(“A button”);

// text and length of the field
nameField = new TextField(“A TextField”,100);

// initialize the radio buttons group
radioGroup = new CheckboxGroup();

// first radio button. Gives the label text, tells to which
// group it belongs and sets the default state (unselected)
radio1 = new Checkbox(“Radio1″, radioGroup,false);

// same but selected
radio2 = new Checkbox(“Radio2″, radioGroup,true);

// Label and state of the checkbox
option = new Checkbox(“Option”,false);

// now we will specify the positions of the GUI components.// this is done by specifying the x and y coordinate and
//the width and height.

okButton.setBounds(20,20,100,30);
nameField.setBounds(20,70,100,40);
radio1.setBounds(20,120,100,30);
radio2.setBounds(140,120,100,30);
option.setBounds(20,170,100,30);

// now that all is set we can add these components to the applet
add(okButton);
add(nameField);
add(radio1);
add(radio2);
add(option);
}

}


// Thats’s it, you now have given the user visual options.
// However there are no actions related to these comonents.
// that makes it easier to place components.

How To Delete the textbox using the Javascript

This topic is to delete the textbox/textarea/selectbox which will be created dynamically in the application using javascript

if you need to delete the rows just u need to select that check box and go for the delete button .

You can have this code for using in your application this must be related to the button which you will use in your application

the Code is


function deleteRow() {
try {
var table = document.getElementById(‘myTable’);
//alert(‘table’+table);
var rowCount = table.rows.length;

for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && false == chkbox.checked) {
table.deleteRow(i);
rowCount–;
i–;
}

}
}catch(e) {
alert(e);
}
}

<INPUT type=”button” value=”Delete Row” onclick=”deleteRow()” />