Do not implement Serializable lightly, since it restricts future flexibility, and publicly exposes class implementation details which are usually private. As well, implementing Serializable correctly is not trivial.
The serialVersionUID is a universal version identifier for a Serializable class. Deserialization uses this number to ensure that a loaded class corresponds exactly to a serialized object. If no match is found, then an InvalidClassException is thrown.
Guidelines for serialVersionUID :
always include it as a field, for example: "private static final long serialVersionUID = 7526472295622776147L; " include this field even in the first version of the class, as a reminder of its importance
do not change the value of this field in future versions, unless you are knowingly making changes to the class which will render it incompatible with old serialized objects
new versions of Serializable classes may or may not be able to read old serialized objects; it depends upon the nature of the change; provide a pointer to Sun's guidelines for what constitutes a compatible change, as a convenience to future maintainers
In Windows, generate serialVersionUID using the JDK's graphical tool like so :
use Control Panel | System | Environment to set the classpath to the correct directory
run serialver -show from the command line
point the tool to the class file including the package, for example, finance.stock.Account - without the .class
readObject and writeObject :
readObject implementations always start by calling default methods
deserialization must be treated as any constructor : validate the object state at the end of deserializing - this implies that readObject should almost always be implemented in Serializable classes, such that this validation is performed.
deserialization must be treated as any constructor : if constructors make defensive copies for mutable object fields, so must readObject
when serializing a Collection, store the number of objects in the Collection as well, and use this number to read them back in upon deserialization; avoid tricks using null
Other points :
use javadoc's @serial tag to denote Serializable fields
the .ser extension is conventionally used for files representing serialized objects
no static or transient fields undergo default serialization
extendable classes should not be Serializable, unless necessary
inner classes should rarely, if ever, implement Serializable
container classes should usually follow the style of Hashtable, which implements Serializable by storing keys and values, as opposed to a large hash table data structure
Example in code:
* Maintainers must change this value if and only if the new version * of this class is not compatible with old versions. See Sun docs * for * /serialization/spec/version.doc.html> details. * * Not necessary to include in first version of the class, but * included here as a reminder of its importance. */ privatestaticfinallong serialVersionUID = 7526471155622776147L;
Make a class immutable by following these guidelines :
* ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private * make fields private and final * force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention) * do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state * if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
How can we make a class Singleton
1) make the constructor private. 2)Override clone method and throw clone supported exception. 3) Have a public method that creates an new instance when the instance is null or returns the new one. A) If the class is Serializable class Singleton implements Serializable { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } /** If the singleton implements Serializable, then this * method must be supplied. */ protected Object readResolve() { return instance; } /** This method avoids the object fro being cloned */ public Object clone() { throws CloneNotSupportedException ; //return instance; } } B) If the class is NOT Serializable class Singleton { private static Singleton instance; private Singleton() { }
public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } /** This method avoids the object from being cloned **/ public Object clone() { throws CloneNotSupportedException ; //return instance; } }
Return type can not change. But can be the subtype of super,
Can throw runTime excpetion. Can throe subtype of super class exception.
Access level can not be more restrictive.
In case of exception, overrided method can not throw boarder unchecked exceptions or any new unchecked exception.
It can always throw a checked exception (runtime)
Run time
Overloading:
Arguments number or type should change.
Overloaded method can throw any type of exception,
Method args list should be different.
Return type can be changed.
Compile time
->Can I overload an extended method. Then how
->How to access overridded method in base class and extended class, by using base class object and extended class object.
Here polymorphisms is nothing but the concept that using base class object you can call the method of extended class.
ObjectA will call different methods, depending on the object type which it points.
Casting can be done downwards. But ClassCastexception occur in run time.
Casting done in the following cases with out any run time excp.
A a = new C();
C c = (C) a;
In this case of with out casting into C, compiler will not allow you to compile.
->In case for 3 rd level inheritance, how to access using the 3 types of objects.
Base class object ref can be assigned to extended class Object. Reverse is not allowed.
->Access specifier while doing overriding, overloading, implementing interfaces.
public – should be public
protected – can increase the visibility can not reduce(only public)
default - can increase the visibility can not reduce(public///protected)
private method – can not override
->Method with same name and type in two interfaces and abstract methods.
Its possible. Only thump rule is the child class has to implement the method
->Method with different return type
Never can have two methods with diff return type and 0 arguments and same name.
Never can different return type and same argumentno and type and same name.
Can have methods with diff return type and different argument type(arg no or type) with same name.
that is polymorphisms achived through overloading.
->Overriding static methods through abstract and interfaces
no static method in interface.
static method can not be overriden. But you can create two methods with same sign in both super and sub classes. But you can't achienve run time polymorphism there.
Overiding means run time polymorphism.
but we can't call super.paranetmethod() from a overrided static method.
->How jvm binds the methods, early binding or late binding?
All class methods are early binded, that is static and final methods and private methods.
instruction used is invokestatic.
Methods which can be accessile by instants are late binding by the virtual machine
instruction used is invokevirtual
->Overriding Constructor
Cant override constructor.
but u can overload.
super() will call parent constructor.
->final keyword. for a class, for method, for variables,
making final to class makes only methods final, that class cant extend
making final to class doesn't make the members final
If we want a member variable final we need to explicitly declare as final
Abstraction:
Hiding the inner details by projecting only the required details.
Method hiding.
→ Difference protected and default
dafult > instant access in the same package. Subclass access with in the same package. No subclass access in the other package. No instant access in the other package.
Protected > instant access in the same package, subclass anywhere.
->Advantages of using abstract class, different usage,using with inheritance.
If one method is abstract class must be abstract.
Class A implements interface I and extends class B. If a method in I is already implemented in B, compiler wont force to override that in A.
A method in abstract class can not be abstract static,by default its public ,
Variables in abstract are final.
->protected, default specifier for abstract method.
->Difference between method implementation with semi col and with out semi col
->Constructor in abstract class. What happens while extending this.
->Overloading and overriding of constructor.
->Can I make a Constructor as private, what will happen while making the object of this class.
Encapsulation:
Wrapping up of data and the functionality which works on this data is single unit: class
data hiding
-> Access Specification for class
In a java file we can only have 1 public class and more than one default classes. Other combinations not permitted.
Once a java file with 2 default and 1 public classes compiled, 3 .class filed will be created.
Default classes can be created more than one public class. Separate class files in the form of pubclassname$defaultclassname, wille be created from 1st repetition of default classes.
First case will create newdefaultclass, so that we cann't create new class after that.
private classes can be inside of other top level classes.
->Different type of inner classes, inside public class,
->Inner class inside default class,
->Inner class inside interfaces.
->Can an interface object can call static variables in interface.
->Can I have other classes under a abstract class. If yes what type of class.
Inheritance:
->How class casting works
->Method access specification after overriding
->Exception handling of extended method
->
Aggregation:
Car and driver
Class A having a private member object Class B
Composition:
Car and Engine
Class A having a inner class B
Coupling:
No tight coupling. Should be loose
Lose coupling.
Cohesion:
tight cohesion. Logical relationship between the items in object.
Delegation:
Refers to delegation of responsibility. One object delegate the method call to another object through messages.
->Tight enacapsulation, loose coupling nad higher cohesson. what is this stands for?
->Difference between Abstraction and Encapsulation:
Abstraction: Method implementation hiding. how?
Encapsulation:Data hiding, how?
JVM:
->Use of finalize method. Can I override? other way to start GC
When ever an object is eligible for garbage collection, it will call the object finalize method.
-> Mark & sweep algorithm
Disadvatag is entire memory will scanned by suspending the operations.
-> Tri color Marking: different state of the object will be marked with different colors
->System.gc() and other methods OR Runtime.getRuntime.gc()
Force the jvm to do best effort for making the free memory by garbage collections
→ System.runFinalization or Runtime.getRuntime.runFinalization()
This cause the JVM to call finalize method for object which found to be gc collected.
->Weak reference and hard reference
->Different type of class loaders?
JVM has internal classloader called bootstrap loader which loads class from CLASSPATH.
Dynamic Loading: Inside the code
->Diff Class.forName() and ClassLoader.loadClass()?
Reflection:
java.lang:
->What is serialization, transient keyword, private get serialized?
->How are we use final keyword.
->Difference between mutable and immutable.
->Difference
String,
Immutable
Stringbuffer.
Sychronized . So Thread safe
Mutable
Stringbuilder,
Not Sychronized
Faster than StringBuffer
->Shallow comparison & Deep comparison
equals :
Deep comparison
Compare the values
== :
Shallow comparison
Compare the object references.
String a =”hi”
String b = “hi”
a==b is true. But
String a = new String(”hi”)
String b = new String(“hi”)
a==b is false.
Because, when ever new string in declared, jvm looks string pool to find this constant is alrdeady assigned to any reference or not. If yes maked the
new reference to point that object. But while creating with new, new memmory area has been created.
->Operator overload is not there in java, Then how string+another works
->What is mean by the hash code of an Object?
return the integer number created from the physical address
->Methods in Object, purpose.Can I override equals method then how?
Override equal for redifining the equality.
Person class with name, age equal means person objects equals.
there is contract to override hascode when u redifine equels, because equal there is a contract in java spec, which force equality of object means same hashcode.
producing distinct integer results for unequal objects may improve the performance of hashtables.
table bucket arrangement
->How gc works ?
System.runFinalization();
System.gc
Overriding finalize method.
->Transient declaration and Serialization
transient to switch of that particular element while serialization. Can use only with variables. When an object get serialized, only that object state get saved. No static member will be serialized.No final member will get serialized. No need of explicit transient declaration for final, static members.
If u are giving transient to a method, that should be static method. But no need of giving
transient to static method. Anyway all static are transient only. Will not consider while serialization.
->Difference between Comparator Comparable interfaces. Scenarios where we implement this.
comparable interfaces >> CompareTo
all the wrapper class implements comparable interfaces
The Collection.sort() does the sorting by calling compareTo method of comparable interface if the list passed is set of wrapper objects.
If the list having our own objects we can implement either comparable in the object and override compareTo(Obj1)
comparator interface >> Compare(Obj1, obj2)
Another way of sorting is pass list and along with another object which implements comparator which is overrided compare(obj1,obj2) method.
->Try to access String's private class method compare ??...
->How do you use System.setProperty, what will happen if you set a property,
Using this in a web application.
->java.lang.Runtime
static getRuntime()
getRunTime().exit()
0 indicated the JVM that the programm exit normally
None zero value indicates the abnormal situation
There are 2 steps for JVM shutdown. First strep it
exec()
gc()
difference between
Object.finilize() & System.runFinalization() or Runtime.getRuntime().runFinalization()
->ProcessBuilder
its a final class.
start()
directory()
environment()
ProcessEnvironment.environment()
new ProcessBuilder(cmdarray).environment(envp).directory(dir).start();
Other class can implement cloneable() to mark that is conable
->java.lang.Class
All Class extends Object. Its a final Class.
Class.formname(name) returns the Class object associated with this name.
Class x = Class.formname(“x”);
URL x = x.getResources(“resName”)
// this statement in turn calls ClssLoader.getSystemResource(“resourceName”) and
get the url of the resource.
->java.lang.ClassLoader
Its an abstract class, its extended in security related application to load class in the program itself.
->java.lang.Enum
Its an abstract class,
->java.io.Serializable
->How to hang a machine using java program
->Two arrays, we have find the element occur in both arrays
->How to check circular link in Linked list.
->How memory is allocated
->Create an object on which garbage collection never execute.
->what is weakhashmap
java.lang.Thread
->Two ways to implement thread.
extend Thread class,
how to start a thread?
implements Runnable
how to start a thread?
->Main static methods in Thread class and their purpose.
static sleep(long milsec) >> Current thread goes to sleep. all lock on object will not be released. For other threads to get cpu cycle.
static yeild() >> While threads with priority, Thread.yield() couse current thread to go runnable, so that threads with same priority will get slot. NO gauranty
static interupted() >> If the current thread status interrupted, this method call will clear that state and return false.
isinterupted()
interupt() current thread goes blocked state.
join() Current thread goes wait for, until the called thread die.
join(long sec) Current thread goes wait for milliseconds, while called thread is alive
start()
stop() depreicated
suspend() deprecated because this may cause to arise deadlock situation.
Resume() also deprecated
-> Class level lock & Object level Lock
Lets say we have
Class A{
}
Thread1 and trhead2 trying to access Class A instance methods using class Aobject.
Object level lock >>
If threa1 accessing synchronized instance method, thread2 cant access other synchronized instance method using the same Class A object.
Other none syschronized methods can be accessed by thread2
Class level lock >>>
If thred1 accessing sycronized statis method, thread2 can't access other static sychrnoized methods,
but other sychronized instance method (if it get the lock means no other thread have the object level lock), none sychrozed static and instant method can be accessed,
->Main methods in Object using with thread programming. Uses for thread interaction.
Following will call with in the synchronized block
wait() >> thread temp orly releasing the lock on the object. and goes to block states. It will resume only if it get the lock again.
notify() >> One of the thread which waits the lock will get notified. No gurantie.depends JVM
notifyall() >> Notify all objects waiting...that particular object lock...
notify notify all doesn't release the lock, but just cause the notified thread to go to runnable state from blocked state.
Using read/write sample
->Thread states
New >> Runnable >> Running >> Dead
waiting/timedwaiting/block/sleep
->Differece Synchronized block and synchronized methods.which is best.
->Different types locks.Can a lock happen on memeber varable.
->How it works when a static method become synchronized.
->Why some methods are deprecated in Thread class.
->What is demone thread.
setDemon(true) final method , indicates jvm. JVM will exist if all nonedemon threads are killed. means they are in dead state.
In linux cron is demonthread. Its background thread.
->How volatile works?
This is a indication to the JVM that, the variable declared as volatile may be modified from different threads. Why we are giving this because, different threads will be using its own local memory forstoring the varialbes value. and there will be a master copy of the varaible in the main memory . By giving volaile jvm will synch up these two values.
->Why synchronization on constructor is not allowed?
->What is common exception occurs in thread programming and when
InteruptException
IllegalMonitorStateException >> When the current thread is not owner of the lock and still we calls objectName.wait()
IllegalThreadStatementException
->Declare a volatile variable. Create two threads to access this.
java.util.cuncurrent
->All classes under this package, how to use
->Creating a thread pool
->Cuncurrent hashmap how to use and advantages?
java.util
->All collection implements Iterator. Why and how it uses internally.
Iteration in two ways can be done
For(InteraTor<string> it = s.Iterator(); it.hasNext())
String s = it.Next()
foreach(String s: col)
syso(s)
->Main Util classes in collection Framework?
Arrays,
binarasearch
copyof
fill
sort
asList
Collections
binarysearch
newSetFromMap
raplaceAll(List,oldValue,newValue)
synchronizedMap
synchronizedList
synchronizedSet
reverse
sort
Main interfaces and implementation in collection
Iterable
Collection
List
Ordered collection
(ArrayList)
-> permits null
-> Not synchronized
->Array implementation, insertion is costly
->Slower than arrays
->Crates a new array internaly when u add
->ensureCapacity(min capacity) needs to set, so array will be created only once.
(Linked List)
→ insertion deletion faster than arrayList
->Linked implementation.
->Implements Queue interface
poll(),remove(), peak(), element()
->Permits null
->
(Vector)
->synchronizedList
(Stack) extends Vector
->LIFO
->push(),pop(),peek(),search()
Queue
(ArrayDeque)
-> push pop peek remove
-> Its a resizable array, no capacity restrictions.
-> Allows null
Set
No duplicates
(Hash Set)
->hashmap implimentation of set.
->permits null
->Not synchronized
(LinkedHashSet)
->Hash table and linkedList implementation.
->permits null
->Doubly linked list
->Not Synchronized
SortedSet
(TreeSet)
->tree map implementation
->Ascending order
->ts.add(null) is possible.
->Second time add will check the compareTo then it will
give nullpointer exception
->Not Synchronized
NavigableSet(1.6)
Map
Key value pair implementation
ConcurrentMap
(HashMap)
->Null values and null keys are accepted
->Not Synchronized
->Key object should override equals & hashcode methods.
put
putAll
remove
get
(LinkedHashMap)
->permits nulls
->retaining the insertion order.
Sample print ABCB 1234. LinkedHashMap prints ABC,B HashMap prints ACBB.
(HashTable)
->No nulls keys, No null values. if add it will throw NullPointerException
->Synchronized
->Key object should override equals & hashcode methods.
SortedMap
(TreeMap) → Not sychronized
Collections.sychronizedSortedMap(new TreeMap(....) will return the TreeMap which is sychronized
in, out,error etc are public static final variables in System class.
RandomAccessFile
Can do both read and write to a file
readByte()
readLine()
readChar()
writeByte()
writeChars()
seek()
length()
java.nio.file
java.nio.*
java.lang.ref:
javax.swing:
javax.awt:
Annotations:
Earlier versions also have ad hoc annotation like @deprecated, transient etc
In java 5 we can create our own annotation types.
Java5 & java6 difference:
Scripting language support
Reorganized some interfaces and added some concreate classes in collections frmwk.
ArrrayDeque
Metod in Collectios util newSetFromMap
Added more classed in Swings package
Serialization:
need to impliment serializable interface. Its a markable interface. All collection concrete class impented this. Why it is implimented is to nottify jvm to store the object state.
Convert object into byte while passing to stream. Example writing an object to a file, passing throgh a network.
While getting that object from the stream, jvm automatically deserialize.
transient declaration to avoid instant varialbles state to be stored.
java Tricky Qts:
Can I give private access modifier to a class. Where?.how?.
2)JAVA Utilities
->Random Text image creation
->Base-64 encoding of images.
->xml parsing and other operation
DOM
Load the xml in memory, Use with small docuemts, while random access or needs to modify the document.
DocumentBuilderFactory
DocumentBuilder
Document = builder.pars(“xml file or url to xml”)
Element
NodeList
Node
getNodeValue
getNodeElement
SAX
Works based on event and listener,
SaxParserFactory
SaxParser >> SaxParser.pars(uri, handlerObject)
Handler extends DefdaultHandler
Inside the overrided method, we have to give the logic to implement on each event
Jaxp
Use sax, dom, xslt
->xsl transformation
->Calling perl or shell scripts
->Using POI
->Using Apache FOP pdf generation
->Zip and unzipping
->Xtream API
->org.apache.commons.collections.DoubleOrderedMap
3)JDBC and SQL
->Two steps to make connectionusing DriverManager
Load the driver
Class.forname(“driver name”)
this will intialize the driver class. Basically instantiate the driver and register driver.
We can give the drivername in the ~/.java/properties file and load the file.
get the connection
Connection con =DriverManager .getConnection(url) has its own logic to find out the loaded driver class object using that driver it will return the connection object corresponding to the parameter specified in the url.
A JBC driver is the code that implements the JDBC API interfaces.
Type -1:
not multi threaded
Build on top of other native drivers
Use native client library to implement jdbc api interface. Probably written in c++
ex JDBC ODBC bridge driver
Type-2:
jdbc interfaces were implemented partially in java and partially native code c++
thick drivers
not portable
has native client library specific to DataSource
Type-3:
Uses a pure java clinet for Communication
Clinet Communicate with the middleware server using database indpenedent protocaol. http.
Middileware server communicate with datasource
Type:-4
Pure java implimentation. So platform independent
so they thin drivers
No clinet program required
Communicate directly with data source using java socket
→ Using DataSource
using JNDI
using pooled Connection
Main interfaces & classes in java.sql package
DriverManager
Connection
statement
ResultSet
Main interfaces and classes in javax.sql package
new ConnectionEvent(ConnectionPool obj)
DataSource
ConnectionPoolDataSource
PooledConnection
RawSet
->Difference types of statements
callable stmt
prepared stmt
->Different ways to connect db
->Connection pooling
using apache dbcp
4)Servlets
ServletConfig(Containts that particular servlet configuration info given in the web.xml file) contains ServletContext(Gives the info of that webapplication).
ServletRequest
HttpServletRequest
getRequestDispather(String) gives the path of the resource and get the RequestDispatcher
getSession():
getSession(boolean): Return current session. if passed true&no current session,create new
getRemteAddr >> ip
getRemoteHost >> hostname
getAttribute >> get the object assigned to the request
getParameter(name) >> get the params value attached in the querystring or form
getParameterNames >> return enumerated list.
getParameterValue >> String[] of all values
getCookies() >> return all cockie info in an array Cookie[]
getMethod() >> retunr POST or GET ...which used by client for submitting
getQueryString() >> url after the path
SetAttribute()
removeAttribute()
getServerName()
getSession() >> session infor in HttpSession:
HttpSession:
ivalidate()
getAtributes() return all sessionsin enumaration
setAttributes.
isNew()
Container maintain the session in 2 ways.
Using coockies client based.
URL rewriting server based.
Hidden Form fields
ServletResponse
HttpServletResponse
addCookie
addHeader
getWriter() return a PrintWriter object
reset() >> clear data in buffer, status code and header
isCommitted()
sc_accpted = 202
sc_continue = 100
sc_ok = 200
encodeURL() >> addthe session id along with the url
sendError(code, message);
sendRedirect(location) >> give relative url. Container will convert that to absolute url.
Update the broswer hstory
New request, nd response object getting created.So no way to
setAttribute in reuest
setStatus(StatuCode) >> sc_OK, SC_ABORT etc
GenericSrvlet implemetes Servlets, ServletConfig
HttpServlet extends GenericServlet
getInitParameter(pramName in web.xml)
getInitPrameters() return the Enumeration obj of init params
getServletConfig() returns conf inof as
ServletConfig
getServletContext()
getInitParameterNames >> Enumerated output
getInitParameter(name) >> return the value
getservletName()
getServletContext return webapp info as
ServletContext
getContext(path)>> return the contex inof corre to the path
This will be a singleton object for a web application. This instance can be shared amonng different servlet in that web application. This sores as member varibale in ServletConfig object, which will be pass to init method by the container.
RequestDispatcher
forward(request,reponse) >> Attributes can be set to the req
include(request,response)
->Life cycle
Init
Container calls this by passing ServletConfig object which containts container specific
information.
Service
doGet
If client uses getmothod only 1024 characters can be send to server
doPost
Unlimited length of data can be send to the server.
DoPut
Use to place a file to server like FTP.
Dodelete
delete a document or webpage from server
doHead
reurns only header info. No response body
doOption
doTrace
destroy
->javax.servlet.Filter
doFilter(ServletReq, ServletResp, FilterChain)
init(FilterConfig)
distroy
FilterConfig
getFilterItem()
getInitParameterName()
getParameter()
getServletContext()
FilterChain
doFilter(HttpRequest req, HttpResponse resp)
Can be used to change the request/response.pre or post process of servlet
A servlet can n filters. 1 filter can use by n servlets
doFilter will be invoked by container passing req,resp and FilterChain object which can be use to call next filter or the configures resource (servlet, htmlfile).
Without doing filterchainObj.doFilter(req,resp) the servlet to which filter configured will not execute.
To get container info in filter, we have to override the filters init(FilterConfig) method in our filter and using that
filterconfig.getServleContext();
->Can I override the methods. how?
->difference generics and http servlet
->Redirecting form one servlet to another. different types
web-app is the root element of deployment descriptor
filter >> filter-name
filter-class
init-param
init-name
init-value
filter-mapping
filter-name
url-pattern
dispatcher
dispatcher value can be either REQUEST, FORWARD, INCLUDE, ERROR
listener >> listener
listener-class
Listerner object will be called by the container whenever some event object. and Passes the eventObject to corresponding implemented Listeners. These can any of the following type
ServletContextListener
Class which implement this interface has to configure in web.xml. 2 methods
contextIntiated(ServletContextEvent_Obj). When container intialize the app
contextDestroyed(ServletContextEvent_Obj) .When context deleted by user
Class which implement this interface has to configure in web.xml. Methods are
sessionCreatd(HttpSessonEvent_obj)). When session created
sessionDestroyed(HttpSessonEvent_obj)). When session about to invalidated
HttpSessionActivationListener
HttpSessionAtributeListener
HttpsSessinBindingListener
Implemented by the object for which we have to track the session state.
valueBound(HttpSessionBindingEvent)
valueUnbound(HttpSessionBindingEvent)
HttpSessionBindingEvent
getName
getValue
getSession
ServletRequestListener
ServletRequestAttributeListener
servlet
servlet-name
servlet-class
description
init-param
param-name
param-value
load-on-startup . The servlet will be initialized when the container starts.
run-at
servlet-mapping
servlet-name
url-mapping
session-config
session-timeout
jsp-config
tag-lib
taglib-uri
taglib-location
context-param : Mention the params needed for entire web application.
description
param-name
param-value
distributable
Self closing tag to specify this is an distributable application, so that container can replicate the session from one jvm to another.
resource-ref
resource-env-ref
locale-encoding-mapping-list
env-entry
login-config
Servelets difference 2.3 2.4 2.5
: introduced Filters and FilterChains
Context and session listerners.
: introduced new methods in ServletRequest, for eg
getRemotePort()
getLocalName()
getLocalAddress
getLocalPort
Introduced Requestlisterners
: Intriduced annotations. Works only with jdk -1.5
In web.xml mutiple “url-pattern” can be given for filters. Or “servlet-name” can be *
for filter-mapping.
Tomcat difference 4, 5, 6
5)JSP
JSP Life cycle:
First is translation phase:
Syntax checking
Code generation
Compilation phase:
Compile the servlet code and create the class file.
these two phases happens just before the first request
Load Servlet classification:
create instance:
best practice is creating single instance, depends on the container
Multiple threads of this single instance serves the multiple requests
call the jspinit method:
call the _jspService method
call the jspDistroy method
All generated servlet will be extending the container Servlet. And generated servlet will override the methods _jspService
tomcat: org.apashe.jasper.runtime.HttpJspBase
This should
extend HttpServlet >> GenericServlet
implement HttpJspPage >>
_JspService
JspPage >>
jspDestroy
jspInit
Servlet
init, service,destoy
Page Elements:
Directive Elements:
page
import
session
isThreadSafe
include
taglig
Action Elements:
forward
usebean
Implecit Objects:
request
response
application
Scripts:
expression:
peace of code to give output directly to the page: <%= new Date() %>
scriptlet:
The code written here will go to _jspService() method. And this will not show in the
front end. <% SYSO(“something”) %>
declarations :
If we want to override the init method or or the code which we dont need to go inside _jspServce() method will written here.
<%! public void jspInit() {super.init()} %>
comments:
Comments which appear in jsp page source. No where else
<%-- some comment --%>
PageContext is the abstract class which will be extended by the container specific class which provides the JspWritter object to response, session to response etc.
out is an insstance in JspWritter object and will be part of response. This mechanism cotrolled by PagContext extended class in the container.
Eg: <%= new Date()%> will be converted into out.print(new Date())
The template element will be changed as out.writ(<table>...</table>)
JSP Directives :
page:
import
<%@ page import=”java.util.ArrrayList %>”
session
contentType
isEliIgnore
language
extends
isThreadSafe
errorPage
isErrorPage
include
<%@ include file=”a/x.xml”%>
<%@ include file=”/a/x.xml”%>
appName
WEB-INF
web.xmls
classes
lib
jsp
image
html
src
taglib:
<%@ taglib prefix=”mytag” uri=”http://..url” %>
Implict Objects:
request:
HttpServletRequest
response:
HttpServletResponse
out:
JspWriter object.
Session
HttpSession
config:
ServletConfig
application:
ServletContext
page:
corresponding to current servlet. Page.getMymethod() to get the private method defined in the servlet
pageContext:
container implementation of Jsp.PageContext extends jsp.JspContext
used to get context patams
exception:
uses in error page. Page should defind ad isErrorPage=”true”.
The error page will not be called directly. In every page we will add like
For creating custom tags we have to creat tag handling class and configure the tag in tld file.
TagHandler must implement
Tag
doEndTag
doStartTag
release
or
BodyTag
doInitBody
setBodyContent
TagSupport
BodyTagSupport
The generated servlet will create an object of the tag handler and calls methods in taghandler class.
The lifecycle is ,first it will call
hndlerObj.setPageContext
setParaent
setAtribute1
doStartTag
doEndTag
release
Usring the PageContext API we will get the jsp imlicit objects in the taglib class. Using this we can access the page elements in the jsp page in taglib class.
Avoiding browser caching while same url hits:
Set the header values
response.setHeader(“pragma”, no-cache)
cache-controll, no-cache
Expires, 0
OR
Set http eqaulent in meta tags:
<meta http-equv=”pragma” content=”no-cache”>
Difference jsp 1.2 & 2.0
In 2.0
introduced JSTL
introduced JspFragment interface
6)Design Patterns
Singleton Pattern:
What is
One to many
Make sure that only one object will get created for class, and client the access to that object through a public method.
Make a class with private constructor
The static getObject method will create the private static member object and return u.
Sample
Logger classed we uses this
Configuration classes.
Accessing resource in shared mode.
I used in the simulator framework.
We have to read a configuration file for response mapping. We need to check the configuration xml multiple times for every request. So we created an object, using that the caller will get the configuration properties given in the file. This object will read the xml file and set the configuration properties. Each time we check the status flag and return this object.
static getObject() return connection
Static flag to hold the status of object.
Users can make this flag active once it done with the object
static getObject return the private static object only if the flag is flase.
Adv&Disadv
cant be resused
difficult to extend
→ Is singleton thread safe.
→ How to make it thread safe
Factory Pattern:
What is it:
Client refers an object though an interface and and an another class which is called a factory engine decides and instantiate the object based on the parameter passed by client.
Make sure the inner object constructor to be private, so we can restrict the direct object creation and make it only through the Factory.
Makes a factory class which creates the object and return that based on the parameters used for initialization.
Sample: Name {} factory class.
public factoryName(“param”) based on the params it will return Name1 or Name2 object.The thump rule is Name1 and Name2 should extend Name.
Where u used in your project:
Messaging object
Advantages:
Achieves polymorphism
Its easy to add one more type of implementation. With out any change in the client side
In java:
xml parser
Both abstract classes DocumentBuilderFactory and SaxParserFactory has
newInstance()
This looks at the lib/jaxp.properties file and return the instance of the class configured there, which will be having the parser factory implementation.
4)Sample PHP page, created with any of PHP framework
19)SOA
Intro
Basic idea is if two application know the following 2 points
1)how to construct and reconstruct SOAP messages and
2)how to send and receive HTTP transmissions.
It should be able to communicate regardless of the technologies.
Can be different type as follows:
*Core Web Services:
These technologies include solutions for the processing of XML content, databinding and the development SOAP based web services.
JAX-WS->java api and xml based.Also uses jax-rpc in web services and in web applications.
JAXB implementation also available
*Enhanced Web Services:(JAX-WS)
Giving features such as reliable messaging and atomic transactions.
WSIT->Using tech like web Service Interoperability Technologies(Microsoft comm foundation),make sure the featurs in web services like atomic transaction etc.
*Secure Web Services:(JAXB)
Ensure the secure channel
Using WSIT
Using XWSS
Using saaj also we can secure the transactions
*Legacy Web Services:
Same like core.But service which support older versions of java
Can be create for System Management also.
AXIS Engine
)What AxisServlet do
AxisServlet acts as a mediator between the Web request and the Axis Engine. It reads all the parameters from the Web request, constructs a SOAP request (XML), and hands the XML to the Axis Engine. The Axis Engine processes the request and returns the SOAP response message (XML). AxisServlet in turn writes the response back to the Web client. It roots the service request to Axis engine. Intern it calls reportAvailableFunction(request,response) and lists all services.
2)How AxisServlet processing the request comes as serviceName?wsdl
AxisServlet diverts the corresponding service call to the Axis engine
3)How AxisEngine uses the server-config.wsdd
Axis engine uses the server section of that service defined in the server-config.wsdd file and identify the java class to be invoked.Once its invokes the java classs we will get the wsdl file for that service.
Steps
The entry step of creating jws is creating a interface which describes the service.
->implements Calculator and setPortName corresponding to each functions.
CalSoapBindingImpl->Impliments Calculator Interface,Service logic is calling from here which can be implimented in some other file and can be called here.
CalSoapBindingSkeleton->implements Calculator, and inside that Calls the functions implimented in SoapBindingImpl. ->impliments org.apache.axis.wsdl.Skeleton
->impliments CalculatorService which creates object of CalSoapBindingStub and setPortName
deploy.wsdd-> <service name=”” provider=”” etc>
undeploy.wsdd->
->Write Implementation code logic
Implimentation logic can be given seperatly and call this in soapBindingImpl.
->Create server-config.wsdd
->Build (maven or ant)/out put should be as web application
->
->deploy
->write client and test the service.
Flow in Axis based web service system
When we send a RPC-style soap message to axis it will hit the org.apache.soap.server.http.RPCRouterServlet
jars needed in class path
activation-1.0.2.jar -> activatin framework has been used by javax.mail to manage mime type from
mail-1.3.1.jar-> for messaging services sun's
axis-1.4.jar -> axis core from apache
axis-support-1.0-SNAPSHOT.jar ->etrade API having BindingImplbase class.
commons-discovery-0.2.jar->apache API for finding particular resource,for locating classes that implement a given Java interface etc. commons-logging-1.0.4.jar->API for integrate different logging impimentation
jaxrpc-1.4.jar
jsx-1.0.jar
log4j-1.2.13.jar
saaj-1.4.jar
wsdl4j-1.5.1.jar
xercesImpl-2.6.2.jar
xmlsec-1.0.4.jar
axis/jars/axis-ant-1.4.jar
ant/jars/ant-1.6.5.jar
java2wsdl
Flow
From client->
XSD
Xml schema Definition: Gives the structure of an xml document.
Defines the each element type.
A wsdl file will be generated from xsd's.
WSDL(Web Services Description Language)
The main structure of a wsdl file is
1)Port type shows the operations performed by the servi ce. The operations can be
a)One way operation :only input in operation tag
<portType name= >
<operation name= > can be many
<input message= >
b)Request-Response Operation
<portType name= >
<operation name= > can be many
<input message= >
<output message= >
c)Solicite response:
This type of portType will send a request and wait for the response
d)Notification
This type will send a request and they will not wait for response.
2)Messages shows the messages used by the webservice
<message name=”xxx” >
<part name= type=xs:String>
Every message having the part name which is the parameter name type means the parameter type.
3)Types ->The data types used by the service
<types>
If the service defined by the WSDL document uses only the built-in XML Schema simple types, you don't have to include a <types> element; instead, you can use the element to define your own types.
4)Binding ->The communication protocaol used.
<binding>
wsdl Syntax Order
->types
->message
->portType
->serviceType
->binding
->service
import:brings declaration in other namespace
include:brings declarations in current namespace
UDDI->Universal Description Discovery Integration
1)Its like a directory of web service interfaces described by wsdl.
2)UDDI developed under .Net Platform.
Alternatives for UDDI is :
IBM's recent standardized Web Services Inspection Language,
This class uses to generate clinet side java compents to access the services also Skelton for SoapBindingImpl.Also deploy.wsdd
SOAP(Simple Object Access Protocol)
Http standard is not capable for communication between two application objects.
Other altrantive is RPC which is using by DCOM and CORBA objects.But the problems with RPC is , the firewalls and proxy servers will block this kind of traffic.
Soap is created on top of http.Soap is a intiative from microsoftt.
Other xml bases messaging protocol is xml-RPC.
Below the soap Structure
<soap:Envelope>
<soap:Header>
...
</soap:Header>
<soap:Body>
...
<soap:Fault>
...
</soap:Fault>
</soap:Body>
</soap:Envelope>
WSDD(Web Services Deployment Descriptor)
AxisServlet uses the information in the wsdd to generate the corresponding wsdl.
deploy.wsdd & undeploy.wsdd
For each we can have a deploye.wsdd and undeploye.wsdd file which helps to deployment easily.diploy file containts the service name and the class defines that service name.
server-config.wsdd
The axis engine having a deployment descriptor of all service deployed,which is configures in server-config.wsdd.The file is like the web.xml for servlet configuration.
How to configure with tomcat
JWS Hello World
Ant
<ant > tag
antfile={build.xml path }
dir=??
<project> tag
name=”name of the project”
default=”what target should execute if the script execute with out any parameter”
somevar=”.” or “..” (indicates base dir name)
inside “ ” we can give shell commands which will execute as like any other scripts as
in (.bat or .sh)
we have <property> tag
name=”some name”
vale=”${basedir}” or value can be ${somename},value of some name
4) <java classname=”---”>
<arg name=”arg to the class”>
5)system commands
<mkdir dir=” ”>
<move file=” ”>
<delete file=” ”>
we have <taskdef name=”somename”
classname=”org.fds.fd...”>
we can define a task and corresponding class and this task can be include in an of the target.as like
<target-quick>
<taskChk argname=”dsd”
arg2=”fd”
arg3=”arg3Vales” we can give arguments inside the task tag>
</taskChk>
</target-quick>
How to call a WS
Using Axis clients
httpclient
bea.jolt.* clients for tuxe services
JAXB
Comapre Maven1.1 & Maven 2
1->have build.properties file can put in home folder or each project folder having info about the repository information
2->has the file called settings.xml,which we need to create and put in ${HOME}/.m2/repository/,which has the repo information.
3->Caching happens in maven1.
4->difference in pointing groupid,artifact id
5->maven site generation pluginn added with maven-2/can be use as mvn site
creates documentation site.Project doc can be given as .awt format.
Common Tips
Remote debugging in eclipse & tomcat
1)start tomcat in debug mode by replacing the existing configuration in start.sh as follows:
Generate the tag file for the Ingres source:ctags -R -f ~/.vim/tags/ingres.ctags /home/grant/src/svn/ingres/main/
~/.vim/tags/ingres.ctags is the target tag file. Windows: Use $HOME in place of ~
/home/grant/src/svn/ingres/main/ is the full path to the Ingres source tree. The path used needs to absolute and not relative since Vim will need to navigate from the current working directory to the file containing the function definition.
Copy the following code into your $HOME/.vimrc: " Tag files set tags+=$HOME/.vim/tags/ingres.ctags " Ctrl+Right Arrow to goto source of function under the cursor map <silent><C-Left> <C-T> " Ctrl+Left Arrow to go back map <silent><C-Right> <C-]>
when we start some command from terminal and if we wnat to stop Ctrl C
If we want to suspend that process nad send to backgrount Ctrl Z
If we want to run that command in background while starting itself add & at the end
List all the backgoround jobs in that terminal>> jobs
Make the back ground job come to forground and start running >> fg
Continue a suspended job in back ground itself>> bg
28)grep lines which has last work “abc” : grep -irl “abc$”
29)grep lines which has first work “abc” : grep -irl “^abc”
30)grep or/and/not grep -e or egrep “abc|xyz”
30)find files touched on jan 2nd
31)How to use CUT command
Creating debian package.deb apt
Download all contents in a particular folder >> wget -r url_upto_flodername
Result of the last command: $? .
if $? is 0 last command or function executed correctly.
else its 1 – 250, some error happened in the execution.
21)SMS
kannel gateway
WAP protocol
22)HSQL DB
1)Unzip the down loaded hsql
2)set classpath
3)Start in server mode
4)in process mode ->In same JVM along with the application in webserver
5)
23)Ibatis
Its basically a data mapper using map table data and the corresponding object.
The basic idea behind the iBATIS introduction was to significantly reduce the amount of Java code that a Java developer normally needs to access a relational database with the use of XML files containing SQL queries.
version is ibatic.2.3. from apache.
hibernate is similar kind of tool using for O/R mapping.
Advantage as 80/20 .80% of jdbc functionality/with 20% of code.
//the result map can be more than one according to the queries
<resultMap id="Resultname need to get" class="aliasname of the class which mappe">
<result property=”privatemem name in the DO” column=”corresponding table name”>
<result property=”privatemem name in the DO” column=”corresponding table name”>
</resultMap>
<select id="name using in the code to get result" parameterClass=”String-parameters passing to the query” resultMap="resultmap id created aboce">
//select statements
//parameters can be use as #name_passed_in the code#
</select>
//queries can be given inside
<statement>
...
</statement>
<insert>..</insert>
<update>...</update>
<delete>....</delete>
<procedure>..<procedure> for stored procedure
<sqlMap>
24)C-Questions
1)Diff b/n malloc & calloc
2)How to debugg c code->> using dd
3)
25)Perl
1)chomp & chop
2)How to debug in perl
different type of variables
functions on scalar variables
Modules to do other operations
Get Arguments @ARGV
No of arguments @#ARGV
Result of command functions execution _@
26)Site Minder:
27)Ping Federate:
IDP
SM
IDM
29)About my testing experience
Started career as a tester. Worked around 2 years in testing. Both manual and automation in selenium.
Moved into development because we have better idea of there business. We get task like
small enhancement in there customer and CSR site.
30)Testing Concepts:
Life cycle
End to end flow
Which method used
Sample testcases
31)QC
32)Selenium
33)Junit
Difference junit 3 & 4
34)Using mock objects
29)About my scripting experience
Started my carrer as a java developer. Right now I am enagaged with the client called Etrade Financil CoOp. Open source client. We are using redhat AS3, AS4 machines here.
The batch jobs basically done in both perl and shell script. We have a customized sceduler here, which inturn makes the crontab entry and make job shceduled.
The jobs are basically file processing. For example we have the Cashtransfer system called ACH, Automatic Clearing house which handle the cash transfer between Etrade accounts and other external bank accounts.
Spike source was the first customer i worked with. There I worked infrastrucure kind of project basically we did the open source product development. One of the project we did was the core stack. In that I was part wrting build scripts and post installation scripts for the Coponent Stack
30)About Banking Experience
Working for customer called Etrade. They are online share trading company is US. Basically a brokerage firm. Which gives a platform for trading. Like icicidirect in india. Our team handles the banking operation in the customer site & customer care site.
We basically interacts with lot of third party tools through webservices. Like
We uses fidilities profile as our core banking solutions.
Uses Alogent system for check processing. and we have check free, its ASP solution, check free for check image scanning.
Also we have a dedicated batch system doing the ACH posting and handling return transfers. ACH (Automatic Clearing Houses) system in US just like NEFT here for handling interbank money transfers.
The main project we completed recently is HomeDesposits. The business requirment comes because of a new FED rule in US. FED is like our RBI in india.
The new fed rule says a check image have the same validity of a papper check. So all banks forced to accept checks as image files, also endof the day submitting to FED, FED also will accept images
As a module lead, first of all i have to understand the business requirement and decided how many resource needed for my module.
We do the middleware component development and webdevleopment
We uses SOA framework, which we costomuzed on top of struts.
We does the web develpment and middileware compoent development. So we have map appropriate resources for the requirement. Basically our projects are fixed billed projects.
The project i am doing right now ACH Check Hold.
31) QA Experience
I am working for as part etrade testing team, we are working along with the offshore dev team here.
The project which we are doing write now is SIT phase.
Before code goes to SIT we are doing alpha testing. we are doing in the developer integrated box called P6 environment. Its a combination of virtual envirnment.
Also we have webservice testing. We have a tester program, which is perl script.
When ever a service ready and its cehcked in, the code will be available in P6 box
and we have to do alpha testing on the service. The data setup will be done using the simulator.
I was involved in the initial RD along with the development team, and in the fecebility sturdy. Dev team developed a framework for selenium.
Using RC
We uses this framework for testing. Once we found that a test case can be automate, we will do that.
Banglore team does the actual regression.
My here is responsible for developing new scritps, maintaning the existing one as per the front end changes.
Setting up RC machines.
So that banglore team will do the regression.
Sample selenium generated java class.
Package testscript.retailbank
import com.thoughtworks.selnium.*
public class TestMessagingACH extends SeleniumTestCase{