30
Class { 1. Data // variables/fields/properties 2. Methods which act on that data // functions/operations } Variable field declared to be of a primitive data type int x; //int, float, long, double,.. Object field declared to be of a class type String g; Vector v; Hashtable h; Instance 'only' when you use 'new' operator to call the constructor to create a new instance of that class. g = new String("abc"); Declarat ion defining a variable to be of a specific datatype/class type int x; String g; Initiali zation assigning a value to the variable/field/property x = 100; // initialization g = "abc"; // stored in stack g = new String("abc"); // stored in heap Instanti ation calling new operator to create a new instance of that class g = new String("abc"); Method signature : 1. method name 2. method params (no.of.params, and datatypes) 3. access modifier/specifiers 4. return type 5. exceptions it throws parameter - variables that receive values. Public void foo(int x, float y)

Bible

  • Upload
    ro

  • View
    4

  • Download
    3

Embed Size (px)

DESCRIPTION

s

Citation preview

Class

1 Data variablesfieldsproperties

2 Methods which act on that data functionsoperations

Variable field declared to be of a primitive data type int x int float long double

Object field declared to be of a class type String g Vector v Hashtable h

Instance only when you use new operator to call the constructor to create a new instance of that class

g = new String(abc)

Declaration defining a variable to be of a specific datatypeclass type

int x String g

Initialization assigning a value to the variablefieldproperty x = 100 initializationg = abc stored in stackg = new String(abc) stored in heap

Instantiation calling new operator to create a new instance of that class

g = new String(abc)

Method signature 1 method name2 method params (noofparams and datatypes)3 access modifierspecifiers4 return type5 exceptions it throws

parameter - variables that receive values Public void foo(int x float y)argument - values that are passed (pass by value not by reference) to a method foo(6 44)

Access Specifiers Public all and any classesDefault all classes of same package Private only to that classProtected all classes of same package + sub classes of other packages

Access Modifiers

Static access without instantiating the class only static methods can access static fields static methods can call only other static methodsFinal can be applied to - field [ once assigned a value cannot reassign ] -method [ cannot be overridden ] -class [ cannot be extended ]Volatile not cached always read from main memoryTransient not persisted not serializedAbstract not clear vague incomplete to be implemented Serialization process of writing an object to a network as a byte stream (bunch of bytes)

finalfinally ndash is a block in exception handling finalize() ndash method that is called just before garbage collection

Volatile Transientused as an indicator to Java compiler and Thread to not cache value of this variable and always read it from main memory used in Concurrent programming in Java

used along with instance variables to exclude them from serialization process its value will not be persisted

cannot be used with method or class and it can only be used with variable

Along with static variables transient variables are not serialized during Serialization

An object has three characteristics------------------------------------------------state represents data (value) of an objectbehavior represents the behavior (functionality) of an object such as deposit withdraw etcidentity Object identity is typically implemented via a unique ID The value of the ID is not visible to the external user

Object class methods clone finalize wait notify notifyAll equals hashcode tostring

equals() and hashcode() methods---------------------------------------------

- JVM assigns unique hashcode value to each object when they are created in memory - It is not necessary that two different object must have different hashcode values it

might be possible that they share common hash bucket- If two objects are same then they must return same value in hashcode() and equals()

method whenever invoked

OOPS ndash Object Oriented Programming- Data Abstraction- Encapsulation- Inheritance- Polymorphism

Overloading OverridingSame method name different

method signatureSame method name same method signature but

method bodyimpl will varyWithin the same class Between class and its sub classReturn types may vary Return types are sameDeclared exceptions may vary Declared exceptions will also be same

Class Abstract class InterfaceImplements(provide method

body) all of methodsImplements some none

or all of its methodsImplements none of

its methodsCan have instances Cannot have instances Cannot have

instancesCan have sub classes (extends) Must have sub class Cannot have sub

class but may have class that (implements) this interface

Public static void main(String args[]) to be globally accessible and for JVM to be able to call it be able to call without instantiating class no return type as JVM cannot do anything receiving the return reserved word to collect command line arguments

cgtjavac Testjavajava Test lt1gt lt11gt lt222gt

Possible ------------------------class extends classclass implements interfaceinterface extends interfaceclass implements interfaceinterfaceinterface

Not Possible -----------------------class implements classinterface implements interfaceinterface extends class

Singleton Class - Should have a private constructor and at least one constructor- Should have a private static object of the class- Should have public static method to return that private static instance

Cloning Deep and Shallow ------------------------------------------

- Shallow copies duplicate as little as possible is a copy of the collection structure not the elements two collections now share the individual elements

- Deep copies duplicate everything A deep copy of a collection is two collections with all of the elements in the original collection duplicated

Multithreading in java is a process of executing multiple threads simultaneously But we use multithreading than multiprocessing because threads share a common memory area They dont allocate separate memory area so saves memory and context-switching between the threads takes less time than process

The life cycle of the thread in java is controlled by JVM The java thread states are as followsNewRunnableRunningNon-Runnable (Blocked)Terminated

Thread scheduler in java is the part of the JVM that decides which thread should runUnder preemptive scheduling the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence Under time slicing a task executes for a predefined slice of time and then reenters the pool of ready tasks

Each thread have a priority Priorities are represented by a number between 1 and 103 constants defiend in Thread classpublic static int MIN_PRIORITYpublic static int NORM_PRIORITYpublic static int MAX_PRIORITYDefault priority of a thread is 5 (NORM_PRIORITY) The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10

Daemon thread in java is a service provider thread that provides services to the user thread Its life depend on the mercy of user threads ie when all the user threads dies JVM terminates this thread automatically There are many java daemon threads running automatically eg gc finalizer etc

No After starting a thread it can never be started again If you does so an IllegalThreadStateException is thrown

Each thread starts in a separate call stack Invoking the run() method from main thread the run() method goes onto the current call stack rather than at the beginning of a new call stack

The join() method waits for a thread to die In other words it causes the currently running threads to stop executing until the thread it joins with completes its task t1join() t2start() t3start() As you can see in the above examplewhen t1 completes its task then t2 and t3 starts executing t1join(1500) In the above examplewhen t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing

getName() setName(String) and getId() methodt1setName(Sonoo Jaiswal)t1getName()t1getId()

The currentThread() method returns a reference to the currently executing thread objectSystemoutprintln(ThreadcurrentThread()getName())

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times

In case of thread pool a group of fixed size threads are created A thread from the thread pool is pulled out and assigned a job by the service provider After completion of the job thread is contained in the thread pool again Advantage of Java Thread Pool isBetter performance It saves time because there is no need to create new thread Real time usage isIt is used in Servlet and JSP where container creates a thread pool to process the request

Synchronization in java is the capability to control the access of multiple threads to any shared resourceThe synchronization is mainly used to To prevent thread interferenceTo prevent consistency problem

There are two types of thread synchronization mutual exclusive and inter-thread communication

Mutual Exclusive - helps keep threads from interfering with one another while sharing data This can be done by three ways in java

-Synchronized method

If you declare any method as synchronized it is known as synchronized method-Synchronized block Suppose you have 50 lines of code in your method but you want to synchronize only 5 lines you can use synchronized block-static synchronization If you make any static method as synchronized the lock will be on the class not on object

Cooperation (Inter-thread communication in java) Is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed It is implemented by following methods of Object class

wait() Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object or a specified amount of time has elapsed The current thread must own this objects monitor so it must be called from the synchronized method only otherwise it will throw exceptionnotify() Wakes up a single thread that is waiting on this objects monitor If any threads are waiting on this object one of them is chosen to be awakened The choice is arbitrary and occurs at the discretion of the implementation notifyAll() Wakes up all threads that are waiting on this objects monitor

Synchronization is built around an internal entity known as the lock or monitor Every object has an lock associated with it By convention a thread that needs consistent access to an objects fields has to acquire the objects lock before accessing them and then release the lock when its done with them

t1 -gt Obj1 lt- t2 t3 -gt Obj2 lt- t4

Suppose there are two objects of a shared class(eg Table) named object1 and object2In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lockBut there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lockI want no interference between t1 and t3 or t2 and t4Static synchronization solves this problem

Deadlock in java is a part of multithreading Deadlock can occur in a situation when a thread is waiting for an object lock that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread

Since both threads are waiting for each other to release the lock the condition is called deadlock

t1 -gt obj1 t2 -gt obj2 t1 waiting on t2 t2 waiting on t1

Wait() Sleep()wait() method releases the lock sleep() method doesnt release the lockis the method of Object class is the method of Thread classis the non-static method is the static methodshould be notified by notify() or notifyAll() methods

after the specified amount of time sleep is completed

wait() notify() and notifyAll() are methods of ObjectisInterrupted() interrupt() are methods of Threadsleep() and yield() are static methods of Thread class

start() method registers thread into the Thread Scheduler

wait() sleep() and join() will make thread leave Running state

String StringBuffer StringBuilderStorage Area Stack Heap HeapMutation Immutable Mutable MutableThread Safe Yes Yes NoPerformance Fast Slow Fast

Comparable Comparator

1) Comparable provides single sorting sequence Comparator provides multiple element sorting sequence

2) Comparable affects the original class

ie actual class is modified

Comparator doesnt affect the original class

ie actual class is not modified

3) Comparable provides compareTo() method to sort

elements

Comparator provides compare() method

4) Comparable is found in javalang package Comparator is found in javautil package

5) Collectionssort(List) method Collectionssort(ListComparator)

Variables can store only one value int x = 10

Arrays store multiple values but have specific size restriction

Collections ndash mutable

Collection (I) List (I) first in first out maintain the order of values allows duplicates

Vector(C) ArrayList (C) LinkedList (C)

Set (I) not ordered collection unique collection of values HashSet (unsorted) TreeSet (sorted)

Map (I) Key-Value pairs (a100) ordered HashMap

TreeMapHashtable

Vector Array listSynchronized UnsynchronizedAllows duplicates Allows null

Hashtable HashmapSynchronized UnsynchronizedNo duplicates Allows null

Array list Linked listSlow access Fast accessRandom access No random access

Ordered DuplicatesLIST Yes YesSET No No

LIST ndash ordered LINKED ndash faster access and ordered accessSET and MAP ndash unique values no duplicatesMAP ndash key-value pairs and no duplicatesHASH ndash not sortedTREE ndash sorted

Checked exceptions are checked and warned by JVM at compile time Unchecked exceptions are not checked and warned by JVM at compile time

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Static access without instantiating the class only static methods can access static fields static methods can call only other static methodsFinal can be applied to - field [ once assigned a value cannot reassign ] -method [ cannot be overridden ] -class [ cannot be extended ]Volatile not cached always read from main memoryTransient not persisted not serializedAbstract not clear vague incomplete to be implemented Serialization process of writing an object to a network as a byte stream (bunch of bytes)

finalfinally ndash is a block in exception handling finalize() ndash method that is called just before garbage collection

Volatile Transientused as an indicator to Java compiler and Thread to not cache value of this variable and always read it from main memory used in Concurrent programming in Java

used along with instance variables to exclude them from serialization process its value will not be persisted

cannot be used with method or class and it can only be used with variable

Along with static variables transient variables are not serialized during Serialization

An object has three characteristics------------------------------------------------state represents data (value) of an objectbehavior represents the behavior (functionality) of an object such as deposit withdraw etcidentity Object identity is typically implemented via a unique ID The value of the ID is not visible to the external user

Object class methods clone finalize wait notify notifyAll equals hashcode tostring

equals() and hashcode() methods---------------------------------------------

- JVM assigns unique hashcode value to each object when they are created in memory - It is not necessary that two different object must have different hashcode values it

might be possible that they share common hash bucket- If two objects are same then they must return same value in hashcode() and equals()

method whenever invoked

OOPS ndash Object Oriented Programming- Data Abstraction- Encapsulation- Inheritance- Polymorphism

Overloading OverridingSame method name different

method signatureSame method name same method signature but

method bodyimpl will varyWithin the same class Between class and its sub classReturn types may vary Return types are sameDeclared exceptions may vary Declared exceptions will also be same

Class Abstract class InterfaceImplements(provide method

body) all of methodsImplements some none

or all of its methodsImplements none of

its methodsCan have instances Cannot have instances Cannot have

instancesCan have sub classes (extends) Must have sub class Cannot have sub

class but may have class that (implements) this interface

Public static void main(String args[]) to be globally accessible and for JVM to be able to call it be able to call without instantiating class no return type as JVM cannot do anything receiving the return reserved word to collect command line arguments

cgtjavac Testjavajava Test lt1gt lt11gt lt222gt

Possible ------------------------class extends classclass implements interfaceinterface extends interfaceclass implements interfaceinterfaceinterface

Not Possible -----------------------class implements classinterface implements interfaceinterface extends class

Singleton Class - Should have a private constructor and at least one constructor- Should have a private static object of the class- Should have public static method to return that private static instance

Cloning Deep and Shallow ------------------------------------------

- Shallow copies duplicate as little as possible is a copy of the collection structure not the elements two collections now share the individual elements

- Deep copies duplicate everything A deep copy of a collection is two collections with all of the elements in the original collection duplicated

Multithreading in java is a process of executing multiple threads simultaneously But we use multithreading than multiprocessing because threads share a common memory area They dont allocate separate memory area so saves memory and context-switching between the threads takes less time than process

The life cycle of the thread in java is controlled by JVM The java thread states are as followsNewRunnableRunningNon-Runnable (Blocked)Terminated

Thread scheduler in java is the part of the JVM that decides which thread should runUnder preemptive scheduling the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence Under time slicing a task executes for a predefined slice of time and then reenters the pool of ready tasks

Each thread have a priority Priorities are represented by a number between 1 and 103 constants defiend in Thread classpublic static int MIN_PRIORITYpublic static int NORM_PRIORITYpublic static int MAX_PRIORITYDefault priority of a thread is 5 (NORM_PRIORITY) The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10

Daemon thread in java is a service provider thread that provides services to the user thread Its life depend on the mercy of user threads ie when all the user threads dies JVM terminates this thread automatically There are many java daemon threads running automatically eg gc finalizer etc

No After starting a thread it can never be started again If you does so an IllegalThreadStateException is thrown

Each thread starts in a separate call stack Invoking the run() method from main thread the run() method goes onto the current call stack rather than at the beginning of a new call stack

The join() method waits for a thread to die In other words it causes the currently running threads to stop executing until the thread it joins with completes its task t1join() t2start() t3start() As you can see in the above examplewhen t1 completes its task then t2 and t3 starts executing t1join(1500) In the above examplewhen t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing

getName() setName(String) and getId() methodt1setName(Sonoo Jaiswal)t1getName()t1getId()

The currentThread() method returns a reference to the currently executing thread objectSystemoutprintln(ThreadcurrentThread()getName())

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times

In case of thread pool a group of fixed size threads are created A thread from the thread pool is pulled out and assigned a job by the service provider After completion of the job thread is contained in the thread pool again Advantage of Java Thread Pool isBetter performance It saves time because there is no need to create new thread Real time usage isIt is used in Servlet and JSP where container creates a thread pool to process the request

Synchronization in java is the capability to control the access of multiple threads to any shared resourceThe synchronization is mainly used to To prevent thread interferenceTo prevent consistency problem

There are two types of thread synchronization mutual exclusive and inter-thread communication

Mutual Exclusive - helps keep threads from interfering with one another while sharing data This can be done by three ways in java

-Synchronized method

If you declare any method as synchronized it is known as synchronized method-Synchronized block Suppose you have 50 lines of code in your method but you want to synchronize only 5 lines you can use synchronized block-static synchronization If you make any static method as synchronized the lock will be on the class not on object

Cooperation (Inter-thread communication in java) Is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed It is implemented by following methods of Object class

wait() Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object or a specified amount of time has elapsed The current thread must own this objects monitor so it must be called from the synchronized method only otherwise it will throw exceptionnotify() Wakes up a single thread that is waiting on this objects monitor If any threads are waiting on this object one of them is chosen to be awakened The choice is arbitrary and occurs at the discretion of the implementation notifyAll() Wakes up all threads that are waiting on this objects monitor

Synchronization is built around an internal entity known as the lock or monitor Every object has an lock associated with it By convention a thread that needs consistent access to an objects fields has to acquire the objects lock before accessing them and then release the lock when its done with them

t1 -gt Obj1 lt- t2 t3 -gt Obj2 lt- t4

Suppose there are two objects of a shared class(eg Table) named object1 and object2In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lockBut there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lockI want no interference between t1 and t3 or t2 and t4Static synchronization solves this problem

Deadlock in java is a part of multithreading Deadlock can occur in a situation when a thread is waiting for an object lock that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread

Since both threads are waiting for each other to release the lock the condition is called deadlock

t1 -gt obj1 t2 -gt obj2 t1 waiting on t2 t2 waiting on t1

Wait() Sleep()wait() method releases the lock sleep() method doesnt release the lockis the method of Object class is the method of Thread classis the non-static method is the static methodshould be notified by notify() or notifyAll() methods

after the specified amount of time sleep is completed

wait() notify() and notifyAll() are methods of ObjectisInterrupted() interrupt() are methods of Threadsleep() and yield() are static methods of Thread class

start() method registers thread into the Thread Scheduler

wait() sleep() and join() will make thread leave Running state

String StringBuffer StringBuilderStorage Area Stack Heap HeapMutation Immutable Mutable MutableThread Safe Yes Yes NoPerformance Fast Slow Fast

Comparable Comparator

1) Comparable provides single sorting sequence Comparator provides multiple element sorting sequence

2) Comparable affects the original class

ie actual class is modified

Comparator doesnt affect the original class

ie actual class is not modified

3) Comparable provides compareTo() method to sort

elements

Comparator provides compare() method

4) Comparable is found in javalang package Comparator is found in javautil package

5) Collectionssort(List) method Collectionssort(ListComparator)

Variables can store only one value int x = 10

Arrays store multiple values but have specific size restriction

Collections ndash mutable

Collection (I) List (I) first in first out maintain the order of values allows duplicates

Vector(C) ArrayList (C) LinkedList (C)

Set (I) not ordered collection unique collection of values HashSet (unsorted) TreeSet (sorted)

Map (I) Key-Value pairs (a100) ordered HashMap

TreeMapHashtable

Vector Array listSynchronized UnsynchronizedAllows duplicates Allows null

Hashtable HashmapSynchronized UnsynchronizedNo duplicates Allows null

Array list Linked listSlow access Fast accessRandom access No random access

Ordered DuplicatesLIST Yes YesSET No No

LIST ndash ordered LINKED ndash faster access and ordered accessSET and MAP ndash unique values no duplicatesMAP ndash key-value pairs and no duplicatesHASH ndash not sortedTREE ndash sorted

Checked exceptions are checked and warned by JVM at compile time Unchecked exceptions are not checked and warned by JVM at compile time

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Overloading OverridingSame method name different

method signatureSame method name same method signature but

method bodyimpl will varyWithin the same class Between class and its sub classReturn types may vary Return types are sameDeclared exceptions may vary Declared exceptions will also be same

Class Abstract class InterfaceImplements(provide method

body) all of methodsImplements some none

or all of its methodsImplements none of

its methodsCan have instances Cannot have instances Cannot have

instancesCan have sub classes (extends) Must have sub class Cannot have sub

class but may have class that (implements) this interface

Public static void main(String args[]) to be globally accessible and for JVM to be able to call it be able to call without instantiating class no return type as JVM cannot do anything receiving the return reserved word to collect command line arguments

cgtjavac Testjavajava Test lt1gt lt11gt lt222gt

Possible ------------------------class extends classclass implements interfaceinterface extends interfaceclass implements interfaceinterfaceinterface

Not Possible -----------------------class implements classinterface implements interfaceinterface extends class

Singleton Class - Should have a private constructor and at least one constructor- Should have a private static object of the class- Should have public static method to return that private static instance

Cloning Deep and Shallow ------------------------------------------

- Shallow copies duplicate as little as possible is a copy of the collection structure not the elements two collections now share the individual elements

- Deep copies duplicate everything A deep copy of a collection is two collections with all of the elements in the original collection duplicated

Multithreading in java is a process of executing multiple threads simultaneously But we use multithreading than multiprocessing because threads share a common memory area They dont allocate separate memory area so saves memory and context-switching between the threads takes less time than process

The life cycle of the thread in java is controlled by JVM The java thread states are as followsNewRunnableRunningNon-Runnable (Blocked)Terminated

Thread scheduler in java is the part of the JVM that decides which thread should runUnder preemptive scheduling the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence Under time slicing a task executes for a predefined slice of time and then reenters the pool of ready tasks

Each thread have a priority Priorities are represented by a number between 1 and 103 constants defiend in Thread classpublic static int MIN_PRIORITYpublic static int NORM_PRIORITYpublic static int MAX_PRIORITYDefault priority of a thread is 5 (NORM_PRIORITY) The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10

Daemon thread in java is a service provider thread that provides services to the user thread Its life depend on the mercy of user threads ie when all the user threads dies JVM terminates this thread automatically There are many java daemon threads running automatically eg gc finalizer etc

No After starting a thread it can never be started again If you does so an IllegalThreadStateException is thrown

Each thread starts in a separate call stack Invoking the run() method from main thread the run() method goes onto the current call stack rather than at the beginning of a new call stack

The join() method waits for a thread to die In other words it causes the currently running threads to stop executing until the thread it joins with completes its task t1join() t2start() t3start() As you can see in the above examplewhen t1 completes its task then t2 and t3 starts executing t1join(1500) In the above examplewhen t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing

getName() setName(String) and getId() methodt1setName(Sonoo Jaiswal)t1getName()t1getId()

The currentThread() method returns a reference to the currently executing thread objectSystemoutprintln(ThreadcurrentThread()getName())

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times

In case of thread pool a group of fixed size threads are created A thread from the thread pool is pulled out and assigned a job by the service provider After completion of the job thread is contained in the thread pool again Advantage of Java Thread Pool isBetter performance It saves time because there is no need to create new thread Real time usage isIt is used in Servlet and JSP where container creates a thread pool to process the request

Synchronization in java is the capability to control the access of multiple threads to any shared resourceThe synchronization is mainly used to To prevent thread interferenceTo prevent consistency problem

There are two types of thread synchronization mutual exclusive and inter-thread communication

Mutual Exclusive - helps keep threads from interfering with one another while sharing data This can be done by three ways in java

-Synchronized method

If you declare any method as synchronized it is known as synchronized method-Synchronized block Suppose you have 50 lines of code in your method but you want to synchronize only 5 lines you can use synchronized block-static synchronization If you make any static method as synchronized the lock will be on the class not on object

Cooperation (Inter-thread communication in java) Is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed It is implemented by following methods of Object class

wait() Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object or a specified amount of time has elapsed The current thread must own this objects monitor so it must be called from the synchronized method only otherwise it will throw exceptionnotify() Wakes up a single thread that is waiting on this objects monitor If any threads are waiting on this object one of them is chosen to be awakened The choice is arbitrary and occurs at the discretion of the implementation notifyAll() Wakes up all threads that are waiting on this objects monitor

Synchronization is built around an internal entity known as the lock or monitor Every object has an lock associated with it By convention a thread that needs consistent access to an objects fields has to acquire the objects lock before accessing them and then release the lock when its done with them

t1 -gt Obj1 lt- t2 t3 -gt Obj2 lt- t4

Suppose there are two objects of a shared class(eg Table) named object1 and object2In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lockBut there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lockI want no interference between t1 and t3 or t2 and t4Static synchronization solves this problem

Deadlock in java is a part of multithreading Deadlock can occur in a situation when a thread is waiting for an object lock that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread

Since both threads are waiting for each other to release the lock the condition is called deadlock

t1 -gt obj1 t2 -gt obj2 t1 waiting on t2 t2 waiting on t1

Wait() Sleep()wait() method releases the lock sleep() method doesnt release the lockis the method of Object class is the method of Thread classis the non-static method is the static methodshould be notified by notify() or notifyAll() methods

after the specified amount of time sleep is completed

wait() notify() and notifyAll() are methods of ObjectisInterrupted() interrupt() are methods of Threadsleep() and yield() are static methods of Thread class

start() method registers thread into the Thread Scheduler

wait() sleep() and join() will make thread leave Running state

String StringBuffer StringBuilderStorage Area Stack Heap HeapMutation Immutable Mutable MutableThread Safe Yes Yes NoPerformance Fast Slow Fast

Comparable Comparator

1) Comparable provides single sorting sequence Comparator provides multiple element sorting sequence

2) Comparable affects the original class

ie actual class is modified

Comparator doesnt affect the original class

ie actual class is not modified

3) Comparable provides compareTo() method to sort

elements

Comparator provides compare() method

4) Comparable is found in javalang package Comparator is found in javautil package

5) Collectionssort(List) method Collectionssort(ListComparator)

Variables can store only one value int x = 10

Arrays store multiple values but have specific size restriction

Collections ndash mutable

Collection (I) List (I) first in first out maintain the order of values allows duplicates

Vector(C) ArrayList (C) LinkedList (C)

Set (I) not ordered collection unique collection of values HashSet (unsorted) TreeSet (sorted)

Map (I) Key-Value pairs (a100) ordered HashMap

TreeMapHashtable

Vector Array listSynchronized UnsynchronizedAllows duplicates Allows null

Hashtable HashmapSynchronized UnsynchronizedNo duplicates Allows null

Array list Linked listSlow access Fast accessRandom access No random access

Ordered DuplicatesLIST Yes YesSET No No

LIST ndash ordered LINKED ndash faster access and ordered accessSET and MAP ndash unique values no duplicatesMAP ndash key-value pairs and no duplicatesHASH ndash not sortedTREE ndash sorted

Checked exceptions are checked and warned by JVM at compile time Unchecked exceptions are not checked and warned by JVM at compile time

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Cloning Deep and Shallow ------------------------------------------

- Shallow copies duplicate as little as possible is a copy of the collection structure not the elements two collections now share the individual elements

- Deep copies duplicate everything A deep copy of a collection is two collections with all of the elements in the original collection duplicated

Multithreading in java is a process of executing multiple threads simultaneously But we use multithreading than multiprocessing because threads share a common memory area They dont allocate separate memory area so saves memory and context-switching between the threads takes less time than process

The life cycle of the thread in java is controlled by JVM The java thread states are as followsNewRunnableRunningNon-Runnable (Blocked)Terminated

Thread scheduler in java is the part of the JVM that decides which thread should runUnder preemptive scheduling the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence Under time slicing a task executes for a predefined slice of time and then reenters the pool of ready tasks

Each thread have a priority Priorities are represented by a number between 1 and 103 constants defiend in Thread classpublic static int MIN_PRIORITYpublic static int NORM_PRIORITYpublic static int MAX_PRIORITYDefault priority of a thread is 5 (NORM_PRIORITY) The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10

Daemon thread in java is a service provider thread that provides services to the user thread Its life depend on the mercy of user threads ie when all the user threads dies JVM terminates this thread automatically There are many java daemon threads running automatically eg gc finalizer etc

No After starting a thread it can never be started again If you does so an IllegalThreadStateException is thrown

Each thread starts in a separate call stack Invoking the run() method from main thread the run() method goes onto the current call stack rather than at the beginning of a new call stack

The join() method waits for a thread to die In other words it causes the currently running threads to stop executing until the thread it joins with completes its task t1join() t2start() t3start() As you can see in the above examplewhen t1 completes its task then t2 and t3 starts executing t1join(1500) In the above examplewhen t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing

getName() setName(String) and getId() methodt1setName(Sonoo Jaiswal)t1getName()t1getId()

The currentThread() method returns a reference to the currently executing thread objectSystemoutprintln(ThreadcurrentThread()getName())

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times

In case of thread pool a group of fixed size threads are created A thread from the thread pool is pulled out and assigned a job by the service provider After completion of the job thread is contained in the thread pool again Advantage of Java Thread Pool isBetter performance It saves time because there is no need to create new thread Real time usage isIt is used in Servlet and JSP where container creates a thread pool to process the request

Synchronization in java is the capability to control the access of multiple threads to any shared resourceThe synchronization is mainly used to To prevent thread interferenceTo prevent consistency problem

There are two types of thread synchronization mutual exclusive and inter-thread communication

Mutual Exclusive - helps keep threads from interfering with one another while sharing data This can be done by three ways in java

-Synchronized method

If you declare any method as synchronized it is known as synchronized method-Synchronized block Suppose you have 50 lines of code in your method but you want to synchronize only 5 lines you can use synchronized block-static synchronization If you make any static method as synchronized the lock will be on the class not on object

Cooperation (Inter-thread communication in java) Is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed It is implemented by following methods of Object class

wait() Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object or a specified amount of time has elapsed The current thread must own this objects monitor so it must be called from the synchronized method only otherwise it will throw exceptionnotify() Wakes up a single thread that is waiting on this objects monitor If any threads are waiting on this object one of them is chosen to be awakened The choice is arbitrary and occurs at the discretion of the implementation notifyAll() Wakes up all threads that are waiting on this objects monitor

Synchronization is built around an internal entity known as the lock or monitor Every object has an lock associated with it By convention a thread that needs consistent access to an objects fields has to acquire the objects lock before accessing them and then release the lock when its done with them

t1 -gt Obj1 lt- t2 t3 -gt Obj2 lt- t4

Suppose there are two objects of a shared class(eg Table) named object1 and object2In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lockBut there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lockI want no interference between t1 and t3 or t2 and t4Static synchronization solves this problem

Deadlock in java is a part of multithreading Deadlock can occur in a situation when a thread is waiting for an object lock that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread

Since both threads are waiting for each other to release the lock the condition is called deadlock

t1 -gt obj1 t2 -gt obj2 t1 waiting on t2 t2 waiting on t1

Wait() Sleep()wait() method releases the lock sleep() method doesnt release the lockis the method of Object class is the method of Thread classis the non-static method is the static methodshould be notified by notify() or notifyAll() methods

after the specified amount of time sleep is completed

wait() notify() and notifyAll() are methods of ObjectisInterrupted() interrupt() are methods of Threadsleep() and yield() are static methods of Thread class

start() method registers thread into the Thread Scheduler

wait() sleep() and join() will make thread leave Running state

String StringBuffer StringBuilderStorage Area Stack Heap HeapMutation Immutable Mutable MutableThread Safe Yes Yes NoPerformance Fast Slow Fast

Comparable Comparator

1) Comparable provides single sorting sequence Comparator provides multiple element sorting sequence

2) Comparable affects the original class

ie actual class is modified

Comparator doesnt affect the original class

ie actual class is not modified

3) Comparable provides compareTo() method to sort

elements

Comparator provides compare() method

4) Comparable is found in javalang package Comparator is found in javautil package

5) Collectionssort(List) method Collectionssort(ListComparator)

Variables can store only one value int x = 10

Arrays store multiple values but have specific size restriction

Collections ndash mutable

Collection (I) List (I) first in first out maintain the order of values allows duplicates

Vector(C) ArrayList (C) LinkedList (C)

Set (I) not ordered collection unique collection of values HashSet (unsorted) TreeSet (sorted)

Map (I) Key-Value pairs (a100) ordered HashMap

TreeMapHashtable

Vector Array listSynchronized UnsynchronizedAllows duplicates Allows null

Hashtable HashmapSynchronized UnsynchronizedNo duplicates Allows null

Array list Linked listSlow access Fast accessRandom access No random access

Ordered DuplicatesLIST Yes YesSET No No

LIST ndash ordered LINKED ndash faster access and ordered accessSET and MAP ndash unique values no duplicatesMAP ndash key-value pairs and no duplicatesHASH ndash not sortedTREE ndash sorted

Checked exceptions are checked and warned by JVM at compile time Unchecked exceptions are not checked and warned by JVM at compile time

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

The join() method waits for a thread to die In other words it causes the currently running threads to stop executing until the thread it joins with completes its task t1join() t2start() t3start() As you can see in the above examplewhen t1 completes its task then t2 and t3 starts executing t1join(1500) In the above examplewhen t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing

getName() setName(String) and getId() methodt1setName(Sonoo Jaiswal)t1getName()t1getId()

The currentThread() method returns a reference to the currently executing thread objectSystemoutprintln(ThreadcurrentThread()getName())

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times

In case of thread pool a group of fixed size threads are created A thread from the thread pool is pulled out and assigned a job by the service provider After completion of the job thread is contained in the thread pool again Advantage of Java Thread Pool isBetter performance It saves time because there is no need to create new thread Real time usage isIt is used in Servlet and JSP where container creates a thread pool to process the request

Synchronization in java is the capability to control the access of multiple threads to any shared resourceThe synchronization is mainly used to To prevent thread interferenceTo prevent consistency problem

There are two types of thread synchronization mutual exclusive and inter-thread communication

Mutual Exclusive - helps keep threads from interfering with one another while sharing data This can be done by three ways in java

-Synchronized method

If you declare any method as synchronized it is known as synchronized method-Synchronized block Suppose you have 50 lines of code in your method but you want to synchronize only 5 lines you can use synchronized block-static synchronization If you make any static method as synchronized the lock will be on the class not on object

Cooperation (Inter-thread communication in java) Is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed It is implemented by following methods of Object class

wait() Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object or a specified amount of time has elapsed The current thread must own this objects monitor so it must be called from the synchronized method only otherwise it will throw exceptionnotify() Wakes up a single thread that is waiting on this objects monitor If any threads are waiting on this object one of them is chosen to be awakened The choice is arbitrary and occurs at the discretion of the implementation notifyAll() Wakes up all threads that are waiting on this objects monitor

Synchronization is built around an internal entity known as the lock or monitor Every object has an lock associated with it By convention a thread that needs consistent access to an objects fields has to acquire the objects lock before accessing them and then release the lock when its done with them

t1 -gt Obj1 lt- t2 t3 -gt Obj2 lt- t4

Suppose there are two objects of a shared class(eg Table) named object1 and object2In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lockBut there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lockI want no interference between t1 and t3 or t2 and t4Static synchronization solves this problem

Deadlock in java is a part of multithreading Deadlock can occur in a situation when a thread is waiting for an object lock that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread

Since both threads are waiting for each other to release the lock the condition is called deadlock

t1 -gt obj1 t2 -gt obj2 t1 waiting on t2 t2 waiting on t1

Wait() Sleep()wait() method releases the lock sleep() method doesnt release the lockis the method of Object class is the method of Thread classis the non-static method is the static methodshould be notified by notify() or notifyAll() methods

after the specified amount of time sleep is completed

wait() notify() and notifyAll() are methods of ObjectisInterrupted() interrupt() are methods of Threadsleep() and yield() are static methods of Thread class

start() method registers thread into the Thread Scheduler

wait() sleep() and join() will make thread leave Running state

String StringBuffer StringBuilderStorage Area Stack Heap HeapMutation Immutable Mutable MutableThread Safe Yes Yes NoPerformance Fast Slow Fast

Comparable Comparator

1) Comparable provides single sorting sequence Comparator provides multiple element sorting sequence

2) Comparable affects the original class

ie actual class is modified

Comparator doesnt affect the original class

ie actual class is not modified

3) Comparable provides compareTo() method to sort

elements

Comparator provides compare() method

4) Comparable is found in javalang package Comparator is found in javautil package

5) Collectionssort(List) method Collectionssort(ListComparator)

Variables can store only one value int x = 10

Arrays store multiple values but have specific size restriction

Collections ndash mutable

Collection (I) List (I) first in first out maintain the order of values allows duplicates

Vector(C) ArrayList (C) LinkedList (C)

Set (I) not ordered collection unique collection of values HashSet (unsorted) TreeSet (sorted)

Map (I) Key-Value pairs (a100) ordered HashMap

TreeMapHashtable

Vector Array listSynchronized UnsynchronizedAllows duplicates Allows null

Hashtable HashmapSynchronized UnsynchronizedNo duplicates Allows null

Array list Linked listSlow access Fast accessRandom access No random access

Ordered DuplicatesLIST Yes YesSET No No

LIST ndash ordered LINKED ndash faster access and ordered accessSET and MAP ndash unique values no duplicatesMAP ndash key-value pairs and no duplicatesHASH ndash not sortedTREE ndash sorted

Checked exceptions are checked and warned by JVM at compile time Unchecked exceptions are not checked and warned by JVM at compile time

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

If you declare any method as synchronized it is known as synchronized method-Synchronized block Suppose you have 50 lines of code in your method but you want to synchronize only 5 lines you can use synchronized block-static synchronization If you make any static method as synchronized the lock will be on the class not on object

Cooperation (Inter-thread communication in java) Is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed It is implemented by following methods of Object class

wait() Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object or a specified amount of time has elapsed The current thread must own this objects monitor so it must be called from the synchronized method only otherwise it will throw exceptionnotify() Wakes up a single thread that is waiting on this objects monitor If any threads are waiting on this object one of them is chosen to be awakened The choice is arbitrary and occurs at the discretion of the implementation notifyAll() Wakes up all threads that are waiting on this objects monitor

Synchronization is built around an internal entity known as the lock or monitor Every object has an lock associated with it By convention a thread that needs consistent access to an objects fields has to acquire the objects lock before accessing them and then release the lock when its done with them

t1 -gt Obj1 lt- t2 t3 -gt Obj2 lt- t4

Suppose there are two objects of a shared class(eg Table) named object1 and object2In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lockBut there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lockI want no interference between t1 and t3 or t2 and t4Static synchronization solves this problem

Deadlock in java is a part of multithreading Deadlock can occur in a situation when a thread is waiting for an object lock that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread

Since both threads are waiting for each other to release the lock the condition is called deadlock

t1 -gt obj1 t2 -gt obj2 t1 waiting on t2 t2 waiting on t1

Wait() Sleep()wait() method releases the lock sleep() method doesnt release the lockis the method of Object class is the method of Thread classis the non-static method is the static methodshould be notified by notify() or notifyAll() methods

after the specified amount of time sleep is completed

wait() notify() and notifyAll() are methods of ObjectisInterrupted() interrupt() are methods of Threadsleep() and yield() are static methods of Thread class

start() method registers thread into the Thread Scheduler

wait() sleep() and join() will make thread leave Running state

String StringBuffer StringBuilderStorage Area Stack Heap HeapMutation Immutable Mutable MutableThread Safe Yes Yes NoPerformance Fast Slow Fast

Comparable Comparator

1) Comparable provides single sorting sequence Comparator provides multiple element sorting sequence

2) Comparable affects the original class

ie actual class is modified

Comparator doesnt affect the original class

ie actual class is not modified

3) Comparable provides compareTo() method to sort

elements

Comparator provides compare() method

4) Comparable is found in javalang package Comparator is found in javautil package

5) Collectionssort(List) method Collectionssort(ListComparator)

Variables can store only one value int x = 10

Arrays store multiple values but have specific size restriction

Collections ndash mutable

Collection (I) List (I) first in first out maintain the order of values allows duplicates

Vector(C) ArrayList (C) LinkedList (C)

Set (I) not ordered collection unique collection of values HashSet (unsorted) TreeSet (sorted)

Map (I) Key-Value pairs (a100) ordered HashMap

TreeMapHashtable

Vector Array listSynchronized UnsynchronizedAllows duplicates Allows null

Hashtable HashmapSynchronized UnsynchronizedNo duplicates Allows null

Array list Linked listSlow access Fast accessRandom access No random access

Ordered DuplicatesLIST Yes YesSET No No

LIST ndash ordered LINKED ndash faster access and ordered accessSET and MAP ndash unique values no duplicatesMAP ndash key-value pairs and no duplicatesHASH ndash not sortedTREE ndash sorted

Checked exceptions are checked and warned by JVM at compile time Unchecked exceptions are not checked and warned by JVM at compile time

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Since both threads are waiting for each other to release the lock the condition is called deadlock

t1 -gt obj1 t2 -gt obj2 t1 waiting on t2 t2 waiting on t1

Wait() Sleep()wait() method releases the lock sleep() method doesnt release the lockis the method of Object class is the method of Thread classis the non-static method is the static methodshould be notified by notify() or notifyAll() methods

after the specified amount of time sleep is completed

wait() notify() and notifyAll() are methods of ObjectisInterrupted() interrupt() are methods of Threadsleep() and yield() are static methods of Thread class

start() method registers thread into the Thread Scheduler

wait() sleep() and join() will make thread leave Running state

String StringBuffer StringBuilderStorage Area Stack Heap HeapMutation Immutable Mutable MutableThread Safe Yes Yes NoPerformance Fast Slow Fast

Comparable Comparator

1) Comparable provides single sorting sequence Comparator provides multiple element sorting sequence

2) Comparable affects the original class

ie actual class is modified

Comparator doesnt affect the original class

ie actual class is not modified

3) Comparable provides compareTo() method to sort

elements

Comparator provides compare() method

4) Comparable is found in javalang package Comparator is found in javautil package

5) Collectionssort(List) method Collectionssort(ListComparator)

Variables can store only one value int x = 10

Arrays store multiple values but have specific size restriction

Collections ndash mutable

Collection (I) List (I) first in first out maintain the order of values allows duplicates

Vector(C) ArrayList (C) LinkedList (C)

Set (I) not ordered collection unique collection of values HashSet (unsorted) TreeSet (sorted)

Map (I) Key-Value pairs (a100) ordered HashMap

TreeMapHashtable

Vector Array listSynchronized UnsynchronizedAllows duplicates Allows null

Hashtable HashmapSynchronized UnsynchronizedNo duplicates Allows null

Array list Linked listSlow access Fast accessRandom access No random access

Ordered DuplicatesLIST Yes YesSET No No

LIST ndash ordered LINKED ndash faster access and ordered accessSET and MAP ndash unique values no duplicatesMAP ndash key-value pairs and no duplicatesHASH ndash not sortedTREE ndash sorted

Checked exceptions are checked and warned by JVM at compile time Unchecked exceptions are not checked and warned by JVM at compile time

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Arrays store multiple values but have specific size restriction

Collections ndash mutable

Collection (I) List (I) first in first out maintain the order of values allows duplicates

Vector(C) ArrayList (C) LinkedList (C)

Set (I) not ordered collection unique collection of values HashSet (unsorted) TreeSet (sorted)

Map (I) Key-Value pairs (a100) ordered HashMap

TreeMapHashtable

Vector Array listSynchronized UnsynchronizedAllows duplicates Allows null

Hashtable HashmapSynchronized UnsynchronizedNo duplicates Allows null

Array list Linked listSlow access Fast accessRandom access No random access

Ordered DuplicatesLIST Yes YesSET No No

LIST ndash ordered LINKED ndash faster access and ordered accessSET and MAP ndash unique values no duplicatesMAP ndash key-value pairs and no duplicatesHASH ndash not sortedTREE ndash sorted

Checked exceptions are checked and warned by JVM at compile time Unchecked exceptions are not checked and warned by JVM at compile time

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Checked exceptions are checked and warned by JVM at compile time Unchecked exceptions are not checked and warned by JVM at compile time

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Exception handling is process of managing the runtime exceptions

try ndash the block where you expect code to go wrong and throw an exceptioncatch ndash the block(s) which has code to react to a caught exception Every lsquotryrsquo should have

atleast one lsquocatchrsquo or lsquofinallyrsquo Can have many lsquocatchrsquo blocksfinally ndash optional block this code gets fired irrespective of whether an exception occurs or

not

Static text ndash non intuitiveHyper text ndash intuitiveinteractive

Protocol - set of rules HTTP FTP SMTP

HTTP - static content + hyper textWeb - HTTP + Servlets JSPsApplication - Web + EJB also

Servlet extends GenericServlet- init()- service()- destroy()

Servlet extends HttpServlet- init()- service()- destroy()- doGet()- doPost()

Servlet Life Cycle

If an instance of the servlet does not exist the web containera Loads the servlet class (class)b Creates an instance of the servlet classc Initializes the servlet instance by calling the init method d Invokes the service method passing request and response objects

ServletConfig ServletContextSpecific to one servlet Applies to all servletsUsed to pass initialization parameters

to the servletUsed to define context parameters common to

all servlets

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

ltinit-paramgt tags are used ltcontext-paramgt tags are used

To make servlets to thread safe -------------------------------------------

- By implementing SingleThreadModel- Synchornize the part of sensitive code- Your servlet service() method should not access any member variables unless these

member variables are thread safe themselves

JSP Life Cycle

When a request is comes to a JSP page the web container first checks whether the JSP pagersquos servlet is older than the JSP page If the servlet is older the web container translates the JSP page into a servlet class and compiles the classAfter the page has been translated and compiled the JSP pagersquos servlet (for the most part) follows the servlet life cycle

Directives lt gtDeclarations lt gtExpressions lt= gtScriptlets lt gt

Directives lt page import = rdquordquo gtlt include file = rdquordquo gtlt taglib uri = rdquordquo gtlt page errorPage = rdquordquo gt

Servlet RequestDispatcher (I) forward() ndash same request is passed to other jsp and control does not go to UIInclude()

responsesendRedirect(ldquootherjsprdquo) ndash control goes to UI and then gets re-routed to other jsp with new request

forward() method sendRedirect() method

The forward() method works at server side The sendRedirect() method works at client side

It sends the same request and response objects to another servlet It always sends a new request

There are four techniques used in Session tracking

1 Cookies

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

2 Hidden Form Field

3 URL Rewriting

4 HttpSession

Cookie ck=new Cookie(usersonoo jaiswal)creating cookie object responseaddCookie(ck)adding cookie in the response Cookie ck[]=requestgetCookies()

ltinput type=hidden name=uname value=Vimal Jaiswalgt

urlname1=value1ampname2=value2amp

String n=requestgetParameter(userName) HttpSession session=requestgetSession() sessionsetAttribute(unamen) String n=(String)sessiongetAttribute(uname)

JSP action tags ltjspinclude page = ldquordquo gt response of the second jsp is included in the response

of the first jspltjspforward page = ldquordquo gt request is routed to several other jsps before response

is sent backltjspparam name = ldquordquo value =

rdquordquo gtParameters you pass along while forwarding

ACID Transaction Set of statements executed on a database or file systemAtomicity Set of statements executed as a single unit of workConsistency Txn exists in a consistent state before and after the executionIsolation One txn executes independent of the other txnDurability Once COMMIT is fired txn survives even network failures

Dirty Read Reading uncommitted data First txn could roll back before committing data read by second txn

Non-Repeatable Read

In a same transaction same query yields different results This happens when another transaction updates the data returned by other transaction

Phantom Read First txn still not done adding data and may add more data after second txn made a read

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Normalization - It is the process of organizing data in order to achieve 2 things 1 Eliminate redundant data2 Ensure data dependency makes sense by store related data in the same table

Data Definition Language (DDL) create alter rename drop truncateData Manipulation Language (DML) select insert update delete (CRUD)Data Control Language (DCL) grant revokeTransaction Control Language (TCL) commit rollback savepoint

Delete Truncate DropDelete some or all records Delete all records Remove tableWHERE clause can be used WHERE clause cannot be

usedNeed explicit COMMIT Auto COMMITCan be rolled back Cannot be rolled backDoes not trim the table Trims the table

Stored Procedure Function TriggerMay or may not return a

valueMust return a value Code fragment that runs before

or after a row or table is modified

Called by EXEC command

Called from SQL statements

Can call function Cannot call procedure

Join Returns rows when there is atleast one match in both tablesLeft All rows of left table with or without matching rows in the right tableLeft Outer Rows of left without matching rows in right table

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Right All rows of right table with or without matching rows in the left tableRight

OuterRows of right without matching rows in left table

Inner All rows common between left and right tablesOuter All rows from both left and right tables except the commonmatching ones

Clustered Index Non-clustered IndexOrder of the indexes matches order of

data storageOrder of the indexes does not match order

of data storageTelephone directory Index at the back of the bookSorting of the indexes sorts the data Sorting of the indexes does not sort the

data

Optimistic locking Pessimistic lockingAssuming data duplication will never occur

bother about locks and eliminate duplicates as they occur

Assuming data duplication always occurs address duplication before it occurs

Performance tuning can be done in the following ways - Too much normalization is bad denormalize where required- Too much of indexing is bad optimize index usage- Reduce noofcols that make up the composite key- Proper partitioning of table spaces have separate space for BLOBs and CLOBs- Use stored procedures

View Materialized ViewRuns the query each time it is accessed Runs the query only once and updates

periodicallyGets latest data but performance depends on

well-formed queryFast but may not refresh on time to

get latest data

Only when there is a IS-A relation use Inheritance If you want just code reuse use Composition

Use Interfaces if you want polymorphism

Aggregation Contained object is not dependent on container object when container is destroyed contained remains undestroyed Eg School-students

Composition Contained object is dependent on container object when container is destroyed contained is also destroyed Eg House-rooms

Data Modeling - Identify entities- Identify entity attributes

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

- Apply naming conventions as per logical model standards- Identify relationships ndash cardinality- Apply design patterns- Assign keys- Normalize eliminate data redundancy- Denormalize improve performance

CREATIONAL Design Patterns Factory Abstraction or interface to let sub class or the implementing class to

decide which class is to be instantiated or which method is to be calledPrototype Cloning of an object to reduce the cost of creation Eg method overridingSingleton Only one instance of the object exists at anytime

STRUCTURAL Design Patterns Adapter Convert existing interface to new interface in order to achieve reusability of

unrelated classes Eg wrapper classesComposite Build complex objects out of elemental objects Eg file directory structureDecorator Add additional functions to existing interface dynamically Eg JScrollPane

to JTextAreaFaccedilade Make complex system look simple by providing a generic interfaceProxy Simple object to represent complex object providing a placeholder for the

complex object to access it Eg stub-skeleton

BEHAVIORAL Design Patterns Chain of

Responsibility

more than one object participate in handling the request without the knowledge of each other Eg servlet chaining

Observer One object changes state and all dependent objects are updated automatically Eg wait-notify

J2EE Design Patterns Front Controller Single component to receive all input requestsService Locator Centralizing the distributed object lookupBusiness

DelegateDecoupling the presentation and service tiers

DAO Uniform interface to access multiple databasesTO Serialized object to act as data carrier for related attributes

STRUTS Open source framework built on MVC architecture for developing web applications using Java EE

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Model Java beans EJBView HTML JSPController ActionServletActionForm Java beans representing form inputs containing request parameters

from the view referencing the action beanvalidate() ndash used to validate the input parameters called before form

bean is handed over to the Action class it returns ActionErrors object

ActionErrors validate(ActionMapping HttpServletRequest)ActionMapping Contains all maps between views to other views and views to action

classesDeployment

descriptorStruts-configxml contains - form beans- action classes- action mappings- global forwards- controller configuration(action servlet)

Action class Adapter between request contents and logic that need to be executedexecute()- business logic resides hereexecute(ActionMapping ActionForm Request Response)

Struts Life Cyle when a req comes from a jsp or html - Retrieve or create form bean- Store form bean in appropriate scope- Reset propertiesattributes- Populate properties- Validate properties- Pass form bean to action class

SPRINGCore BeanFactory IOC engineContext Config file to define enterprise services

(beansxml)AOPDAO (JDBC)ORM (Hibernate JDO IBatis)Web(MVC StrutsJSF Servlets JSP)Web MVC

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

BeanFactory Collection of beans holds bean definitions auto-instantiates beans at runtime

ApplicationContext BeanFactory + resolves text messages internationalization loads file resources event listeners

ClassPathXmlApplicationContext It Loads context definition from an XML file located in the classpath treating context definitions as classpath resources The application context is loaded from the applications classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext(beanxml)

FileSystemXmlApplicationContext It loads context definition from an XML file in the filesystem The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext(beanxml)

XmlWebApplicationContext It loads context definition from an XML file contained within a web application

Bean Scopes Singleton(d) Single definition maps to single object instancePrototype Single definition maps to multiple object instancesRequest Single definition maps to life cycle of a HttpRequestSession Single definition maps to life cycle of a HttpSession

IOC You do not create an object but define how it is to be created so that they are automatically instantiated at runtimeDependency Injection Do not connect services and components but define the dependency of components on services so that those

services are wired-in at runtime

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

- Constructor- Setter- Interface

Spring Life Cycle - Container finds bean definition from config file and instantiate the bean- Using IOC dependency injection populates all properties as specified in config file- Call init()- Call service methods

Advantages of Spring - POJO programming- Layered architecture- Open source (free)- IOC DI and AOP

JDBC (DB table)TemplateDAOSupport

Hibernate (ORM-objs)

TemplateDAOSupport

Spring-Hibernate Integration 2 ways to connect Spring and Hibernate - IOC with Hibernate template (there is a Spring JDBC template also for doing DB txns via

JDBC)- Extend HibernateDAOSupport and AOP

o Configure HibernateSessionFactoryo Extend the DAO implementation of the HibernateDAOSupport classo Wire in the transaction support using AOP

AOP Modularize cross cutting concerns such as logging transaction management etc

Aspect Cross cutting concernJoint Point A certain point in the execution of a programAdvice Action taken by Aspect at a Joint Point Can be done in 2 ways

1 Annotations based - it is defined by a lsquopoint cut expressionrsquo2 Schema based ndash everything defined using ltaop tags in the config file

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Before advice ndash advice executes before joint pointAfter returning ndash advice executes after joint point exits normally without

exceptionAfter throwing ndashadvice executes after joint point throws exceptionAfter advice (finally) ndash advice executes after joint point whether exits

normally or with exceptionAround advice ndash advice executes both before and after joint point

Interceptors preHandle() ndash fired before request is processedpostHandle() ndash fired after request is processedafterCompletion() ndash fired after view is rendered

Hibernate- hbm files- cfg fileAdvantages of Hibernate - Boiler plate code is abstracted out into xml files- Mapping between tables and objects using xml- Database independentDisadvantages of Hibernate - Have to learn new API- Debug and performance issues- Slower than JDBC- Gets complicated when there is many-many relationships

Session SessionFactory1st level cache 2nd level cacheData is shared across txns within the same

sessionData is shared across sessions

Sessionload() Sessionget()If you are certain object exists in cache

avoid DB hitIf you are not sure if object exists in cache hit the DB

to fetch dataIf object not found in cache it throws an

exceptionIf object not found in cache it returns null so check

for null

Transient ndash object is instantiated but not associated with sessionPersistent ndash object is associated with sessionDetached ndash object exists but detached from session (session is closed)

update() merge()

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Use update() when you are sure that object already exists and is associated to a session

Use merge() when you are not sure that object exists and is associated to a session

WEB SERVICES

Reusable component that can be exposed as a service and made available over the network for remote access

Interoperability ability to integrate when we have diverse systems platforms languages frameworks applications

XML language gives capability to send data in generic format that can be ported across network over communication protocol like SOAP

SOAP Simple Object Access Protocol allows communication between applications located on remote machines It in turn uses transport protocols like HTTP SMTP and FTP

Envelope- Header(o)- Body

o Requesto Responseo Fault(o)

SOAP FaultsVersion Mismatch Invalid namespace in envelopeMust understand SOAP processor is unable to process headerClient Client incorrectly formed the SOAP messageServer Server cannot process SOAP message

Principles of SOA

1 Standard service contract between provider and consumer2 Loose coupling to reduce dependency and maintain only awareness of each other3 Abstraction to hide logic from outside world4 Autonomous so that services alone have total control over the logic5 Reusable6 Statelessness7 Granularity8 Discoverability9 Composability10 Interoperability

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

Webservice protocol stack

Service transport layer

Responsible for transporting messages between applications using HTTP FTP and SMTP

XML messaging layer

Responsible for encoding messages into common XML format so that both provider and consumer can understand

Service discovery layer

Responsible for centralized distributed object lookup providing publishsubscribe using UDDI

Service description layer

Responsible for describing the public interface for the service using WSDL

Bottom Up(Java first) Top Down(WSDL first) ndash write Java interface use WSDL annotations(JAXWS)

and then generate WSDLRequires less knowledge of WSDL XML XSD Requires more knowledge of WSDL XML

XSDInteroperability issues may occur with consumersproviders written in other languages

Better interoperability

If end point interface changes WSDL changes and client to be rewritten

Less sensitive to change

WSDL elements Types Data types pojos XSD elements All XSD types can be declared in separate file

and then linked into WSDLMessage Message types based on XSD types for REQUEST RESPONSE and FAULTPort Type Links operations and message types

-request-response-fault

Binding Protocol and data format for particular port typeService Binds java service to port this is where you define soap address(end point)

JAXWS specification is used it is pre-included in JEE5 Once you have application server plugin if you create a web project the required jars are auto included by application server

You use Endpointpublish(ldquohttprdquonew MyService()) If you paste endpoint url in browser it will give the WSDL so use WSDL to generate client

Class will have WebService and method will have WebMethod

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

WebMethod action ndash value of soap actionexclude ndash truefalseoperationName - ltwsdloperation

WebService name - ltwsdlportType name=portName - ltwsdlport name=serviceName - ltwsdlservice name=targetNamespace ndash namespace for ltwsdlportTypeendpointInterface ndash complete name of service endpointwsdlLocation ndash location of pre-defined WSDL

If class has WebService then all public methods are automatically webmethods no need to explicitly put WebMethod for each method

Oneway means method has only input but no outputWebParam (name ndash maps to ltpart name=

(header = true means it is a header fieldWebFault maps to ltwsdlfaultWebResult return value of a webmethodpostConstruct This method is executed after dependency injection is applied on the classpreDestroy This method is executed just before instance is being removed by containerResource Maps webservicecontext resource to a field or method

JAX RPC JAX WSCannot support asynchronous and message oriented web services

Supports asynchronous and message oriented web services

Uses java type binding and only 90 XML 100 XML with JAXBNo annotations and Deployment Descriptor is must

Uses annotations and Deployment Descriptor is optional

Advantages of webservices- JAXWS has API to access the header info- Stateless so only one instance available for all callers so thread safe

Disadvantages of webservices- Need to know XML- All data types to be XML types- Marshalling and unmarshalling overhead- Distributed transaction management is not possible Eg there are 3 method calls and

method2 call is to a webservice If method 3 fails then there is no way to tell the webmethod to rollback

SOAP engines ndash Apache Axis JBoss WSJBoss 50 is the best app server for webservices

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)

REST SOAPExposes resources which represent data Exposes operations which represent logicUses HTTP (GETPOSTDELETE) Uses HTTP POST onlyPoint-to-point tunneling Distributed messagingSupports multiple data formats Supports only XMLSupports stateless communication only Supports stateless stateful and

asynchronous messagingLightweight does not require XML parsingNot secure does not use contract(WSDL)