Wednesday, October 31

Calculator in WPF application C#.NET

C# Code:
Download here: source code
Concatenate of two numbers:





namespace calculator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string numberBTN  = String.Concat(button1.Content.ToString(), textBox1.Text);
            textBox1.Text = numberBTN;
        }
    }
}

XAML COde:



<Window x:Class="calculator.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Calculator" Height="350" Width="525">
    <Grid>
        <TextBox Height="27" HorizontalAlignment="Center" Margin="153,35,0,0" Name="textBox1" VerticalAlignment="Top" Width="200" />
        <Button Content="1" Height="23" Margin="234,109,0,0" Name="button1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="36" Click="button1_Click" />
    </Grid>
</Window>

Monday, October 29

Applets in Java


Applets

Where Do Applets and Classes Come from?
When a web browser sees an applet tag and decides to download and play the applet,
it starts a long chain of events. Let's say your browser sees the following applet tag:

<APPLET codebase="http://metalab.unc.edu/javafaq/classes"
code="Animation.class" width="200" height="100" >
<PARAM NAME = “FRAMErATE”   VALUE = “10”>
</APPLET>

1.      The web browser sets aside a rectangular area on the page 200 pixels wide and
100 pixels high. In most web browsers, this area has a fixed size and cannot be
modified once created. The appletviewer in the JDK is a notable exception.
2.      The browser opens a connection to the server specified in the codebase parameter, using port 80 unless another port is specified in the codebase URL. If there's no codebase parameter, then the browser connects to the same server that served the HTML page.
3.      The browser requests the .class file from the web server as it requests any other file. If a codebase is present, it is prefixed to the requested filename. Otherwise, the document base (the directory that contains the HTML page) is used. For example:
GET /javafaq/classes/Animation.class HTTP 1.0

4.      The server responds by sending a MIME header followed by a blank line (\r\n) followed by the binary data in the .class file. A properly configured server sends .class files with MIME type application/octet-stream. For example:
HTTP 1.0 200 OK
Date: Mon, 10 Jun 1999 17:11:43 GMT
Server: Apache/1.2.8
Content-type: application/octet-stream
Content-length: 2782
Last-modified: Fri, 08 Sep 1998 21:53:55 GMT
5.      The web browser receives the data and stores it in a byte array. The byte code verifier goes over the byte codes that have been received to make sure they don't do anything forbidden, such as converting an integer into a pointer.
6.      If the byte code verifier is satisfied with the bytes that were downloaded, then the raw data is converted into a Java class using the defineClass( ) and loadClass( ) methods of the current ClassLoader object.
7.      The web browser instantiates the Animation class using its noargs constructor.
8.      The web browser invokes the init( ) method of Animation.
9.       The web browser invokes the start( ) method of Animation.

10.  If the Animation class references another class, the Java interpreter first searches for
the new class in the user's CLASSPATH. If the class is found in the user's CLASSPATH,
then it is created from the .class file on the user's hard drive. Otherwise the web
browser goes back to the site from which this class came and downloads the .class file for the new class. The same procedure is followed for the new class and any other
class that is downloaded from the Net. If the new class cannot be found, a
ClassNotFoundException is thrown



Who Can an Applet Talk to and What Can It Say?

1.      Applets cannot access arbitrary addresses in memory. Unlike the other restrictions in the list, which are enforced by the browser's SecurityManager instance, this restriction is a property of the Java language itself and the byte code verifier.
2.      Applets cannot access the local filesystem in any way. They cannot read from or write to the local filesystem nor can they find out any information about files. Therefore, they cannot find out whether a file exists or what its modification date may be.
3.      Applets cannot launch other programs on the client. In other words, they
cannot call System.exec( ) or Runtime.exec( ).
4.      Applets cannot load native libraries or define native method calls.
5.      Applets are not allowed to use System.getProperty( ) in a way that reveals
information about the user or the user's machine, such as a username or home
directory. They may use System.getProperty( ) to find out what version of
Java is in use.
6.       Applets may not define any system properties.
7.      In Java 1.1 and later, applets may not create or manipulate any Thread or
ThreadGroup that is not in the applet's own ThreadGroup. They may do this
in Java 1.0.
8.       Applets cannot define or use a new instance of ClassLoader, SecurityManager, ContentHandlerFactory, SocketImplFactory, or URLStreamHandlerFactory. They must use the ones already in place.

9.      An applet can only open network connections to the host from which the applet itself was downloaded.
10.  An applet cannot listen on ports below 1,024. (Internet Explorer 5.0 doesn't
allow applets to listen on any ports.)
11.  Even if an applet can listen on a port, it can accept incoming connections only
from the host from which the applet itself was downloaded.


















The Network Methods of java.applet.Applet

Using java.applet.Applet to Download Data
  • Sound
  • Images

public URL getDocumentBase( )
The getDocumentBase( ) method returns the URL of the page containing the applet.

Example
import java.applet.*;
import java.awt.*;
public class WhereAmI extends Applet {
public void paint (Graphics g) {
g.drawString(this.getDocumentBase().toString( ), 25, 50);
}
}
public URL getCodeBase( )
The getCodeBase( ) method returns the URL of the directory where the applet is
located. If the applet is in a JAR archive, then the codebase is the URL of the directory where the JAR archive is. If the applet is in a package (e.g.com.macfaq.applets.MyApplet instead of just MyApplet), then the codebase is the directory or JAR archive containing the outermost package such as com.

Downloading Images
public Image getImage(URL url)
Image myLogo = getImage (new URL("http://metalab.unc.edu/java/cup.gif"));


public Image getImage(URL url, String name)
Image logo = this.getImage(new URL("http://metalab.unc.edu/java/"),
"cup.gif");

Example
public class ImageView extends Applet {
Image picture;
public void init( ) {
try {
URL u = new URL(this.getCodeBase( ), this.getParameter("IMAGE"));
this.picture = this.getImage(u);
System.err.println(u);
}
catch (MalformedURLException e) {
// shouldn't happen, the codebase is never malformed
}
}
public void paint (Graphics g) {
g.drawImage(this.picture, 0, 0, this);
}
}

Note:
The getImage( ) method returns immediately, even before it knows whether the
image actually exists. The image isn't loaded until some other part of the program
actually tries to draw it, or you explicitly force the image to start loading

Downloading Sounds
public void play(URL u)
The play( ) method looks for a sound file at the URL u. If the sound file is found, then it is downloaded and played. Otherwise, nothing happens.
Example
try {
URL soundLocation =
new URL( "http://metalab.unc.edu/java/course/week9/spacemusic.au" );
play(soundLocation);
}
catch (MalformedURLException e) {
System.err.println(

Example
import java.applet.*;
import java.awt.*;
import java.net.*;
public class PlaySound extends Applet {
public void init( ) {
try {
URL u = new URL(this.getCodeBase( ), this.getParameter("sound"));
this.play(u);
}
catch (MalformedURLException e) {}

}
}

public void play(URL url, String filename)
This is similar to the previous method, except that it uses the url argument to find the sound file's directory and the filename argument to get the actual filename. For
Example:
play(new URL("http://www.macfaq.com/", "gong.au"));

public AudioClip getAudioClip(URL u)
The java.applet.AudioClip interface represents a sound. You can download a sound from a web site with the getAudioClip( ) method. Once you have an AudioClip object, play it at your leisure by calling the clip's play( ) and loop( ) methods; play( ) plays the file once, and loop( ) plays it repeatedly. Both of these methods let you keep the audio clip around for future use—unlike the play( ) method of the last section, which discarded the audio data after it had finished.

Example
AudioClip theGong;
try {
URL u = new URL(http://metalab.unc.edu/javafaq/gong.au);
theGong = this.getAudioClip(u);
theGong.loop();
//theGong.play();

}
catch (MalformedURLException e) {
System.err.println(e);
}
public AudioClip getAudioClip(URL url, String filename)

Example
import java.applet.*;
import java.awt.*;
public class RelativeBeep extends Applet implements Runnable {

private AudioClip beep;
private boolean stopped = false;

public void init( ) {
beep = this.getAudioClip(this.getDocumentBase( ),"sounds/beep.au");
if (beep != null) {
Thread t = new Thread(this);
t.start( );
}
}
public void start( ) {
this.stopped = false;
}
public void stop( ) {
this.stopped = true;
}
public void run( ) {
Thread.currentThread( ).setPriority(Thread.MIN_PRIORITY);
while (true) {
if (!stopped) beep.play( );
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {}

The MediaTracker Class

1.       This class is used for loading multiple images.
2.       The java.awt.MediaTracker class can track the loading status of many different images and organize them into logical groups.
3.  Create an instance of MediaTracker and then use the MediaTracker's addImage(Image pic, int ID ) method for each Image.
4.      ID does not have to be unique; it is really a group ID that is used to organize different images into groups.
5.      Before using the image, call a method such as checkID( ) to see whether the image is ready.
6.       Other methods let you force loading to start, discover which images in a group have failed to load successfully, wait for images to finish loading, and so on.

7.      The Constructor
The MediaTracker class has one constructor:
public MediaTracker(Component comp)
This constructor creates a MediaTracker object that tracks images for a specified Component. It's usually invoked like this:
MediaTracker tracker = new MediaTracker(this);

8.      Adding Images to MediaTrackers
Image picture = this.getImage(this.getDocumentBase( ), "logo.gif");
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(picture, 1);
public void addImage(Image image, int id, int width, int height)
The image will eventually be displayed scaled to the width ‘width’ and the height ‘height’.

9.      Checking Whether Media Has Loaded

There are four check methods that tell you whether particular images tracked by a
MediaTracker have loaded. These are:
public boolean checkID(int id)
public boolean checkID(int id, boolean load)
public boolean checkAll( )
public boolean checkAll(boolean load)

10.  public boolean checkID(int id)
This method checks whether all the images with the indicated ID that are tracked by
this MediaTracker have finished loading. If they have, it returns true; otherwise, it
returns false. Multiple Image objects may have the same ID.




public void paint(Graphics g) {
if (theTracker.checkID(1)) {
g.drawImage(thePicture, 0, 0, this);
}
else {
g.drawString("Loading Picture. Please hang on", 25, 50);
}
}
11.  public boolean checkID(int id, boolean load)
This method checks whether all the Image objects with the indicated ID that are tracked by this MediaTracker have finished loading. If they have, it returns true; otherwise, it returns false. Multiple Image objects may have the same ID. If the boolean argument load is true, all images with that ID that are not yet being loaded will begin loading.

public void paint(Graphics g) {
if (theTracker.checkID(1, true)) {
g.drawImage(thePicture, 0, 0, this);
}
else {
g.drawString("Loading Picture. Please hang on", 25, 50);
}
}
12.  public boolean checkAll( )
This method checks whether all the Image objects that are tracked by this object have
finished loading. ID numbers are not considered. If all images are loaded, it returns
true; otherwise, it returns false. It does not start loading images that are not already
loading.

13.  public boolean checkAll(boolean load)
This version of checkAll( ) checks whether all the Image objects that are tracked by
this MediaTracker have finished loading. If they have, it returns true; otherwise, it
returns false. If the boolean argument load is true, then it also starts loading any
Image objects that are not already being loaded.

14.  public void waitForID(int id) throws InterruptedException
This method forces the images with the ID number id that are tracked by this
MediaTracker to start loading and then waits until each one has either finished
loading, aborted, or received an error.

try {
tracker.waitForID(1);
}
catch (InterruptedException e) {
}
15.  public boolean waitForAll( ) throws InterruptedException
The waitForAll( ) method starts loading all the images that are tracked by this
MediaTracker in up to four separate threads while pausing the thread that invoked it
until each tracked image has either finished loading, aborted, or received an error. An
InterruptedException is thrown if another thread interrupts the waiting thread.

Downloading the images is easy
à           Create URL objects that point to each image.
à           Then call Applet’s ‘Image getImage( )’ with each URL.
à           Add returned image to MediaTracker Object.
à           Use it (MediaTracker) to force the images to load;
à           Then use waitForAll( ) to make sure all frames have loaded.
à           Finally, call drawImage( ) method of class Graphics
to display the images in sequence.


Example A Very Simple Animator Applet

public class Animator extends Applet
implements Runnable, MouseListener {
private boolean running = false;
private int currentCell = 0;
private Vector cells = new Vector( );
private MediaTracker tracker;

public void init( ) {
this.addMouseListener(this);
String nextCell;
this.tracker = new MediaTracker(this);

for (int i = 0; (nextCell = this.getParameter("Cell" + i)) != null; i++) {
Image img = this.getImage(this.getDocumentBase( ), nextCell);
cells.addElement(img);
tracker.addImage(img, i);
// start loading the image in a separate thread
tracker.checkID(i, true);
}
}
public void run( ) {
// wait for all images to finish loading
try {
this.tracker.waitForAll( );
}
catch (InterruptedException e) {
}
for (currentCell=0; currentCell < cells.size( ); currentCell++)
{
if (!running) return;
// paint the cell
this.repaint( );
// sleep for a tenth of a second
// i.e. play ten frames a second

try {
Thread.sleep(100);
}
catch (InterruptedException ie) {}
}
}
public void stop( ) {
this.running = false;
}
public void start( ) {
this.running = true;
Thread play = new Thread(this);
play.start( );
}
public void paint(Graphics g) {
g.drawImage((Image) cells.elementAt(currentCell), 0, 0, this);
}
// The convention is that a mouseClick starts
// a stopped applet and stops a running applet.
public void mouseClicked(MouseEvent e) {
if (running) {
this.stop( );
}
else {
this.start( );
}
}
// do-nothing methods required to implement the MouseListener
interface
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}

Polymorphism Concept in OOP


  • Polymorphism is declaring a uniform interface that isn't type aware, leaving implementation details to concrete types that implement the interface.
  • ad-hoc polymorphism (looks like a duck and walks like a duck => is a duck). Can be seen in Haskell and Python for example.
  • generic polymorphism (where a type is an instance of some generic type). Can be seen in C++ for example (vector of int and vector of string both have a member function size).
  • subtype polymorphism (where a type inherits from another type). Can be seen in most OO programming languages (i.e. Triangle is a Shape).
  • Wikipedia: Polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. Pretty straightforward for me.
  • Multiple implementations of the same interface.
  • Multiple forms of a single object is called Polymorphism.
  • Different objects can respond to the same message in different ways, enable objects to interact with one another without knowing their exact type.
  • Polymorphism is a programming feature that allows an object to have many types ('shapes') and lets you treat it as any of those types depending on what you need to do without knowing or caring about its other types.
  • Polymorphism at the lower level is the ability to invoke methods that are defined by the implementors of an interface from the interface instance.
  • Polymorphism is ability of an object to appear and behave differently for the same invocation. ex: each animal appear and sound differently ( when you hit it.

Saturday, October 27

Trigonometry Function in c# WPF application

Download Here: Source Code


<Window x:Class="Trigonometry.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Height="33" HorizontalAlignment="Left" Margin="174,90,0,0" Name="inputDisplay" VerticalAlignment="Top" Width="156" />
        <Button Content="Cos (" Height="23" HorizontalAlignment="Left" Margin="174,129,0,0" Name="cosBTN" VerticalAlignment="Top" Width="75" Click="cosBTN_Click" />
        <Button Content="Sin (" Height="23" HorizontalAlignment="Left" Margin="255,129,0,0" Name="sinBTN" VerticalAlignment="Top" Width="75" Click="sinBTN_Click" />
        <Button Content="Tan (" HorizontalAlignment="Left" Margin="174,158,0,0" Name="tanBTN" Width="75" Height="23" VerticalAlignment="Top" Click="tanBTN_Click" />
        <Button Content="Cot (" Height="23" HorizontalAlignment="Left" Margin="255,158,0,0" Name="cotBTN" VerticalAlignment="Top" Width="75" Click="cotBTN_Click" />
        <Button Content="Sec (" Height="23" HorizontalAlignment="Left" Margin="255,187,0,0" Name="secBTN" VerticalAlignment="Top" Width="75" Click="secBTN_Click" />
        <Button Content="Cosec (" Height="23" HorizontalAlignment="Left" Margin="174,187,0,0" Name="cosecBTN" VerticalAlignment="Top" Width="75" Click="cosecBTN_Click" />
        <Label Content="* Angle must be in radian" Foreground="Red" Height="28" HorizontalAlignment="Left" Margin="174,56,0,0" Name="label1" VerticalAlignment="Top" Width="156" />
    </Grid>
</Window>




namespace Trigonometry
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void cosBTN_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show( "Cos("+inputDisplay.Text+") = "+Math.Cos(double.Parse(inputDisplay.Text)).ToString());
        }

        private void sinBTN_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Sin(" + inputDisplay.Text + ") = " + Math.Sin(double.Parse(inputDisplay.Text)).ToString());
        
        }

        private void tanBTN_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Tan(" + inputDisplay.Text + ") = " + Math.Tan(double.Parse(inputDisplay.Text)).ToString());
        
        }

        private void cotBTN_Click(object sender, RoutedEventArgs e)
        {
            double cot = 1/(Math.Tan(double.Parse(inputDisplay.Text)));
            MessageBox.Show("Cos(" + inputDisplay.Text + ") = " + cot.ToString());
        
        }

        private void cosecBTN_Click(object sender, RoutedEventArgs e)
        {

            double cosec = 1 / (Math.Sin(double.Parse(inputDisplay.Text)));
            MessageBox.Show("Cosec(" + inputDisplay.Text + ") = " + cosec.ToString());
        }

        private void secBTN_Click(object sender, RoutedEventArgs e)
        {

            double sec = 1 / (Math.Cos(double.Parse(inputDisplay.Text)));
            MessageBox.Show("Sec(" + inputDisplay.Text + ") = " + sec.ToString());
        }
    }
}



Friday, October 26

WPF Application with SQL Server 2008

Download Here: SourceCode 






using System.Data.SqlClient;

namespace dataBaseConnectionTutorial
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        SqlConnection connectToDataBase = null;
        string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|Datadirectory|\testDataBase.mdf;Integrated Security=True;User Instance=True";
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (connectToDatabase())
            {
                MessageBox.Show("Connection Established");
            }
            else
            {
                MessageBox.Show("Connection couldn't be Established");
            }
        }
        public bool connectToDatabase()
        {
            bool connectionStatus = false;
            connectToDataBase = new SqlConnection(connectionString);
            try
            {
                connectToDataBase.Open();
                connectionStatus = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                connectionStatus = false;
            }
            return connectionStatus;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (connectToDataBase == null)
            {
                MessageBox.Show("Please Connect to Database");
            }
            else
            {
                string query = "Select * from testTable";
                SqlCommand queryToDataBase = new SqlCommand(query, connectToDataBase);
                SqlDataReader dataReader = queryToDataBase.ExecuteReader();
                while (dataReader.Read())
                {
                    tableData.Items.Add(dataReader[1].ToString());
                }
                connectToDataBase.Close();
            }
        }
    }
}

Friday, October 19

Remote Method invocation



1.      Networking has been concerned with two fundamental applications.
·         The first application is moving files and data between hosts, which is handled by FTP, SMTP (email), HTTP, NFS, and many other protocols.
·         The second application is allowing one host to run programs on another host.

2.      Remote Method Invocation (RMI) is an example of the second application for networking: running a program on a remote host from a local machine.
3.      RMI is a core Java API and class library that allows Java programs to call certain methods on a remote server.
4.      The methods running on the server can invoke methods in objects on the client.
5.      Return values and arguments can be passed back and forth in both directions.
6.      In essence, parts of a single program run in a Java virtual machine on a local client while other parts of the same program run on a Java virtual machine on a remote server.
7.      RMI creates the illusion that the distributed program is running on one system with one memory space holding all the code and data used on either side of the actual physical connection.

RMI API
1.      The Remote Method Invocation API lets Java objects on different hosts communicate with each other.
2.      A remote object lives on a server.
3.      Each remote object implements a remote interface that specifies which of its methods can be invoked by clients.
4.      Clients invoke the methods of the remote object almost exactly as they invoke local methods.
Example an object running on a local client can pass a database query as a String argument to a method in a database object running on a remote server to ask it to sum up a series of records. The server can return the result to the client as a double.
This is more efficient than downloading all the records and summing them up locally.

Programmer's perspective
From the programmer's perspective, remote objects and methods work just like the local objects and methods you're accustomed to. All the implementation details are hidden.

  • Import one package.
  • Look up the remote object in a registry (which takes one line of code).
  • Make sure that you catch RemoteException when you call the object's methods.
  • From that point on, you can use the remote object almost as freely and easily as you use an object running on your own system.




Remote Object
  • is an object whose methods may be invoked from a different Java virtual machine than the one in which the object itself lives, generally one running on a different computer.
  • Each remote object implements one or more remote interfaces that declare which methods of the remote object can be invoked by the foreign system.

Object Serialization
a way to convert the object into a stream of bytes.
When an object is passed to or returned from a Java method, what's really transferred is a reference to the object. Passing objects between two machines thus raises some problems.
  • The remote machine can't read what's in the memory of the local machine.
  • A reference that's valid on one machine isn't meaningful on the other.
There are two ways around this problem.
  • A special remote reference to the object (a reference that points to the memory in the remote machine) can be passed,
  • or a copy of the object can be passed.

When the local machine passes a remote object to the remote machine, it passes a remote reference. The object has never really left the remote machine.
However, when the local machine passes one of its own objects to the remote machine, it makes a copy of the object and sends the copy. The copy moves from the local machine to the remote machine.


The RMI Layer Model


1.      To the programmer, the client appears to talk directly to the server.
2.      In reality, the client program talks only to a stub. The stub passes that conversation along to the remote reference layer, which talks to the transport layer.
3.      The transport layer on the client passes the data across the Internet to the transport layer on the server.
4.      The server's transport layer then communicates with the server's remote reference layer, which talks to a piece of server software called the skeleton.
5.      The skeleton communicates with the server itself.
6.      In the other direction (server-to-client), this flow is simply reversed.
7.      Logically, data flows horizontally (client-to-server and back), but the actual flow of data is vertical.
Registry
The registry is a program that runs on the server. It contains a list of all the remote objects that server is prepared to export and their names. A client connects to the registry and gives it the name of the remote object that it wants. Then the registry sends the client a reference to the object that it can use to invoke methods on the server.

Stub
The stub is a local object that implements the remote interfaces of the remote object; this means that the stub has methods matching the signatures of all the methods the remote object exports. In effect, the client thinks it is calling a method in the remote object, but it is really calling an equivalent method in the stub. Stubs are used in the client's virtual machine in place of the real objects and methods that live on the server. When the client invokes a method, the stub passes the invocation to the remote reference layer.

Skelton
The skeleton reads the arguments and passes the data to the server program, which makes the actual method call. If the method call returns a value, that value is sent down through the skeleton, remote reference, and transport layers on the server side, across the Internet and then up through the transport, remote reference, and stub layers on the client side.

Remote Reference Layer
On client side, the remote reference layer translates the local reference to the stub into a remote reference to the object on the server. Then it passes the invocation to the transport layer. On server side, the remote reference layer converts the remote references sent by the client into references for the local virtual machine. Then it passes the request to the skeleton.

Transport Layer
The transport layer sends the invocation across the Internet.

The Server Side
1.      To create a new remote object, first define an interface that extends the
java.rmi.Remote interface.
2.      Subinterface of Remote determines which methods of the remote object may be
called by clients. A remote object may have many public methods, but only those
declared in a remote interface can be invoked remotely. The other public methods
may be invoked only from within the virtual machine where the object lives.
3.      Each method in your subinterface must declare that it throws RemoteException.
RemoteException is the superclass for most of the exceptions that can be thrown
when RMI is used. Many of these are related to the behavior of external systems and
networks and are thus beyond your control.


import java.rmi.*;
import java.math.BigInteger;

public interface Fibonacci extends Remote {
public BigInteger getFibonacci(int n) throws RemoteException;
public BigInteger getFibonacci(BigInteger n) throws RemoteException;
}

4.      The next step is to define a class that implements this remote interface. This class
should extend java.rmi.server.UnicastRemoteObject, either directly or ndirectly
(i.e., by extending another class that extends UnicastRemoteObject):
public class UnicastRemoteObject extends RemoteServer

public class UnicastRemoteObject extends RemoteServer

5.      If extending UnicastRemoteObject isn't convenient—for instance, because you'd
like to extend some other class—then you can instead export your object as a remote
object by passing it to one of the static UnicastRemoteObject.exportObject( )
methods:

public static RemoteStub exportObject(Remote obj)throws RemoteException

Example
import java.rmi.*;
import java.net.*;
import java.rmi.server.UnicastRemoteObject;


public class FibonacciImpl implements Fibonacci {
public FibonacciImpl( ) throws RemoteException {
UnicastRemoteObject.exportObject(this);
}
public BigInteger getFibonacci(int n) throws RemoteException {
//impleementation
}
public BigInteger getFibonacci(BigInteger n) throws RemoteException
{
            //impleementation
}

}//End Class
Public class FibonacciServer
{

public static void main(String[] args) {

try {
FibonacciImpl f = new FibonacciImpl( );
Naming.rebind("fibonacci", f);
System.out.println("Fibonacci Server ready.");
}
catch (RemoteException re) {
System.out.println("Exception in FibonacciImpl.main: " + re);
}
catch (MalformedURLException e) {
System.out.println("MalformedURLException " + e);
}
}
Although the main( ) method finishes fairly quickly here, the server will continue to
run because a nondaemon thread is spawned when the FibonacciImpl( ) exports the
FibonacciImpl object.

Client Side
import java.rmi.*;
import java.net.*;

public class FibonacciClient {
public static void main(String args[]) {

try {
Object o = Naming.lookup(“rmi://localhost:12/Fibonacci”);
Fibonacci calculator = (Fibonacci) o;

try {
BigInteger f = calculator.getFibonacci(1000);
}

}

}catch (RemoteException e) {
System.err.println("Remote object threw exception " + e);
}
catch (NotBoundException e) {
System.err.println(
"Could not find the requested remote object on the server");
}
}
}

Compiling the Stubs
rmic FibonacciImpl
copy the Fibonacci.class and FibonacciImpl_Stub.class files to both the directory on the remote server from which the Fibonacci object will be run and the directory on the local client where the Fibonacci object will be invoked.


Starting the Server
1.      Start the registry first.
C:> start rmiregistry
The registry runs in the background. The registry tries to listen to port 1,099 by default.
2.      Run the Server
Running the Client
1.      Make sure that the client system has FibonacciClient.class, Fibonacci.class, and FibonacciImpl_Stub.class in its class path.
2.      Run the Client

CallBacks
Server can call back methods of clients

Threads
The RMI specification says "A method dispatched by the RMI runtime to a remote object implementation may or may not execute in a separate thread. The RMI runtime makes no guarantees with respect to mapping remote object invocations to threads. Since remote method invocation on the same remote object may execute concurrently, a remote object implementation needs to make sure its implementation is threadsafe."
In other words, the RMI implementation is free to dispatch an incoming RMI call on any thread. It may dispatch them all consecutively to the same thread; concurrently to many threads; or any other way it likes. There is no implication that there is—or is not—one specific dispatch thread per exported object. There is no guarantee about mapping clients, or client threads, to server threads. There are no guarantees and you can make no assumptions. Your implementations of remote methods must be threadsafe. It is up to you.