Why do we need a web server ?
Why do we need a web server ?
In an Web or Enterprise Application perspective, you need a webserver as a first entry point since all the requests have to be originated from a single place. Say, your login page to the application. But processing the login operation may not be the job of a Web Server and it would be done by a Web Application.
As such, a Web Server is preferred to serve any static files, which is not changing in nature for any type of requests. Whereas, you need a Web application to produce a dynamic response according to the type of inputs you provide along with your request.
XML
DOM (Document Object Model)
The XML DOM defines a standard way for accessing and manipulating XML documents.
The DOM presents an XML document as a tree-structure.
Knowing the XML DOM is a must for anyone working with XML.
SAX
Simple API for XML (SAX)
for the events-based parsing of XML documents
Difference
SAX parsers operate on each piece of the XML document sequentially while the DOM operates on the document as a whole.
The quantity of memory that a SAX parser must use in order to function is typically much smaller than that of a DOM parser.
DOM parsers must have the entire tree in memory before any processing can begin, so the amount of memory used by a DOM parser depends entirely on the size of the input data. The memory footprint of a SAX parser, by contrast, is based only on the maximum depth of the XML file (the maximum depth of the XML tree) and the maximum data stored in XML attributes on a single XML element
JDOM
The JDOM is open source Java API for manipulating XML files within Java Program.
it allow writing Java programs that can read, manipulate and output XML data
The JDOM API is faster than DOM API and it simplifies the interaction with the XML.
JDOM’s provide XPath support.
StAX
goal of the StAX API is to give “parsing control to the programmer by exposing a simple iterator based API
Namespace
When a namespace is defined for an element, all child elements with the same prefix are associated with the same namespace.
Defining a default namespace for an element saves us from using prefixes in all the child elements. It has the following syntax:
<root
xmlns:h=”http://www.w3.org/TR/html4/”
xmlns:f=”http://www.w3schools.com/furniture”>
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
CDATA
All text in an XML document will be parsed by the parser.
But text inside a CDATA section will be ignored by the parser.
service contract
= data contract + operational contract
data contract will define the messages going in and out of the service.
operational contract will define the operations that our service will perform.
WSDL file contains both:-
1) contains an embedded xsd file that defines data contract.
2) The rest of he WSDL file defines the opeartional contract,including one or more <wsdl:operation> elements within the <wsdl:binding> element
XPath
is used for identifying or extracting parts of an XML structure.
You could say that XPath is to XML what SQL is to relation database.
Leadership
Put courage first
Be mentally tough
Decline yourself
Value your character
Project confidence
It is not work that kills men, it is worry. Work is healthy; you can hardly put more on a man than he can bear. But worry is rust upon the blade. It is not movement that destroys the machinery, but friction. ~ Henry Ward Beecher
Design Pattern
Adapter Pattern:-
Converts the interface of the class to another one that client expects.
eg: Converting a Turkey into a Duck.
we wrap Turkey into a TurkeyAdapter and send the adapter to the client.
Client has a Target Interface,
Adapter implements Target Interface and has a Adaptee.
Two types of adapter:-
1. object adapter
2. class adapter
1. Object Adapter:- is what we read so far.
2. Class Adapter:- Require multiple inheritance by sub-classing both target and adaptee.
Difference between Object and Class Adapter:-
Object Adapter, based on composition, can adapt the adaptee or any of its sub class.
Class Adapter, can override behavior
Real world adapter example:-
Adapting an Enumeration to an Iterator.
Bridge Pattern
Use Bridge Pattern to vary not only your implementations, but your abstractions.
example:- Universal remote and controller and various TV implementation.
Both TV remote and TV implementation.
Decorator Pattern
Inheritance: behavior is set statically at compile time.
All sub class inherit the same behavior.
Composition: dynamically composing objects, we can add functionality in the new code, rather than altering existing code.
Design Principal: Classes should be open for extension but closed for modification.
Definition: Decorator pattern attaches additional responsibility to an object dynamically. It provides a flexible alternative to sub classing for extending the functionality.
Component is the base class, eg Beverage
Concrete component & Decorator, both extends Component, eg. Expresso & CondimentDecorator (for type matching, not for inheriting behavior.
We acquire behavior by composing objects together.
With composition, we can mix and match behavior as we want.)
Decorator also has a Component eg. Condiment also has a Beverage.
Concerete Decorators extend Decorator, eg. Milk & Soya extend Condiment.
Similar objects doing similar operations, abstract class Beverage, abstract method cost(), requirement is to call cost method on some object in hierarchy dynamically is a candidate for such pattern
Requirement:
Write code as per abstract component, writing to concrete will brake decorator.
Cost in implementing decorator:
Many small classes
Following type is necessary
Increase code complexity that factory pattern can help to reduce.
Adapter is used to match with the client requirement for an adaptee, while facade is used to simplify the interface
The facade pattern provide a unified interface to a set of interfaces. It defines a higher level of interface that make the subsystem easy to use.
Design principle : principle of least knowledge, talk only to your immediate friends.
Flyweight: one single instance of a class can be used to provide many virtual instances, in this way you are able to flw away the memory weight of creation of multiple instance
Its Approach is to collect the state of many object and rather centralize the state at one location and form virtual objects out of one object.
It is used when class has many state and can be controlled identically.
Single logical instance of a class can not behave independently from other
Example : large tree plantation project
Proxy pattern provides a surrogate or placeholder for another object to control access to.
Another object, which may be remote, expensive to create or in the need of securing.
Both RealSubject and the Proxy implement Subject interface.
This allows any client to treat the proxy just like the real subject.
Proxy keep the reference to the real object, so it can forward the requests to the subject when necessary. it also often instantiate or handles the creation of the realsubject
Realsubject is usually the object the does most of the work.
Composite pattern: allows to compose objects into tree structure to represent part-whole hierarchies.
It let client treat individual & composition of objects uniformly.
We can apply same operations over both composite & individual object.
Eg: menu & sub menu
Client has a component, which is extended by leaf & composite. Composite contains component ( recursive )
Servlets – Question Answer way!
Q. What is Container ?
A. Servlets dint have a main() method. They are under control of another Java application called a “Container”.
Example of a Container is Tomcat.
Example of a web server is Apache.
Container provides:-
1. Communication Support: provide easy way for servlet to talk to your web server.
2. Lifecycle Management: of servlet
3. Multithreading support: a new java thread is create to handle each servlet request.
4. Declarative security: via xml configuration.
5. JSP Support: converting JSP to real java code.
Q. Explain Life-cycle of a servlet
A.1 Container Load class
2. Instantiate Servlet (Invoke its default constructor)
2.A Load ServletConfig
2.B Load ServletContext
3. Call init() -> which may contain, getting a DB Connection.
4. service(), which eventually generate a thread to process each request and subsequently call doGet() & doPost()
5. destroy()
!Note
When you have multiple parameter values for a single parameter, you need getPatameterValues() that returns an array instead of getParameter()
Q. Beside parameter, what can I get from request object?
A. request.getHeader(“User-Agent”); -> Get request header
request.getCookies();
request.getSession();
request.getMethod();
request.getInputStream(); -> get all raw request information.
Q. Important method to call on response
A. setContentType()
getWriter()
getOutputStream()
Q. Difference between forward and sendRedirect
A.1 forward (page 89)
- Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved.
- The original request and response objects are transfered along with additional parameters if needed.
RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);
view.forward(request, response);
A.2 sendRedirect (page 136)
if (workforme)
{
//hadel request
}else {
response.sendRedirect(“http://www.oreilly.com”);
}
Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.
For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward cannot do this.
‘session’ is not lost in both forward and redirect.
To feel the difference between forward and sendRedirect visually see the address bar of your browser,
in forward, you will not see the forwarded address (since the browser is not involved)
in redirect, you can see the redirected address.
You can call sendRedirect() after response is already written. ->IlligalStateException.
Attributes are not parameters!
3 Attribute types:-
1. Application/context
2. Request
3. Session
1. Application/context
getServletContext().set/getAttribute(“”,”");
They are not thread safe. to make it thread safe, we need to lock servletContext as below:-
Synchronized (getServletContext()) {}
2. Session
requirest.getSession().get/setAttribute(“”,”");
Multiple request from same session, say multiple browser window
Lock on session
Synchronized (session){}
Implementing SingleThreadModel interface is also not a solution , it is as good as synchronizing service method.
Also result in poor performance.
3. Request
Only request attribute and local variable are thread safe
Use when some other component of the app take over all or part of the request via
RequestDispatcher.
By two of its method forward() & include() ()
Get RD from request or servletContext(/ is must, root of application, not relative to current request)
Session
If http uses state less connection so how container keep track of the user session ?
On first request , container generate a unique session Id to send with the response & client keep sending it for each subsequent request.
This happen via cookie maintained by the container.
What if client has cookies disabled on his browser ?
URL re-writing happen automatically if cookies not supported, we only need to call response.encodeUrl()
Invalidate the session if not active
Now! JSP
Page directives:-
@
scriptlet
%%
expression
=
s and e land up in service method
Declaration
!
Added to class outside of the service method, it can be variable declaration or method.
Implicit objects :-
out JspWriter
session HttpSession
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
exception JspException
pageContext PageContext
page Object
Comments
HTML !
Jsp %%
Core Java Question Answers
Static members:-
- Certain member should only belong to class, and not be part of any object created from the class.
- Static member is initialized when a class is loaded at run time.
- Java enforce a rule that at the most, one class in a java file has public accessibility.
- A Class is compiled to Java byte code.
- Reserved literals in Java: null, true, false
- int i = 010; system.out.println(“i = ” + i); Output => 8
- Integral type: int 16 0, long 32 0L, byte 8 0, short 16 0, unsigned char 16 ‘\u0000′
- Float type: float 23; double 64
- Boolean type: boolean, default is false.
- Reference type are default to null
- Initialization of primitive variable are checked at compile time
- public static void main(String args[]) throws Exception works
- public : so that it is accessible to jvm
- static : so that class object is not needed to call it.
- if void or static not present, we get run time error “Exception in thread “main” java.lang.NoSuchMethodError: main”
- We need casting when narrowing down in the hierarchic
Arithmetic
- Integer Arithmetic always return a value which is in the range, other than divide by zero which gives Arithmetic Exception.
- Floating point Arithmetic can result in value that are out of range
- When divide by zero, Infinity and -Infinity; 0.0F and -0.0F, NaN(0.0/0,0)
- Primitive: Values are copied.
- Object Reference: Can only change the state not the value (can not change to null … hence always call by value)
- Passing array reference is same as Object reference passing
Static
- Static code can not access non static members by there simple name
- static code is not executed in the context of an object, hence this and supper are not available.
- To put class files in package directory
- javac -d . MainTests.
- Can not be instantiated
- must be abstract if it has one+ abstract method
- Sub class not implementing abstract from supper, must also be abstract
- just specify method prototype and implicitly abstract.
- abstract interface abc, -> Redundent
- can not be extended
- class whose definition is complete
- primitive final variable can not change its value once initialized
- reference type final variable once initialized can not change its reference, but can change the state of the object it refers.
- Only an instance method can be declared as abstract
- Static method can not be overridden, declaring an abstract static method make no sense.
- MainTests.java:4: illegal combination of modifiers: abstract and static
- method specified in an interface is implicitly abstract
- Implementation is defined in other language
- such field will not be stored to persistent storage when object will be stored.
- Static are by default transient.
- stop compiler from optimizing the field by caching its value, preventing unpredictable results when retrieving the value in a multi-threaded environment.
- one default label
- all labels after the matched label are executed until u add break statement
- All exception are derived from java.lang.Throwable
- getMessage(), printStackTrace() are two method in it

- New exception usually extends Exception or one of its checked sub-classes, there by making the new exception as checked exception.
- after a catch block is executed, control is transferred to finally block as long as one is present, regardless of whether the catch block itself throws an exception.
- compiler complains if a super class shadows sub class exception catch block.
- say, if finally block throes an exception, the new exception overrules any previous exception
- return or break from finally block will determine further control flow, irrespective of how try block or any catch block were executed… it will
- if no catch block handle the exception, exception are handled by default exception handler.
- a program can throw an exception using “throw” statement
- throw <object of type Throwable class>, when<> null throw null pointer
- checked exception thrown by method are part of throws clause in method prototype
- sub class can be thrown once supper class is in throws clause (bad prog style).
- method overriding can specify a subset of checked exception in throws clause, because client may be ill prepared for newly added checked exception.
- Private, override, hidden members are not inherited (they cant be accessed in base class without supper keyword)
- constructor & initializer blocks are not member of a class, they are not inherited
- Down-casting require type-casting.
- non static method only
- same signature: method name, parameter list in order & same return type
- parameter being final is at discretion of sub class.
- Accessibility can not be narrow
- throws can not be widen
- static method can not be overridden in sub class – compiler error, however can be hidden
- final method can not be overridden – compiler error
- private method can not be overridden, however can be as exactly same prototype in sub class.
- all above no override cases, early binding is done!
- sub class can not override field, it can hide field
- use super to access super class fields including the ones hidden in sub class
- static fields of supper class can also be hidden
- only name has to be same to be hidden, rest all is ok!
- unlike this, it can not cast to other references or cast to other references type.
- super.super .. not allowed
- typecasting the “this” only changes its type, but its reference remains the same.
- chaining by this(), this() being the first statement in constructor.
- super() constructor call must be the fist statement in sub class constructor
- super() and this() can not be used together in a constructor.
- if no explicit call to super(), default super() call is inserted implicitly.
- in such case, if super dont have default constructor, compiler error occur.
- sub interface extends base interface
- all member variable are public static final and hence initialization is must.
- all method/class/interface declaration are public and abstract.
- class implementing interface method, have to keep method as public
- class can not narrow access and can not broaden throws exception
- One interface can extend several interfaces (supper interfaces)
- one nested interface
- static member interfaces
- Four categories of nested classes
- static member class
- non static member class
- local classes
- anonymous classes
- last three classes are called inner classes.
- instance of an inner class may be associated with (iei) immediately enclosing instance.
- instance of an inner class can also access members of iei by there simple name.
- static member class can be instantiated as any top level class using its full name.
- no iei is required.
- interface are only at top level or static member, nothing else!
- instance of a non static member can be defined like other member of a class, such class always have iei instance associated with it.
- local classes are defined just as local member variable.
- Anonymous class can be defined as expressions and instantiated on the fly.
- A nested class can not have the same name as any of its enclosing classes.
- Top level class can only be public or default.
- Any object not accessible by a live thread is candidate for GC.
- gc can be facilitated by nullifying the reference.
- Program can request garbage collection, but no way it can be forced. GC call is not guaranteed so is finalizer call.
- finalizer:- from the Object class, protected void finalize() throws Throable{super.finalize();} get called before the object get gc.
- System.gc(); -> request GC
- System.runFunalizer(); -> request to run any pending
Access Specifiers:- Modifier | Class | Package | Subclass | World public | Y | Y | Y | Y protected | Y | Y | Y | N no modifier | Y | Y | N | N private | Y | N | N | N
Collection Framework – Question Answer way!
Q. What is collection framework ?
A. The collection framework presents a set of standard utility classes for manging group of objects.
Arbitrary objects can be stored, retrieved and manipulated as elements of collection.
Q. Which package has collection framework ?
this framework is provided in java.util package
Q. What is Mathamatical concept of a set?
A. A set is just a group of unique items, meaning that the group contains no duplicates.
Some real-world examples of sets include the following:
- The set of uppercase letters ‘A’ through ‘Z’
- The set of nonnegative integers {0, 1, 2 …}
These examples show the basic properties of sets:
- Sets contains only one instance of each item
- Sets may be finite or infinite
- Sets can define abstract concepts
- The map of IP addresses to domain names (DNS)
- A map from keys to database records
- A dictionary (words mapped to meanings)
- The conversion from base 2 to base 10
Map is to provide access to values stored by keys. The set of collection operations are all there, but you work with a key-value pair, instead of an isolated element. Map is therefore designed to support the basic operations of get() and put() which are not required by Set.- The
Collectioninterface is a group of objects, with duplicates allowed SetextendsCollectionbut forbids duplicatesListextendsCollectionalso, allows duplicates and introduces positional indexing (order of element is retained)Mapextends neitherSetnorCollection
| Interface | Implementation | Historical | |||
| Set(.) no duplicate(.)at most one null | HashSet(.) No OrderHashing: Constant time for add, remove, contain, size
Key->Hashcode->Index (.) no guaranty of order |
TreeSet(.) Sorted
Assenting (.) Use tree for storage (.) large data, sorted order, found quickly Comparator |
LinkedHashSet(.) Insertion Order | ||
| List(.)allow duplicate(.)Positional indexing(.) Insertion Order | ArrayList(.)notSynchronized(.)Random Access
(.)Easy Tail manipulation (.)default size 0. |
LinkedList(.)Sequential Access(.)Add Remove Element in between | Vector Stack(.)synchronized, make it slow(.) default size 10Then double |
||
| Map(.)Unique Key | HashMap(.)Allow Null as key & value(.)unsynchronized(.)no order
(.) get/put constant time for larger map |
TreeMap(.) Sorted in Key order(.)Natural ordering
Comparator |
LinkeHashMap(.) Key insertion order. | Hashtable Properties(.)synchronized(.)can only store object the override hashCode() and equals() Sting does. |
|
Collection Interface
The Collection interface is used to represent any group of objects, or elements. You use the interface when you wish to work with a group of elements in as general a manner as possible.

HashSet need to implement the hashCode() method in a manner that properly distributes the hash codes. While most system classes override the default hashCode() implementation in Object, when creating your own classes to add to a HashSet remember to override hashCode()TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. In order to work property, elements added to a TreeSet must be sortable.To optimize HashSet space usage, you can tune the initial capacity and load factor. The TreeSet has no tuning options, as the tree is always balanced, ensuring log(n) performance for insertions, deletions, and queries.
!Note: All Collection concrete classes implements Cloneable & Serializable interface.
Q. Can an implementation of collection be changed ?
Each of the implementation of Collection interface provides a constructor for creating a collection based on elements of another Collection object passed as an argument. This interchangeability is true among Map implementation as well.
But Collection and Maps are not interchangeable.
Below example demonstrate use of HashSet, TreeSet and the way HashSet can be interchanged to TreeSet.
public class SetExample {
public static void main(String args[]) {
Set set = new HashSet();
set.add("Bernadine");
set.add("Elizabeth");
set.add("Gene");
set.add("Elizabeth");
set.add("Clara");
System.out.println(set);
Set sortedSet = new TreeSet(set);
System.out.println(sortedSet);
}
}
Running the program produces the following output. Notice that the duplicate entry is only present once, and the second list output is sorted.
[Gene, Clara, Bernadine, Elizabeth]
[Bernadine, Clara, Elizabeth, Gene]
Q. What does AbstractSet class overrides?
A.The AbstractSet class overrides the equals() and hashCode() methods to ensure two equal sets return the same hash code. Two sets are equal if they are the same size and contain the same elements. By definition, the hash code for a set is the sum of the hash codes for the elements of the set. Thus, no matter what the internal ordering of the sets, two equal sets will report the same hash code.
Q. How List is different from Set ?
A. List is an
Ordered collection
Permitting Duplicates
Ability to work with part of the list
Bidirectional Iterattion
Q. When to use LinkedList & when ArrayList?
ArrayList: If you need to support random access, without inserting or removing elements from any place other than the end, than ArrayList offers the optimal collection
LinkedList: you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially then LinkedList offers the better implementation
!Note: Two List are equal if they are the same size and contain the same elements in the same order.
Q. How can we determine the length of an ArrayList ?
A. a.size();
Q. What is Map.Entity?
A. The entrySet() method of Map returns a collection of objects that implement Map.Entry interface. Each object in the collection is a specific key-value pair in the underlying Map.
!Note : Both the key and value can be null. However, you should not add a Map to itself as a key or value.
Q. Difference between HashMap & TreeMap ?
A. HashMap: Deleting, and locating elements in a Map, the HashMap offers the best alternative
TreeMap: You need to traverse the keys in a sorted order, then TreeMap is your better alternative.
Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal. Using a HashMap requires that the class of key added have a well-defined hashCode() implementation. With the TreeMap implementation, elements added to the map must be sortable.
To optimize HashMap space usage, you can tune the initial capacity and load factor. The TreeMap has no tuning options, as the tree is always balanced.
!Note: Similar to the other abstract collection implementations, the AbstractMap class overrides the equals() and hashCode() methods to ensure two equal maps return the same hash code. Two maps are equal if they are the same size, contain the same keys, and each key maps to the same value in both maps. By definition, the hash code for a map is the sum of the hash codes for the elements of the map, where each element is an implementation of the Map.Entry interface. Thus, no matter what the internal ordering of the maps, two equal maps will report the same hash code.
Q. What is Comparator?
A. Defines how two objects are compared.
Q. What is Autoboxing and Unboxing
A. As Collection can not store primitives. Java perform the proper Autoboxing and Unboxing needed when storing or retrieving primitive types.
Q. Collection extends Iterable interface
A. Means can be cycled using for each type for loop.
Q.
Synchronization – The Question Answer way!
Q. What is the difference between Synchronization Method & Synchronization Block.
They can be differentiated on two basis:-
1) The nature of lock:-
Synchronized method of an object is synchronized on the lock of the object or class (static synchronized method) of the method, while
Synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.
2) Granularity of lock:-
Synchronization Block mechanism allows fine-grained synchronization, while
Synchronized method are to be used when a method can manipulate the state of the object in ways that can corrupt the state if executed concurrently.
Q. What are Locks ?
A. Lock is used to synchronize access to shared resources
A thread gain access to a shared resource by first acquiring the lock associated with the resource
A lock thus implements mutual exclusion
All objects have a lock, only one thread at a time can access the shared resource guarded by the lock.
Q. Number of ways access of the resource can be synchronized ?
There are two ways in which access of the resource can be syncronized
a. Synchronized method
b. Synchronized block
a. Synchronized method:-
A thread wish to execute synchronized method must first obtain the OBJECTS LOCK before it can enter the object to execute the method.
In other words, Synchronized method of an object is synchronized on the lock of the object
Q. How is lock of the object achieved ?
A. This is simply achieved Lock is by calling the method, if the object’s lock is acquired by some other thread, the calling thread waits.
Q. When to Use synchronized method ?
Synchronized method are to be used when a method can manipulate the state of the object in ways that can corrupt the state if executed concurrently.
Example:- Stack Push & Pop methods. When one thread is pushing other thread can not pop.
When one thread is executing the synchronized method of an object, all other threads that wish to execute this or any other sync. method have to wait.
This does not applies to thread that already has the lock, such a method can call other sync. method without being blocked.
Important Note:-
Q. How Static method are synchronized ?
Static method synchronize on the class lock.
Also, synchronization of static method in a class is independent from the synchronization of instance method of the class.
Q. A synchronized method, when overridden in sub class, what happens to its synchronized quality ?
A sub class decides whether the new definition of an inherited synchronized method will remain synchronized in the subclass.
b. Synchronized block
Synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.
synchronized (<object reference expression>) {<Code block>}
“object reference expression” must evaluate to a non null reference value, else a null pointer exception is thrown
The code block is usually related to the object on which synchronization is done.
example:- synchronized (this) {}
Once the thread had entered the code block, no other thread will be able to execute the code block, or any other code requiring the same object lock.
This mechanism allows fine-grained synchronization of code on arbitrary object.
Q. Synchronization Block, are all part of the sytex mandatory?
“synchronized (<object reference expression>) {<Code block>}”
Object specification & {} are mandatory even if we have a single line of code.
Q. An inner object might need to synchronize on its associated outer object, how is it achievable ?
class Outer{
private double myPi;
protected class inner{
public void setPi(){
synchronized void setPi(Outer.this){
myPi = Math.PI;
}
}
}
}
Q. Can Synchronized block be specified on class lock ?
Yes, by:-
synchronized (<class name>.class) {<code block>}
A static synchronized method of class A is equivalent to
static void classAction(){
synchronized (A.class) {
…
}
}
Q. In how many ways a thread can hold a lock on an object ?
1) By executing a member synchronized method, object lock.
2) By executing a static synchronized method, class lock.
3) By executing a synchronized block, lock on an object or class.
What is “System”, “out”, “println” in System.out.println ? Explain !
System is a built-in class present in java.lang package.
This class has a final modifier, which means that, it cannot be inherited by other classes.
It contains pre-defined methods and fields, which provides facilities like standard input, output, etc.
out is a static final field (ie, variable)in System class which is of the type PrintStream (a built-in class, contains methods to print the different data values).
static fields and methods must be accessed by using the class name, so ( System.out ).
out here denotes the reference variable of the type PrintStream class.
println() is a public method in PrintStream class to print the data values.
Hence to access a method in PrintStream class, we use out.println() (as non static methods and fields can only be accessed by using the refrence varialble)
System.out.println();
eg:
int i = 3;
System.out.println(i);
the above code prints the value of 3 in the screen and brings the control to the next line.
Demo Program:-
class SystemTester
{
public static void main(String[] args)
{
int i = 3;
System.out.println(i);
System.out.println(System.currentTimeMillis());
//Return the current time in terms of milliseconds.
System.out.println(System.getProperty("user.dir"));
}
}
Output:-
E:\Java\Examples>java SystemTester
3
1306662087283
E:\Java\Examples
Programming with JBoss Seam, using eclipse
Seam is an application framework for Java EE 5.
The best thing to start programming in seam is by going through the examples bundled with the seam distribution from http://labs.jboss.com/jbossseam/download/index.html, any thing else to start of will be second best for sure, I tried two books but non could give me a jump start like the start given by the seam examples.
Here I would also like to give you some comments about the two books I have gon through so that I could support you in making a choice of book for learning ahead after this post.
1) Apress.Beginning.JBoss.Seam.Feb.2007
Is a beginners book and assume that you have very little knowledge of EJBs and starts from scratch. the book clearly shows how easy and fast it is to program in JBoss Seam by comparing the way we program in struts with jboss for the same problem at hand.
2) Prentice.Hall.JBoss.Seam.Simplicity.and.Power.Beyond.Java.EE.Apr.2007
this book is not a beginners book but an intermediate one, the book is a comprehensive guide on Seam.
Let’s start Learning
Here we will cover one of the seam example application to understand how easy it is to develop application in JBoss Seam, various features of JBoss seam has been covered in my previous post titled “Features of JBoss Seam”.
Here we will also cover the way we can run the same examples using eclipse IDE and use the examples as template for our custom application development.
before starting with the example, lets have a quick look where seam sits in an enterprise application.
Seam does the role of a Context Management and JSF serving as a Request Controller, while in the presentation tier we have the option to use any of the three, JSP, Facelets and Portal and similarly for the State Management we can use EJB3, JBossjBPM or Hibernate.
It turns out that the combination of Seam, JSF and EJB3 is the simplest way to write a complex web application in Java. You won’t believe how little code is required!
Before starting the example please follow the steps in my earlier post “Install and configure JBoss Seam” for performing the necessary setup for running JBoss Seam application.
“Registration Example”
The registration example is a fairly trivial application that lets a new user store his username, real name and password in the database. The example isn’t intended to show off all of the cool functionality of Seam. However, it demonstrates the use of an EJB3 session bean as a JSF action listener, and basic configuration of Seam.
Following is the registration screen of the application
Understanding the structure of application.
The application is implemented using two JSP pages, one entity bean and one stateless session bean.
Let’s take a look at the code, starting from the “bottom”.
The entity bean: User.java
This class serve two purposes
1) define persistence
2) and validation declaratively, via anotations
The code of this class is as follows, please find my comments with code as the explanation of the code with “->” mark
@Entity // -> indicates that the User class is an entity bean
@Name(“user”) // -> Seam components requre a component name provided by @Name anotations
@Scope(SESSION) // -> User bean is a session scope component.
@Table(name=”users”) // -> Persistence: User class is mapped to user table.
public class User implements Serializable {
private static final long serialVersionUID = 1881413500711441951L;
// -> name, password and username are the persistent attributes of the entity bean
private String username; (5)
private String password;
private String name;
public User(String name, String password, String username) {
this.name = name;
this.password = password;
this.username = username;
}
public User() {} (6)
// -> The @NotNull and @Lengthannotations are part of the Hibernate Validator framework
@NotNull @Length(min=5, max=15) (7)
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
@NotNull
public String getName() { return name; }
public void setName(String name) { this.name = name; }
// -> EJB standard @Id annotation indicates primary key attribute of entity bean.
@Id @NotNull @Length(min=5, max=15) (8)
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
}
Properties of our Userclass are bound to directly to JSF components and are populated by JSF during the update model values phase.
Now we will have a look at the state less session bean class RegisterAction.java which defines the action listner method.
RegisterAction.java
@Stateless // -> stateless session bean.@Name(“register”)public class RegisterAction implements Register{
@In // -> marks an attribute injected by Seam, In this case, the attribute is injected
// from a context variable named user private User user; @PersistenceContext // -> used to inject the EJB3 entity manager. private EntityManager em; @Logger // -> used to inject the component’s Log instance private Log log;public String register() (5)
{
List existing = em.createQuery(
“select username from User where username=#{user.username}”) (6)
.getResultList();
if (existing.size()==0)
{
em.persist(user);
log.info(“Registered new user #{user.username}”); (7)
return “/registered.jsp”; (8)
}
else
{
FacesMessages.instance().add(“User #{user.username} already exists”); (9)
return null;
}
}
}
Note that:
1) The LogAPI lets us easily display templated log messages.
2) JSF action listener methods return a string-valued outcome that determines what page will be displayed next. A null outcome (or a void action listener method) redisplays the previous page. In plain JSF, it is normal to always use a JSF navigation ruleto determine the JSF view id from the outcome. For complex application this indirection is useful and a good practice. However, for very simple examples like this one, Seam lets you use the JSF view id as the outcome, eliminating the requirement for a navigation rule. Note that when you use a view id as an outcome, Seam always performs a browser redirect.
3) Seam provides a number of built-in components to help solve common problems.
The FacesMessagescomponent makes it easy to display templated error or success messages. Built-in Seam components may be obtained by injection, or by calling an instance() method.
The session bean local interface:
Register.java
@Local public interface Register { public String register(); }
That’s the end of the Java code.
Now we will cover some of the deployment descriptors as most of the deployment files have common code among various applications.
1) components.xml
<components xmlns=”http://jboss.com/products/seam/components”
xmlns:core=”http://jboss.com/products/seam/core”>
<core:init jndi-pattern=”@jndiPattern@”/>
</components>
This code configures a property named jndiPattern of a built-in Seam component named org.jboss.seam.core.init.
2) web.xml
This web.xmlfile configures Seam and MyFaces
3) faces-config.xml
The faces-config.xmlfile integrates Seam into JSF
In fact, once you have all the basic descriptors set up, the onlyXML you need to write as you add new functionality to a Seam application is the navigation rules, and possibly jBPM process definitions. Seam takes the view that process flow and configuration data are the only things that truly belong in XML.
In this simple example, we don’t even need a navigation rule, since we decided to embed the view id in our action code.
4) ejb-jar.xml
The ejb-jar.xml file integrates Seam with EJB3, by attaching the SeamInterceptor to all session beans in the archive.
5) persistence.xml
The persistence.xmlfile tells the EJB persistence provider where to find the datasource
The view files
1) register.jsp
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %>
<%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %>
<%@ taglib uri=”http://jboss.com/products/seam/taglib” prefix=”s” %>
<html>
<head>
<title>Register New User</title>
</head>
<body>
<f:view>
<h:form>
<table border=”0″>
<s:validateAll>
<tr>
<td>Username</td>
<td><h:inputText value=”#{user.username}”/></td>
</tr>
<tr>
<td>Real Name</td>
<td><h:inputText value=”#{user.name}”/></td>
</tr>
<tr>
<td>Password</td>
<td><h:inputSecret value=”#{user.password}”/></td>
</tr>
</s:validateAll>
</table>
<h:messages/>
<h:commandButton type=”submit” value=”Register” action=”#{register.register}”/>
</h:form>
</f:view>
</body>
</html>
The only thing here that is specific to Seam is the <s:validateAll>tag. This JSF component tells JSF to validate all the contained input fields against the Hibernate Validator annotations specified on the entity bean.
2) registered.jsp
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %>
<%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %>
<html>
<head>
<title>Successfully Registered New User</title>
</head>
<body>
<f:view>
Welcome, <h:outputText value=”#{user.name}”/>,
you are successfully registered as <h:outputText value=”#{user.username}”/>.
</f:view>
</body>
</html>
How it works
When the form is submitted, JSF asks Seam to resolve the variable named user. Since there is no value already bound to that name (in any Seam context), Seam instantiates the user component, and returns the resulting Userentity bean instance to JSF after storing it in the Seam session context.
The form input values are now validated against the Hibernate Validator constraints specified on the Userentity. If the constraints are violated, JSF redisplays the page. Otherwise, JSF binds the form input values to properties of the User entity bean.
Next, JSF asks Seam to resolve the variable named register. Seam finds the RegisterActionstateless session bean in the stateless context and returns it. JSF invokes the register() action listener method.
Seam intercepts the method call and injects the User entity from the Seam session context, before continuing the invocation.
The register()method checks if a user with the entered username already exists. If so, an error message is queued with the FacesMessages component, and a null outcome is returned, causing a page redisplay. The FacesMessagescomponent interpolates the JSF expression embedded in the message string and adds a JSF FacesMessage to the view.
If no user with that username exists, the "/registered.jsp" outcome triggers a browser redirect to the registered.jsppage. When JSF comes to render the page, it asks Seam to resolve the variable named user and uses property values of the returned User entity from Seam’s session scope.
To run the example from eclipse
Step 1) In eclipse create a new java project with existing source code and give the name of the project as “registration”, browse to pint the directory where the “registration” example source code is unziped, then click on finish.
Step 2) add
testng.jar
myfaces-all.jar
jsf-api.jar
jboss-seam.jar
jboss-ejb3-all.jar
jboss-4.2.1.GA.jar
hibernate-all.jar
ejb3-persistence.jar
to your classpath.
Step 3) Right click build.xml of the registration project and select Run As – > Ant Build
Step 4) (make sure you have jboss server add before doing this step)
Select the “registration project” tree node from the navigator window to select “Debug As” -> “Open Debug Dialog” -> “Debug” to start the server in debug mode.
Step 5) open the browser window and type http://localhost:8080/seam-registration to start the “registration application”.





