Monday, December 28, 2009
Immutable and Singelton
* 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;
}
}
tech_notes_Rakesh
1)Core JAVA
Oops Concept
Polymorphisms:
Overriding:
Should not change the method ars types.
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()
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();
its final class extended hashmap
->java.lang.Process
Its an abstracy class
destroy
getOutputStream
->java.lang.System
static arraycopy()
static PrintStream out
static PrintStream err
static InputStream in
static gc()
static getenv() returns a map
System.exit(0) internally calls RunTime.getRuntime().exit(0)
->How to run a shell script in java
->java.lang.Object
clone()
creates another reference no new object.
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
NavigatableMap
ConcurrentNavigatableMap
Collection:
ArrayList:
-> Initial capacity will be 10
-> Does Arrays.copyOf(existingarray,newCapacity) for adding
-> does System.ArrayCopy() and then add that element in the coresponding position.
System.ArrayCopy(arrar, index, newarray, index+1,no_elemt_Needs_Cop_frm_FirstAr)
newArray(index) = element
-> Increases the array size by 50% when room full while adding new
->Fast iteration required and no need of thread safe
Linked List:
-> Contains a private static class for holding the structure of node.
-> Constructor having the element, previous,next
How to find the loop in a single linked list
How to find the loop in doubly linked list
Scenario where we have frequent insertion deletion
Vector:
added
set
remove
-> All methods are synchronized
-> Initial capacity will be 10
-> We can set the increment capacity also in the constructor
-> By default increases the array size by doubling the existing capacity
-> Scenario where we know the the increment rate, and required thread safe.
Map
Collections:
Arrays:
Generics:
Inner Classes
->where is Iterator interface is implemented?
->When ConcurrentModificationException occure ?
->How collections.synchronizedcollection(), Collections.synchronizedSet
usefull
How Collection.sort works?How can we decide the sorting base?
How Collection.srot can be use for sorting the elements of a Hashmap
WeakHashMap and weakreference:
8)What are all the sorted maps and sets in what basis it sort elements, how can we make the sorting criteria.
How maps implementation in memory(check docjar of map impls)
Difference Hashmap and Linked hashmap
Use of >>>>>>>> java.util.random
Use of >>>>>>>> java.util.Date
Use of >>>>>>>>
java.lang.Throwable
java.lang.Error
AssertionError
VirtualMachineError
OutOfMemoryError
StackOverflowError
UnknownError
InternalError
ThreadDeath
java.lang.Exceptions >>>>> checked forced
java.text.ParseException
ClassNotFoundException
InvocationTargetException
IOException
FileNotFoundException
javax.servlet.excpetion
java.lang.RunTimeException >>>> unchecked/runtime/not forced
ClassCastException
ArithmeticException
NullPointerException
IllegalMonitorStateException
InterruptedException
ConcurrentModificationException
BufferOverflowException
IndexOutofBound
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
IllegalArgumentException
NumberFormatException
IllegalThreadStateException
InvalidParameterException
IllegalSelectorException
UnsupportedOperationException
ReadOnlyBufferException
ArrayStoreException
SecurityException
AccessControlException
RMISecurityException
IllegalStateException
AlreadyConnectedException
.....
org.omg.corbra.SystemException
org.omg.CORBA.TRANSACTION_ROLLEDBACK
......
javax.net.*
java.io.*
IO streams are made for 3 purpose
read bytes to characters
Read bytes to text
File >> File or Diractory path name
InputStream >> Reading character
ByteArrayInputStream
FileInputStream
FilterInputStream
BufferedInputStream
OutputStream >> writing character
ByteArrayOutputStream
FileOutputStream
FilterOutputStream
BufferedOutputStream
DataOutPutStream
PrintStream >> No IO exception will be thrown
Automatic flushing happens after each println
Convert each character data to byte
Reader >> Reading text
Writer >> Writing text
BufferedWriter
CharacterArrayWriter
OutputStreamWriter
FileWriter >> Use while writing character data.
Need flush and close after writing
Throughs IO exception
PrintWriter >> Automatic flushing after each line
No io Exception
Error flag can be obtained checkError() method
StringWriter
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.
Statement stmt = con.createStatement();
Resultset rt=stmt.executeUpdate("CREATE DATABASE JunkDB");
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
getNameDispatcher(nam) >> return RequestDispatcher
getRequestDispatcher(path) >> return RequestDispatcher
log() >> log message in he servlet log file.
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
reqobject.sendRedirect(servlet_name);
getServletConfig().getRequestDispatcher(“servlet_name_to_redirect”).forqard(req.resp)
->Inite params to Servlet
->How filters work.
->Passing arguments from one servlet to another.
->Get other servlet info from a servlet
->How to get the container info from servlet
getServletConfig().getServletContext() will give the info of web application
->Deployment descriptor configs. Sample tomcat web.xml configurations
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
ServletContext cntx = ServletContextEvent_Obj.getServletContext();
ServletContextAttributeListener
HttpSessionListener
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
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
<%@ page errorPage=”/raleative path”>
JSP Actions:
<jsp:useBean id=”a” class=”com.test.NameofClass” scope=”session”/>
<jsp:getPropery name=”a” property=”weight” value=”10”/>
<jsp:setProperty name=”a” property=”weight”/ > request params should be same
<jsp:setProperty name=”a” property=”*”/ >
<jsp:include page=”somepage.jsp” flush=”true/false”>
it should be the url inside the webapp.
/ means relative path from the context directory
no / means the relative path from the directory contains the source page
<jsp:frward page=”pagename.jsp”>
<jsp:param name=”messagekey” value=”message”>
</jsp:farward>
Difference jsp @ include directive & jsp:include action
directive is evaluated at translation time ; action at runtime
static ; dynamic
1 servlet ; 2 servlet will be created
Use if resource not changing frequently : Use for resource which changes dynamically
Difference between jsp:include & jsp:forward action:
In include page should be inside the same server.
If the resource is out side of the server, we have to use forward
<jsp:plugins>
JSP xml syntax
Scripts >> <jsp:scriptlet>
Expression >> <jsp:expression>
Declaration >> <jsp:declaration>
<%@ page >> <jsp:directive.jsp>
<%@ include> >> <jsp:directive.include>
<% @ taglib> >> xmlns:abc=”..url...”
JSP EL
pageScope
requestScope
sessionScope
applicationScope
param >> request.getParamer() Map contains first values of request parameters
paramValues >> request.getParamerValues() Map contains all request params
initParam
coockie
JSPTagLibs:
<%@ taglib prefix=”mytag” uri=”http://tagliburi”>
<mytags.tagname> ${3.2}</mytag.tagname>
The taglib uri should be defined in web.xml
<jsp-config>
<taglib-uri> tagliburi </taglib-uri>
<taglib-location> /WEB-INF/tags/mytag.tld </taglib-location>
tld file contains the the tag name and the class file which contains this tag
<function>
<function-name> tagname </function-name>
<function-class>classname </function-class>
…...
</function>
the functions should be static.
JSTL:
Mainly 5 catogaries taglibraries are already available with sun
<@ taglib prefix=”c” uri=”http://....../jsp/jstl/core”>
Core:
<c:out value=${value} dafault/>
<c:set value=09 var=”sampleVar”/>
<c:remove var=”sessionVar scope=”session””>
<catch> <jsp:scriptlet> …...</jsp:scriptlet> </catch>
if
choose
when
otherwise
import
url
redirect
param
xml:
sql:
fmt:
function:
JSP Custom tags:
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.
newInstance(String filename, Classloader loaderobj)
New feature in 1.6, we can specify the implementaion class file name and classloader object, instead of configuring jaxp.propeties
java.land.URLConnection
How to make singleton inside factory: Just to confuse ..just use as it is
DOA pattern:
Not usfull when OR mapping tools avaialbel.
Proxy:
Deligates the method invocation on a particular object to another one.
Visitor Pattern:
Prototype:
Observer Pattern:
7)UML
->Representation of different relations
A extends B
A implements B
Aggregation
Composition
->Activity diagram
Purpose
How to show parallel process
Action state and state.
->Sequence diagram
Purpose
representation of synchronous&asynchronous messages
->deployment diagram
Purposes
Artifact and Node
->Class diagram
purposes
Representation of different elements
8)MySQL
9)Sybase
source /....sybase_install_dir/SYBASE.sh
isql -S USDTSIT -U tuxuser -P tuxedo -c -w 2000
Get the nth larget salary
select salary from (select distinct(salary) from emp where salary NOT NULL order by salary desc) where rownum=n
Get the nth smallect salary
select salary from (select distinct(salary) from emp where salary NOT NULL order by salary asc) where rownum=n
Joins:
Inner: Only matching values from both table.
(select * from emp, dep where emp.did = dep.did)
equi: Same result of inner join can be give differnet way. supported by mysql no sybase
(select * from emp inner join dep using(did))
natural: Implicitly takes the columns with same name
(select * from emp natural join dep )
Cross: (Cartesion product)
select * from emp cross join dep.
All in Emp to dep1
All in EMP to dep2
Outer Joins:
Left: Take all values in the first and matching values from the Right
(select * from emp left join dep where emp.did = dep.did) mysql syntax
instead of saying left out *= in syabase
Right: Take matching values in left and all values in the right
(select * from emp left join dep where emp.did = dep.did) mysql syntax
instead of saying left out =* in syabase
Full: Both matched and unmatched records and fill nulls for corr unmatched fileds
(select * from emp full join dep where emp.did = dep.did) mysql syntax
Self Joins: Joins the same column in a particular table.
Indexing:
Adv:
Faster access to data
ensure uniquness
Disadv:
Insert/delete/update operation may get slow
Type:
Composit Index: more than one column in the key
(create index indx on emp (smpno, devision, depid))
Clustered index:
Non Clustered Index:
sp_help
sp_helpdb
sp_spaceused
sp_helpjoins table1 table2
9)DS&Algoriths
->Linked list finding cycle
1 way is marking all visited once. and if met marked once before end means repeated
2 nd approach is take 2 heads and transverse once behind another. If two starters are equal
it means repetition.
->Sorting
Bubble sorting is the common approach
for 1 to n take each one compare with the next one and if greater swap it
After 1 st iteration of outer loop smallest goes to last.
10)Struts
Action Servlet >> ServletEnv > > Controller
ActionClass >> Compoents >> Model
struts-config.xml >> appconfig
Action Form >>
JSP >> xsl transformation >> View
We don't have the implementation of ActionForms, Message Rsource, Validation Framework
11)Spring
Inversion of Control
Aspect Oriented Programming
Based on Simple POJO (Plain Old Java Object)
org.springframework.beans.factory.BeanFactory
org.springframework.beans.factory.xml.XmlBeanFactory
org.springframework.web.context.ContextLoaderServlet:
org.springframework.web.servlet.DispatcherServlet
How af used spring and struts
12)HTML & XHTML
13)CSS
14)Java Script
Types:
Number String boolean Function Object Null Undefined
paseInt(3f,16) >> parse hexadecimal to decimal
isNan return true if the argument is not a number
Boolean operators:
&& || !
Redirecting:
location.href=”newlocation”
window.location.href=”newlocation”
Node
insertBefore
cloneNode
hasChildNodes
removeNode
Document
getElementById
getElementByTagName
createTextNode
createElement
HtmlDocument (document)
body
coockie
document.coocke=”String;strin2”
docment.coockie.indexOf(“;”,2)
url
window
Frames
Element
HtmlElement
Navigator:
Navigator contains the information about the visitors browser
navigator.appName gives broser name
navigator.appVersion
History:
back
forward
go
Window
Screen
Location
JS Time:
var t =SetTimeout(script, 5000)
clearTimeout(t)
Js Objects:
String
toUpperCase
toLoweCase
substring(start,end)
substr(start, length)
slice(start,end)
indexOf(searchStr, startPostion)
big
bold
Array
push
pop
slice
concat
join
shift
sort
reverse
Date
15)XML
XSL means >>> Xpath, Xslt, XSL-FO
16)XPath
Navigating xml document
17)XSLT
Can use to transform xml and create html and xml.
1)-> <xsl:template match=”path to the node / stands for root node”
//you can add tag which should come in out put
</xsl:template>
2)--> <xsl:for-each select="catalog/cd">
//iterate for each value in catalog/cd
</xsl:for-each>
Also we can add conditions with the nodes.Example given below,which selects,
unser catalog/cd all child nodes with artist='BobDylan'
Other conditions which we can use are
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
!= (not equal)
< less than
> greater than
3)-> <xsl:value-of select=”title”/>
//this write the value of the title node
//We can use this under for writing all chiled node values under the foreach selection.
4)<xsl:sort select="artist"/>
//We can use this under for each to sort all the child node values under the selected value to sort according to the artist.
If should be in a loop or some where ,there the nodes upto price should be selected.
Now we can apply condition on price
<xsl:if test="price > 10">
//under this we can give the nodes to print.
//this part will execute only if the above condition matches.
</xsl:if>
6)<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
//need to do the sample.
7)The <xsl:apply-templates>
//need to look into this
we can @ to access atributes of the node.
<xsl:for-each select="tool/field">
<tr>
<td><xsl:value-of select="@id" /></td>
</tr>
</xsl:for-each>
Here it prints the value of “id”,which is an atribute for the node filed node.
<xsl:with-param
10)We can assign varialbe name
to a node
<xsl:variable name="articles" select="/articles" />
to a value.
<xsl:variable name="planet" select="'earth'" />
18)Ajax
1)xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); //for firefox
}catch (e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); //IE
2)Propetry of xmlHttp. object
a)onreadystatechange=funName
xmlhttp.onreadystatechange=functioname
//function(){should be define which process the response from the server }
b)Readystate property->Holds the status of the server
if (xmlHttp.readyState==4){
var fileCnt=xmlHttp.responseText;
//response is ready and we can process the response
}
0->not initialized to 4
1->has been set-up
2->has been send
3->Inprocess
4->complete
c)responseText->Retreving the data from the server
d)Methods using open/send
xmlhttp.open(GET/POST,servername/jsp/action name,true)
xmlhttp.send(null);
3)Using with JSON
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.
->java2wsdl
java org.apache.axis.wsdl.Java2WSDL -o svc_cal.wsdl -lhttp://dummy_url -nurn:com.wsdl2java.gen -psamples.myTest.server urn:com.wsdl2java.gen samples.myTest.server.Calculator
->wsdl2java
java org.apache.axis.wsdl.WSDL2Java -avs -S true -d "Session" svc_cal.wsdl
generated file
This generates the client stubs and server side skeltons.
Calculator Interface ->Interface same like we created first,but this
extends the java.rmi.Remote
CalSoapBindingStub-> extends org.apache.axis.client.Stub
Creates the Data structeres like
org.apache.axis.description.OperationDesc
org.apache.axis.description.ParameterDesc
->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
CalculatorService ->Interface in server side,
declare getCal returns the Calculator interface,
declare getAddress
->extends javax.xml.rpc.Service
CalculatorServiceLocator->extends org.apache.axis.client.Service
->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,
older ebXml standard.
wsdl2Java
java org.apache.axis.wsdl.WSDL2Java -avs -S true -d "Session" wsdl/svc_aggtr.wsdl
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:
export CATALINA_OPTS="$CATALINA_OPTS -DAF_BUILD_FROM_JARS=$AF_BUILD_FROM_JARS -Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"
2)apache httpd.conf configuration
3)Tomcat server.xml configuration
4)WebLogic configuration
20)Linux Important
1)find a particular file format and greps a pattern in each and returns the pattern existing files.
->find ..... | xargs grep “ffsf”
-> find -name "*.pdf" -type f -maxdepth 1 >> Search only in current directory
-> ls -alrt | tail -14 | grep -v ^d | awk '{print $9}' | xargs -i mv {} /tmp/
-> sort data.txt | uniq -d -c
VI important short cuts
a) (search and replace all in a file)
:%s/old/new/g
b)cut paste lines
make the cursor at the starting line
Esc mk
make the cursor at ending
Esc “ ay'k
or
Esc “ ad'k for cut
and paste as
Esc “ap
cvs upd -dPA brachname cvspath ->this will sync newly created/deleted dir corr to the remote repo.
finds file name by .svn and deletes each one.
find . -name ".svn" | xargs rm -rf
cvs upd -r odc_1_13719
find tottal number of lines in all the files in the directory
bash$ls | xargs wc -l
Shell scrpting starts with
a)#!/bin/bash
this is for executing the next lines using this particular program.
&& and || can be use instaed of condition checking
b)For conditions execution starts from left to right
In case of &&
[-r simefile] && { echo “file readable” ; other commands }
do the stuff
If left returns false,it wont execute the right
if left returns true then it will execute right and comes to normal flow
c)Debugging in shell scripting
sh -x strangescript -->
Execute line by line and shows the execution
sh -n your_script -->
Check syntax correctness of the script.
Top ->shows the cpu usage
aprops command_name -> Gives the command for a scenario.
java
Creating RPM general
There are 8 sections in an RPM spec file:
a header:Source dir,version and other information
a prep section:
a build instruction section:
an installation section:
file cleanup:
pre- and post-installation:
optional uninstallation script:
a list of files in the package:
and a changelog:
Creating RPM using maven
12)Setting-Ctags
a)Create a file
at home -> bash$vim ~/.exrc
with
content
set tag=/etrade/home/ssuresh1/work/services/tags
b)type the following command at $SVC_HOME/services
bash$: ctags -R -h ".c.cpp.h.hpp.cp" --C-types=+defstupg-cxmnv
Use Ctrl [ , Ctrl ], Ctrl T, Ctrl G
Another Option:
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-]>
13)Change time zone
export TZ = “Asia/Culcutta”
tzset
14)SVN Important
svn mkdir file:///proj/svn_repository/project1/trunk -m 'New directory'
find -name *.java -print0 | xargs -0 grep -o acctListFromService
egrep -w 'acctListFromService|param' ~/test.txt
17)awk
awk '{print $NR}'
awk '{print $NC}'
awk '{print $NF}'
sub (. , new str, targetstr) >> replace the string represented by reg extression with new str
substr (str,start,length)>>
Show hai test in Hai Test
echo "hai test" |awk '{ for ( i=1; i <= NF; i++)
{ sub(".", substr(toupper($i),1,1) , $i) }
print }'
18)sed
sed '//'
19)crontab
EDITOR=VI && crontab -e
This will open the users crontab. We can configure our job here. crontab is simpe text file which keeps the job list.
The is demon thread in linux based system, which keep own poll the crontab file of that particular user and execute the jobs configured there.
20)chown, chmod etc related with permission
21)Sample shell scripts assignments
22)at command
Kill the process in 1 line
kill -9 `ps -aux | grep kcalc | awk '{print $2}'`
Other options to the process other than -9
How to give one signal to the process
24)List last 2 lines in the recent touched file
tail -n 2 `ls -lrt testdata/*.log | awk '{print $9}' | tail -n 1`
25)Last 2 lines of last modified file
tail -1 `ls -lrt | tail -2 | awk '{print $9}' | head -1`
25)du -ah –max-depth=1
size of all child folders
26)How to show back ground process
27)make back ground process foreground
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.
com.ibatis.common.resources.Resources.getResourceAsReader(“path/to/SqlMapConfig.xml”)
This returns the reder object having the sql mappings.Using this reader object we have to build client.
com.ibatis.sqlmap.client.SqlMapClientBuilder.buildSqlMapClient(map_file_reader_object)
This return the object of the com.ibatis.sqlmap.client.SqlMapClient sql map client.
This client object can be used to query as like.
mapper_clinet.queryForList(crieteria_which_configured_in_mapping_xml)
mapper_clinet.queryForObject(crieteria_which_configured_in_mapping_xml)
In case of queryForobject, return type should be casted to the DO object,that should be
defined according to the mapping.
Reader reader = Resources.getResourceAsReader("config/SqlMapConfig.xml");
sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
Beanclassconfigured obj=(Beanclassconfigured)sqlMapper.queryForObject("selectAccountById", id);
sqlMapper.queryForList("selectAll") returns list
Queries corresponding to “selectAccountById” & “selectAll”
needs to be given sqlmap file.
SqlMapConfig.xml Configuration
<sqlMapConfig>
<transactionManager type="JDBC" commitRequired="false">
<dataSource type="SIMPLE" or ”JNDI”>
property tag with name of
driver name,
db name
username
password
<dataSource type>
<transactionManager>
<sqlMap resource="config/AccountBalance.xml" /> points all the sql map files.
...
Then we have set of optional tags
<properties resource=”.properties file”/>
<settings/>
</sqlMapConfig>
SqlMapfile.xml Configuration
for each table there will be one map file and DO class
<sqlMap namespace="name of the DO">
<typeAlias alias=”aliasname” type=”fully.qulaifyies.name.of.class”>
//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{
public void setup() throws Exception {
setup(baseurl);
}
public void testnew() throws Exception{
selenium.click(“link=home”);
….
}
}
Sybase -- Store Query output to a file:
********************************************
isql -Utuxuser -Ptuxedo -SPSITDB1M25 -DUsLegalEntityDB -i input.txt -o output.txt