Saturday, September 14, 2013

Java : Reflection


Java : Reflection

Reflection is the process of examining or modifying the runtime behavior of a class at runtime.

Java.lang.Class class
* provide methods to get the metadata of a class at runtime
* provide methods to examine and change the runtime behavior of a class.

Get the object of Class class
- forName() method of Class class
- getClass() method of Object class
- the .class syntax

forName()
* forName() is used to load class dynamically.
* returns the instance of Class class
* should be use full qualify name of the class

getClass()
* Returns the instance of Class class.
* It should be use if the object is available.

The .class syntax
If a type is available but there is no instance then it is possible to obtain a Class by appending “.class” to the name of the type.
This can be used to Primitive Data Type also.


package O1Concepts.Reflection;

/**
* @author sanjeeva
* Reflection - is the process of examining or modifying the runtime behavior of a class at runtime
* forName()
* getClass()
* .class
*/
public class Reflection {

      /**
      * @param args
      */
      public static void main(String[] args) {
            Reflection reflection = new Reflection();
            reflection.execute();
      }

      private void execute(){

            try {
                 //forName() ..
                 Class cls = Class.forName("O1Concepts.Reflection.Simple");
                 System.out.println("Name[ forName() ] --> " + cls.getName());

                 //getClass() ...
                 Simple simple = new Simple();
                 Class objClass = simple.getClass();
                 System.out.println("Name[ getClass() ] --> " + objClass.getName());

                 Class<Integer> type = Integer.class;
                 System.out.println("Name[ .class :1 ] --> " + type.getName());

                 Class<Reflection> ref = Reflection.class;
                 System.out.println("Name[ .class :2 ] --> " + ref.getName());

            } catch (ClassNotFoundException e) {
                 e.printStackTrace();
            }
      }
}


Output -
Name[ forName() ] --> O1Concepts.Reflection.Simple
Name[ getClass() ] --> O1Concepts.Reflection.Simple
Name[ .class :1 ] --> java.lang.Integer
Name[ .class :2 ] --> O1Concepts.Reflection.Reflection

Networking : Lesson 04 - InetAddress class


Networking : Lesson 04 - InetAddress class

The java.net.InetAddress class represent an IP address.
This class provides methods to get the IP of any host name.

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressClass {

       /**
       * @param args
       */
       public static void main(String[] args) {

            try {
                  InetAddress address =         InetAddress.getByName("educationjavacode.blogspot.com");

                  System.out.println("Host Name : " + address.getHostName());
                  System.out.println("Host Address: " + address.getHostAddress());
            } catch (UnknownHostException e) {
                  e.printStackTrace();
            }
      }
}


Host Name : educationjavacode.blogspot.com
Host Address: 74.125.236.42

Networking : Lesson 03 - URLConnection class


Networking : Lesson 03 - URLConnection class

package Networking;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
* @author sanjeeva
*
* URLConncetion class represent a communication link between the URL and the application.
*
* The class can be used to read and write data to the specified resource refer by the URL.
*/
public class URLConnectionClass {

      /**
      * @param args
      */
      public static void main(String[] args) {

            try {
                   URL url = new URL("http://educationjavacode.blogspot.com/search/label/Networking%20%3A%20Lesson%2001%20%E2%80%93%20Socket%20Programming");

                   URLConnection urlConnection = url.openConnection();
                   InputStream inputStream = urlConnection.getInputStream();

                   int i;
                   while((i=inputStream.read())!=-1){
                          System.out.print((char)i);
                   }
             }catch (Exception e) {
                   // TODO: handle exception
             }
      }
}

Friday, September 13, 2013

Networking : Lesson 02 - URL class


Networking : Lesson 02 - URL class

URL contains :
          Protocol                                    : http
          Server Name / IP address     : localhost
          Port Number                            : 8080
          File Name / Directory Name : NetworkExample/index.html


package Networking;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class URLExample {

     /**
     * @param args
     */
     public static void main(String[] args) {

          try {
                URL url = new URL("http://educationjavacode.blogspot.com/search/label/Networking%20%3A%20Lesson%2001%20%E2%80%93%20Socket%20Programming");

                System.out.println("Authority : " + url.getAuthority());
                System.out.println("DefaultPort : " + url.getDefaultPort());
                System.out.println("File : " + url.getFile());
                System.out.println("Host : " + url.getHost());
                System.out.println("Path : " + url.getPath());
                System.out.println("Port : " + url.getPort());
                System.out.println("Protocol : " + url.getProtocol());
                System.out.println("Query : " + url.getQuery());
                System.out.println("Ref : " + url.getRef());
                System.out.println("UserInfo : " + url.getUserInfo());
                System.out.println("Class : " + url.getClass());
                System.out.println("Content : " + url.getContent());
         } catch (MalformedURLException e) {

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


Output :

Authority : educationjavacode.blogspot.com
DefaultPort : 80
File : /search/label/Networking%20%3A%20Lesson%2001%20%E2%80%93%20Socket%20Programming
Host : educationjavacode.blogspot.com
Path : /search/label/Networking%20%3A%20Lesson%2001%20%E2%80%93%20Socket%20Programming
Port : -1
Protocol : http
Query : null
Ref : null
UserInfo : null
Class : class java.net.URL
Content : sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@11b9fb1



Networking : Lesson 01 – Socket Programming


Networking : Lesson 01 – Socket Programming

Networking is a concept of connecting two or more computing devices together.
The java.net package of the J2SE APIs contains a collection of classes and Interfaces.

What is a Protocol ?

A Protocol is a set of rules that is followed for communication.
Examples – FTP, TCP, SMTP, Telnet, POP, etc.

Socket Programming
Sockets provide the communication mechanism between two computers using TCP.

A client program creates a socket on its end and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket.

java.net.Socket class - represents a socket
java.net.ServerSocket class - provides a mechanism for the server program to listen for clients and establish connections with them.

Establishing a TCP connection between two computers using sockets:

1. The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
2. The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.
3. After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to.
4. The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server.
5. On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.

TCP is a two-way communication protocol, so data can be sent across both streams at the same time.


Example 1 – Client / Server communication

package Networking;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientServerExecute {

       /**
       * @param args
       */
       public static void main(String[] args) {

              ClientServerExecute execute = new ClientServerExecute();
              execute.doExecute();
       }

       private void doExecute(){

              Thread threadServer = new Thread(){
                      public void run(){
                             executeServer();
                      }
              };

              Thread threadClient = new Thread(){
                     public void run(){
                             executeClient();
                     }
              };

              threadServer.start();
              threadClient.start();
      }

      private void executeServer(){

              try {
                     ServerSocket serverSocket = new ServerSocket(6666);
                     System.out.println("[Server] Create new socket");

                     //Establish the connection
                     Socket socket = serverSocket.accept();
                     System.out.println("[Server] Establish the connection");

                     DataInputStream dIs = new DataInputStream(socket.getInputStream());
                     System.out.println("[Server] Get data Input stream");

                     String string = (String)dIs.readUTF();
                     System.out.println("[Server] Read the Input stream --> " + string);

                     serverSocket.close();
                     System.out.println("[Server] Close Server socket");
              } catch (IOException e) {
                     e.printStackTrace();
              }
      }

      private void executeClient(){

              try {
                      //Establish the connection
                      Socket socket = new Socket("localhost",6666);
                      System.out.println("[Client] Establish the connection"); 

                      DataOutputStream dOutStrm = new DataOutputStream(socket.getOutputStream());
                      System.out.println("[Client] Create Output Stream Object");

                      dOutStrm.writeUTF("Hello Server");
                      System.out.println("[Client] write Out put stream");
                      dOutStrm.flush();
                      System.out.println("[Client] flush");

                      dOutStrm.close();
                      socket.close();
                      System.out.println("[Client] close");
               } catch (IOException e) {
                      e.printStackTrace();
               }
       }
}


Output as follows :

[Server] Create new socket
[Server] Establish the connection
[Server] Get data Input stream
[Client] Establish the connection
[Client] Create Output Stream Object
[Client] write Out put stream
[Client] flush
[Client] close
[Server] Read the Input stream --> Hello Server
[Server] Close Server socket