Technical Blog Of JackCHAN

August 29, 2010

Servlet Interview Question and Answer

Filed under: java, Jsp/Servlet — Tags: , , — kaisechen @ 3:11 am

Q:Explain the life cycle methods of a Servlet.
A:
The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.

Q:What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
A:

The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a “/” and are interpreted as relative to curent context root.

Q:Explain the directory structure of a web application.
A:

The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory

Q:What are the common mechanisms used for session tracking?
A:

Cookies
SSL sessions
URL- rewriting

Q: Explain ServletContext.
A:

ServletContext interface is a window for a servlet to view it’s environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container’s version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

Q: What is preinitialization of a servlet?
A:

A container does not initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

Q: What is the difference between Difference between doGet() and doPost()?
A:

A doGet() method is limited with 2k of data to be sent, and doPost() method doesn’t have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&…&pN=vN
doPost() method call doesn’t need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it’s impossible to guess the data transmitted to a servlet only looking at a request string.

Q: What is the difference between HttpServlet and GenericServlet?
A:

A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.

Q: What is the difference between ServletContext and ServletConfig?
A:

ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized

ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

Every servlet has the same ServletContext but it also has its own ServletConfig.

JSP Interview Question and Answer

Filed under: java, Jsp/Servlet — Tags: , , , — kaisechen @ 2:54 am

1. What is a JSP and what is it used for?
Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.

2. What is difference between custom JSP tags and beans?
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components:

  1. The tag handler class that defines the tag\’s behavior
  2. The tag library descriptor file that maps the XML element names to the tag implementations
  3. the JSP file that uses the tag library
    When the first two components are done, you can use the tag by using taglib directive:

Then you are ready to use the tags you defined. Let’s say the tag prefix is test:
MyJSPTag or
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags
to declare a bean and use
to set value of the bean class and use
to get value of the bean class.

Custom tags and beans accomplish the same goals — encapsulating complex behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot.
Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans.
Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

3. What are the two kinds of comments in JSP and what’s the difference between them.
<%– JSP Comment –%>
<!– HTML Comment –>

4. What is JSP technology?

Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.

5. What is JSP page?

A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

6. What are the implicit objects?

Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:
–request
–response
–pageContext
–session
–application
–out
–config
–page
–exception

7. How many JSP scripting elements and what are they?

There are three scripting language elements:
–declarations
–scriptlets
–expressions

8. Why are JSP pages the preferred API for creating a web-based client program?

Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

9. Is JSP technology extensible?

YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

10. Can we use the constructor, instead of init(), to initialize servlet?

Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

11. How can a servlet refresh automatically if some new data has entered the database?

You can use a client-side Refresh or Server Push.

12. The code in a finally clause will never fail to execute, right?

Using System.exit(1); in try block will not allow finally code to execute.

13. How many messaging models do JMS provide for and what are they?

JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

14. What information is needed to create a TCP Socket?

The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

15. What Class.forName will do while loading drivers?

It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

16. How to Retrieve Warnings?

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
while (warning != null)
{
System.out.println(“Message: ” +     warning.getMessage());
System.out.println(“SQLState: ” +     warning.getSQLState());
System.out.print(“Vendor error code: “);     System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}

17. How many JSP scripting elements are there and what are they?

There are three scripting language elements: declarations, scriptlets, expressions.

18. In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?

Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

19. What are stored procedures? How is it useful?

A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.

20. How do I include static files within a JSP page?

Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

21. Why does JComponent have add() and remove() methods but Component does not?

because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? – You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe=”false” % > within your JSP page.

22. How can I enable session tracking for JSP pages if the browser has disabled cookies?

We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair.
However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.

Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other.

Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages.

Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.jsp
hello2.jsp
hello2.jsp
<%
Integer i= (Integer )session.getValue(“num”);
out.println(“Num value in session is “+i.intValue());

August 27, 2010

Hibernate Interview questions (3)

Filed under: hibernate, java — Tags: , , — kaisechen @ 2:13 am

31.What is the advantage of Hibernate over jdbc?

Hibernate Vs. JDBC :-

JDBC Hibernate
With JDBC, developer has to write code to map an object model’s data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
With JDBC, caching is maintained by hand-coding. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.
In JDBC there is no check that always every user has updated data. This check has to be added by the developer. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

32.What are the Collection types in Hibernate ?

  • Bag
  • Set
  • List
  • Array
  • Map

33.What are the ways to express joins in HQL?

HQL provides four ways of expressing (inner and outer) joins:-

  • An implicit association join
  • An ordinary join in the FROM clause
  • A fetch join in the FROM clause.
  • A theta-style join in the WHERE clause.

34.Define cascade and inverse option in one-many mapping?

cascade – enable operations to cascade to child entities.
cascade=”all|none|save-update|delete|all-delete-orphan”

inverse – mark this collection as the “inverse” end of a bidirectional association.
inverse=”true|false”
Essentially “inverse” indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
35.What is Hibernate proxy?

The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

36.How can Hibernate be configured to access an instance variable directly and not through a setter method ?

By mapping the property with access=”field” in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.
37.How can a whole class be mapped as immutable?

Mark the class as mutable=”false” (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.
38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set.

  • dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
  • dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

39.What do you mean by fetching strategy ?

A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

40.What is automatic dirty checking?

Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.
41.What is transactional write-behind?

Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.

42.What are Callback interfaces?

Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don’t need to implement these callbacks, but they’re useful for implementing certain kinds of generic functionality.
43.What are the types of Hibernate instance states ?

Three types of instance states:

  • Transient -The instance is not associated with any persistence context
  • Persistent -The instance is associated with a persistence context
  • Detached -The instance was associated with a persistence context which has been closed – currently not associated

44.What are the differences between EJB 3.0 & Hibernate

Hibernate Vs EJB 3.0 :-

Hibernate EJB 3.0
Session–Cache or collection of loaded objects relating to a single unit of work Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit
XDoclet Annotations used to support Attribute Oriented Programming Java 5.0 Annotations used to support Attribute Oriented Programming
Defines HQL for expressing queries to the database Defines EJB QL for expressing queries
Supports Entity Relationships through mapping files and annotations in JavaDoc Support Entity Relationships through Java 5.0 annotations
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API Provides and Entity Manager Interface for managing CRUD operations for an Entity
Provides callback support through lifecycle, interceptor, and validatable interfaces Provides callback support through Entity Listener and Callback methods
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships Entity Relationships are bidirectional or unidirectional

45.What are the types of inheritance models in Hibernate?

There are three types of inheritance models in Hibernate:

  • Table per class hierarchy
  • Table per subclass
  • Table per concrete class

Hibernate Interview questions (2)

Filed under: hibernate, java — Tags: , , — kaisechen @ 2:12 am

16.What’s the difference between load() and get()?

load() vs. get() :-

load() get()
Only use the load() method if you are sure that the object exists. If you are not sure that the object exists, then use one of the get() methods.
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database.
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. get() will hit the database immediately.

17.What is the difference between and merge and update ?

Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.
18.How do you define sequence generated primary key in hibernate?

Using <generator> tag.
Example:-

<id column="USER_ID" name="id" type="java.lang.Long"> 
    <generator class="sequence"> 
     <param name="table">SEQUENCE_NAME</param>
   <generator>
</id>
//
//

19.Define cascade and inverse option in one-many mapping?

cascade – enable operations to cascade to child entities.
cascade=”all|none|save-update|delete|all-delete-orphan”

inverse – mark this collection as the “inverse” end of a bidirectional association.
inverse=”true|false”
Essentially “inverse” indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
20.What do you mean by Named – SQL query?

Named SQL queries are defined in the mapping xml document and called wherever required.
Example:

<sql-query name = "empdetails">
   <return alias="emp" class="com.test.Employee"/>
      SELECT emp.EMP_ID AS {emp.empid},
                 emp.EMP_ADDRESS AS {emp.address},
                 emp.EMP_NAME AS {emp.name} 
      FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

Invoke Named Query :

List people = session.getNamedQuery("empdetails")
		     .setString("TomBrady", name)
		     .setMaxResults(50)
		     .list();

21.How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true">
 <return alias="emp" class="employee">
   <return-property name="empid" column="EMP_ID"/>       

   <return-property name="name" column="EMP_NAME"/>       
   <return-property name="address" column="EMP_ADDRESS"/>
    { ? = call selectAllEmployees() }
 </return>
</sql-query>


22.Explain Criteria API

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set.
Example :

List employees = session.createCriteria(Employee.class)
		         .add(Restrictions.like("name", "a%") )
		         .add(Restrictions.like("address", "Boston"))
			 .addOrder(Order.asc("name") )
			 .list();

23.Define HibernateTemplate?

org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
24.What are the benefits does HibernateTemplate provide?

The benefits of HibernateTemplate are :

  • HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
  • Common functions are simplified to single method calls.
  • Sessions are automatically closed.
  • Exceptions are automatically caught and converted to runtime exceptions.
//
//

25.How do you switch between relational databases without code changes?

Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
26.If you want to see the Hibernate generated SQL statements on console, what should we do?

In Hibernate configuration file set as follows:
<property name="show_sql">true</property>
27.What are derived properties?

The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

28.What is component mapping in Hibernate?

  • A component is an object saved as a value, not as a reference
  • A component can be saved directly without needing to declare interfaces or identifier properties
  • Required to define an empty constructor
  • Shared references not supported

Example:

Component Mapping

29.What is the difference between sorted and ordered collection in hibernate? sorted collection vs. order collection :-

sorted collection order collection
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .

Hibernate Interview questions (1)

Filed under: hibernate, java — Tags: , , — kaisechen @ 1:59 am

1.What is ORM ?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.
2.What does ORM consists of ?

An ORM solution consists of the followig four pieces:

  • API for performing basic CRUD operations
  • API to express queries refering to classes
  • Facilities to specify metadata
  • Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ?

The ORM levels are:

  • Pure relational (stored procedure.)
  • Light objects mapping (JDBC)
  • Medium object mapping
  • Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate?

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.
5.Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

  • Improved productivity
    • High-level object-oriented API
    • Less Java code to write
    • No SQL to write
  • Improved performance
    • Sophisticated caching
    • Lazy loading
    • Eager loading
  • Improved maintainability
    • A lot less code to write
  • Improved portability
    • ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify?

Hibernate simplifies:

  • Saving and retrieving your domain objects
  • Making database column and table name changes
  • Centralizing pre save and post retrieve logic
  • Complex joins for retrieving related items
  • Schema creation from object model

7.What is the need for Hibernate xml mapping file?

Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:

Hibernate Mapping file

8.What are the most common methods of Hibernate configuration?

The most common methods of Hibernate configuration are:

  • Programmatic configuration
  • XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml?

Following are the important tags of hibernate.cfg.xml:

hibernate.cfg.xml

10.What are the Core interfaces are of Hibernate framework?

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

  • Session interface
  • SessionFactory interface
  • Configuration interface
  • Transaction interface
  • Query and Criteria interfaces

11.What role does the Session interface play in Hibernate? The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();

Session interface role:

  • Wraps a JDBC connection
  • Factory for Transaction
  • Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate? The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

13.What is the general flow of Hibernate communication with RDBMS? The general flow of Hibernate communication with RDBMS is :

  • Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
  • Create session factory from configuration object
  • Get one session from this session factory
  • Create HQL Query
  • Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)? Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.
15.How do you map Java Objects with Database tables?

  • First we need to write Java domain objects (beans with setter and getter).
  • Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example :

<hibernate-mapping>
  <class name="com.test.User"  table="user">
   <property  column="USER_NAME" length="255"
      name="userName" not-null="true"  type="java.lang.String"/>
   <property  column="USER_PASSWORD" length="255"
     name="userPassword" not-null="true"  type="java.lang.String"/>
 </class>
</hibernate-mapping>

August 23, 2010

The PHP development environment in Eclipse

Filed under: eclipse, php, Technology — Tags: , , — kaisechen @ 2:00 am

The PDT project provides a PHP Development Tools framework for the Eclipse platform.This project encompasses all development components necessary to develop PHP and facilitate extensibility. It leverages the existing Web Tools Platform (WTP) and Dynamic Languages Toolkit (DLTK) in providing developers with PHP capabilities.

1. Firstly download eclipse classic version

http://www.eclipse.org/downloads/download.php?file=/eclipse/downloads/drops/R-3.6-201006080911/eclipse-SDK-3.6-win32.zip

August 10, 2010

Java concurrent programming (2) — Create a concurrent application in Java

Filed under: concurrent, java — Tags: , , — kaisechen @ 10:20 am

In Java, each thread is associated with a instance of Thread class.

Before JDK1.5, there is only one way to create a concurrent application. This way directly controls thread control and management, just instantiate Thread each time when the application need to initiate an asynchronous Task.

After JDK1.5, there is a new package ‘java.util.concurrent’ which provides new API supporting concurrent.  A new concept ‘executor’ can receive the application’s task and deal with it according to pre-defined rule. It separates the thread management and other rest part of the application.

The first way, when creating an instance of Thread, code running in the thread must be provided. There are two ways to do so.

1. Implement Runnable interface

Runnable interface defines run method, meant to contain the code execute in the thread.The Runnable object need be passed to a Thread constructor.

E.g.

public class Runner1 implements Runnable {

 public void run() {
 for(int i=0;i<30;i++){
 String s = Thread.currentThread().getName();
 System.out.println(s +" : "+i);
 }
 }
 
 public static void main(String args[]) {
 (new Thread(new Runner1())).start();
 }


}

2. Inherit Thread Class

The Thread Class already implements Runnable interface.  An subclass extends Thread need to override run method.

E.g.

public class MyRunner extends Thread {

 private int n;

 public MyRunner(int n) {
 this.n = n;
 }
 
 public void run(){
 for(int i=0;i<n;i++){
 System.out.println(this.getName()+":"+i);            
 }
 System.out.println(this.getName()+" Finished");
 }

 public static void main(String[] args){
 MyRunner m = new MyRunner(4);
 m.start();
 }
 

}

Java concurrent programming (1) — Process and Thread

Filed under: concurrent, java — Tags: , , , — kaisechen @ 6:16 am

There are two units associated with concurrent programming: process and thread. But in Java environment, it is mostly concerned with Thread.

Process

A process has a self-contained executive environment, which owns  a complete , private  set of run-time resources and occupied memory space.

In most situation, it is called program or application. But actually,  a single application may be consist of  a set of cooperating processes. Processes need communicate with each other, and most OSs support Inter Process Communication(IPC) resources, e.g. pipes and sockets.

In Java environment, JVM(Java Virtual Machine) mostly runs as a single process.  However, a Java application can create additional processes using a ProcessBuilder object.

Thread

Some people calls thread ‘lightweight process’.  Thread provides an execution environment like process, but less resource is required when creating a thread than creating a process.

Thread exists in process, so a process at least own a thread.

Threads exists in a process will share the process’s resource including memory and open files.

Java platform supports multi-thread, a Java application starts with one thread — ‘Main thread’,  main thread can create additional threads.

August 4, 2010

Create web service (4) — JAX-RS and JAX-RS Client

Filed under: java, myeclipse, webservice — Tags: , , , — kaisechen @ 1:19 am

It is becoming more and more popular using rest-style web service.

1. create a new web service project, which name is TestWS_RS.

Chose Web Service Framework: REST(JAX-RS)

It automatically produces J2EE structure, and check the web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
 <display-name>JAX-RS REST Servlet</display-name>
 <servlet-name>JAX-RS REST Servlet</servlet-name>
 <servlet-class>
 com.sun.jersey.spi.container.servlet.ServletContainer
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>JAX-RS REST Servlet</servlet-name>
 <url-pattern>/services/*</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

2.Add JAX-RS libraries into the project

chose JAX-RS 1.0.2 Core Libraries(Project Jersey 1.0.2)

JAXB supports the transform between Class and XML.

3. Create a POJO class User and add @XmlRootElement above it

package com.jack.ws;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {
private int id;
private String preferedname;
private String firstname;
private String lastname;
private String gender;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getPreferedname() {
return preferedname;
}

public void setPreferedname(String preferedname) {
this.preferedname = preferedname;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

@Override
public String toString() {
return “Id:”+id+” , FirstName:”+firstname+” , LastName:”+lastname+” , PreferedName:”+preferedname+” , Gender:”+gender;
}

}

4.Build a web service, UserResource

Chose Framework: REST(JAX-RS), Tick ‘Create new Java bean’

In java class field,input ‘UserResource’; chose Produces: application/xml; in URL path field, input ‘users’.

Then click finish button, it produces a ‘UserResource’ Class

5. Now begin to add REST methods in UserResource Class.

Chose UserResource Class,right click ,chose ‘MyEclipse’,chose ‘Add REST Method…’.

Firstly, add ‘getUsers’ method.

Secondly,add ‘getUser’ method.

Thirdly,add ‘addUser’ method.

6. Modify UserResource Class

package com.jack.ws;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import com.sun.jersey.spi.resource.Singleton;

@Produces("application/xml")
@Path("users")
@Singleton
public class UserResource {
 private TreeMap<Integer, User> userMap = new TreeMap<Integer, User>();

 public UserResource(){
 User user = new User();
 user.setFirstname("Jackie");
 user.setLastname("Chan");
 user.setPreferedname("Jack");
 user.setGender("Male");
 addUser(user);
 }

 @GET
 public List<User> getUsers() {
 List<User> users = new ArrayList<User>();
 users.addAll(userMap.values());
 return users;
 }

 @GET
 @Path("{id}")
 public User getUser(@PathParam("id") int cId) {
 return userMap.get(cId);
 }

 @POST
 @Path("add")
 @Produces("text/plain")
 @Consumes("application/xml")
 public String addUser(User user) {
 int id = userMap.size();
 user.setId(id);
 userMap.put(id, user);
 return "Added a new User and Its info is "+user.toString();
 }
}

7.Deploy the web service into tomcat 6 server.

8.Start Tomcat server

Some information about the web service in tomcat6server console.

04/08/2010 11:57:18 AM org.apache.catalina.startup.HostConfig checkResources
INFO: Reloading context [/TestWS_RS]
04/08/2010 11:57:20 AM com.sun.jersey.api.core.ClasspathResourceConfig init
INFO: Scanning for root resource and provider classes in the paths:
 D:\tomcat\webapps\TestWS_RS\WEB-INF\lib
 D:\tomcat\webapps\TestWS_RS\WEB-INF\classes
04/08/2010 11:57:21 AM com.sun.jersey.api.core.ClasspathResourceConfig init
INFO: Root resource classes found:
 class com.jack.ws.CustomersResource
 class com.jack.ws.UserResource
04/08/2010 11:57:21 AM com.sun.jersey.api.core.ClasspathResourceConfig init
INFO: Provider classes found:

9.Now begin to test the web service

chose this project, right click, chose ‘MyEclipse’,then chose ‘Test with web service explore’.


10.click id,input 0 in id field, then click Test button.

It gets a Response

<?xml version="1.0" encoding="UTF-8"?>
 <user>
 <firstname>Jackie</firstname>
 <gender>Male</gender>
 <id>0</id>
 <lastname>Chan</lastname>
 <preferedname>Jack</preferedname>
 </user>

11. Click add,in the content field, input

<user>
 <firstname>Jeanny</firstname>
 <lastname>Shery</lastname>
 <preferedname>Jean</preferedname>
 <gender>Female</gender>
</user>

click test button, get a response

Added a new User and Its info is Id:1 , FirstName:Jeanny , LastName:Shery , PreferedName:Jean , Gender:Female

12. Click User,Click Test Button, it gets a response.

<?xml version="1.0" encoding="UTF-8"?>     
 <users> 
 <user> 
 <firstname>Jackie</firstname> 
 <gender>Male</gender> 
 <id>0</id> 
 <lastname>Chan</lastname> 
 <preferedname>Jack</preferedname> 
 </user> 
 <user> 
 <firstname>Jeanny</firstname> 
 <gender>Female</gender> 
 <id>1</id> 
 <lastname>Shery</lastname> 
 <preferedname>Jean</preferedname> 
 </user> 
 </users>

13. Now begin to use other browser to test the web server, open firefox, input

http://localhost:8080/TestWS_RS/services/users/0

It will invoke getUser method in UserResource Class, and return xml of a user object

http://localhost:8080/TestWS_RS/services/users/1

It will invoke getUser method in UserResource Class, and return xml of another user object

14. Install poster plugin in firefox, use poster to test addUser method of the web service

Open poster

In URL field, input ‘http://localhost:8080/TestWS_RS/services/users/add&#8217;

In Content Type field, input ‘application/xml’

In Content field,input:

<user>
 <firstname>Hilly</firstname>
 <lastname>Paris</lastname>
 <preferedname>Hill</preferedname>
 <gender>Male</gender>
</user>

Click post button, it will get a response quickly.

Added a new User and Its info is Id:2 , FirstName:Hilly , LastName:Paris , PreferedName:Hill , Gender:Male

15. Open firefox, input the url

http://localhost:8080/TestWS_RS/services/users

It will invoke getUsers method in UserResource Class and return a user list.

<users>
−
<user>
<firstname>Jackie</firstname>
<gender>Male</gender>
<id>0</id>
<lastname>Chan</lastname>
<preferedname>Jack</preferedname>
</user>
−
<user>
<firstname>Jeanny</firstname>
<gender>Female</gender>
<id>1</id>
<lastname>Shery</lastname>
<preferedname>Jean</preferedname>
</user>
−
<user>
<firstname>Hilly</firstname>
<gender>Male</gender>
<id>2</id>
<lastname>Paris</lastname>
<preferedname>Hill</preferedname>
</user>
</users>

July 28, 2010

Create web service (3) — JAX-WS and JAX-WS Client

Filed under: java, myeclipse, webservice — Tags: , , — kaisechen @ 12:18 pm

In MyEclipse , it is very easy to build web service base on some web service framework.

Let’s build a JAX-WS web service.

1.Create a web service project in MyEclipse, which name is TestWS_JAXWS.

chose JAX-WS framework

It automatically produces J2EE directory.

2. import JAX-WS 2.1 library into the project

chose MyEclipse Libraries

Select JAX-WS 2.1 Libraries

3. Build a simple java which includes several methods

public class Calculator {
 public int add(int a, int b) {
 return (a + b);
 }

 public int subtract(int a, int b) {
 return (a - b);
 }

 public int multiply(int a, int b) {
 return (a * b);
 }

 public int divide(int a, int b) {
 return (a / b);
 }
}

4. Build a new web service

chose JAX-WS Framework and ‘Create web service from Java class’

In Java Class field, input ‘com.jack.ws.Calculator’ which is created at above step

It automatically fill in other fields,

Modify target namespace field to ‘http://localhost:8080/TestWS_JAXWS&#8217;

tick ‘Generate WSDL in project’

5. After click Finish button, it produces a lot of  files, directory and class

CalculatorDelegate class

wsdl directory, web.xml under WEB-INF

CalculatorDelegate.java

@javax.jws.WebService(targetNamespace = "http://localhost:8080/TestWS_JAXWS", serviceName = "CalculatorService", portName = "CalculatorPort", wsdlLocation = "WEB-INF/wsdl/CalculatorService.wsdl")
public class CalculatorDelegate {

 com.jack.ws.Calculator calculator = new com.jack.ws.Calculator();

 public int add(int a, int b) {
 return calculator.add(a, b);
 }

 public int subtract(int a, int b) {
 return calculator.subtract(a, b);
 }

 public int multiply(int a, int b) {
 return calculator.multiply(a, b);
 }

 public int divide(int a, int b) {
 return calculator.divide(a, b);
 }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
 <description>JAX-WS endpoint - CalculatorService</description>
 <display-name>CalculatorService</display-name>
 <servlet-name>CalculatorService</servlet-name>
 <servlet-class>
 com.sun.xml.ws.transport.http.servlet.WSServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>CalculatorService</servlet-name>
 <url-pattern>/CalculatorPort</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <listener>
 <listener-class>
 com.sun.xml.ws.transport.http.servlet.WSServletContextListener
 </listener-class>
 </listener></web-app>

sun-jaxws.xml

<?xml version = "1.0"?>
<endpoints version="2.0"
 xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime">
 <endpoint name="CalculatorPort"
 implementation="com.jack.ws.CalculatorDelegate"
 url-pattern="/CalculatorPort">
 </endpoint></endpoints>

CalculatorService.wsdl

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.3-hudson-390-. -->
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://localhost:8080/TestWS_JAXWS" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="CalculatorService" targetNamespace="http://localhost:8080/TestWS_JAXWS">
 <types>
 <xsd:schema>
 <xsd:import namespace="http://localhost:8080/TestWS_JAXWS" schemaLocation="CalculatorService_schema1.xsd"/>
 </xsd:schema>
 </types>
 <message name="add">
 <part element="tns:add" name="parameters"/>
 </message>
 <message name="addResponse">
 <part element="tns:addResponse" name="parameters"/>
 </message>
 <message name="divide">
 <part element="tns:divide" name="parameters"/>
 </message>
 <message name="divideResponse">
 <part element="tns:divideResponse" name="parameters"/>
 </message>
 <message name="multiply">
 <part element="tns:multiply" name="parameters"/>
 </message>
 <message name="multiplyResponse">
 <part element="tns:multiplyResponse" name="parameters"/>
 </message>
 <message name="subtract">
 <part element="tns:subtract" name="parameters"/>
 </message>
 <message name="subtractResponse">
 <part element="tns:subtractResponse" name="parameters"/>
 </message>
 <portType name="CalculatorDelegate">
 <operation name="add">
 <input message="tns:add"/>
 <output message="tns:addResponse"/>
 </operation>
 <operation name="divide">
 <input message="tns:divide"/>
 <output message="tns:divideResponse"/>
 </operation>
 <operation name="multiply">
 <input message="tns:multiply"/>
 <output message="tns:multiplyResponse"/>
 </operation>
 <operation name="subtract">
 <input message="tns:subtract"/>
 <output message="tns:subtractResponse"/>
 </operation>
 </portType>
 <binding name="CalculatorPortBinding" type="tns:CalculatorDelegate">
 <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
 <operation name="add">
 <soap:operation soapAction=""/>
 <input>
 <soap:body use="literal"/>
 </input>
 <output>
 <soap:body use="literal"/>
 </output>
 </operation>
 <operation name="divide">
 <soap:operation soapAction=""/>
 <input>
 <soap:body use="literal"/>
 </input>
 <output>
 <soap:body use="literal"/>
 </output>
 </operation>
 <operation name="multiply">
 <soap:operation soapAction=""/>
 <input>
 <soap:body use="literal"/>
 </input>
 <output>
 <soap:body use="literal"/>
 </output>
 </operation>
 <operation name="subtract">
 <soap:operation soapAction=""/>
 <input>
 <soap:body use="literal"/>
 </input>
 <output>
 <soap:body use="literal"/>
 </output>
 </operation>
 </binding>
 <service name="CalculatorService">
 <port binding="tns:CalculatorPortBinding" name="CalculatorPort">
 <soap:address location="http://localhost:8080/TestWS_JAXWS/CalculatorPort"/>
 </port>
 </service>
</definitions>

6.Launch SOAP Web Service Explore to make a test to the web sercie

There are two Explores to be chosen. Select one.

Then click ‘WSDL Page’ in right-top , then click ‘WSDL Main’ in left-top

Input “http://localhost:8080/TestWS_JAXWS/CalculatorPort?WSDL&#8221;

Notice:

1) CalculatorPort  match the servlet-mapping in web.xml

2)?WSDL

This is a universal query string argument that can be added to the end of any web service which will tell the web service to return it’s full WSDL to the caller. In this case, the WSDL is returned to our Web Services Explorer tool which loads it up, and displays the web services exposed operations to us.

click ‘add’, ‘divide’,’subtract’,’multiply’ etc methods

e.g. add, input 100, 555, add go, then will get a return value:655

e.g. subtract, input 1000, 20 , will get 980

7. Build a new Java project as the client to use the web service, which name is TestWS_JAXWSClient

8. Build a new web service client in the project

Chose JAX-WS framework

In WSDL URL input ‘http://localhost:8080/TestWS_JAXWS/CalculatorPort?wsdl&#8217;

Create a java package

It has  a WSDL validation, click finish button

9. It automatically produces a lot of classes under new created java package

It is very easy to understand the meaning of those classes from literal

10. Build a Test Class in the java client project

public class Test {
public static void main(String[] args) {
CalculatorService  cs = new CalculatorService();
CalculatorDelegate cd = cs.getCalculatorPort();
System.out.println("3 + 10    = "+cd.add(3,10));
System.out.println("999 - 222 = "+cd.subtract(999,222));
System.out.println("250 / 5   = "+cd.divide(250, 5));
System.out.println("7 * 23    = "+cd.multiply(7,23));
}
}

11. Run Test.java, it will get

3 + 10    = 13
999 - 222 = 777
250 / 5   = 50
7 * 23    = 161

package com.jack.ws;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;

/**
* This class was generated by the JAX-WS RI. JAX-WS RI 2.1.3-hudson-390-
* Generated source version: 2.0
* <p>
* An example of how this class may be used:
*
* <pre>
* CalculatorService service = new CalculatorService();
* CalculatorDelegate portType = service.getCalculatorPort();
* portType.add(…);
* </pre>
*
* </p>
*
*/
@WebServiceClient(name = “CalculatorService”, targetNamespace = “http://localhost:8080/TestWS_JAXWS&#8221;, wsdlLocation = “http://localhost:8080/TestWS_JAXWS/CalculatorPort?wsdl&#8221;)
public class CalculatorService extends Service {

private final static URL CALCULATORSERVICE_WSDL_LOCATION;
private final static Logger logger = Logger
.getLogger(com.jack.ws.CalculatorService.class.getName());

static {
URL url = null;
try {
URL baseUrl;
baseUrl = com.jack.ws.CalculatorService.class.getResource(“.”);
url = new URL(baseUrl,
http://localhost:8080/TestWS_JAXWS/CalculatorPort?wsdl&#8221;);
} catch (MalformedURLException e) {
logger
.warning(“Failed to create URL for the wsdl Location: ‘http://localhost:8080/TestWS_JAXWS/CalculatorPort?wsdl&#8217;, retrying as a local file”);
logger.warning(e.getMessage());
}
CALCULATORSERVICE_WSDL_LOCATION = url;
}

public CalculatorService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}

public CalculatorService() {
super(CALCULATORSERVICE_WSDL_LOCATION, new QName(
http://localhost:8080/TestWS_JAXWS&#8221;, “CalculatorService”));
}

/**
*
* @return returns CalculatorDelegate
*/
@WebEndpoint(name = “CalculatorPort”)
public CalculatorDelegate getCalculatorPort() {
return super.getPort(new QName(“http://localhost:8080/TestWS_JAXWS&#8221;,
“CalculatorPort”), CalculatorDelegate.class);
}

}

Older Posts »

Create a free website or blog at WordPress.com.