Threads can be created by extending Thread and overriding the
public void run() method.
q Thread objects can also be created by calling the Thread constructor that
takes a Runnable argument. The Runnable object is said to be the target of
the thread.
q You can call start() on a Thread object only once. If start() is called
more than once on a Thread object, it will throw a RuntimeException.
q It is legal to create many Thread objects using the same Runnable object as
the target.
q When a Thread object is created, it does not become a thread of execution
until its start() method is invoked. When a Thread object exists but hasn't
been started, it is in the new state and is not considered alive.
Transitioning Between Thread States (Objective 4.2)
q Once a new thread is started, it will always enter the runnable state.
q The thread scheduler can move a thread back and forth between the
runnable state and the running state.
q For a typical single-processor machine, only one thread can be running at a
time, although many threads may be in the runnable state.
q There is no guarantee that the order in which threads were started
determines the order in which they'll run.
q There's no guarantee that threads will take turns in any fair way. It's up
to the thread scheduler, as determined by the particular virtual machine
implementation. If you want a guarantee that your threads will take turns
regardless of the underlying JVM, you can use the sleep() method. This
prevents one thread from hogging the running process while another thread
starves. (In most cases, though, yield() works well enough to encourage
your threads to play together nicely.)
q A running thread may enter a blocked/waiting state by a wait(), sleep(),
or join() call.
3
q A running thread may enter a blocked/waiting state because it can't acquire
the lock for a synchronized block of code.
q When the sleep or wait is over, or an object's lock becomes available, the
thread can only reenter the runnable state. It will go directly from waiting to
running (well, for all practical purposes anyway).
q A dead thread cannot be started again.
Sleep, Yield, and Join (Objective 4.2)
q Sleeping is used to delay execution for a period of time, and no locks are
released when a thread goes to sleep.
q A sleeping thread is guaranteed to sleep for at least the time specified in
the argument to the sleep() method (unless it's interrupted), but there is
no guarantee as to when the newly awakened thread will actually return to
running.
q The sleep() method is a static method that sleeps the currently executing
thread's state. One thread cannot tell another thread to sleep.
q The setPriority() method is used on Thread objects to give threads
a priority of between 1 (low) and 10 (high), although priorities are not
guaranteed, and not all JVMs recognize 10 distinct priority levels—some
levels may be treated as effectively equal.
q If not explicitly set, a thread's priority will have the same priority as the
priority of the thread that created it.
q The yield() method may cause a running thread to back out if there are
runnable threads of the same priority. There is no guarantee that this will
happen, and there is no guarantee that when the thread backs out there
will be a different thread selected to run. A thread might yield and then
immediately reenter the running state.
q The closest thing to a guarantee is that at any given time, when a thread
is running it will usually not have a lower priority than any thread in the
runnable state. If a low-priority thread is running when a high-priority thread
enters runnable, the JVM will usually preempt the running low-priority
thread and put the high-priority thread in.
q When one thread calls the join() method of another thread, the currently
running thread will wait until the thread it joins with has completed. Think
of the join() method as saying, "Hey thread, I want to join on to the end
of you. Let me know when you're done, so I can enter the runnable state."
Two-Minute Drill 731
732 Chapter 9: Threads
Concurrent Access Problems and Synchronized Threads (Obj. 4.3)
q synchronized methods prevent more than one thread from accessing an
object's critical method code simultaneously.
q You can use the synchronized keyword as a method modifier, or to start a
synchronized block of code.
q To synchronize a block of code (in other words, a scope smaller than the
whole method), you must specify an argument that is the object whose lock
you want to synchronize on.
q While only one thread can be accessing synchronized code of a particular
instance, multiple threads can still access the same object's unsynchronized code.
q When a thread goes to sleep, its locks will be unavailable to other threads.
q static methods can be synchronized, using the lock from the
java.lang.Class instance representing that class.
Communicating with Objects by Waiting and Notifying (Obj. 4.4)
q The wait() method lets a thread say, "there's nothing for me to do now, so
put me in your waiting pool and notify me when something happens that I
care about." Basically, a wait() call means "wait me in your pool," or "add
me to your waiting list."
q The notify() method is used to send a signal to one and only one of the
threads that are waiting in that same object's waiting pool.
q The notify() method can NOT specify which waiting thread to notify.
q The method notifyAll() works in the same way as notify(), only it sends
the signal to all of the threads waiting on the object.
q All three methods—wait(), notify(), and notifyAll()—must be
called from within a synchronized context! A thread invokes wait() or
notify() on a particular object, and the thread must currently hold the lock
on that object.
Deadlocked Threads (Objective 4.4)
q Deadlocking is when thread execution grinds to a halt because the code is
waiting for locks to be removed from objects.
q Deadlocking can occur when a locked object attempts to access another
locked object that is trying to access the first locked object. In other words,
both threads are waiting for each other's locks to be released; therefore, the
locks will never be released!
q Deadlocking is bad. Don't do it.
Saturday, December 12, 2009
Tuesday, December 8, 2009
SCJP 5.0 Syllabus
Objectives
Section 1: Declarations, Initialization and Scoping
· Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).
· Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.
· Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
· Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.
· Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.
Section 2: Flow Control
· Develop code that implements an if or switch statement; and identify legal argument types for these statements.
· Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.
· Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.
· Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.
· Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.
· Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.
Section 3: API Contents
· Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
· Given a scenario involving navigating file systems, reading from files, or writing to files, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader,BufferedWriter, File, FileReader, FileWriter and PrintWriter.
· Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
· Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.
Section 4: Concurrency
· Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
· Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
· Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.
Section 5: OO Concepts
· Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
· Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
· Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
· Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass or overloaded constructors.
· Develop code that implements "is-a" and/or "has-a" relationships.
Section 6: Collections / Generics
· Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
· Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
· Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions.
· Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
· Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.
Section 7: Fundamentals
· Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
· Given an example of a class and a command-line, determine the expected runtime behavior.
· Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
· Given a code example, recognize the point at which an object becomes eligible for garbage collection, and determine what is and is not guaranteed by the garbage collection system. Recognize the behaviors of System.gc and finalization.
· Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.
· Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.
reference : http://java.sun.com/docs/books/tutorial/extra/certification/index.html
Section 1: Declarations, Initialization and Scoping
· Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).
· Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.
· Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.
· Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.
· Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class.
Section 2: Flow Control
· Develop code that implements an if or switch statement; and identify legal argument types for these statements.
· Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.
· Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.
· Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.
· Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.
· Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.
Section 3: API Contents
· Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
· Given a scenario involving navigating file systems, reading from files, or writing to files, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader,BufferedWriter, File, FileReader, FileWriter and PrintWriter.
· Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class.
· Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings.
Section 4: Concurrency
· Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
· Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another.
· Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems.
Section 5: OO Concepts
· Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits.
· Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting.
· Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods.
· Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass or overloaded constructors.
· Develop code that implements "is-a" and/or "has-a" relationships.
Section 6: Collections / Generics
· Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface.
· Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method.
· Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions.
· Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches.
· Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting.
Section 7: Fundamentals
· Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example.
· Given an example of a class and a command-line, determine the expected runtime behavior.
· Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.
· Given a code example, recognize the point at which an object becomes eligible for garbage collection, and determine what is and is not guaranteed by the garbage collection system. Recognize the behaviors of System.gc and finalization.
· Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully.
· Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.
reference : http://java.sun.com/docs/books/tutorial/extra/certification/index.html
Saturday, November 28, 2009
Design Pattern - Java
Creational Patterns
Factory Pattern :
Used to create Object Through an interface
Abstract Factory Pattern :
Create an instance of several families of subclasses, It is one more level of abstraction in Factory Pattern
Singleton Pattern :
A class produces only a single instance of its
Builder Pattern :
Prototype Pattern : A pttern to clone an fully initialised object.
Structural Patterns
Adapter Pattern :
A class which connects unrelated classes through interfaces.
Bridge Pattern :
Interface and its implementation of an object is separateed Here.
Composite Pattern :
Used to defined tree structured objects
Decorator Pattern :
Used to add an object at runtime.
Facade Pattern :
A class whic represent entire sub system
Flyweight Pattern :
Proxy Pattern :
Behavioral Patterns (behavioral pattern can alter the program's running behavior.
)
Chain of Responsibility :
Way of passing a request between a chain of objects : Example Excelption handling.
Command Pattern :
command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time
Interpreter Pattern :
Include Language Element in program
Example : "expression ::= plus | minus | variable"
Iterator Pattern :
Used to access collection of object in sequence.
Mediator Pattern :
provides a unified interface to a set of interfaces in a subsystem.
Momento Pattern :
This pattern gets the previous state of an object
Observer Pattern:
A way of notifying change to number of classes
State Pattern :
This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at runtime.
Strategy Pattern :
Encapsulates an algorithm in inside a class.
Template Pattern :
- Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
- Template Method lets subclasses redefine certain steps of an algorithm without letting them to change the algorithm's structure.
Visitor Pattern :
adds a new operation in a class with out changing the class
Factory Pattern :
Used to create Object Through an interface
Abstract Factory Pattern :
Create an instance of several families of subclasses, It is one more level of abstraction in Factory Pattern
Singleton Pattern :
A class produces only a single instance of its
Builder Pattern :
Prototype Pattern : A pttern to clone an fully initialised object.
Structural Patterns
Adapter Pattern :
A class which connects unrelated classes through interfaces.
Bridge Pattern :
Interface and its implementation of an object is separateed Here.
Composite Pattern :
Used to defined tree structured objects
Decorator Pattern :
Used to add an object at runtime.
Facade Pattern :
A class whic represent entire sub system
Flyweight Pattern :
Proxy Pattern :
Behavioral Patterns (behavioral pattern can alter the program's running behavior.
)
Chain of Responsibility :
Way of passing a request between a chain of objects : Example Excelption handling.
Command Pattern :
command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time
Interpreter Pattern :
Include Language Element in program
Example : "expression ::= plus | minus | variable"
Iterator Pattern :
Used to access collection of object in sequence.
Mediator Pattern :
provides a unified interface to a set of interfaces in a subsystem.
Momento Pattern :
This pattern gets the previous state of an object
Observer Pattern:
A way of notifying change to number of classes
State Pattern :
This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at runtime.
Strategy Pattern :
Encapsulates an algorithm in inside a class.
Template Pattern :
- Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
- Template Method lets subclasses redefine certain steps of an algorithm without letting them to change the algorithm's structure.
Visitor Pattern :
adds a new operation in a class with out changing the class
Tuesday, November 24, 2009
j2ee design pattern
----------------------------------------------------
>>>>>>>>>>>>>>>>Presentation Tier<<<<<<<<<<<<<<<<<<
---------------------------------------------------
Intercepting Filter :
A centralised control which hadles request from the web client.
--------------------------------------------------------------------------------
Front Controller :
A centralized point of contact for handling a request may be useful, for example, to control and log a user's progress through the site.
What is the difference betwenn Intercepting Filter and Front Controller.
--------------------------------------------------------------------------------
Composite View :
A Framework to present content in a single web page, from numerous data sources.
Tiles is a good example for this pattern
Alos it is good to refer this link
http://java.sun.com/blueprints/patterns/CompositeView.html
1. The client requests service
2. After processing the request, MainServlet (the Front Controller) directs the ScreenFlowManager to select the next view
3. The ScreenFlowManager determines the name of the screen to display
4. The request is forwarded to TemplateServlet
5. The TemplateServlet identifies the requested Screen object and stores it in HttpSession
6. The request is forwarded to the template JSP page
7. The template JSP page executes an insert tag
8. The insert tag retrieves the screen from HttpSession
9. The insert tag inserts the content from the URL corresponding to the value of its parameter attribute
10 - 12. The template JSP page executes another insert tag, which inserts the content as in the steps 7 - 9.
13. Template execution is complete, and the server returns the generated response to the client.
--------------------------------------------------------------------------------
View Helper :
Helpers provide a clean separation between presentation and business data by acting as intermediaries between the two
--------------------------------------------------------------------------------
Dispatcher View :
System controls flow of execution and access to presentation processing, which is responsible for generating dynamic content
--------------------------------------------------------------------------------
Service to Worker :
The system controls flow of execution and access to business data, from which it creates presentation content
Refer Link : http://www.corej2eepatterns.com/Patterns/ServiceToWorker.htm
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Business Tier<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
--------------------------------------------------------------------------------
Business Delegate
The business delegate object abstracts the business services API and provides standard interface to al the client components.
--------------------------------------------------------------------------------
Session Facade :
Use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.
--------------------------------------------------------------------------------
Service Locator
--------------------------------------------------------------------------------
Transfer Object Assembler :
The Transfer Object Assembler uses Transfer Objects to retrieve data from various business objects and other objects that define the model or part of the model.
--------------------------------------------------------------------------------
Value List Handler
--------------------------------------------------------------------------------
Composite Entity
--------------------------------------------------------------------------------
Transfer Object :
A pattern used to "Application clients need to exchange data with enterprise beans".
or
Transfer object / value object is a plain serializable Java class that represents a snapshot of some server side data, as in the following code example:
--------------------------------------------------------------------------------
>>>>>>>>>>>>>>>>>>>>>>>>>>>>Integration Tier<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
--------------------------------------------------------------------------------
Service Activator :
Enterprise beans and other business services need a way to be activated asynchronously
--------------------------------------------------------------------------------
Data Access Object :
A Pattern which abstracts and encapsulate all access to the database.The DAO manages the connection with the data source to obtain and store data.
Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.
>>>>>>>>>>>>>>>>Presentation Tier<<<<<<<<<<<<<<<<<<
---------------------------------------------------
Intercepting Filter :
A centralised control which hadles request from the web client.
--------------------------------------------------------------------------------
Front Controller :
A centralized point of contact for handling a request may be useful, for example, to control and log a user's progress through the site.
What is the difference betwenn Intercepting Filter and Front Controller.
--------------------------------------------------------------------------------
Composite View :
A Framework to present content in a single web page, from numerous data sources.
Tiles is a good example for this pattern
Alos it is good to refer this link
http://java.sun.com/blueprints/patterns/CompositeView.html
1. The client requests service
2. After processing the request, MainServlet (the Front Controller) directs the ScreenFlowManager to select the next view
3. The ScreenFlowManager determines the name of the screen to display
4. The request is forwarded to TemplateServlet
5. The TemplateServlet identifies the requested Screen object and stores it in HttpSession
6. The request is forwarded to the template JSP page
7. The template JSP page executes an insert tag
8. The insert tag retrieves the screen from HttpSession
9. The insert tag inserts the content from the URL corresponding to the value of its parameter attribute
10 - 12. The template JSP page executes another insert tag, which inserts the content as in the steps 7 - 9.
13. Template execution is complete, and the server returns the generated response to the client.
--------------------------------------------------------------------------------
View Helper :
Helpers provide a clean separation between presentation and business data by acting as intermediaries between the two
--------------------------------------------------------------------------------
Dispatcher View :
System controls flow of execution and access to presentation processing, which is responsible for generating dynamic content
--------------------------------------------------------------------------------
Service to Worker :
The system controls flow of execution and access to business data, from which it creates presentation content
Refer Link : http://www.corej2eepatterns.com/Patterns/ServiceToWorker.htm
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Business Tier<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
--------------------------------------------------------------------------------
Business Delegate
The business delegate object abstracts the business services API and provides standard interface to al the client components.
--------------------------------------------------------------------------------
Session Facade :
Use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.
--------------------------------------------------------------------------------
Service Locator
--------------------------------------------------------------------------------
Transfer Object Assembler :
The Transfer Object Assembler uses Transfer Objects to retrieve data from various business objects and other objects that define the model or part of the model.
--------------------------------------------------------------------------------
Value List Handler
--------------------------------------------------------------------------------
Composite Entity
--------------------------------------------------------------------------------
Transfer Object :
A pattern used to "Application clients need to exchange data with enterprise beans".
or
Transfer object / value object is a plain serializable Java class that represents a snapshot of some server side data, as in the following code example:
--------------------------------------------------------------------------------
>>>>>>>>>>>>>>>>>>>>>>>>>>>>Integration Tier<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
--------------------------------------------------------------------------------
Service Activator :
Enterprise beans and other business services need a way to be activated asynchronously
--------------------------------------------------------------------------------
Data Access Object :
A Pattern which abstracts and encapsulate all access to the database.The DAO manages the connection with the data source to obtain and store data.
Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.
Friday, November 13, 2009
AJAX with EXCEL POI Import
Import EXCEL Data into Table using POI:
<%@page import="org.apache.poi.poifs.filesystem.POIFSFileSystem"%>
<%@page import="java.io.*"%>
<%@page import="java.sql.*"%>
<%@page import="org.apache.poi.hssf.usermodel.*"%>
<html>
<body>
<%
String DRIVER = "org.gjt.mm.mysql.Driver";
Class.forName(DRIVER).newInstance();
String sql="";
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
try{
String url="jdbc:mysql://localhost/csr?user=root&password=";
con=DriverManager.getConnection(url);
stmt=con.createStatement();
//==========
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("D:\\ABC.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
out.println("<table border=1>");
// This trick ensures that we get the data properly even if it doesnâ??t start from first few rows
for(int i = 0; i < rows; i++)
{
row = sheet.getRow(i);
if(row != null)
{
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
else
{
out.println("ROW is null"+ i+"<BR>");
}
}
out.println("Total Row "+rows+"<BR>");
for(int r = 1; r < rows; r++)
{
out.println("Row "+r+"<BR>");
sql = "insert into csr_mst values (";
row = sheet.getRow(r);
if(row != null)
{
// out.println("<tr><td>"+row.getRowNum()+"</td>");
for(int c = 0; c < cols; c++)
{
cell = row.getCell((short)c);
if(cell == null)
{
sql = sql + "'',";
}
else if(cell != null)
{
// Your code here
// s = cell.getData();
// out.println("<td>");
//out.println(cell);
String cellValue = cell.toString();
CharSequence singleQuote = "'";
CharSequence singleQuoteReplace = "`";
if(cellValue.contains("'"))
{
cellValue = cellValue.replace(singleQuote,singleQuoteReplace);
}
sql = sql + "'"+cellValue+"',";
//out.println("</td>");
}
}
// out.println("</tr>");
sql = sql.substring(0,sql.length()-1);
sql = sql +")";
out.println("<BR>"+sql+"<BR>");
//stmt.addBatch(sql);
con.setAutoCommit(false);
stmt.execute(sql);
con.commit();
}
}
con.close();
}
catch (BatchUpdateException be) {
out.println(be.getMessage());
//handle batch update exception
int[] counts = be.getUpdateCounts();
for (int i=0; i< counts.length; i++) {
System.out.println("Statement["+i+"] :"+counts[i]);
}
con.rollback();
}
catch (SQLException e) {
out.println(e.getMessage());
//handle SQL exception
con.rollback();
}
catch(Exception ioe)
{
out.println(ioe.getMessage());
ioe.printStackTrace();
}
out.println("</table>");
out.println("ALL Infomrations are updated successfully");
%>
</body>
</html>
Table structure which is being imported :
CREATE TABLE /*!32312 IF NOT EXISTS*/ "csr_mst" (
"ATS_ID" varchar(200) DEFAULT NULL,
"Application_Name" varchar(200) DEFAULT NULL,
"Application_Acronym" varchar(200) DEFAULT NULL,
"Sector" varchar(200) DEFAULT NULL,
"GSC" varchar(200) DEFAULT NULL,
"CSR_Number" varchar(200) DEFAULT NULL,
"Priority" varchar(200) DEFAULT NULL,
"CSR_Title" varchar(1000) DEFAULT NULL,
"Business_Case" longtext,
"Change_Classification" varchar(200) DEFAULT NULL,
"State" varchar(200) DEFAULT NULL,
"Business_Request_Date" varchar(200) DEFAULT NULL,
"Proposal_Approved_Date" varchar(200) DEFAULT NULL,
"Implemented_Canceled_Date" varchar(200) DEFAULT NULL,
"Request_Submitted_Date" varchar(200) DEFAULT NULL,
"ROM" varchar(200) DEFAULT NULL,
"CRB1_Approved_Date" varchar(200) DEFAULT NULL,
"Final_Estimated_Hours" varchar(200) DEFAULT NULL,
"Proposal_Date" varchar(200) DEFAULT NULL,
"Project_Status" varchar(200) DEFAULT NULL,
"GM_Requestor" varchar(200) DEFAULT NULL,
"GM_Requestor_Phone" varchar(200) DEFAULT NULL,
"GM_Requestor_Email" varchar(200) DEFAULT NULL,
"GM_Sustain_Lead" varchar(200) DEFAULT NULL,
"GM_Sustain_Lead_Phone" varchar(200) DEFAULT NULL,
"GM_Sustain_Lead_Email" varchar(200) DEFAULT NULL,
"EDS_Sustain_Lead" varchar(200) DEFAULT NULL,
"EDS_Sustain_Lead_Phone" varchar(200) DEFAULT NULL,
"EDS_Sustain_Lead_Email" varchar(200) DEFAULT NULL,
"Impl_Mgmt_Number" varchar(200) DEFAULT NULL,
"Proposed_Implementation_Date" varchar(200) DEFAULT NULL,
"CRB2_Approved_Date" varchar(200) DEFAULT NULL,
"Comments" longtext,
"Funding_Source" varchar(200) DEFAULT NULL,
"SOX_Impact" varchar(200) DEFAULT NULL,
"Change_Category" varchar(200) DEFAULT NULL,
"SAP_Code" varchar(200) DEFAULT NULL,
"Attachment00" varchar(200) DEFAULT NULL,
"Note00" longtext,
"Attachment01" varchar(200) DEFAULT NULL,
"Note01" longtext,
"Attachment02" varchar(200) DEFAULT NULL,
"Note02" longtext,
"Attachment03" varchar(200) DEFAULT NULL,
"Note03" longtext,
"Attachment04" varchar(200) DEFAULT NULL,
"Note04" longtext,
"Attachment05" varchar(200) DEFAULT NULL,
"Note05" longtext
) /*!40100 DEFAULT CHARSET=latin1*/;
#
# Dumping data for table 'csr_mst'
#
LOCK TABLES "csr_mst" WRITE;
/*!40000 ALTER TABLE "csr_mst" DISABLE KEYS;*/
REPLACE INTO "csr_mst" ("ATS_ID", "Application_Name", "Application_Acronym", "Sector", "GSC", "CSR_Number", "Priority", "CSR_Title", "Business_Case", "Change_Classification", "State", "Business_Request_Date", "Proposal_Approved_Date", "Implemented_Canceled_Date", "Request_Submitted_Date", "ROM", "CRB1_Approved_Date", "Final_Estimated_Hours", "Proposal_Date", "Project_Status", "GM_Requestor", "GM_Requestor_Phone", "GM_Requestor_Email", "GM_Sustain_Lead", "GM_Sustain_Lead_Phone", "GM_Sustain_Lead_Email", "EDS_Sustain_Lead", "EDS_Sustain_Lead_Phone", "EDS_Sustain_Lead_Email", "Impl_Mgmt_Number", "Proposed_Implementation_Date", "CRB2_Approved_Date", "Comments", "Funding_Source", "SOX_Impact", "Change_Category", "SAP_Code", "Attachment00", "Note00", "Attachment01", "Note01", "Attachment02", "Note02", "Attachment03", "Note03", "Attachment04", "Note04", "Attachment05", "Note05") VALUES
('2704.0','SAP Compass','SAP Finance,
PRIDE','GMAP','20','8410.0','14.0','Confiigeration for ZPRC to operated for HNZ','HNZ currently updates the Condition Records Manually into the different condition types and this can lead to errors.','Business Improvement','Design','23-Jun-2009','07-Jul-2008','','02-Jul-2008','Large','07-Jul-2008','105.0','07-Jul-2008','','Jan Smillie','+64 9 9783643','Jan.Smillie@gm.com','Steven Celar',' +61 3 9038 4666','steven.celar@gm.com','Atul Gokhale','020-66069000','atul.gokhale@eds.com','','','07-Jul-2008','"18 Nov - Awaiting resourcing at completion of CR 8923.
07 Nov - This CR is necessary before an important change to DDR payments (CR being drafted by HNZ). Priority increased to 1.4
02 Sep - Placed on hold at GM request, pending refinement of business reqts.
29 Jul - Grant in discussion with Wilhelm/Jan for review of business requirements. Meeting scheduled
07 Jul - ROM submitted"','Discretionary','No','Enhancement','','','0 7/2/2008 It is required that ZPRC program works for HNZ the same way that GMH operates ZPRC, however requires to be altered for HNZ rules.
NZ populates the ZPRC price master tables via an Excel upload file or manual input, including contract table.','','','','','','','','','','');
REPLACE INTO "csr_mst" ("ATS_ID", "Application_Name", "Application_Acronym", "Sector", "GSC", "CSR_Number", "Priority", "CSR_Title", "Business_Case", "Change_Classification", "State", "Business_Request_Date", "Proposal_Approved_Date", "Implemented_Canceled_Date", "Request_Submitted_Date", "ROM", "CRB1_Approved_Date", "Final_Estimated_Hours", "Proposal_Date", "Project_Status", "GM_Requestor", "GM_Requestor_Phone", "GM_Requestor_Email", "GM_Sustain_Lead", "GM_Sustain_Lead_Phone", "GM_Sustain_Lead_Email", "EDS_Sustain_Lead", "EDS_Sustain_Lead_Phone", "EDS_Sustain_Lead_Email", "Impl_Mgmt_Number", "Proposed_Implementation_Date", "CRB2_Approved_Date", "Comments", "Funding_Source", "SOX_Impact", "Change_Category", "SAP_Code", "Attachment00", "Note00", "Attachment01", "Note01", "Attachment02", "Note02", "Attachment03", "Note03", "Attachment04", "Note04", "Attachment05", "Note05") VALUES
('2704.0','SAP Compass','SAP Finance,
PRIDE','GMAP','20','8412.0','12.0','BULLETIN INPUT SCREEN (ZDC1) & ZVI001 TABLES - ADD AUSTRALIAN STATE','The business has made a decision via Sales and Marketing to begin processing bonus bulletin payments across each Australian state .','Business Improvement','Testing','01-Oct-2008','04-Jul-2008','','03-Jul-2008','Small','04-Jul-2008','80.0','04-Jul-2008','','LOU BASCHIERA','+61 3 96472534','lou.baschiera@gm.com','Steven Celar',' +61 3 9038 4666','steven.celar@gm.com','Atul Gokhale','020-66069000','atul.gokhale@eds.com','','','04-Jul-2008','"
15 July- UATTesting in progress
8 july - Issues identified during testing in QBS. Team reviewing the code again.
24 June - Build completed. Stamp Duty Claim amount upload successful. Currently testing the automatic claims process
17 june- SOL prepration in progress.
10 june- Priority moved up to 1.2
03 June - SOL prepartion is in progress.
18-May - Team discussing on requirements of bulletin number validation, upload of stamp duty claim file etc. Design and Build could take longer time as the logic to be built is complex
15-May- Clarified points on claim code maintenance and Aus state as unique key field in custom table. additional requirement of bulletin number also was raised
13 May, 4-May- SOL is under progress. Priority changed from 1.9 to 1.5
29Apr - Team discussed with Lou on 21/04/2009. Additional input of claim code needs to be taken care. Also discussed internally on 22/04/2009. Work in progress
24 Apr - Few modifications recognized in SOL. Also, need few clarifications in the process to make this work
22 Apr- ABAP team is modifying SOL to meet the requirements.
17 Mar - Design underway. prasad is working on Design. As other high priority CR`s are in progress, this will be taken care in parallel.
07 Nov - Impacted by LEPA; no development until 25/01/09.
23 Sep - Coding underway.
16 Sep - Design progressing
01 Sep - Seeking customer feedback on requirements.
18 Aug - Working on design in background
07 Aug - Implementation pending completion of VDC project. Will attempt to work around
05 Aug - Design proceeding
22 Jul - Seeking customer feedback on requirements.
04 Jul - ROM submitted and approved."','Discretionary','No','Enhancement','','','0 7/3/2008 Currently Holden has many bonus driveaway deals. These deals are seperated by Australian state due to onroad costs being different across each state.
We would like the facility to add the Australian state to the bulletin input screen (ZDC1','','1 7/3/2008','','','','','','','','');
REPLACE INTO "csr_mst" ("ATS_ID", "Application_Name", "Application_Acronym", "Sector", "GSC", "CSR_Number", "Priority", "CSR_Title", "Business_Case", "Change_Classification", "State", "Business_Request_Date", "Proposal_Approved_Date", "Implemented_Canceled_Date", "Request_Submitted_Date", "ROM", "CRB1_Approved_Date", "Final_Estimated_Hours", "Proposal_Date", "Project_Status", "GM_Requestor", "GM_Requestor_Phone", "GM_Requestor_Email", "GM_Sustain_Lead", "GM_Sustain_Lead_Phone", "GM_Sustain_Lead_Email", "EDS_Sustain_Lead", "EDS_Sustain_Lead_Phone", "EDS_Sustain_Lead_Email", "Impl_Mgmt_Number", "Proposed_Implementation_Date", "CRB2_Approved_Date", "Comments", "Funding_Source", "SOX_Impact", "Change_Category", "SAP_Code", "Attachment00", "Note00", "Attachment01", "Note01", "Attachment02", "Note02", "Attachment03", "Note03", "Attachment04", "Note04", "Attachment05", "Note05") VALUES
('2704.0','SAP Compass','SAP Finance,
PRIDE','GMAP','20','8640.0','33.0','CLAIMS NOT PAID ON OPTIONS - (ZDC1)','The business is not able to pay dealers any claims relating to options within the ZDC1 bulletin input screen , causing much frustration and disatisfaction amongst the dealer network across Australia','Business Improvement','Workload','01-Oct-2008','05-Aug-2008','','29-Jul-2008','Large','05-Aug-2008','154.5','04-Aug-2008','','LOU BASCHIERA','+61 3 96472534','lou.baschiera@gm.com','Steven Celar',' +61 3 9038 4666','steven.celar@gm.com','Atul Gokhale','020-66069000','atul.gokhale@eds.com','','','05-Aug-2008','"07 Nov - Impacted by LEPA; no development until 25/01/09.
07 Aug - Placed on hold, pending completion of VDC project.
05 Aug - ROM approved
04 Aug - ROM submitted for approval"','Discretionary','No','Enhancement','','','0 7/29/2008 Currently all Vehicles ("VE") and Smartpacks ("SP" ) are loaded to the bulletin input screen and claims are automatically paid if the retail (RETL) records matches the material codes loaded within the bulletin input screen.
Issue is that a','','','','','','','','','','');
REPLACE INTO "csr_mst" ("ATS_ID", "Application_Name", "Application_Acronym", "Sector", "GSC", "CSR_Number", "Priority", "CSR_Title", "Business_Case", "Change_Classification", "State", "Business_Request_Date", "Proposal_Approved_Date", "Implemented_Canceled_Date", "Request_Submitted_Date", "ROM", "CRB1_Approved_Date", "Final_Estimated_Hours", "Proposal_Date", "Project_Status", "GM_Requestor", "GM_Requestor_Phone", "GM_Requestor_Email", "GM_Sustain_Lead", "GM_Sustain_Lead_Phone", "GM_Sustain_Lead_Email", "EDS_Sustain_Lead", "EDS_Sustain_Lead_Phone", "EDS_Sustain_Lead_Email", "Impl_Mgmt_Number", "Proposed_Implementation_Date", "CRB2_Approved_Date", "Comments", "Funding_Source", "SOX_Impact", "Change_Category", "SAP_Code", "Attachment00", "Note00", "Attachment01", "Note01", "Attachment02", "Note02", "Attachment03", "Note03", "Attachment04", "Note04", "Attachment05", "Note05") VALUES
('2704.0','SAP Compass','SAP Finance,
PRIDE','GMAP','20','8748.0','11.0','Create SAP Finance interface to accept SAP Extract file out of LN Sundry Invoicing','Load LN invoice & credit notes into SAP and streamline GMH & HNZ processes.','Business Improvement','Testing','31-Dec-2008','13-Aug-2008','','08-Aug-2008','Small','13-Aug-2008','80.0','12-Aug-2008','','Jan Smillie','+64 9 9783643','Jan.Smillie@gm.com','Steven Celar',' +61 3 9038 4666','steven.celar@gm.com','Atul Gokhale','020-66069000','atul.gokhale@eds.com','','','13-Aug-2008','17 Mar - Customer confirmation that testing will recommence 18/03.
20 Jan - Awaiting UAT.
10 Dec - Testing delayed by CR 9734.
24 Nov - Testing progressing
13 Aug - ROM approved
12 Aug - ROM submitted for approval','Discretionary','No','Enhancement','','','0 8/8/2008 Create a new SAP Finance interface to upload and process a newly generated SAP Extract file out of LN Sundry invoicing.
The SAP Finance interface needs to be able to accept and process a file with the following information:
- Header
- Q','','','','','','','','','','');
<strong>AJAX</strong>
The Ajax technique accomplishes this by using the following technologies:
JavaScript that allows for interaction with the browser and responding to events
The DOM for accessing and manipulating the structure of the HTML of the page
XML, which represents the data passed between the server and client.
An XMLHttpRequest object for asynchronously exchanging the XML data between the client and the server.
The following graphic shows how these technologies work together to update a piece of a page with new data from the server.
Figure 1: General Sequence of Ajax Request
Figure 1 illustrates the following steps in a generalized Ajax request:
The user generates an event, such as by clicking a button. This results in a JavaScript call.
An XMLHttpRequest object is created and configured with a request parameter that includes the ID of the component that generated the event and any value that the user might have entered.
The XMLHttpRequest object makes an asynchronous request to the web server. An object (such as a servlet or listener) receives the request, processes it, and stores any data in the request to the data store. In the case of Ajax-aware JavaServer Faces components, the object that processes the request is a PhaseListener object. We'll cover that more later in the document.
The object that processed the request returns an XML document containing any updates that need to go to the client.
The XMLHttpRequest object receives the XML data, processes it, and updates the HTML DOM representing the page with the new data.
In the below Example
Run ->Call.jsp it invokes db.jsp through Ajax
<strong>
CALL.JSP</strong>
<%@page contentType="text/html"%>
<!-- The above is the page directive with attribute "contentType" which is used to get the content type of the page -->
<%@page pageEncoding="UTF-8"%>
<!-- The above is the page directive with the attribute "pageEncoding" tells us that we are working with unicode encoding within the page -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- We call a ajax.js javascript which makes an asynchronous request to the server -->
<script language="javascript" src="ajax.js"></script> .
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>JSP Page using AJAX
</title>
</head>
<body>
<form name=testFrm">
Sector : <select name="sector" id="sector">
<option value=''></option>
<option value='GME'>GME</option>
<option value='Corp Finance'>Corp Finance</option>
<option value='GMNA'>GMNA</option>
<option value='Corp Staff - EDES'>Corp Staff - EDES</option>
</select>
Application Acronym :
<select name="application_acronym" id="application_acronym">
<option value=''></option>
<option value='eCVMS'>eCVMS</option>
<option value='vcps'>vcps</option>
<option value='e.VPS'>e.VPS</option>
</select>
State : <select name="state" id="state">
<option value=''></option>
<option value='ROM'>ROM</option>
<option value='Design'>Design</option>
<option value='Workload'>Workload</option>
<option value='Testing'>Testing</option>
<option value='Build'>Build</option>
<option value='Deploy'>Deploy</option>
<option value='On Hold'>On Hold</option>
</select>
ATS No : <input type='text' name="ats_id" id="ats_id"/>
CR#: <input type='text' name="csr_number" id="csr_number"/>
<input id="submit" type="button" value="Submit" onclick="sendRequest('GET','db.jsp')">
<div id="ajax_res"> Please get CR detail by entering the above values
</div>
</form>
</body>
</html>
AJAX.js
=======
function createRequestObject(){
var req; try {
// Firefox, Opera, Safari
req = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
//For IE 6
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//For IE 5
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
}
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == 'get' || method == 'GET'){
var ats_id = document.getElementById("ats_id").value;
var sector = document.getElementById("sector").value;
var application_acronym = document.getElementById("application_acronym").value;
var csr_number = document.getElementById("csr_number").value;
var state = document.getElementById("state").value;
url=url+"?ats_id="+ats_id;
url=url+"§or="+sector;
url=url+"&application_acronym="+application_acronym;
url=url+"&csr_number="+csr_number;
url=url+"&state="+state;
url=url+"&sid="+Math.random();
http.open(method,url,true);
http.onreadystatechange = antonyfntest;
http.send(null);}
}
function antonyfntest(){
//alert('Hi Antony');
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
}
}
}
========
DB.JSP
<%@page import="java.sql.*"%>
<html>
<body>
<table>
<tbody>
<div>
<center>
<%
String ats_id= request.getParameter("ats_id");
String sector= request.getParameter("sector");
String application_acronym = request.getParameter("application_acronym");
String csr_number= request.getParameter("csr_number");
String state= request.getParameter("state");
String sql = null;
/*
out.println("<BR>*******************ats_id*********************==>"+ats_id);
out.println("<BR>*******************sector*********************==>"+sector);
out.println("<BR>*******************application_acronym*********************==>"+application_acronym);
out.println("<BR>*******************csr_number*********************==>"+csr_number);
out.println("<BR>*******************state*********************==>"+state);
*/
String condition = null;
if(ats_id != null || sector != null || application_acronym != null || csr_number != null)
{
condition = " where ";
}
if (ats_id != null && !ats_id.equalsIgnoreCase(""))
{
ats_id = ats_id +".0";
condition = condition + "ats_id ='"+ats_id+"' and ";
}
if (sector != null && !sector.equalsIgnoreCase(""))
{
condition = condition + "sector ='"+sector+"' and ";
}
if (application_acronym != null && !application_acronym.equalsIgnoreCase(""))
{
condition = condition + "application_acronym ='"+application_acronym+"' and ";
}
if (csr_number != null && !csr_number.equalsIgnoreCase(""))
{
csr_number = csr_number+".0";
condition = condition + "csr_number ='"+csr_number+"' and ";
}
if (state != null && !state.equalsIgnoreCase(""))
{
condition = condition + "state ='"+state+"' and";
}
//out.println("Copndtin ="+condition);
if(condition!=null)
{
int len = condition.length();
//out.println("Beforecondition"+condition);
condition = condition.substring(1,len-4);
}
else
{
condition = "";
}
String DRIVER = "org.gjt.mm.mysql.Driver";
Class.forName(DRIVER).newInstance();
Connection con=null;
ResultSet rs=null;
Statement stmt=null;
try{
String url="jdbc:mysql://localhost/csr?user=root&password=";
con=DriverManager.getConnection(url);
stmt=con.createStatement();
sql = "select * from csr_mst " + condition;
rs=stmt.executeQuery(sql);
//out.println("SQL"+sql);
String column="";
ResultSetMetaData rsm =rs.getMetaData();
out.println("<table border=1>");
int cc = rsm.getColumnCount();
System.out.println("running......cnt...."+cc);
int c=1;
String header ="<tr><td>S.No</td>";
for(int i=1;i<=cc;i++)
{
System.out.println("is "+rsm.getColumnName(i));
header = header+"<td>"+rsm.getColumnName(i)+"</td>";
}
header = header+"</tr>";
out.println(header);
int row = 0;
while(rs.next())
{
row= row +1;
System.out.println(row);
out.println("<tr><td>"+row+"</td>");
for(int i=1;i<=cc;i++)
{
//column = column+rs.getString(rsm.getColumnName(i))+"#";
out.println("<td>"+rs.getString(rsm.getColumnName(i))+"</td>");
}
out.println("</tr>");
}
out.println("</table>");
rs.close();
stmt.close();
con.close();
}catch(Exception e){out.println(e.getMessage()+"<BR>"+sql);
}
%>
</tbody>
</table>
</center>
</div>
</body>
</html>
<%@page import="org.apache.poi.poifs.filesystem.POIFSFileSystem"%>
<%@page import="java.io.*"%>
<%@page import="java.sql.*"%>
<%@page import="org.apache.poi.hssf.usermodel.*"%>
<html>
<body>
<%
String DRIVER = "org.gjt.mm.mysql.Driver";
Class.forName(DRIVER).newInstance();
String sql="";
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
try{
String url="jdbc:mysql://localhost/csr?user=root&password=";
con=DriverManager.getConnection(url);
stmt=con.createStatement();
//==========
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("D:\\ABC.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
out.println("<table border=1>");
// This trick ensures that we get the data properly even if it doesnâ??t start from first few rows
for(int i = 0; i < rows; i++)
{
row = sheet.getRow(i);
if(row != null)
{
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
else
{
out.println("ROW is null"+ i+"<BR>");
}
}
out.println("Total Row "+rows+"<BR>");
for(int r = 1; r < rows; r++)
{
out.println("Row "+r+"<BR>");
sql = "insert into csr_mst values (";
row = sheet.getRow(r);
if(row != null)
{
// out.println("<tr><td>"+row.getRowNum()+"</td>");
for(int c = 0; c < cols; c++)
{
cell = row.getCell((short)c);
if(cell == null)
{
sql = sql + "'',";
}
else if(cell != null)
{
// Your code here
// s = cell.getData();
// out.println("<td>");
//out.println(cell);
String cellValue = cell.toString();
CharSequence singleQuote = "'";
CharSequence singleQuoteReplace = "`";
if(cellValue.contains("'"))
{
cellValue = cellValue.replace(singleQuote,singleQuoteReplace);
}
sql = sql + "'"+cellValue+"',";
//out.println("</td>");
}
}
// out.println("</tr>");
sql = sql.substring(0,sql.length()-1);
sql = sql +")";
out.println("<BR>"+sql+"<BR>");
//stmt.addBatch(sql);
con.setAutoCommit(false);
stmt.execute(sql);
con.commit();
}
}
con.close();
}
catch (BatchUpdateException be) {
out.println(be.getMessage());
//handle batch update exception
int[] counts = be.getUpdateCounts();
for (int i=0; i< counts.length; i++) {
System.out.println("Statement["+i+"] :"+counts[i]);
}
con.rollback();
}
catch (SQLException e) {
out.println(e.getMessage());
//handle SQL exception
con.rollback();
}
catch(Exception ioe)
{
out.println(ioe.getMessage());
ioe.printStackTrace();
}
out.println("</table>");
out.println("ALL Infomrations are updated successfully");
%>
</body>
</html>
Table structure which is being imported :
CREATE TABLE /*!32312 IF NOT EXISTS*/ "csr_mst" (
"ATS_ID" varchar(200) DEFAULT NULL,
"Application_Name" varchar(200) DEFAULT NULL,
"Application_Acronym" varchar(200) DEFAULT NULL,
"Sector" varchar(200) DEFAULT NULL,
"GSC" varchar(200) DEFAULT NULL,
"CSR_Number" varchar(200) DEFAULT NULL,
"Priority" varchar(200) DEFAULT NULL,
"CSR_Title" varchar(1000) DEFAULT NULL,
"Business_Case" longtext,
"Change_Classification" varchar(200) DEFAULT NULL,
"State" varchar(200) DEFAULT NULL,
"Business_Request_Date" varchar(200) DEFAULT NULL,
"Proposal_Approved_Date" varchar(200) DEFAULT NULL,
"Implemented_Canceled_Date" varchar(200) DEFAULT NULL,
"Request_Submitted_Date" varchar(200) DEFAULT NULL,
"ROM" varchar(200) DEFAULT NULL,
"CRB1_Approved_Date" varchar(200) DEFAULT NULL,
"Final_Estimated_Hours" varchar(200) DEFAULT NULL,
"Proposal_Date" varchar(200) DEFAULT NULL,
"Project_Status" varchar(200) DEFAULT NULL,
"GM_Requestor" varchar(200) DEFAULT NULL,
"GM_Requestor_Phone" varchar(200) DEFAULT NULL,
"GM_Requestor_Email" varchar(200) DEFAULT NULL,
"GM_Sustain_Lead" varchar(200) DEFAULT NULL,
"GM_Sustain_Lead_Phone" varchar(200) DEFAULT NULL,
"GM_Sustain_Lead_Email" varchar(200) DEFAULT NULL,
"EDS_Sustain_Lead" varchar(200) DEFAULT NULL,
"EDS_Sustain_Lead_Phone" varchar(200) DEFAULT NULL,
"EDS_Sustain_Lead_Email" varchar(200) DEFAULT NULL,
"Impl_Mgmt_Number" varchar(200) DEFAULT NULL,
"Proposed_Implementation_Date" varchar(200) DEFAULT NULL,
"CRB2_Approved_Date" varchar(200) DEFAULT NULL,
"Comments" longtext,
"Funding_Source" varchar(200) DEFAULT NULL,
"SOX_Impact" varchar(200) DEFAULT NULL,
"Change_Category" varchar(200) DEFAULT NULL,
"SAP_Code" varchar(200) DEFAULT NULL,
"Attachment00" varchar(200) DEFAULT NULL,
"Note00" longtext,
"Attachment01" varchar(200) DEFAULT NULL,
"Note01" longtext,
"Attachment02" varchar(200) DEFAULT NULL,
"Note02" longtext,
"Attachment03" varchar(200) DEFAULT NULL,
"Note03" longtext,
"Attachment04" varchar(200) DEFAULT NULL,
"Note04" longtext,
"Attachment05" varchar(200) DEFAULT NULL,
"Note05" longtext
) /*!40100 DEFAULT CHARSET=latin1*/;
#
# Dumping data for table 'csr_mst'
#
LOCK TABLES "csr_mst" WRITE;
/*!40000 ALTER TABLE "csr_mst" DISABLE KEYS;*/
REPLACE INTO "csr_mst" ("ATS_ID", "Application_Name", "Application_Acronym", "Sector", "GSC", "CSR_Number", "Priority", "CSR_Title", "Business_Case", "Change_Classification", "State", "Business_Request_Date", "Proposal_Approved_Date", "Implemented_Canceled_Date", "Request_Submitted_Date", "ROM", "CRB1_Approved_Date", "Final_Estimated_Hours", "Proposal_Date", "Project_Status", "GM_Requestor", "GM_Requestor_Phone", "GM_Requestor_Email", "GM_Sustain_Lead", "GM_Sustain_Lead_Phone", "GM_Sustain_Lead_Email", "EDS_Sustain_Lead", "EDS_Sustain_Lead_Phone", "EDS_Sustain_Lead_Email", "Impl_Mgmt_Number", "Proposed_Implementation_Date", "CRB2_Approved_Date", "Comments", "Funding_Source", "SOX_Impact", "Change_Category", "SAP_Code", "Attachment00", "Note00", "Attachment01", "Note01", "Attachment02", "Note02", "Attachment03", "Note03", "Attachment04", "Note04", "Attachment05", "Note05") VALUES
('2704.0','SAP Compass','SAP Finance,
PRIDE','GMAP','20','8410.0','14.0','Confiigeration for ZPRC to operated for HNZ','HNZ currently updates the Condition Records Manually into the different condition types and this can lead to errors.','Business Improvement','Design','23-Jun-2009','07-Jul-2008','','02-Jul-2008','Large','07-Jul-2008','105.0','07-Jul-2008','','Jan Smillie','+64 9 9783643','Jan.Smillie@gm.com','Steven Celar',' +61 3 9038 4666','steven.celar@gm.com','Atul Gokhale','020-66069000','atul.gokhale@eds.com','','','07-Jul-2008','"18 Nov - Awaiting resourcing at completion of CR 8923.
07 Nov - This CR is necessary before an important change to DDR payments (CR being drafted by HNZ). Priority increased to 1.4
02 Sep - Placed on hold at GM request, pending refinement of business reqts.
29 Jul - Grant in discussion with Wilhelm/Jan for review of business requirements. Meeting scheduled
07 Jul - ROM submitted"','Discretionary','No','Enhancement','','','0 7/2/2008 It is required that ZPRC program works for HNZ the same way that GMH operates ZPRC, however requires to be altered for HNZ rules.
NZ populates the ZPRC price master tables via an Excel upload file or manual input, including contract table.','','','','','','','','','','');
REPLACE INTO "csr_mst" ("ATS_ID", "Application_Name", "Application_Acronym", "Sector", "GSC", "CSR_Number", "Priority", "CSR_Title", "Business_Case", "Change_Classification", "State", "Business_Request_Date", "Proposal_Approved_Date", "Implemented_Canceled_Date", "Request_Submitted_Date", "ROM", "CRB1_Approved_Date", "Final_Estimated_Hours", "Proposal_Date", "Project_Status", "GM_Requestor", "GM_Requestor_Phone", "GM_Requestor_Email", "GM_Sustain_Lead", "GM_Sustain_Lead_Phone", "GM_Sustain_Lead_Email", "EDS_Sustain_Lead", "EDS_Sustain_Lead_Phone", "EDS_Sustain_Lead_Email", "Impl_Mgmt_Number", "Proposed_Implementation_Date", "CRB2_Approved_Date", "Comments", "Funding_Source", "SOX_Impact", "Change_Category", "SAP_Code", "Attachment00", "Note00", "Attachment01", "Note01", "Attachment02", "Note02", "Attachment03", "Note03", "Attachment04", "Note04", "Attachment05", "Note05") VALUES
('2704.0','SAP Compass','SAP Finance,
PRIDE','GMAP','20','8412.0','12.0','BULLETIN INPUT SCREEN (ZDC1) & ZVI001 TABLES - ADD AUSTRALIAN STATE','The business has made a decision via Sales and Marketing to begin processing bonus bulletin payments across each Australian state .','Business Improvement','Testing','01-Oct-2008','04-Jul-2008','','03-Jul-2008','Small','04-Jul-2008','80.0','04-Jul-2008','','LOU BASCHIERA','+61 3 96472534','lou.baschiera@gm.com','Steven Celar',' +61 3 9038 4666','steven.celar@gm.com','Atul Gokhale','020-66069000','atul.gokhale@eds.com','','','04-Jul-2008','"
15 July- UATTesting in progress
8 july - Issues identified during testing in QBS. Team reviewing the code again.
24 June - Build completed. Stamp Duty Claim amount upload successful. Currently testing the automatic claims process
17 june- SOL prepration in progress.
10 june- Priority moved up to 1.2
03 June - SOL prepartion is in progress.
18-May - Team discussing on requirements of bulletin number validation, upload of stamp duty claim file etc. Design and Build could take longer time as the logic to be built is complex
15-May- Clarified points on claim code maintenance and Aus state as unique key field in custom table. additional requirement of bulletin number also was raised
13 May, 4-May- SOL is under progress. Priority changed from 1.9 to 1.5
29Apr - Team discussed with Lou on 21/04/2009. Additional input of claim code needs to be taken care. Also discussed internally on 22/04/2009. Work in progress
24 Apr - Few modifications recognized in SOL. Also, need few clarifications in the process to make this work
22 Apr- ABAP team is modifying SOL to meet the requirements.
17 Mar - Design underway. prasad is working on Design. As other high priority CR`s are in progress, this will be taken care in parallel.
07 Nov - Impacted by LEPA; no development until 25/01/09.
23 Sep - Coding underway.
16 Sep - Design progressing
01 Sep - Seeking customer feedback on requirements.
18 Aug - Working on design in background
07 Aug - Implementation pending completion of VDC project. Will attempt to work around
05 Aug - Design proceeding
22 Jul - Seeking customer feedback on requirements.
04 Jul - ROM submitted and approved."','Discretionary','No','Enhancement','','','0 7/3/2008 Currently Holden has many bonus driveaway deals. These deals are seperated by Australian state due to onroad costs being different across each state.
We would like the facility to add the Australian state to the bulletin input screen (ZDC1','','1 7/3/2008','','','','','','','','');
REPLACE INTO "csr_mst" ("ATS_ID", "Application_Name", "Application_Acronym", "Sector", "GSC", "CSR_Number", "Priority", "CSR_Title", "Business_Case", "Change_Classification", "State", "Business_Request_Date", "Proposal_Approved_Date", "Implemented_Canceled_Date", "Request_Submitted_Date", "ROM", "CRB1_Approved_Date", "Final_Estimated_Hours", "Proposal_Date", "Project_Status", "GM_Requestor", "GM_Requestor_Phone", "GM_Requestor_Email", "GM_Sustain_Lead", "GM_Sustain_Lead_Phone", "GM_Sustain_Lead_Email", "EDS_Sustain_Lead", "EDS_Sustain_Lead_Phone", "EDS_Sustain_Lead_Email", "Impl_Mgmt_Number", "Proposed_Implementation_Date", "CRB2_Approved_Date", "Comments", "Funding_Source", "SOX_Impact", "Change_Category", "SAP_Code", "Attachment00", "Note00", "Attachment01", "Note01", "Attachment02", "Note02", "Attachment03", "Note03", "Attachment04", "Note04", "Attachment05", "Note05") VALUES
('2704.0','SAP Compass','SAP Finance,
PRIDE','GMAP','20','8640.0','33.0','CLAIMS NOT PAID ON OPTIONS - (ZDC1)','The business is not able to pay dealers any claims relating to options within the ZDC1 bulletin input screen , causing much frustration and disatisfaction amongst the dealer network across Australia','Business Improvement','Workload','01-Oct-2008','05-Aug-2008','','29-Jul-2008','Large','05-Aug-2008','154.5','04-Aug-2008','','LOU BASCHIERA','+61 3 96472534','lou.baschiera@gm.com','Steven Celar',' +61 3 9038 4666','steven.celar@gm.com','Atul Gokhale','020-66069000','atul.gokhale@eds.com','','','05-Aug-2008','"07 Nov - Impacted by LEPA; no development until 25/01/09.
07 Aug - Placed on hold, pending completion of VDC project.
05 Aug - ROM approved
04 Aug - ROM submitted for approval"','Discretionary','No','Enhancement','','','0 7/29/2008 Currently all Vehicles ("VE") and Smartpacks ("SP" ) are loaded to the bulletin input screen and claims are automatically paid if the retail (RETL) records matches the material codes loaded within the bulletin input screen.
Issue is that a','','','','','','','','','','');
REPLACE INTO "csr_mst" ("ATS_ID", "Application_Name", "Application_Acronym", "Sector", "GSC", "CSR_Number", "Priority", "CSR_Title", "Business_Case", "Change_Classification", "State", "Business_Request_Date", "Proposal_Approved_Date", "Implemented_Canceled_Date", "Request_Submitted_Date", "ROM", "CRB1_Approved_Date", "Final_Estimated_Hours", "Proposal_Date", "Project_Status", "GM_Requestor", "GM_Requestor_Phone", "GM_Requestor_Email", "GM_Sustain_Lead", "GM_Sustain_Lead_Phone", "GM_Sustain_Lead_Email", "EDS_Sustain_Lead", "EDS_Sustain_Lead_Phone", "EDS_Sustain_Lead_Email", "Impl_Mgmt_Number", "Proposed_Implementation_Date", "CRB2_Approved_Date", "Comments", "Funding_Source", "SOX_Impact", "Change_Category", "SAP_Code", "Attachment00", "Note00", "Attachment01", "Note01", "Attachment02", "Note02", "Attachment03", "Note03", "Attachment04", "Note04", "Attachment05", "Note05") VALUES
('2704.0','SAP Compass','SAP Finance,
PRIDE','GMAP','20','8748.0','11.0','Create SAP Finance interface to accept SAP Extract file out of LN Sundry Invoicing','Load LN invoice & credit notes into SAP and streamline GMH & HNZ processes.','Business Improvement','Testing','31-Dec-2008','13-Aug-2008','','08-Aug-2008','Small','13-Aug-2008','80.0','12-Aug-2008','','Jan Smillie','+64 9 9783643','Jan.Smillie@gm.com','Steven Celar',' +61 3 9038 4666','steven.celar@gm.com','Atul Gokhale','020-66069000','atul.gokhale@eds.com','','','13-Aug-2008','17 Mar - Customer confirmation that testing will recommence 18/03.
20 Jan - Awaiting UAT.
10 Dec - Testing delayed by CR 9734.
24 Nov - Testing progressing
13 Aug - ROM approved
12 Aug - ROM submitted for approval','Discretionary','No','Enhancement','','','0 8/8/2008 Create a new SAP Finance interface to upload and process a newly generated SAP Extract file out of LN Sundry invoicing.
The SAP Finance interface needs to be able to accept and process a file with the following information:
- Header
- Q','','','','','','','','','','');
<strong>AJAX</strong>
The Ajax technique accomplishes this by using the following technologies:
JavaScript that allows for interaction with the browser and responding to events
The DOM for accessing and manipulating the structure of the HTML of the page
XML, which represents the data passed between the server and client.
An XMLHttpRequest object for asynchronously exchanging the XML data between the client and the server.
The following graphic shows how these technologies work together to update a piece of a page with new data from the server.
Figure 1: General Sequence of Ajax Request
Figure 1 illustrates the following steps in a generalized Ajax request:
The user generates an event, such as by clicking a button. This results in a JavaScript call.
An XMLHttpRequest object is created and configured with a request parameter that includes the ID of the component that generated the event and any value that the user might have entered.
The XMLHttpRequest object makes an asynchronous request to the web server. An object (such as a servlet or listener) receives the request, processes it, and stores any data in the request to the data store. In the case of Ajax-aware JavaServer Faces components, the object that processes the request is a PhaseListener object. We'll cover that more later in the document.
The object that processed the request returns an XML document containing any updates that need to go to the client.
The XMLHttpRequest object receives the XML data, processes it, and updates the HTML DOM representing the page with the new data.
In the below Example
Run ->Call.jsp it invokes db.jsp through Ajax
<strong>
CALL.JSP</strong>
<%@page contentType="text/html"%>
<!-- The above is the page directive with attribute "contentType" which is used to get the content type of the page -->
<%@page pageEncoding="UTF-8"%>
<!-- The above is the page directive with the attribute "pageEncoding" tells us that we are working with unicode encoding within the page -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- We call a ajax.js javascript which makes an asynchronous request to the server -->
<script language="javascript" src="ajax.js"></script> .
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>JSP Page using AJAX
</title>
</head>
<body>
<form name=testFrm">
Sector : <select name="sector" id="sector">
<option value=''></option>
<option value='GME'>GME</option>
<option value='Corp Finance'>Corp Finance</option>
<option value='GMNA'>GMNA</option>
<option value='Corp Staff - EDES'>Corp Staff - EDES</option>
</select>
Application Acronym :
<select name="application_acronym" id="application_acronym">
<option value=''></option>
<option value='eCVMS'>eCVMS</option>
<option value='vcps'>vcps</option>
<option value='e.VPS'>e.VPS</option>
</select>
State : <select name="state" id="state">
<option value=''></option>
<option value='ROM'>ROM</option>
<option value='Design'>Design</option>
<option value='Workload'>Workload</option>
<option value='Testing'>Testing</option>
<option value='Build'>Build</option>
<option value='Deploy'>Deploy</option>
<option value='On Hold'>On Hold</option>
</select>
ATS No : <input type='text' name="ats_id" id="ats_id"/>
CR#: <input type='text' name="csr_number" id="csr_number"/>
<input id="submit" type="button" value="Submit" onclick="sendRequest('GET','db.jsp')">
<div id="ajax_res"> Please get CR detail by entering the above values
</div>
</form>
</body>
</html>
AJAX.js
=======
function createRequestObject(){
var req; try {
// Firefox, Opera, Safari
req = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
//For IE 6
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//For IE 5
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
}
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == 'get' || method == 'GET'){
var ats_id = document.getElementById("ats_id").value;
var sector = document.getElementById("sector").value;
var application_acronym = document.getElementById("application_acronym").value;
var csr_number = document.getElementById("csr_number").value;
var state = document.getElementById("state").value;
url=url+"?ats_id="+ats_id;
url=url+"§or="+sector;
url=url+"&application_acronym="+application_acronym;
url=url+"&csr_number="+csr_number;
url=url+"&state="+state;
url=url+"&sid="+Math.random();
http.open(method,url,true);
http.onreadystatechange = antonyfntest;
http.send(null);}
}
function antonyfntest(){
//alert('Hi Antony');
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
}
}
}
========
DB.JSP
<%@page import="java.sql.*"%>
<html>
<body>
<table>
<tbody>
<div>
<center>
<%
String ats_id= request.getParameter("ats_id");
String sector= request.getParameter("sector");
String application_acronym = request.getParameter("application_acronym");
String csr_number= request.getParameter("csr_number");
String state= request.getParameter("state");
String sql = null;
/*
out.println("<BR>*******************ats_id*********************==>"+ats_id);
out.println("<BR>*******************sector*********************==>"+sector);
out.println("<BR>*******************application_acronym*********************==>"+application_acronym);
out.println("<BR>*******************csr_number*********************==>"+csr_number);
out.println("<BR>*******************state*********************==>"+state);
*/
String condition = null;
if(ats_id != null || sector != null || application_acronym != null || csr_number != null)
{
condition = " where ";
}
if (ats_id != null && !ats_id.equalsIgnoreCase(""))
{
ats_id = ats_id +".0";
condition = condition + "ats_id ='"+ats_id+"' and ";
}
if (sector != null && !sector.equalsIgnoreCase(""))
{
condition = condition + "sector ='"+sector+"' and ";
}
if (application_acronym != null && !application_acronym.equalsIgnoreCase(""))
{
condition = condition + "application_acronym ='"+application_acronym+"' and ";
}
if (csr_number != null && !csr_number.equalsIgnoreCase(""))
{
csr_number = csr_number+".0";
condition = condition + "csr_number ='"+csr_number+"' and ";
}
if (state != null && !state.equalsIgnoreCase(""))
{
condition = condition + "state ='"+state+"' and";
}
//out.println("Copndtin ="+condition);
if(condition!=null)
{
int len = condition.length();
//out.println("Beforecondition"+condition);
condition = condition.substring(1,len-4);
}
else
{
condition = "";
}
String DRIVER = "org.gjt.mm.mysql.Driver";
Class.forName(DRIVER).newInstance();
Connection con=null;
ResultSet rs=null;
Statement stmt=null;
try{
String url="jdbc:mysql://localhost/csr?user=root&password=";
con=DriverManager.getConnection(url);
stmt=con.createStatement();
sql = "select * from csr_mst " + condition;
rs=stmt.executeQuery(sql);
//out.println("SQL"+sql);
String column="";
ResultSetMetaData rsm =rs.getMetaData();
out.println("<table border=1>");
int cc = rsm.getColumnCount();
System.out.println("running......cnt...."+cc);
int c=1;
String header ="<tr><td>S.No</td>";
for(int i=1;i<=cc;i++)
{
System.out.println("is "+rsm.getColumnName(i));
header = header+"<td>"+rsm.getColumnName(i)+"</td>";
}
header = header+"</tr>";
out.println(header);
int row = 0;
while(rs.next())
{
row= row +1;
System.out.println(row);
out.println("<tr><td>"+row+"</td>");
for(int i=1;i<=cc;i++)
{
//column = column+rs.getString(rsm.getColumnName(i))+"#";
out.println("<td>"+rs.getString(rsm.getColumnName(i))+"</td>");
}
out.println("</tr>");
}
out.println("</table>");
rs.close();
stmt.close();
con.close();
}catch(Exception e){out.println(e.getMessage()+"<BR>"+sql);
}
%>
</tbody>
</table>
</center>
</div>
</body>
</html>
Tuesday, November 10, 2009
Saturday, November 7, 2009
Java Interview Question
Questions:
Core
Type I
1. What is Oops?
2. What is function overloading
3. What is function overriding
4.
Type II
1. What is abstract Class?
2. What is Interface?
3. What is a difference between abstract and interface?
4. What is Vector, Array List?2
5. What is Hash table and Hash map
6. What is StringTokenizer?
7. What is the difference between string and string buffer?
8. What is Exception? How many type of Exceptions
9. What is the difference between compile time exception and run time exception
10. What is synchronization
11.
Type III
1. What is Hash Tree and Hash map?
2. What is IO?
3. What is socket and datagram?
4.
Type IV
1. What is Thread?
2. What is wait, Join, sleep?
DataBase:
Standard Questions:
1. How will you connect to the Database?
2. What is mean by Class.forName, sun.jdbc.odbc
3. What is the difference between prepared statement and callable statement.
4. How many types of dirvers available? *
5. What is difference between statement and prepared statement?
6. What is the difference between executeQuery, executeUpdate and execute.
7. What is ResultSet meta data and database meta data? *
8.
9.
Servlet
1. What is servlet?
2. What is the difference between doGet and doPost?
JSP
1. What are the advantages of the JSP
2. What is difference between include and forward? *
3. What is the difference between sendreaderwrite and forward *
4. What are the implicits objects in JSP
5. How will you handle error page in Java. *
6. What is the difference between page, session, request and application
7. How will you make JSP thread at safe? *
8.
Face to Face Interview Questions:
1. How will setup Tomcat:
Core
Type I
1. What is Oops?
2. What is function overloading
3. What is function overriding
4.
Type II
1. What is abstract Class?
2. What is Interface?
3. What is a difference between abstract and interface?
4. What is Vector, Array List?2
5. What is Hash table and Hash map
6. What is StringTokenizer?
7. What is the difference between string and string buffer?
8. What is Exception? How many type of Exceptions
9. What is the difference between compile time exception and run time exception
10. What is synchronization
11.
Type III
1. What is Hash Tree and Hash map?
2. What is IO?
3. What is socket and datagram?
4.
Type IV
1. What is Thread?
2. What is wait, Join, sleep?
DataBase:
Standard Questions:
1. How will you connect to the Database?
2. What is mean by Class.forName, sun.jdbc.odbc
3. What is the difference between prepared statement and callable statement.
4. How many types of dirvers available? *
5. What is difference between statement and prepared statement?
6. What is the difference between executeQuery, executeUpdate and execute.
7. What is ResultSet meta data and database meta data? *
8.
9.
Servlet
1. What is servlet?
2. What is the difference between doGet and doPost?
JSP
1. What are the advantages of the JSP
2. What is difference between include and forward? *
3. What is the difference between sendreaderwrite and forward *
4. What are the implicits objects in JSP
5. How will you handle error page in Java. *
6. What is the difference between page, session, request and application
7. How will you make JSP thread at safe? *
8.
Face to Face Interview Questions:
1. How will setup Tomcat:
HTML ADD Dynamic ROW in table
This code is taken from http://www.mredkj.com/tutorials/tableaddrow.html it is an excellent site for DHTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<script language="javascript">
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// right cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'txtRow' + iteration;
el.id = 'txtRow' + iteration;
el.size = 40;
el.onkeypress = keyPressTest;
cellRight.appendChild(el);
// select cell
var cellRightSel = row.insertCell(2);
var sel = document.createElement('select');
sel.name = 'selRow' + iteration;
sel.options[0] = new Option('text zero', 'value0');
sel.options[1] = new Option('text one', 'value1');
cellRightSel.appendChild(sel);
}
function keyPressTest(e, obj)
{
var validateChkb = document.getElementById('chkValidateOnKeyPress');
if (validateChkb.checked) {
var displayObj = document.getElementById('spanOutput');
var key;
if(window.event) {
key = window.event.keyCode;
}
else if(e.which) {
key = e.which;
}
var objId;
if (obj != null) {
objId = obj.id;
} else {
objId = this.id;
}
displayObj.innerHTML = objId + ' : ' + String.fromCharCode(key);
}
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'TableAddRowNewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'TableAddRowNewWindow';
// submit
frm.submit();
}
function validateRow(frm)
{
var chkb = document.getElementById('chkValidate');
if (chkb.checked) {
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length - 1;
var i;
for (i=1; i<=lastRow; i++) {
var aRow = document.getElementById('txtRow' + i);
if (aRow.value.length <= 0) {
alert('Row ' + i + ' is empty');
return;
}
}
}
openInNewWindow(frm);
}
</script>
</HEAD>
<BODY>
<form action="tableaddrow_nw.html" method="get">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
<input type="button" value="Submit" onclick="validateRow(this.form);" />
<input type="checkbox" id="chkValidate" /> Validate Submit
</p>
<p>
<input type="checkbox" id="chkValidateOnKeyPress" checked="checked" /> Display OnKeyPress
<span id="spanOutput" style="border: 1px solid #000; padding: 3px;"> </span>
</p>
<table border="1" id="tblSample">
<tr>
<th colspan="3">Sample table</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="txtRow1"
id="txtRow1" size="40" onkeypress="keyPressTest(event, this);" /></td>
<td>
<select name="selRow0">
<option value="value0">text zero</option>
<option value="value1">text one</option>
</select>
</td>
</tr>
</table>
</form>
</BODY>
</HTML>
New Document
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<script language="javascript">
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// right cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'txtRow' + iteration;
el.id = 'txtRow' + iteration;
el.size = 40;
el.onkeypress = keyPressTest;
cellRight.appendChild(el);
// select cell
var cellRightSel = row.insertCell(2);
var sel = document.createElement('select');
sel.name = 'selRow' + iteration;
sel.options[0] = new Option('text zero', 'value0');
sel.options[1] = new Option('text one', 'value1');
cellRightSel.appendChild(sel);
}
function keyPressTest(e, obj)
{
var validateChkb = document.getElementById('chkValidateOnKeyPress');
if (validateChkb.checked) {
var displayObj = document.getElementById('spanOutput');
var key;
if(window.event) {
key = window.event.keyCode;
}
else if(e.which) {
key = e.which;
}
var objId;
if (obj != null) {
objId = obj.id;
} else {
objId = this.id;
}
displayObj.innerHTML = objId + ' : ' + String.fromCharCode(key);
}
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'TableAddRowNewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'TableAddRowNewWindow';
// submit
frm.submit();
}
function validateRow(frm)
{
var chkb = document.getElementById('chkValidate');
if (chkb.checked) {
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length - 1;
var i;
for (i=1; i<=lastRow; i++) {
var aRow = document.getElementById('txtRow' + i);
if (aRow.value.length <= 0) {
alert('Row ' + i + ' is empty');
return;
}
}
}
openInNewWindow(frm);
}
</script>
</HEAD>
<BODY>
<form action="tableaddrow_nw.html" method="get">
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
<input type="button" value="Submit" onclick="validateRow(this.form);" />
<input type="checkbox" id="chkValidate" /> Validate Submit
</p>
<p>
<input type="checkbox" id="chkValidateOnKeyPress" checked="checked" /> Display OnKeyPress
<span id="spanOutput" style="border: 1px solid #000; padding: 3px;"> </span>
</p>
<table border="1" id="tblSample">
<tr>
<th colspan="3">Sample table</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="txtRow1"
id="txtRow1" size="40" onkeypress="keyPressTest(event, this);" /></td>
<td>
<select name="selRow0">
<option value="value0">text zero</option>
<option value="value1">text one</option>
</select>
</td>
</tr>
</table>
</form>
</BODY>
</HTML>
Thursday, September 24, 2009
Good Flash Templates
http://www.flashvillage.com/ is the best site to view and download Flash Templates
Friday, August 21, 2009
MY Back UP
PHP BACK UP :
This is only for my reference others dont use it
http://www.efreelearn.com/BCP/test/BCP_CALL_COMMON.html
PHP Oject CODE
// first test simple associative arrays
$memory1 = xdebug_memory_usage( );
$data = array();
for($i=0;$i<1000;$i++) {
$data[] = array(
'property1' => md5(microtime()),
'property2' => md5(microtime()),
'property3' => md5(microtime()),
);
}
$array = xdebug_memory_usage()-$memory1 . "\n";
// Now do the same thing, but with a class..
class Test {
public $property1;
public $property2;
public $property3;
}
$data = array();
$memory1 = xdebug_memory_usage( );
for($i=0;$i<1000;$i++) {
$test = new Test();
$test->property1 = md5(microtime());
$test->property2 = md5(microtime());
$test->property3 = md5(microtime());
$data[] = $test;
}
$object = xdebug_memory_usage()-$memory1;
echo 'Arrays: ' . $array . "\n";
echo 'Objects: ' . $object;
?>
This is only for my reference others dont use it
http://www.efreelearn.com/BCP/test/BCP_CALL_COMMON.html
PHP Oject CODE
// first test simple associative arrays
$memory1 = xdebug_memory_usage( );
$data = array();
for($i=0;$i<1000;$i++) {
$data[] = array(
'property1' => md5(microtime()),
'property2' => md5(microtime()),
'property3' => md5(microtime()),
);
}
$array = xdebug_memory_usage()-$memory1 . "\n";
// Now do the same thing, but with a class..
class Test {
public $property1;
public $property2;
public $property3;
}
$data = array();
$memory1 = xdebug_memory_usage( );
for($i=0;$i<1000;$i++) {
$test = new Test();
$test->property1 = md5(microtime());
$test->property2 = md5(microtime());
$test->property3 = md5(microtime());
$data[] = $test;
}
$object = xdebug_memory_usage()-$memory1;
echo 'Arrays: ' . $array . "\n";
echo 'Objects: ' . $object;
?>
Wednesday, August 5, 2009
Spring Tutor
Spring Practical Questions : (reference http://www.java2s.com/Code/Java/Spring/RegexpPointcutExample.htm)
===================
1. What is dependencyInjection explain with Configuration Example?
Instead of a code calls a component a configuration file will be used to call component this is known us dependencyInjection.
- Container Takes care maintainblity of Component. Detail information will updated later.
- Loose coupling exists between Component and Client.
<beans>
<bean class="com.seetab.scar.matchmaker.impl.StudyDaoImpl" id="studyDao">
</beans>
2.How many types of depency Injections are there? Explain with Code.
-Constructor Injection.
-Setter Injection.
-Interface Injection.
3.Please explain the follwing terms in AOP?
a.org.springframework.aop.framework.ProxyFactoryBean - Spring Defined Proxy Bean
b.proxyInterfaces - Defines which interface needs to be called.
c.interceptorNames - Defines which Impl needs to be mapped
<bean id = "beforeCall" class = "com.spring.aop.LogBeforeCallAdvice" />
<!-- Implementation Class -->
<bean id = "adderImpl" class = "com.spring.aop.AdderImpl" />
<!-- Proxy Implementation Class -->
<bean id = "adder" class = "org.springframework.aop.framework.ProxyFactoryBean">
<property name = "proxyInterfaces">
<value>com.spring.aop.Adder</value>
</property>
<property name = "interceptorNames">
<list>
<value>beforeCall</value>
</list>
</property>
<property name = "target">
<ref bean = "adderImpl"/>
</property>
</bean>
4.What is Static Point Cuts (Name Method Match and Regular Expression Point Cuts)?
5.How a constructor values are initialised in IOC or Dependency Injection?
6.What is interceptor Pattern?
7.Please Explain Steps to Integrate spring with Hiberante?
- Required Component : ______.HBM.XML, Configuration.XML (Spring Configuration File)
1)Create Bean ID for DAO or Impl
2)Create Datasource. Note : datasource Name
3)Create Session Factory From
org.springframework.orm.hibernate3.LocalSessionFactoryBean (datasource,mappingreosurces,hibernateproperties are mapped).
8.How the Client Program is defined?
1.Define classpath : ClassPathXmlApplicationContext
2.getBean
3.Assign Bean to DAO
4.Save
9.What is HIbernate Template?
1. What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.
2. What are the different types of IOC (dependency injection) ?
There are three types of dependency injection:
Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection
3. What are the benefits of IOC (Dependency Injection)?
Benefits of IOC (Dependency Injection) are as follows:
Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.
4. What is Spring ?
Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.
5. What are the advantages of Spring framework?
The advantages of Spring are as follows:
Spring has layered architecture. Use what you need and leave you don't need now.
Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
Dependency Injection and Inversion of Control Simplifies JDBC
Open source and no vendor lock-in.
6. What are features of Spring ?
Lightweight:
spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
Inversion of control (IOC):
Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP):
Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container:
Spring contains and manages the life cycle and configuration of application objects.
MVC Framework:
Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS
7. How many modules are there in Spring? What are they?
(Roll over to view the Image )
Spring comprises of seven modules. They are..
The core container:
The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code.
Spring context:
The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.
Spring AOP:
The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.
Spring DAO:
The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy.
Spring ORM:
The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies.
Spring Web module:
The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.
Spring MVC framework:
The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.
8. What are the types of Dependency Injection Spring supports?>
Setter Injection:
Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Constructor Injection:
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.
9. What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
10. What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
A means for resolving text messages, including support for internationalization.
A generic way to load file resources.
Events to beans that are registered as listeners.
11. What is the difference between Bean Factory and Application Context ?
On the surface, an application context is same as a bean factory. But application context offers much more..
Application contexts provide a means for resolving text messages, including support for i18n of those messages.
Application contexts provide a generic way to load file resources, such as images.
Application contexts can publish events to beans that are registered as listeners.
Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable
12. What are the common implementations of the Application Context ?
The three commonly used implementation of 'Application Context' are
ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code .ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code . ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
13. How is a typical spring implementation look like ?
For a typical Spring Application we need the following files:
An interface that defines the functions.
An Implementation that contains properties, its setter and getter methods, functions etc.,
Spring AOP (Aspect Oriented Programming)
A XML file called Spring configuration file.
Client program that uses the function.
14. What is the typical Bean life cycle in Spring Bean Factory Container ?
Bean life cycle in Spring Bean Factory Container is as follows:
The spring container finds the bean’s definition from the XML file and instantiates the bean.
Using the dependency injection, spring populates all of the properties as specified in the bean definition
If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
If an init-method is specified for the bean, it will be called.
Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
15. What do you mean by Bean wiring ?
The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring.
16. What do you mean by Auto Wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes.
no
byName
byType
constructor
autodirect
17. What is DelegatingVariableResolver?
Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard Java Server Faces managed beans mechanism which lets you use JSF and Spring together. This variable resolver is called as DelegatingVariableResolver
18. How to integrate Java Server Faces (JSF) with Spring?
JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By declaring JSF managed-beans in the faces-config.xml configuration file, you allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to these beans and all of their properties.We can integrate JSF and Spring in two ways:
DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF and Spring together.
org.springframework.web.jsf.DelegatingVariableResolver
The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring's 'business context' WebApplicationContext. This allows one to easily inject dependencies into one's JSF-managed beans.
FacesContextUtils:custom VariableResolver works well when mapping one's properties to beans in faces-config.xml, but at times one may need to grab a bean explicitly. The FacesContextUtils class makes this easy. It is similar to WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter.
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
19. What is Java Server Faces (JSF) - Spring integration mechanism?
Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard JavaServer Faces managed beans mechanism. When asked to resolve a variable name, the following algorithm is performed:
Does a bean with the specified name already exist in some scope (request, session, application)? If so, return it
Is there a standard JavaServer Faces managed bean definition for this variable name? If so, invoke it in the usual way, and return the bean that was created.
Is there configuration information for this variable name in the Spring WebApplicationContext for this application? If so, use it to create and configure an instance, and return that instance to the caller.
If there is no managed bean or Spring definition for this variable name, return null instead.
BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
As a result of this algorithm, you can transparently use either JavaServer Faces or Spring facilities to create beans on demand.
20. What is Significance of JSF- Spring integration ?
Spring - JSF integration is useful when an event handler wishes to explicitly invoke the bean factory to create beans on demand, such as a bean that encapsulates the business logic to be performed when a submit button is pressed.
21. How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:
Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.
22. What are ORM’s Spring supports ?
Spring supports the following ORM’s :
Hibernate
iBatis
JPA (Java Persistence API)
TopLink
JDO (Java Data Objects)
OJB
23. What are the ways to access Hibernate using Spring ?
There are two approaches to Spring’s Hibernate integration:
Inversion of Control with a HibernateTemplate and Callback
Extending HibernateDaoSupport and Applying an AOP Interceptor
24. How to integrate Spring and Hibernate using HibernateDaoSupport?
Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
Configure the Hibernate SessionFactory
Extend your DAO Implementation from HibernateDaoSupport
Wire in Transaction Support with AOP
25. What are Bean scopes in Spring Framework ?
The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext). The scopes supported are listed below:
Scope
Description
singleton
Scopes a single bean definition to a single object instance per Spring IoC container.
prototype
Scopes a single bean definition to any number of object instances.
request
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
26. What is AOP?
Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.
27. How the AOP used in Spring?
AOP is used in the Spring Framework: To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on the Spring Framework's transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP.
28. What do you mean by Aspect ?
A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).
29. What do you mean by JointPoint?
A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
30. What do you mean by Advice?
Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point.
31. What are the types of Advice?
Types of advice:
Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
After throwing advice: Advice to be executed if a method exits by throwing an exception.
After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception
32. What are the types of the transaction management Spring supports ?
Spring Framework supports:
Programmatic transaction management.
Declarative transaction management.
33. What are the benefits of the Spring Framework transaction management ?
The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:
Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
Supports declarative transaction management.
Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
Integrates very well with Spring's various data access abstractions.
34. Why most users of the Spring Framework choose declarative transaction management ?
Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container.
35. Explain the similarities and differences between EJB CMT and the Spring Framework's declarative transaction management ?
The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to individual method level. It is possible to make a setRollbackOnly() call within a transaction context if necessary. The differences are:
Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction management works in any environment. It can work with JDBC, JDO, Hibernate or other transactions under the covers, with configuration changes only.
The Spring Framework enables declarative transaction management to be applied to any class, not merely special classes such as EJBs.
The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent. Both programmatic and declarative support for rollback rules is provided.
The Spring Framework gives you an opportunity to customize transactional behavior, using AOP. With EJB CMT, you have no way to influence the container's transaction management other than setRollbackOnly().
The Spring Framework does not support propagation of transaction contexts across remote calls, as do high-end application servers.
37. When to use programmatic and declarative transaction management ?
Programmatic transaction management is usually a good idea only if you have a small number of transactional operations. On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.
38. Explain about the Spring DAO support ?
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.
google_protectAndRun("ads_core.google_render_ad", google_handleError, google_render_ad);
39. What are the exceptions thrown by the Spring DAO classes ?
Spring DAO classes throw exceptions which are subclasses of DataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception.
40. What is SQLExceptionTranslator ?
SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own data-access-strategy-agnostic org.springframework.dao.DataAccessException.
41. What is Spring's JdbcTemplate ?
Spring's JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.
JdbcTemplate template = new JdbcTemplate(myDataSource);
42. What is PreparedStatementCreator ?
PreparedStatementCreator:
Is one of the most common used interfaces for writing data to database.
Has one method – createPreparedStatement(Connection)
Responsible for creating a PreparedStatement.
Does not need to handle SQLExceptions.
43. What is SQLProvider ?
SQLProvider:
Has one method – getSql()
Typically implemented by PreparedStatementCreator implementers.
Useful for debugging.
44. What is RowCallbackHandler ?
The RowCallbackHandler interface extracts values from each row of a ResultSet.
Has one method – processRow(ResultSet)
Called for each row in ResultSet.
Typically stateful.
45. What are the differences between EJB and Spring ?
Spring and EJB feature comparison.
Feature
EJB
Spring
Transaction management
Must use a JTA transaction manager.
Supports transactions that span remote method calls.
Supports multiple transaction environments through its PlatformTransactionManager interface, including JTA, Hibernate, JDO, and JDBC.
Does not natively support distributed transactions—it must be used with a JTA transaction manager.
Declarative transaction support
Can define transactions declaratively through the deployment descriptor.
Can define transaction behavior per method or per class by using the wildcard character *.
Cannot declaratively define rollback behavior—this must be done programmatically.
Can define transactions declaratively through the Spring configuration file or through class metadata.
Can define which methods to apply transaction behavior explicitly or by using regular expressions.
Can declaratively define rollback behavior per method and per exception type.
Persistence
Supports programmatic bean-managed persistence and declarative container managed persistence.
Provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS.
Declarative security
Supports declarative security through users and roles. The management and implementation of users and roles is container specific.
Declarative security is configured in the deployment descriptor.
No security implementation out-of-the box.
Acegi, an open source security framework built on top of Spring, provides declarative security through the Spring configuration file or class metadata.
Distributed computing
Provides container-managed remote method calls.
Provides proxying for remote calls via RMI, JAX-RPC, and web services.
These questions are taken from http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php
My Questions :
What is Spring ? How it is better than other Framework?
Exlain AOP in detail : What is point cut,How log implemented
what is the difference between ref- Bean and bean-id
What is the difference between Normal Exception and Spring way of exceptionHandling
What are the core components of Spring?
What is AutoWiring?
How to Intergrate Spring with Hibernate?
How to Intergrate Spring with Struts?
How to Intergrate Spring with JSF?
How Transctions are handled in Spring?
===================
1. What is dependencyInjection explain with Configuration Example?
Instead of a code calls a component a configuration file will be used to call component this is known us dependencyInjection.
- Container Takes care maintainblity of Component. Detail information will updated later.
- Loose coupling exists between Component and Client.
<beans>
<bean class="com.seetab.scar.matchmaker.impl.StudyDaoImpl" id="studyDao">
</beans>
2.How many types of depency Injections are there? Explain with Code.
-Constructor Injection.
-Setter Injection.
-Interface Injection.
3.Please explain the follwing terms in AOP?
a.org.springframework.aop.framework.ProxyFactoryBean - Spring Defined Proxy Bean
b.proxyInterfaces - Defines which interface needs to be called.
c.interceptorNames - Defines which Impl needs to be mapped
<bean id = "beforeCall" class = "com.spring.aop.LogBeforeCallAdvice" />
<!-- Implementation Class -->
<bean id = "adderImpl" class = "com.spring.aop.AdderImpl" />
<!-- Proxy Implementation Class -->
<bean id = "adder" class = "org.springframework.aop.framework.ProxyFactoryBean">
<property name = "proxyInterfaces">
<value>com.spring.aop.Adder</value>
</property>
<property name = "interceptorNames">
<list>
<value>beforeCall</value>
</list>
</property>
<property name = "target">
<ref bean = "adderImpl"/>
</property>
</bean>
4.What is Static Point Cuts (Name Method Match and Regular Expression Point Cuts)?
5.How a constructor values are initialised in IOC or Dependency Injection?
6.What is interceptor Pattern?
7.Please Explain Steps to Integrate spring with Hiberante?
- Required Component : ______.HBM.XML, Configuration.XML (Spring Configuration File)
1)Create Bean ID for DAO or Impl
2)Create Datasource. Note : datasource Name
3)Create Session Factory From
org.springframework.orm.hibernate3.LocalSessionFactoryBean (datasource,mappingreosurces,hibernateproperties are mapped).
8.How the Client Program is defined?
1.Define classpath : ClassPathXmlApplicationContext
2.getBean
3.Assign Bean to DAO
4.Save
9.What is HIbernate Template?
1. What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up.i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.
2. What are the different types of IOC (dependency injection) ?
There are three types of dependency injection:
Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters.
Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
Interface Injection (e.g. Avalon): Injection is done through an interface.
Note: Spring supports only Constructor and Setter Injection
3. What are the benefits of IOC (Dependency Injection)?
Benefits of IOC (Dependency Injection) are as follows:
Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.
Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own.
IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.
4. What is Spring ?
Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.
5. What are the advantages of Spring framework?
The advantages of Spring are as follows:
Spring has layered architecture. Use what you need and leave you don't need now.
Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
Dependency Injection and Inversion of Control Simplifies JDBC
Open source and no vendor lock-in.
6. What are features of Spring ?
Lightweight:
spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
Inversion of control (IOC):
Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
Aspect oriented (AOP):
Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
Container:
Spring contains and manages the life cycle and configuration of application objects.
MVC Framework:
Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS
7. How many modules are there in Spring? What are they?
(Roll over to view the Image )
Spring comprises of seven modules. They are..
The core container:
The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code.
Spring context:
The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.
Spring AOP:
The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.
Spring DAO:
The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy.
Spring ORM:
The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies.
Spring Web module:
The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.
Spring MVC framework:
The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.
8. What are the types of Dependency Injection Spring supports?>
Setter Injection:
Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Constructor Injection:
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.
9. What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client.
BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
10. What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
A means for resolving text messages, including support for internationalization.
A generic way to load file resources.
Events to beans that are registered as listeners.
11. What is the difference between Bean Factory and Application Context ?
On the surface, an application context is same as a bean factory. But application context offers much more..
Application contexts provide a means for resolving text messages, including support for i18n of those messages.
Application contexts provide a generic way to load file resources, such as images.
Application contexts can publish events to beans that are registered as listeners.
Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
ResourceLoader support: Spring’s Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances.
MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable
12. What are the common implementations of the Application Context ?
The three commonly used implementation of 'Application Context' are
ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code .ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code . ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
13. How is a typical spring implementation look like ?
For a typical Spring Application we need the following files:
An interface that defines the functions.
An Implementation that contains properties, its setter and getter methods, functions etc.,
Spring AOP (Aspect Oriented Programming)
A XML file called Spring configuration file.
Client program that uses the function.
14. What is the typical Bean life cycle in Spring Bean Factory Container ?
Bean life cycle in Spring Bean Factory Container is as follows:
The spring container finds the bean’s definition from the XML file and instantiates the bean.
Using the dependency injection, spring populates all of the properties as specified in the bean definition
If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
If an init-method is specified for the bean, it will be called.
Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
15. What do you mean by Bean wiring ?
The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring.
16. What do you mean by Auto Wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes.
no
byName
byType
constructor
autodirect
17. What is DelegatingVariableResolver?
Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard Java Server Faces managed beans mechanism which lets you use JSF and Spring together. This variable resolver is called as DelegatingVariableResolver
18. How to integrate Java Server Faces (JSF) with Spring?
JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By declaring JSF managed-beans in the faces-config.xml configuration file, you allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to these beans and all of their properties.We can integrate JSF and Spring in two ways:
DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF and Spring together.
org.springframework.web.jsf.DelegatingVariableResolver
The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring's 'business context' WebApplicationContext. This allows one to easily inject dependencies into one's JSF-managed beans.
FacesContextUtils:custom VariableResolver works well when mapping one's properties to beans in faces-config.xml, but at times one may need to grab a bean explicitly. The FacesContextUtils class makes this easy. It is similar to WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter.
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
19. What is Java Server Faces (JSF) - Spring integration mechanism?
Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard JavaServer Faces managed beans mechanism. When asked to resolve a variable name, the following algorithm is performed:
Does a bean with the specified name already exist in some scope (request, session, application)? If so, return it
Is there a standard JavaServer Faces managed bean definition for this variable name? If so, invoke it in the usual way, and return the bean that was created.
Is there configuration information for this variable name in the Spring WebApplicationContext for this application? If so, use it to create and configure an instance, and return that instance to the caller.
If there is no managed bean or Spring definition for this variable name, return null instead.
BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
As a result of this algorithm, you can transparently use either JavaServer Faces or Spring facilities to create beans on demand.
20. What is Significance of JSF- Spring integration ?
Spring - JSF integration is useful when an event handler wishes to explicitly invoke the bean factory to create beans on demand, such as a bean that encapsulates the business logic to be performed when a submit button is pressed.
21. How to integrate your Struts application with Spring?
To integrate your Struts application with Spring, we have two options:
Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.
22. What are ORM’s Spring supports ?
Spring supports the following ORM’s :
Hibernate
iBatis
JPA (Java Persistence API)
TopLink
JDO (Java Data Objects)
OJB
23. What are the ways to access Hibernate using Spring ?
There are two approaches to Spring’s Hibernate integration:
Inversion of Control with a HibernateTemplate and Callback
Extending HibernateDaoSupport and Applying an AOP Interceptor
24. How to integrate Spring and Hibernate using HibernateDaoSupport?
Spring and Hibernate can integrate using Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps.
Configure the Hibernate SessionFactory
Extend your DAO Implementation from HibernateDaoSupport
Wire in Transaction Support with AOP
25. What are Bean scopes in Spring Framework ?
The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext). The scopes supported are listed below:
Scope
Description
singleton
Scopes a single bean definition to a single object instance per Spring IoC container.
prototype
Scopes a single bean definition to any number of object instances.
request
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
26. What is AOP?
Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.
27. How the AOP used in Spring?
AOP is used in the Spring Framework: To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on the Spring Framework's transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP.
28. What do you mean by Aspect ?
A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).
29. What do you mean by JointPoint?
A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
30. What do you mean by Advice?
Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point.
31. What are the types of Advice?
Types of advice:
Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.
After throwing advice: Advice to be executed if a method exits by throwing an exception.
After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception
32. What are the types of the transaction management Spring supports ?
Spring Framework supports:
Programmatic transaction management.
Declarative transaction management.
33. What are the benefits of the Spring Framework transaction management ?
The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:
Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
Supports declarative transaction management.
Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
Integrates very well with Spring's various data access abstractions.
34. Why most users of the Spring Framework choose declarative transaction management ?
Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container.
35. Explain the similarities and differences between EJB CMT and the Spring Framework's declarative transaction management ?
The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to individual method level. It is possible to make a setRollbackOnly() call within a transaction context if necessary. The differences are:
Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction management works in any environment. It can work with JDBC, JDO, Hibernate or other transactions under the covers, with configuration changes only.
The Spring Framework enables declarative transaction management to be applied to any class, not merely special classes such as EJBs.
The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent. Both programmatic and declarative support for rollback rules is provided.
The Spring Framework gives you an opportunity to customize transactional behavior, using AOP. With EJB CMT, you have no way to influence the container's transaction management other than setRollbackOnly().
The Spring Framework does not support propagation of transaction contexts across remote calls, as do high-end application servers.
37. When to use programmatic and declarative transaction management ?
Programmatic transaction management is usually a good idea only if you have a small number of transactional operations. On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.
38. Explain about the Spring DAO support ?
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology.
google_protectAndRun("ads_core.google_render_ad", google_handleError, google_render_ad);
39. What are the exceptions thrown by the Spring DAO classes ?
Spring DAO classes throw exceptions which are subclasses of DataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception.
40. What is SQLExceptionTranslator ?
SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own data-access-strategy-agnostic org.springframework.dao.DataAccessException.
41. What is Spring's JdbcTemplate ?
Spring's JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.
JdbcTemplate template = new JdbcTemplate(myDataSource);
42. What is PreparedStatementCreator ?
PreparedStatementCreator:
Is one of the most common used interfaces for writing data to database.
Has one method – createPreparedStatement(Connection)
Responsible for creating a PreparedStatement.
Does not need to handle SQLExceptions.
43. What is SQLProvider ?
SQLProvider:
Has one method – getSql()
Typically implemented by PreparedStatementCreator implementers.
Useful for debugging.
44. What is RowCallbackHandler ?
The RowCallbackHandler interface extracts values from each row of a ResultSet.
Has one method – processRow(ResultSet)
Called for each row in ResultSet.
Typically stateful.
45. What are the differences between EJB and Spring ?
Spring and EJB feature comparison.
Feature
EJB
Spring
Transaction management
Must use a JTA transaction manager.
Supports transactions that span remote method calls.
Supports multiple transaction environments through its PlatformTransactionManager interface, including JTA, Hibernate, JDO, and JDBC.
Does not natively support distributed transactions—it must be used with a JTA transaction manager.
Declarative transaction support
Can define transactions declaratively through the deployment descriptor.
Can define transaction behavior per method or per class by using the wildcard character *.
Cannot declaratively define rollback behavior—this must be done programmatically.
Can define transactions declaratively through the Spring configuration file or through class metadata.
Can define which methods to apply transaction behavior explicitly or by using regular expressions.
Can declaratively define rollback behavior per method and per exception type.
Persistence
Supports programmatic bean-managed persistence and declarative container managed persistence.
Provides a framework for integrating with several persistence technologies, including JDBC, Hibernate, JDO, and iBATIS.
Declarative security
Supports declarative security through users and roles. The management and implementation of users and roles is container specific.
Declarative security is configured in the deployment descriptor.
No security implementation out-of-the box.
Acegi, an open source security framework built on top of Spring, provides declarative security through the Spring configuration file or class metadata.
Distributed computing
Provides container-managed remote method calls.
Provides proxying for remote calls via RMI, JAX-RPC, and web services.
These questions are taken from http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php
My Questions :
What is Spring ? How it is better than other Framework?
Exlain AOP in detail : What is point cut,How log implemented
what is the difference between ref- Bean and bean-id
What is the difference between Normal Exception and Spring way of exceptionHandling
What are the core components of Spring?
What is AutoWiring?
How to Intergrate Spring with Hibernate?
How to Intergrate Spring with Struts?
How to Intergrate Spring with JSF?
How Transctions are handled in Spring?
Tuesday, August 4, 2009
Hibernate Practical & Interview Questions
Hibernate Practical Questions :
1.In which folder hibernate.cfg.xml & ____.hbm.xml will be there?
hibernate.cfg.xml in root folder and ____.hbm.xml will be in Bean Folder.
2)What is the key defines it is a Composite Key?
composite-id
3.What are the Key properties while defining Composite key?
a)Create CompositePK Class
b)Defined parameter in XML
<class name="com.hibernate.composite.Book_info" table="book_info">
<composite-id name="bookPK" class="com.hibernate.composite.BookPK">
<key-property name="book_id" column="book_id" type="string" />
<key-property name="book_name" column="book_name" type="string" />
</composite-id>
<property name="author" column="author" type="string"/>
</class>
c) Send Composite Key values as Object
Hibernate Interview Questions :
Q1. Which statement is correct ?
1 session.contains() method to determine if an instance belongs to the session cache.
2 session.contains() method to determine if an instance belongs to the data base .
3 Both are correct
4 none of the above
4Correct Answer is :
Q2. What does hibernate.show_sql true mean ?
1 show sql results on console.
2 show sql inputs on console.
3 show sql statement on console.
4 None
Correct Answer is : 3
Q3. What is the naming convention for Hibernate XML mapping file extensions?
1 .hbm.xml
2 .hhm.xml
3 .hb.xml
4 none of the above
Correct Answer is : 1
Q4. What does session.createCriteria().uniqueResult() return ?
1 Object
2 String
3 ResultSet
4 HibernateResultSet
Correct Answer is : 1
Q5. ____ forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.
1 By mapping the property with access="onlyfield" in Hibernate metadata
2 By mapping the property with access="variable" in Hibernate metadata
3 By mapping the property with access="field" in Hibernate metadata
4 none of the above
Correct Answer is : 3
Q6. What does session.load() return if there is no matching database row ?
1 NULL
2 Empty Object
3 unrecoverable exception
4 None of the above
Correct Answer is : 3
Q7. It is possible to re-load an object and all its collections at any time, using the xxxx() method. This is useful when database triggers are used to initialize some of the properties of the object. What is the xxxx() method ?
1 refresh();
2 flush();
3 fetch();
4 load()
Correct Answer is : 1
Q8. What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath?
1 The settings of the properties file will override the settings used in the XML configuration
2 The settings of the XML configuration file will override the settings used in the properties
3 DuplicateConfigurationException
4 None
Correct Answer is : 2
Q9. What is the naming convention for Hibernate XML mapping file extensions?
1 .hibernate.xml
2 .hbm.xml
3 .hibernate_data.xml
4 none
Correct Answer is : 1
Q10. What is dirty checking in Hibernate?
1 bject state changes in order to synchronize the updated state with the database
2 remove the dirty data from data base.
3 check the data when insert into data base.
4 None
Correct Answer is : 1
Q11. If instances are not in the session or second-level cache which will give better performance?
1 Query.list()
2 Query.iterate()
3 Both are same
4 None of the above
Correct Answer is : 1
Q12. Which fetching strategy tuned query automatically ?
1 session.createQuery();
2 session.createCriteria();
3 session.createSQLQuery();
4 None Of the above
Correct Answer is : 2
Q13. Is Hibernate Session threadsafe?
1 threadsafe
2 not threadsafe
3 No relation to Thread
4 None of the above
Correct Answer is : 2
Q14. In the .bhm.xml file? ] ]> What is correct way of executipon of the above query in the .bhm.xml file.
1 Query q = sess.getNamedQuery("abc");
2 Query q = sess.createQuery("abc");
3 Query q = sess.createSQLQuery("abc");
4 none of the above
Correct Answer is : 1
Q15. What is Configuration interface in hibernate?
1 used to create SessionFactory.
2 used to create Session.
3 used to create Transaction.
4 none of the above
Correct Answer is : 1
Q16. By default, Hibernate uses _ for JVM-level caching.
1 OSCache
2 EHCache
3 JBOSSCache
4 None of the above
Correct Answer is : 2
Q17. Which Cache Strategy particularly useful in cases where underlying data may have been updated via a separate process (i.e., not modified through Hibernate)?
1 Query.setCacheMode(CacheMode.READ).
2 Query.setCacheMode(CacheMode.REFRESH).
3 Query.setCacheMode(CacheMode.NONE).
4 Query.setCacheMode(CacheMode.REFRESHDATABASE).
Correct Answer is : 2
Q18. What does session.evict() method do ?
1 remove the object and its collections from the first level cache
2 remove the object and its collections from the second level cache
3 remove the object and its collections from the data base
4 None of the above
Correct Answer is : 1
Q19. Is the below code work ? Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { Customer customer = new Customer(.....); session.save(customer); } tx.commit(); session.close();
1 true
2 false
3 can't say
4 none
Correct Answer is : 2
Q20. SessionFactory represent which level of cache ?
1 2nd
2 Ist
3 3rd
4 4th
Correct Answer is : 1
Q21. How can get a session object ?
1 SessionFactory.getSession();
2 SessionFactory.openSession();
3 SessionFactory.get();
4 (session)SessionFactory.getObject();
Correct Answer is : 2
Q22. To completely evict all objects from the session cache which method is appropriate ?
1 Session.evict()
2 Session.clear()
3 Session.flush()
4 None of the above
Correct Answer is : 2
Hibernate Mock Online test
Q23. What Session.flush() do ?
1 the state of that object will be synchronized with the database.
2 the state of that object will be synchronized with the SessionFactory.
3 remove state of that object from Session.
4 remove state of that object from SessionFactory.
Correct Answer is : 1
Q24. How to create SessionFactory ?
1 configuration.buildSessionFactory();
2 configuration.createSessionFactory();
3 configuration.createNewSessionFactory();
4 none of the above
Correct Answer is : 1
Q25. Difference between Emp e = session.load(Emp.class) and Emp e = session.createCriteria(Emp.class) ?
1 On session close session.load() Emp Object unavilabe to access.
2 On session close session.createCriteria() Emp unavilabe to access.
3 None
4 None
Correct Answer is : 1
Q26. Which statement is correct ?
1 A Session will not obtain a JDBC Connection (or a Datasource) unless it is needed
2 A Session will obtain a JDBC Connection (or a Datasource) on object create
3 A Session has no relation with JDBC Connection (or a Datasource)
4 none of the above
Correct Answer is : 2
Q27. what is the default value in hibernate ?
1 lazy=false;
2 lazy=true;
3 lazy=yes;
4 lazy=no;
You have choosen : 1Correct Answer is : 2You were wrong.
Explanations : null
Q28. Which statement is correct
1 The CacheMode controls how a particular session interacts with the second-level cache.
2 The CacheMode don't controls session interaction with the second-level cache.
3 both
4 none
Correct Answer is : 1
Q29. Which statement is true about session.saveOrUpdate()?
1 if another object associated with the session has the same identifier, throw an exception
2 if the object has no identifier property, save() it
3 Both of the above
4 none of the above
Correct Answer is : 1
Q30. Which statement is correct ?
1 Specifying join as the fetch strategy in the mapping document does affect HQL queries.
2 Specifying join as the fetch strategy in the mapping document does not affect HQL queries.
3 None
4 None
Correct Answer is : 2
1.In which folder hibernate.cfg.xml & ____.hbm.xml will be there?
hibernate.cfg.xml in root folder and ____.hbm.xml will be in Bean Folder.
2)What is the key defines it is a Composite Key?
composite-id
3.What are the Key properties while defining Composite key?
a)Create CompositePK Class
b)Defined parameter in XML
<class name="com.hibernate.composite.Book_info" table="book_info">
<composite-id name="bookPK" class="com.hibernate.composite.BookPK">
<key-property name="book_id" column="book_id" type="string" />
<key-property name="book_name" column="book_name" type="string" />
</composite-id>
<property name="author" column="author" type="string"/>
</class>
c) Send Composite Key values as Object
Hibernate Interview Questions :
Q1. Which statement is correct ?
1 session.contains() method to determine if an instance belongs to the session cache.
2 session.contains() method to determine if an instance belongs to the data base .
3 Both are correct
4 none of the above
4Correct Answer is :
Q2. What does hibernate.show_sql true mean ?
1 show sql results on console.
2 show sql inputs on console.
3 show sql statement on console.
4 None
Correct Answer is : 3
Q3. What is the naming convention for Hibernate XML mapping file extensions?
1 .hbm.xml
2 .hhm.xml
3 .hb.xml
4 none of the above
Correct Answer is : 1
Q4. What does session.createCriteria().uniqueResult() return ?
1 Object
2 String
3 ResultSet
4 HibernateResultSet
Correct Answer is : 1
Q5. ____ forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.
1 By mapping the property with access="onlyfield" in Hibernate metadata
2 By mapping the property with access="variable" in Hibernate metadata
3 By mapping the property with access="field" in Hibernate metadata
4 none of the above
Correct Answer is : 3
Q6. What does session.load() return if there is no matching database row ?
1 NULL
2 Empty Object
3 unrecoverable exception
4 None of the above
Correct Answer is : 3
Q7. It is possible to re-load an object and all its collections at any time, using the xxxx() method. This is useful when database triggers are used to initialize some of the properties of the object. What is the xxxx() method ?
1 refresh();
2 flush();
3 fetch();
4 load()
Correct Answer is : 1
Q8. What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath?
1 The settings of the properties file will override the settings used in the XML configuration
2 The settings of the XML configuration file will override the settings used in the properties
3 DuplicateConfigurationException
4 None
Correct Answer is : 2
Q9. What is the naming convention for Hibernate XML mapping file extensions?
1 .hibernate.xml
2 .hbm.xml
3 .hibernate_data.xml
4 none
Correct Answer is : 1
Q10. What is dirty checking in Hibernate?
1 bject state changes in order to synchronize the updated state with the database
2 remove the dirty data from data base.
3 check the data when insert into data base.
4 None
Correct Answer is : 1
Q11. If instances are not in the session or second-level cache which will give better performance?
1 Query.list()
2 Query.iterate()
3 Both are same
4 None of the above
Correct Answer is : 1
Q12. Which fetching strategy tuned query automatically ?
1 session.createQuery();
2 session.createCriteria();
3 session.createSQLQuery();
4 None Of the above
Correct Answer is : 2
Q13. Is Hibernate Session threadsafe?
1 threadsafe
2 not threadsafe
3 No relation to Thread
4 None of the above
Correct Answer is : 2
Q14. In the .bhm.xml file
1 Query q = sess.getNamedQuery("abc");
2 Query q = sess.createQuery("abc");
3 Query q = sess.createSQLQuery("abc");
4 none of the above
Correct Answer is : 1
Q15. What is Configuration interface in hibernate?
1 used to create SessionFactory.
2 used to create Session.
3 used to create Transaction.
4 none of the above
Correct Answer is : 1
Q16. By default, Hibernate uses _ for JVM-level caching.
1 OSCache
2 EHCache
3 JBOSSCache
4 None of the above
Correct Answer is : 2
Q17. Which Cache Strategy particularly useful in cases where underlying data may have been updated via a separate process (i.e., not modified through Hibernate)?
1 Query.setCacheMode(CacheMode.READ).
2 Query.setCacheMode(CacheMode.REFRESH).
3 Query.setCacheMode(CacheMode.NONE).
4 Query.setCacheMode(CacheMode.REFRESHDATABASE).
Correct Answer is : 2
Q18. What does session.evict() method do ?
1 remove the object and its collections from the first level cache
2 remove the object and its collections from the second level cache
3 remove the object and its collections from the data base
4 None of the above
Correct Answer is : 1
Q19. Is the below code work ? Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { Customer customer = new Customer(.....); session.save(customer); } tx.commit(); session.close();
1 true
2 false
3 can't say
4 none
Correct Answer is : 2
Q20. SessionFactory represent which level of cache ?
1 2nd
2 Ist
3 3rd
4 4th
Correct Answer is : 1
Q21. How can get a session object ?
1 SessionFactory.getSession();
2 SessionFactory.openSession();
3 SessionFactory.get();
4 (session)SessionFactory.getObject();
Correct Answer is : 2
Q22. To completely evict all objects from the session cache which method is appropriate ?
1 Session.evict()
2 Session.clear()
3 Session.flush()
4 None of the above
Correct Answer is : 2
Hibernate Mock Online test
Q23. What Session.flush() do ?
1 the state of that object will be synchronized with the database.
2 the state of that object will be synchronized with the SessionFactory.
3 remove state of that object from Session.
4 remove state of that object from SessionFactory.
Correct Answer is : 1
Q24. How to create SessionFactory ?
1 configuration.buildSessionFactory();
2 configuration.createSessionFactory();
3 configuration.createNewSessionFactory();
4 none of the above
Correct Answer is : 1
Q25. Difference between Emp e = session.load(Emp.class) and Emp e = session.createCriteria(Emp.class) ?
1 On session close session.load() Emp Object unavilabe to access.
2 On session close session.createCriteria() Emp unavilabe to access.
3 None
4 None
Correct Answer is : 1
Q26. Which statement is correct ?
1 A Session will not obtain a JDBC Connection (or a Datasource) unless it is needed
2 A Session will obtain a JDBC Connection (or a Datasource) on object create
3 A Session has no relation with JDBC Connection (or a Datasource)
4 none of the above
Correct Answer is : 2
Q27. what is the default value in hibernate ?
1 lazy=false;
2 lazy=true;
3 lazy=yes;
4 lazy=no;
You have choosen : 1Correct Answer is : 2You were wrong.
Explanations : null
Q28. Which statement is correct
1 The CacheMode controls how a particular session interacts with the second-level cache.
2 The CacheMode don't controls session interaction with the second-level cache.
3 both
4 none
Correct Answer is : 1
Q29. Which statement is true about session.saveOrUpdate()?
1 if another object associated with the session has the same identifier, throw an exception
2 if the object has no identifier property, save() it
3 Both of the above
4 none of the above
Correct Answer is : 1
Q30. Which statement is correct ?
1 Specifying join as the fetch strategy in the mapping document does affect HQL queries.
2 Specifying join as the fetch strategy in the mapping document does not affect HQL queries.
3 None
4 None
Correct Answer is : 2
Subscribe to:
Posts (Atom)