Wednesday, 26 August 2015

Java WebServices


SOA
    It is collection of architectural principles to design and implement our software applications in such a way they are composed of several software services that have simple and well defined interfaces and can use each other in a loosely coupled manner.

Webservices is a way to implement SOA priciples. There are 2 types of webservice technologies. SOAP & REST. Standard for SOAP in java world is Jax-WS. Similarly Jax-Rs for Rest.


SOA (service oriented architecture) is a set of architectural principles to build loosely coupled applictions. It is maintained by open bodies like W3C
webservices is a way to implement those principles in our applications that we create

Service: According to SOA, it is implementation of business logic  that operates independent of state of an other service.  



Web services are Consumer/Provider applications that communicate on Network thru HTTP protocol. They exchange messages or data as XML, SOAP, JSON.
  • They provide interoperability between software applications.(Platform independent)
  • Loosely couple applications(Switch to any other services which provides same service)
  • Extensibility
  • Reusability 
  • Scalability - Deploy on multiple servers
  • Availability - Available even if one of the servers is down
  • Mashups - Build mashup application by consuming several different services that are available out there with in enterprise OR over internet.
Types of webservices(webservice technologies)
   - SOAP based- communicates using soap xml and Uses HTTP Post for message exchange. Follows JAX-WS standards
   - RESTful services - Uses HTTP methods to the full & supports multiple data formats for data exchange. Follows JAX-RS standards

In Java world
  • JAX-WS(Java api for XML based webservices) is the standard for implementing SOAP based webservices
  •  JAX-RS(Java api for  RESTful webservices) is a standard for implementing Restful webservices
Webservice is a specification.  It is a set of rules and guidelines to share data between 2 interoperable applications.
  • soW3C & OASIS defines and maintains the specification or principles 

Components suggested by webservice to support communication are:
  wsdl -> Webservice description language
  uddi(optional) -> universal
  skeleton
  stub
  soap protocol
  http protocol

WSDL sections:




Soap Bindings: Effect the way wsdl gets generated. Suppose for following method def
public void myMethod(int x, float y);

1. RPC/encoded (types are defined directly in message). They do not go to xml xsd of wsdl types.
Strengths:
  • WSDL is straight forward
  • Operation name appears in the message, 
Weaknesses:
  • type encoding is overhead in SOAP message. 
  • not WSI compliant
  •  
RPC /literal:
 
 
Strenghts:
  • Type encoding eliminated
  • WS-I compliant
Weakness
  • Cannot easily validate from schema
 Document/Encoded - No body follows and not WS-I compliant

 Document/Literal -
 
  •   Strengths
    • No type encoding
    • WS-i compliant with restrictions.
    • can validate message with any XML validator
  • Weakness
    • WSDL is bit more complicated
    • Operation name in message body is not available. 
    • Operation name is gone. Engines will have tough time to dispatch the request.

 Document/Literal Wrapped: Preferred style






2. RPC/literal ()




DOCUMENT/encoded
DOCUMENT/literal

wsdl contains name of service class, name of method, # of parameter and parameter types.
wsdl is uploaded uddi registry with a unique name.
Clint will download wsdl from uddi, and generate stub using stub generation tool. The methods available in service class will be available in stub also.
Stub will create SOAP request and send it to server using HTTP protocol
Server will hand over the request to the skeleton. Skeleton invokes the actual api on the service class and receives the result value. It prepares SOAP response and sends it back to stub.
Stub in turn returns the value to client program.

SUN has provided 4 APIS. JAX-RPC, JAX-M(xml messaging), JAX-WS, JAX-RS
They contain wsdl generation tools, skeleton and stub generation tools. We can develop both client and service.
SAX-M is used for asynchronous web service while others are for synchronous web service. 

Service development and communication works in the following manner:
Service provider
1. A service class(POJO class) is created and deployed on a webserver
2. Generate wsdl using wsdl generation tool
3. upload the wsdl to uddi or share it to client directly

Client
4. Client- download wsdl from uddi
5. Client- generate stub using stub generation tool
6. Create Client application  - instantiate stub class and call required method on it

Communication:
7. Client application calls method on stub object.
8. Stub generates SOAP requests with parameter values and sends to server using HTTP protocol
8. Server receives the SOAP request and forwards to skeleton.
9. Skeleton invokes the actual method on the service class
10. Skeleton receives the return value
11. Skeleton prepares SOAP response with return value and sends it to stub
11. stub receives the return value and sends it over to client program.

JAX-RPC- Java API for xml- Remote procedure call. It is a specification given by SUN as part of jdk1.4. This API can be used to develop both SOAP based web services or SOAP based web service client
 implementations:
             jax-rpc-si  (sun implementation) - not part of jdk. need to be downloaded separately
             Axis1 - Apache foundation
             weblogic implementation - bea/oracle - part of weblogic software
             websphere - IBM
              jboss - RedHat

All the above should provide wsdl generation tool, skeleton and stub generation tools

JAX-WS- Implementations -
      JAX-WS-RI (reference implementation) - SUN - available in jdk1.6
      METRO - full implementation -  SUN - download separetely
      Axis2 - Apache foundation
      Apache CXF - supports Spring integration where as Axis2 is not
      weblogic implementation
      websphere
       jboss
      glassfish - sun - it internally refers to Metro implementation

JAX-RS- implementations: specification is part of jdk1.6
  Java api for xml - restful services
     Jersey - sun - need to download separately
     RESTEASY - REDHAT
     RESTLET -
     APACHE CXF - Supports String integration
     APACHE WINK - doesn't Supports String integration

Webservice example using Axis1 implementation Manually
Axis1 is Jax-RPC implementation
1. Download Axis1 jar
2. Create a webappliction, copy axis1 jar files into WEB-INF/lib folder and then configure skeleton(org.apache.axis.transport.http.AxisServlet in web.xml)
3. In WEB-INF/classes folder create HelloService.java(service class)
4. Set axis1 jar files in the classpath and generate wsdl file

   java org.apache.axis.wsdl.Java2WSDL -o HelloService.wsdl -n http://www.hello.com
           -l http://localhost:8080/<skeleton url pattern>  <unique service class name>
5. Provide unique name to Service class in server-config.wsdd file
6. deploy the webservice

Webservice example using Axis1 implementation in Eclipse
1. Create dynamic web project
2. Create service class
3. Follow steps to convert the service class into webservices using axis1 implementation.
right click on the service class -> new -> others -> webservices->  webservice-> select server & webservice runtime options -> finish.

(Eclipse internally will create required files like wsdl, configures skeleton in web.xml with some url pattern, creates server-config.wsdd in WEB-INF folder and copies axis1 jar files to lib folder.
 Also deploys the application to server.)

Now the service is ready. Open browser and use end point url (from wsdl file) appended with ?wsdl
eg: http://localhost:8081/HelloService/services/HelloServ?wsdl

if the service provider, provides the wsdl, then the service is successfully deployed and running on to server.

Webservice client using Axis1 implementation in Eclipse
Types of webservice clients
 1. Proxy based client (Client generates stubs and uses them to invoke the service)
 2. DII client -> Dynamic invocation interface client (webservice implementation provider classes are used to invoke the webservice)

In both the types, client requires wsdl file or wsdl url to create webservice client
(wsdl contains service class details + end point url(Location where service is running))

1. Create a java project.
2. Copy wsdl file into client java project root directory
3. Generate stubs/proxies.  src folder -> new -> others-> webservices -> webservice client
-> provide wsdl, select server and webservice runtime options.
This step will copy axis jars to build/class patch. In src it will generate stubs.
Stubs will have the methods that are available in SERVICE class with a different implementation.

4. Create TestHello.java with main method and use generated stubs in main method to invoke webservice

    public static void main(String[] args) throws Exception {
          java.net.URL endpointurl= new java.net.URL("http://localhost:8081/HelloService/services/HelloServ");
        org.apache.axis.client.Service service = new org.apache.axis.client.Service();
        HelloServSoapBindingStub stub = new HelloServSoapBindingStub(endpointurl, service);
        String str=stub.hello("venkat.....");
        System.out.println(str);
    }

Webservice example using Axis2 implementation in Eclipse
Eclipse has the Axis2 plugins but not Axis2 jar files
1. Download Axis2 jars and extract downloaded zip file
2. Add Axis2 jars to eclipse (Windows-> preferences -> webservices -> Axis2 preferences -> add root directory of axis2 extracted folder)
3. Create dynamic webproject
4. Create HelloServ2.java in src folder.
5. Convert HelloServ2.java into webservice using Axis2
(Eclipse internally will create required files like wsdl, configures skeleton in web.xml with some url pattern, creates server-config.wsdd in WEB-INF folder and copies axis1 jar files to lib folder.
 Also deploys the application to server.)
6. Open browser and enter http://localhost:8081/<project name>. Go to services and copy the end point url
6. Test whether service is deployed or not.
http://localhost:8081/HelloAxis2/services/HelloServ2?wsdl

Webservice client using Axis2 implementation in Eclipse

1. Create a dynamic web project(2.5 version).

2. Generate stubs/proxies.  src folder -> new -> others-> webservices -> webservice client
-> provide wsdl, select server and webservice runtime options.
This step will copy axis jars to build/class patch. In src it will generate stubs.

4. Create TestHello.java with main method and use generated stubs in main method to invoke webservice

For every SERVICE class method, stub will have respective method & an inner classes(request & response). The method parameters are declared as class members with setters/getters.

Invoke the service method on STUB by passing inner class object as parameter.

    public static void main(String[] args) throws Exception {
        HelloServ2Stub stb = new HelloServ2Stub();
        HelloServ2Stub.Hello params= new HelloServ2Stub.Hello();
        params.setStr("venkat,,.");
        HelloServ2Stub.HelloResponse res=stb.hello(params);
        System.out.println(res.get_return());
    }


Why REST is light weight compared to SOAP?
  • SOAP is XML only, while REST allows you to send any payload, such as JSON which is less verbose and simpler than XML. Generally speaking, it takes less memory and less bandwidth to deal with JSON than XML.
  • On another level, using SOAP you typically describe everything as services. So, you need to define a message schema/structure for each verb and noun i.e. "CreateOrder". In REST, you use the predefined HTTP methods such as POST and put the noun/"resource" in the URI which uses already existing constructs on the HTTP level - not reinventing them in XML.
  • Then there is the effort it takes to adapt to change. A small change in SOAP requires you to redefine the schema, redefine the wsdl and handle versions. In rest, in the best of worlds, there is a degree of dynamic coded into the API (links to referenced resources, among other things), so that some changes can be implemented and takes effect directly.
  • All the heavy weight strictness of SOAP of course has a valid reason for existence. It's less likely two implementations have different interpretations of the API, than in a loosely defined REST API. SOAP also allows you to implement skeleton code in various languages based on a WSDL. In some complex scenarios, this is actually almost the only productive way to work with SOAP. Marshalling and unmarshalling between objects and serialized XML is rather heavy and adds to the heavyness of SOAP.
  • REST will return only data structure defined by XSD (DataContract) but the SOAP will wrap the structure into SOAP envelope. The complexity of SOAP envelope is based on used message version and additional WS* protocols.
  • SOAP was designed for a distributed computing environment where as REST was designed for a point to point environment
  • SOAP(using WSDL) is a heavy-weight XML standard that is centered around document passing. The advantage with this is that your requests and responses can be very well structured, and can even use a DTD. The downside is it is XML, and is very verbose. However, this is good if two parties need to have a strict contract(say for inter-bank communication). SOAP also lets you layer things like WS-Security on your documents. SOAP is generally transport-agnostic, meaning you don't necessarily need to use HTTP.
    REST is very lightweight, and relies upon the HTTP standard to do it's work. It is great to get a useful web service up and running quickly. If you don't need a strict API definition, this is the way to go. Most web services fall into this category. You can version your API so that updates to the API do not break it for people using old versions(as long as they specify a version). REST essentially requires HTTP, and is format-agnostic(meaning you can use XML, JSON, HTML, whatever).

     





Wednesday, 19 August 2015

Core Java


Java Home: JAVA_HOME= C:\Program Files\Java\jdk1.8.0_45;

It is a JDK/jre installation directory. Programs look for the Java_Home environment variable, when they need java run

Which one should java home point, JDK or JRE
Developers should need to point to the JDK where utilities such as javac reside. Others, can point to the JRE. the JDK contains everything the JRE has and more. If you're just executing Java programs, you can point to either the JRE or the JDK.



Path: It describes the location where executable (javac, java) are available. It is referred by Operating System eg: patch=<Java Home>\bin;
Class Path: It describes the location where the required .class files are available. It is referred by both java compiler and jvm.

NOTE: To place a jar file in class path, one have to include the name of jar file. Directory alone is not sufficient.

JAR file - Java Archive
  1. Bundles all the resources and class files associated to a project
  2. Advantages are security, download time,compression, portability and versioning
  3. Compile .java class files
    javac -d . Hello.java
  4. Create jar file
    jar -cvf hello.jar Hello.class Hello$1.class <picsfolder if any>
Executable JAR file
  1. Create a java file com.team1.MHello
  2. Generate .class files
    javac -d . MHello.java
  3. Create manifest file with any name eg: manifest.mf and mention the class with main()
    Main-Class: com.team1.MHello
  4. Create jar file
    jar -cvfm ehello.jar manifest.mf com/team1/Hello.class Hello$1.class <picsfolder if any>
  5. Execute jar file
    java -jar hello.jar 
             OR
    Double click the jar file from Windows file explorer
Create Executable JAR file in Eclipse
  1. Create project & java files
  2. right click on project name -> Export ->   Runnable jar file(under java folder) -> Create jar under launch configuration-> select required destination directory -> Finish
Java Web Start (Jnlp - Java Network Launching Protocol) 
Java Web Start is a mechanism for program delivery through a standard Web server. Typically initiated through the browser, these programs are deployed to the client and executed outside the scope of the browser. Once deployed, the programs do not need to be downloaded again, and they can automatically download updates on startup without requiring the user to go through the whole installation process again.

  1.     Create a simple program and jar it as TestJnlp.jar
    jar -cf TestJnlp.jar *.*
  2.     Create and assign keystore into TestJnlp.jar
    keytool -genkey -keystore testKeys -alias jdc
    jarsigner -keystore testKeys TestJnlp.jar jdc
  3. Copy "TestJnlp.jar" to Tomcat's default web server folder, for example, in Widnows - C:\Program Files\Apache\Tomcat 6.0\webapps\ROOT
  4. Create a Jnlp file Test.jnlp
    <?xml version="1.0" encoding="utf-8"?>
    <jnlp spec="1.0+" codebase="http://localhost:8080/" href="Test.jnlp"> 
    <information> 
    <title>Jnlp Testing</title> 
    <vendor>YONG MOOK KIM</vendor> 
    <homepage href="http://localhost:8080/" /> 
    <description>Testing Testing</description> 
    </information>
    <security>
    <all-permissions/>
    
    
    </security> 
    <resources> 
    <j2se version="1.6+" /> 
    <jar href="TestJnlp.jar" /> 
    </resources> 
    <application-desc main-class="com.mkyong.TestJnlp" />
    </jnlp> 
  5. Deploy jnlp file
    Copy Test.jnlp to your Tomcat default web server folder also. C:\Program Files\Apache\Tomcat 6.0\webapps\ROOT
  6. Access TestJnlp.jar from web through http://localhost:8080/Test.Jnlp
    Access URL http://localhost:8080/Test.jnlp, it will prompt you to download the Test.jnlp file, just accept and double click on it.
 

Use JAR file in Client Program
  1. Copy jar file to D:\
  2. javac -cp d:\hello.jar client.java
  3. java -cp .;d:\hello.jar client
    OR
  4. alternatively one can place the jar file in jdk -> jre -> lib -> ext folder

    Java, javaw, javaws

    java -> execute program with console output
    javaw -> execute program out console output(used in gui based applications)
    javaws -> java web start utility -> It downloads and launches web application
      eg: javaws  D:\Cloud.jnlp"

    Jar vs War vs EAR
    Jar -Java archive - Group of .class files
    war - web archive - Represent one web application and may contain jsps, servlets, html, css, js, xml
    ear - enterprise archive - to package any thing from j2ee suite - ejb, jms

    enum - Enumeration Data Type
    To represent group of named constants. It is to define our own data types.
    Every enum constant is public static final and represents an object of type enum
    Enum is internally implemented using class concept.

    every enum constant is an object of type enum
    Declaration:
    enum Month
      {jan, feb};
     internally converted to:
    class Month
    {
       public static final Month jan=new Month();
       public static final Month feb=new Month();
    }

    Usage:

    class Test{
      public static void main(String[] args){
      Month mth=Month.jan;
    }
    }

    All enums should be direct child(extends) of java.lang.Enum class
    Every Enum is always final implicitly, and hence cannot be extended.
    Enums can implement Interfaces

     java.lang.Enum is the base class for all enums. It is an abstract class, and hence cannot create an object of Enum class. It is direct child class of Object. It implements Serializable and Comparable interfaces.


    Abstract Class:
    Abstract classes are incomplete. Subclasses must declare the "missing pieces" to become "concrete" classes, from which you can instantiate.
    eg:
    abstract class Animal{
       String color
       abstract void printInfo();


    Purpose:
       Provide appropriate super class from which other classes can inherit and thus share a common design.

       We can have variable whose type is abstract class. The actual object to which it refers must be an instance of concrete subclass.

      Constructors and static methods cannot be declared as abstract.

    Interface
    •  Interface is declaration of methods and doesn't have any definition
    • Methods in interface are public and abstract
    • Any field that is declared is public, final and static
    • Interface cannot be final, it gives compiler error. Only public and abstract are allowed
    • Interface with NO method declarations is called marker interface. 
      • It is to flag or give permission to execute a particular functionality
      • Marker interface is used as a added to inform a message to the java compiler so that it can add special behavior to the class implementing it
      • Eg of marker interfaces in JDK api are Serializable, Remote, Cloneable, Activateble
    • Why do we need Interfaces
      • No multiple inheritance in java - Cannot extend more than one class at a time
      • Interface can extend any number of interfaces
    • Usage of interfaces
      • Interface help in loose coupling
      •  

     Interface vs Abstract class
    Interface
         Don't know any thing about implementation, just have specification
         Every method is always public and abstract
         Can't declare interface methods as private and protected. Also with  final, static, synchronized. native and strictfp as the methods are Abstract
         Every variable present inside interface is public, static and final implicitly
         We can't declare instance block and static block inside interface
          Constructor not applicable

    Abstract Class
         We have/know partial implementation.
          Every method need not be public and abstract
          No restriction to method modifiers.
          Variables need not be public, static and final implicitly
           constructor can be present

    Access Specifiers vs Access Modifiers
    In java there is no terminology like access specifiers, all are access modifiers.
    public, private, protected, default
    final, static, synchronized, abstract, native, transient, volatile, Strictfp


    java.lang.Object
    • It is parent class to any class in java either directly or indirectly.
    • Java Compiler adds Object class as parent if it doesn't extend any other class.
    • It contains 11 methods which are required for any class in java
      •  toString() 
        • This is called when a class reference is printed. It returns object in string form
        • if not overridden in child class, it returns getClass().getName()+"@"+Integer.toHexString(hashCode())
        • It is highly recommended to override toString() in the child class
      • hashCode()
        • jvm assigns unique value for every object to identify objects uniquely.  It is based on address of object.
      • equals()
        • to compare content of objects
      • clone()
        • to create duplicate object to current object
      • finalize()
        • Before destroying any object, garbage collector calls this method.  
      • getClass() 
        • used to know current class name. It returns Class class object
      • notify()
      • notifyAll()
      • wait()
      • wait(long ms)
      • wait(long ms, int ns)
        • All wait() and notify() are for inter thread communication.


    Java Bean is a simple java class with private variables and public getter and setter methods.

    public class MyBean
    {
      private String name;
      private boolean empty;

      public void setName(String name){
      this.name=name;
    }

    public String getName(){
      return name;
    }

    public boolean isEmpty(){   //getEmpty is also fine, but isEmpty is recommended
    return empty;
    }

    Listeners  listens to events and performs appropriate actions automatically.

    Case1: To register a listener
      public void addMyActionListener(MyActionListener l) //method name should be prefixed with add and parameter type should be method name

    Case2: To unregister a listener
      public void removeMyActionListener(MyActionListener l) //method name should be prefixed with remove and parameter type should be method name


    New vs NewInstance 
    • new operator can be used only if we know the Class name at the design time. Can't be used if class name is available only at run time
    • NewInstance can be used if class name is available only at run time.
    • When new operator is used, if .class file is not available at run time, then it will raise Runtime Exception-NoClassDefFound error
    • When newInstance method is used, if .class file is not available at run time, then it will raise Runtime Exception-ClassNotFoundException. It is a checked exception.
     eg:   Object o=Class.forName(args[0]).newInstance());


    Parent p=new Child() vs Child c=new Child() 
    • We should go for Parent p=new Child(), when we do not know exact object type at run time. eg: return from ArrayList as ArrayList can hold hetero genious objects.
    • By using parent reference, we can invoke only methods from Parent class.

    instanceOf vs isInstance

    Abstract Class vs Abstract Method
    We can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.


    Java
    • JAVA_HOME(Java installation directory) 
      • C:\Program Files\Java\jdk1.6
    • Path & Classpath
      • Both are operating system level environment variables. %JAVA_HOME%\bin
      • Path is to define the location where the system can find executables(.exe).
      • Classpath is location where required class/jar files are available. It is referred or used by Java compiler & JVM. It is required only when third party jar files are referred. eg: jdbc driver.
      • The classpath is the conventional way to tell the Java compiler and the Java runtime where to find compiled classes.
      • The classpath used by the compiler and the runtime system don't have to be the same
    • Buildpatch(IDE terminology)
      • IDE uses this to figure out the classpath and sourcepath for compiling the Java code, and the classpath for running it.
      • IDE also uses the build path to figure out how to package up your code and its dependencies as (for example) a WAR file.
      •  
    • JDK, JRE & JVM
      • JDK provides environment to develop and run java applications
      • JRE provides environment to just run java applications
      • JVM is an interpreter (part of JRE), which is responsible to execute the java applications line by line. 
      • JDK= JRE +Development tools
      • JRE=JVM+Library classes 
      • JVM=Java interpreter + Just in time compiler (JIT)
    • JIT
      • Part of JVM. 
      • Repeatedly used code/classes are pre compiled to machine language and makes it available to JVM.
    • Platform independent high level programming language
    • Modifiers
    • JVM
    • Packages
    • Exception handling
    • Interfaces - for Dynamic binding
    • Threads
    • Network programming
    • Nested classes
    • Util packages
    • Java Beans
    • Applets and applet programming (AWT)
    • Java native interface - to access system resources(replacement for pointers)
    Features of Java
    • Almost purely Objected Oriented Language (except primitive data types)
    • Platform independence -> OS independent
    • Architecturally neutral -> hardware independent (JVM and byte code)
    DataTypes
    • Charecter
      • char - 2 bytes to support unicode chars
    • Integer
      • short - 2 bytes
      • int - 4 bytes
      • long - 8 bytes
      • byte - 1 byte
    • Float
      • float - 4 bytes
      • double  - 8 bytes
    • Boolean - 1 bit
    Arrays
    • int a[]=new int[5];
    Strings:
    • String
      • Non Mutable class(Which means the value cannot be changed)
      •  String s={"hello"}  //Memory allocated on method area
      • String s=new String("Hello"); //Memory allocated on heap area
    • StringBuffer
      • Mutable class
      • Use StringBuffer when ever modifications are needed
      • methods
        • length(), indexOf(), charAt(), subString(), compareTo(), equals(), equalsIgnoreCase()
    Wrapper Classes: 
    • Classes that exists for every primitive data type
    • Integer, Float, Character
    • These are needed to convert from one data type to another
      • Integer.parseInt(<String>)
    • When method parameter is of Object type
     Modifiers
    • abstract
    • static -
      • can be given to any member but not to class
      • Its global for all the objects
      • memory is allocated in method area when class is loaded into jvm
      • accessed by class name
      • It cannot access instance member directly
      • 'this' cannot be referenced in static method
    • final
      • class, variable, method
      • final variable can be declared either during declaration or in constructor
      • final methods cannot be overriden in sub class
      • final class cannot have sub class
    • native
    • transient
    • synchronized
    • access specifiers - To specify the scope of members of class and class itself. Variable, member, constructor.
      • Private - access within same class
      • Protected 
        • within the same class where member is defined
        • Within sub classes within same/different package
        • With in non-sub class using an object provided it is in same package
      • default/package scope  - access within same class, Child class same package, non sub class with in same package
      • Public - any where
      • Private & Protected can be given to any number of a class but not for class itself.

    Static block
    • They get executed as soon as class is loaded into jvm
    • executed only once
    Instance block
    • executed once per object
    • executed before constructor
    Private constructor
    • Constructor is defined as private, when the class is to be made as single ton pattern.
    • Singeton pattern means, for a class at a any point should have a single instance
    • Users cannot create instance from outside
    • Eg:
      Class A{
      static A obj;
      private A(){}
      public static getA(){
          if (obj==null){
                  obj=new A();
            }
         return obj;
         }
      }
    Inheritance
    • Child class can only expand the scope of the inherited methods but cannot restrict the scope

    Interfaces
    • They are pure abstract classes, which doesn't have any implementation.
    • It should contain methods of type public and abstract only
    • Variables should be public, static & final (Class constants)
    • Even if the modifiers are not mentioned explicitly, methods are treated as public & abstract, variables as public, static & final
    • An interface can extend/inherit other interfaces
      • interface i3 extends i1,i2
    • A class implementing any interface should mandatoryly implement all the methods.
    • Interfaces are used for dynamic binding 
    Marker Interface
    • They are interfaces with noting defined in them
      • Interface m {}
    • It is used to flag or give permission for a class to execute particular functionality
    • Marker interfaces that exists as part of jdk api 
      • Cloneable - To make bit by bit copy of an object
        • Clone() is a protected class in Object class and throws CloneNotSupported Exception
          • A a2=(A)a1.clone();
      • Remote - To access an Object on another machine
      • Serializable -
      • Activatable
    • instanceOf() is the method used to check if a particular object is of particular Class Type or Interface Type. Alternatively, one can use reflection api as well

    Abstact Class vs Interfaces
    • Abstract class can have any scope members
    • Abstract member cannot be private
    • Abstract class can have combination of implemented and non implemented methods

    Packages:
    • Java packages exist as directories in file system and contain related class files
    • Classes from different packages can derive from each other
    • When a class is in a package, package name should specified in which the class is available by using import statement.
    • Only the classes that are referred in the client code are compiled & loaded at run time, even when all the classes are referred using import A.*
    • At compilation time, the import statements are removed & the class references are overridden with fully qualified names.
    • It is good coding practice to specially import required classes rather than using *.
    • * means only the classes in speicified package/directory and not its sub classes.(non recursive) 
    • When class belongs to package, the compile command should use -d option. 
      • javac -d <path> <file.java> //path should specify the parent directory where the package directory should reside.
    Exception Handling
    • Exceptions are run time errors(that happen due to bad code/program)
      • ClassCastException - When you downcast a class to a wrong type
      • EndOfFileException - Access a file beyond its length
      • NumberFormatException - Convert a alpha numeric string  using parseInt method
      • IllegalAccessException - Access method which is not in scope
      • NullPointerException - Access Object variable on an object that is not yet referencing any where(still null)
      • ArrayIndexOutOfBounds - Try access array beyond length
      • ArthimeticException - devide by zero
    • How to handle run time errors
      • Using if-else statements - However, it becomes too complex due to nested statements and code readability becomes difficult. 
      • Exception handling
    • Handling exceptions in Java
      • try {} catch(<ExceptionType to be handled obj>){ <instructions to be executed>} finally{}
      • Try block can have any number of catch blocks but only ONE finally block
      • Child Exception should come first than Parent exception 
      • Try block must have atleast a Catch() or finally block.

    • Checked & Unchecked exceptions
      • Exceptions checked by compiler are known as Checked exceptions
        • eg: SQLException, IOException
      • Unchecked exceptions - Runtime exceptions
    • When exception is raised, an object of that Exception Type is created and thrown. The Object is captured in the catch block. The code after the catch block will be executed as usual. 
    • Finally block will be executed regardless of what ever happens (Return, break, unhandled exception). Only in case of System.exit, it will not execute Finally block.
    • try catch block can be placed with in try, catch or even finally block as well.
    • Exception Object printStackTrace() - It gives ErrorMessage, line where error has occured, and ExceptionType at the console. 
      • obj.getMessage() - returns the error message alone.
    • UserDefined Exceptions
      • public class MyException extends Exception {
            <add default & parameterized constructor, and call super constructor passing the message>   
        }
    • Throw - To raise exception
      • throw new MyException()
    • Throws clause is used to Propagate an exception. When ever there is a throws clause against a method, caller of method must handle the exception by writing a try & catch{}.
    • Re-throw exception : Have both try , catch block and re-throw the exception at the end of catch block.
    • If main() throws exception(not handled), jvm handles it by writing the stack trace to console and exit the program. 
    Applets:
    • Object -> Component -> Container-> Panel -> Applet
    • LifeCycle Methods
      • init->start->paint->stop->destroy
    • public class myApp extends Applet
    • JVM creates applet class instances using reflection API
    • 2 types of Applets
      • Trusted Applet
        •  In trusted applet, we specify in policy file the permissions what the applet should be given to do on the local machine. And generate a public/private certificates using key tool or 3rd party certificates.  Sign the jar file using the certificate. And then load on to client machine.
      • Untrusted Applet
        • By default the applets one writes is Untrusted. Applet cannot access local machine/network machines to read/write a file.  
    AWT:
    • Abstract Window Toolkit. It provides limited set of components. It is because AWT depends on OS to build components. Its all native calls.
    • Only components that are supported by all platforms are available in AWT package. Hence, AWT components are limited and basic.
    • We have components like Button, Text Field, Choice, List, Menus, ScrollBar, Window, Frame, Panel, Dialog, Label
    • Menu
      • Menus are supported only by Frames in AWT. Frame has a MenuBar. 
      • Any option that has sub option is of type Menu. 
      • Any option that executes on selection is Menu Item
      • Any option of type toggle is of type CheckBoxMenuItem
    • Layouts
      • Layouts define how the components are placed on a container
        • FlowLayout
          • Default layout for Panel and Applet 
          • Places components one after another in a row and moves to next row when the given row is filled
          • It is aligned to center by default
        • BorderLayout
          • Default for Frame and Dialog 
          • Max 5 components only(North, South, East, West & Center) 
        • CardLayout
          • Component takes entire space of the container. Similar to Tab cards.
        • GridLayout
          • Container having Grid Layout is divided into number of cells. Place components into each of the cell. The component occupies complete cell
          • It extends by columns when the number of cells is not enough
          •  
        • GridbagLayout

    Nested Classes:
    • Class with in a class
    • Nested class is not recognized by jvm. Hence, a .class file is generated for inner class as well with name Outer$Inner.class
    • As the inner class is member of outer class, the access specifier can be private, protected, static as well(which is not the case for outer class)
    • Instantiate inner class
      • Outer out = new Outer();
        Outer.Inner in=out.new Inner();
        in.disp()
      • //for static inner class
        Outer.Inner in=new Outer.Inner();
    Errors:
    • RunOutOfMemory
    • StackOverflow
    Java Beans
    • Java Beans is a component architecture of Java.  It allows you to define components
    • It is just another java class but follows certain rules/procedures
      • Must implement Serializable interface. It is because the bean has to be serialized when class that uses the bean is serialized
      • Will have setter, getter methods for all its properties
    • It is a reusable, inter operable software component. 
    • Component is a group of classes that interact with each other to fulfill a single purpose. One component is one single functionality, but it consists of multiple classes.
      • eg: JButton -  
    • Components can be either GUI bases or Non-GUI based
    • GUI components will be derived from Component Class. Non-GUI based component doesn't derive from any of the Component classes
    • Java bean should ideally support following
      • properties & accessors
      • Might have event handlers - so support communication between 2 beans
      • Must implement serializable interface for persistence
      • Public default constructor so that the object will be created via reflection
      • Upon a bean, a builder tool should be able to make a reflection and be able to create an object. 
      • Using a builder tool, if you were to drag and drop an object into design area, the builder tool should be able to create instance of your bean and be able to display properties of bean via reflection.
      • Using customization, one can specify what properties to be exposed for runtime environment. 
      • 4 type of properties for a bean
        • Simple - has Set & Get
        • Index - Used for Arrays.
        • bound - set & is for boolean
          • PropertyChangeEvent consists old value, new value & property name
          • It will have add listener method as well
        • constraint  - Veto change listeners- property change is allowed only if veto passes. It is in addition to value change listener
      • Bean uses property support object to hold list of listners
      • It should also supply registration and deregistration support.



    Jar, War and EAR
    • Jar - Java Archieve
      • group of .class files
      •  
    • War - Web Archieve
      • Project transportation, delivery and deployment will be easy
      • Placing the war file in webapps folder will work
      • Each war file represents one web application
      • We can use only web related technologies in war file. Like servlets and jsps
    • Ear - Enterprise archieve
      • Any thing from java & J2EE - EJB, JMS and so
    Jar file
    • Create a jar file(zip file)
      • jar -cvf dv1.jar <list of class files>
      • jar -cvf test.jar c:\work  d:\test 
      • Any type of file can be placed in jar
    • Extract a jar file(unzip)
      • jar -xvf <jar file>
    • Find the contents of jar
      • jar -tf <jar file>
    Executable jar file
    • Create manifest.MF file providing the class name that has main method
      • Main-Class:JarDemo
    • Create jar file
      • jar -cvfm myexecjar.jar demo.class demo$1.class manifest.mf
    • Execute jar file
      • java -jar myexecjar.jar

    Ways to run java program
    • java .classfile
    • java -jar myexecjar.jar or double click jar file
    • double click batch file
    SocketProgramming
    • How message is transferred from one appln to another residing on two different machines
      • Source
        • TCP handler adds source & destincation port numbers
        • IP layer adds the protocol from which the message is obtained, source & destincation IPs to the message
        • Ethernet layer adds source IP, ethernet card address of source & destination. Destination ethernet card address can change incase rounters between source & destination
      • Destination
        • Ethernet layer - When ethernet address matches, it picks up and pass to IP address
        • IP reads the message and passes to respective TCP/UDP layer based on protocol
        • TCP layer routes the message to the appln running on the respective port
    ServerSocket
    • Accepts client connections, creates new socket(at different port) to client interaction when client requests connection. Serversockets will wait for next connection requests
    •  Every socket(both at server and client side) will have Input & output Streams
    • What user reads from client input stream is obtained from Server output stream. What ever is writtern on client output stream is input to server input stream.

    Java IO

    • Stream is channel or medium that allows continous flow from input(Keyboard, network, mouse..) to Java applns and java appln to output devices(Monitor, Printer, Network..)
    • Types of Streams
      • Byte oriented streams
        • InputStream
        • OutputStream
      • Character Oriented Streams
        • Reader
        • Writer

    Monday, 17 August 2015

    Design Patterns

    Design patterns are standard way of solving problems, used during the design of the system. It is a general recurrent solution to a common occurring problem in software design.

    Two categories of design patterns:
    1. Normal programming design patterns
    2. Enterprise design patterns

    3 Kinds of J2EE design patterns

    1. Creational -> for creating Object
    2. Structural  -> for relating objects
    3. Behavioural -> dealing with interaction and responsibility of objects

    Creational Design Patterns -
    1) Singleton -> Ensures only one object is create for the entire application

    public class Single{
               private static Single instance =new Single();
               private Single()  {};
               public static Single getInstance(){
                                    return instance;
               }
    }
     Notes: When constructor is private, one cannot instantiate that class from outside.

    2) Factory ->
        eg: Sax Parser, Dom parser
    replica of an object - using clone()


    Behavioural Design Patterns -
      DAO - Design pattern in which single class interacts with database
      DTO - Pattern used to send multiple attributes to server in single go
      MVC- Model View Controller. Model(DB, Programming logic, Business logic) handles data, view(jsp/html) for display, and controller(web.xml) to control the application.

    DAO design pattern
         Main purpose is to isolate/encapsulate DB code to one specific class. This helps in object reuse. Other applications can make use of helper class. It is one self contained area where db code is located.

    It is common pattern, best practise,

    Architectural Design Patterns:

    Challenge: The graphical user interface enables the user to communicate with a computer application. The graphical user interface is not supposed to make decisions, validation, data storage, database connection, and other tasks.
    Solution: MVC Design pattern:
    MVC Design Pattern  - Architectural design pattern for separating the interaction of user and the web application in to 3 main concerns.
    • Isolates business logic from user interface
    • Makes it easier to manage complexity of application through the separation of concerns
    • Other benefits
      • developer specialization, focus and parallel development by separate teams.
    Model
    • Heart of web application. 
    • Represents the information(the data) of the application and the business rules used to manipulate the data
    • Retrieve data and convert(process, validate) to meaningful concepts.
    • At a first glance, it can be looked as the first layer of interaction with any database you might be using for your application.
    • Ejbs, Dao objects, or service objects may be the model
    View
    • View corresponds to elements of user interface - It is just a set of webpages
    Controller 
    • It is like a mediator between Model and View
    • Manages the details involving the communication between Model and View
    • Handles user actions to the Model or View as required
    • Controls the data flow into Model object and updates View whenever data changes. It keeps View and Model Separated


    Proxy Pattern -> Structural Pattern