Wednesday, June 18, 2008

Explanation on Struts flow.


Note before reading this article : this is not for professionals and it is for the people who stepped into Struts(Beginners) and it is for my future reference.



1. When the jsp page is loaded into server, the "" (what you wrote in corresponding jsp page) creates the neccessary html code to represent the form and then checks for the instance of the corresponding ActionForm in the current session scope.If there was ActionForm object available in the session scope then the data members of the ActionForm is mapped with the input form fields respectively. and then that jsp page is presented to the user.

Let me explain with one example.

JSP pages: login.jsp, success.jsp
Action class: LoginAction
Form name: LoginForm

in login.jsp
two fields username and password
login.jsp

2.When you click on Login button the server receives that request and it wil check in web.xml for the form action with login.do
In web.xml there you can see the following url mapping with .do extension. then it calls the ActionServlet
From there the ActionServlet will take the request processing.





3.the ActionServlet will then looks for the LoginForm and populates the data members with form fields and then the LoginForm will be associated with the session.
4.Once, the request comes to the ActionServlet the ActionServlet [ActionServlet will call the RequestProcessor's process()method.
The RequestProcessor's process() method] wil read the struts-config.xml file and looks for the following entry:




if the path attribute equals to the form action attribute i.e login
5. it then creates the LoginAction object and calls the execute() method on that object by passing the ActionMapping[creates ActionMapping instance and passed to execute()], ActionForm,HttpServletRequest,HttpServletResponse objects.
the execute() method will process the business logic [by calling the model component] and then calls the ActionMapping.findForward("string argument") can be success or failure.
6.this ActionMapping.findForward("string argument") will looks for the subelement of the tag with the name attribute equal to the "string argument" . It then returns the ActionForward object which contains results of the
lookup, which is the value of the path attribute /welcome.jsp (upon success) or /login.jsp (upon failure).

If it is success then the LoginAction returns the ActionForward object to the ActionServlet, which will then forward to the view for presentation.
here now you can see welcome.jsp

uhhhhhh......, I did it. please give me feedback.

resources i have used to write this
Mastering Jakarta Struts book by James Goodwill[It is a good book for struts]
and my class notes.


what is the use of reset() method in ActionForm?

The use of reset() method in ActionForm is it is used by the Struts Framework with each request that uses the ActionForm. The main purpose of reset() method is to reset all the data members of the ActionForm object and allow the object to be pooled for reuse.

The difference between MVC and MVC 2(MODEL 2) ?

MVC was a first generation approach that used JSP pages and the JavaBeans component architecture to implement the MVC architecture for the Web. HTTP requests are sent to a JSP page that implements Controller logic and calls out to the “Model” for data to update the “View.” This approach combines Controller and View functionality within a JSP page and therefore breaks the MVC paradigm. MVC1 is appropriate for simple development and prototyping. It is not, however, recommended for serious development.

MVC2 is a term invented by Sun to describe an MVC architecture for Web-based applications in which HTTP requests are passed from the client to a “Controller” servlet which updates the “Model” and then invokes the appropriate “View” renderer-for example, JSP technology, which in turn renders the View from the updated Model.
The hallmark of the MVC2 approach is the separation of Controller code from
content. (Implementations of presentation frameworks such as Struts, adhere to the MVC2 approach).

copied from sun forums site

What is AOP Aspect Oriented Programming ?

generally definition of AOP is modularizing the cross-cutting concerns.

each module main concern is to provide services for its particular domain.
The common object-oriented technique for reusing common functionality is through inheritance or delegation.
But inheritance can lead to a brittle object hierarchy if the same base class is used throughout an application, and delegation can be cumbersome and still
requires duplicated calls to the delegate object.

AOP is an alternative, With
AOP, you still define the common functionality in one place, but you can declaratively
define how and where this functionality is applied without having to modify
the class to which you are applying the new feature.Cross-cutting concerns can
now be modularized into special objects called aspects.
This has two benefits.
1. the logic for each concern is now in one place, as opposed to being scattered all
over the code base.ex. logging.
2. our service modules are now cleaner since they only
contain code for their core functionality and secondary concerns have been
moved to aspects.ex. student, course module.

Aspect
An aspect is the cross-cutting functionality you are implementing. It is the aspect,
or area, of your application you are modularizing. The most common (albeit simple)
example of an aspect is logging. Logging is something that is required
throughout an application. However, because applications tend to be broken
down into layers based on functionality, reusing a logging module through inheritance
does not make sense. However, you can create a logging aspect and apply it
throughout your application using AOP.
Joinpoint
A joinpoint is a point in the execution of the application where an aspect can be
plugged in. This point could be a method being called, an exception being
thrown, or even a field being modified. These are the points where your aspect’s
code can be inserted into the normal flow of your application to add new behavior.
Adviceis the actual implementation of Aspect..It is advising ur application of new behaviour.
In our Logging example, the logging advice would contain the
code that implements the actual logging, such as writing to a log file. Advice is
inserted into our application at joinpoints.
Pointcuts
A pointcut defines at what joinpoint the advice should be applied. Advice can be applied at any joinpoint supported by AOP framework.
These pointcuts will tell where is the advice to be applied .
You can specify these pointcuts using an explicit class or method names or through regular expressions
that define matching class and method name patterns.Some AOP frameworks
allow you to create dynamic pointcuts that determine whether to apply advice
based on runtime decisions, such as the value of method parameters.
Introductionallows you to add new methods or attributes to the existing classes.
TargetA target is the class that is being advised.

Note: the above information i got it from the Manning in Action Series : Spring ebook and some other books

Monday, June 16, 2008

how to clone an object in Java? what is shallow copying and deep copying?

how to clone an object in Java?

Cloning is a way of creating copies of objects in java.

protected Object clone() throws CloneNotSupportedException

the above method creates and returns a copy of the this object.
i.e classes that implement the Cloneable interface should override Object.clone (which is protected) with a public method.

Note: The Cloneable interface doesnot contain the clone method. It is not possible to clone an object by implementing the clone() method.
Note1: invoking the Object.clone() method on instance that doesnot implementing the Cloneable interface will result in Exception " CloneNotSupportedException"

There are two ways of making copy of objects using Cloning.
1. Shallow copying
2. Deep copying

1.Shallow copying : Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects.
2.Deep copying : Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.
Java supports shallow and deep copy with the Cloneable interface to create copies of objects. To make a clone of a Java object, you declare that an object implements Cloneable, and then provide an override of the clone method of the standard Java Object base class. Implementing Cloneable tells the java compiler that your object is Cloneable. The cloning is actually done by the clone method.

example to shallow and deep copying see here http://forum.java.sun.com/thread.jspa?threadID=487186&messageID=2281852

example program

import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;

public class CloningExample implements Cloneable {

private LinkedList names = new LinkedList();
public CloningExample() {
names.add(”Alex”);
names.add(”Melody”);
names.add(”Jeff”);
}
public String toString() {
StringBuffer sb = new StringBuffer();
Iterator i = names.iterator();
while (i.hasNext()) {
sb.append(”\n\t” + i.next());
}
return sb.toString();
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new Error(”This should not occur since we implement Cloneable”);
}
}
public Object deepClone() {
try {
CloningExample copy = (CloningExample)super.clone();
copy.names = (LinkedList)names.clone();
return copy;
} catch (CloneNotSupportedException e) {
throw new Error(”This should not occur since we implement Cloneable”);
}
}

public boolean equals(Object obj) {

/* is obj reference this object being compared */
if (obj == this) {
return true;
}

/* is obj reference null */
if (obj == null) {
return false;
}

/* Make sure references are of same type */
if (!(this.getClass() == obj.getClass())) {
return false;
} else {
CloningExample tmp = (CloningExample)obj;
if (this.names == tmp.names) {
return true;
} else {
return false;
}
}

}


public static void main(String[] args) {

CloningExample ce1 = new CloningExample();
System.out.println(”\nCloningExample[1]\n” +
“—————–” + ce1);

CloningExample ce2 = (CloningExample)ce1.clone();
System.out.println(”\nCloningExample[2]\n” +
“—————–” + ce2);

System.out.println(”\nCompare Shallow Copy\n” +
“——————–\n” +
“ ce1 == ce2 : ” + (ce1 == ce2) + “\n” +
“ ce1.equals(ce2) : ” + ce1.equals(ce2));

CloningExample ce3 = (CloningExample)ce1.deepClone();
System.out.println(”\nCompare Deep Copy\n” +
“——————–\n” +
“ ce1 == ce3 : ” + (ce1 == ce3) + “\n” +
“ ce1.equals(ce3) : ” + ce1.equals(ce3));

System.out.println();

}

}


** The above program is copied from http://www.idevelopment.info/data/Programming/java/object_oriented_techniques/CloningExample.java this location . please follow
this link to get better explanation.
how to find the 2nd, 3rd ,4th ... nth highest salary of the employee from emp table?

select sal from emp e1 where (n-1)=(select count(DISTINCT sal)
from emp where sal > e1.sal )

what is the output of select * from table where 1=2?

SELECT * FROM emp WHERE 1=2

the output of the query is "No records found" i.e returns no records

Sunday, June 15, 2008

select second highest salary from emp table

1.select second highest salary from emp table



select max(sal ) from emp where sal<(select max

(sal)from emp)




select max(sal) from emp where level=2 connect by prior

sal>sal group by level;





2.select the employee details who is having the second highest salary from emp table



select A.* from emp A where 1=(select count(distinct

B.sal) from emp B where B.sal>A.sal)




3.select second highest salary of the employee along with first highest salary from emp table



select ename,sal from

(select ename,sal from emp

order by sal desc)

where rownum <=2;

Thursday, June 12, 2008

Explanation on Data Abstraction and Data Encapsulation

abstraction - The process of abstraction in Java is used to hide certain details and only show the essential features of the object.

Data hiding is just a means by which one hides away data from the external world... example, the lungs of a person is not seen by anyone, but used for the internal working of the human being!

Data Encapusation allows to package all the contents of the object. They may or may not be public to the external world. Example, the skin is part of the human, and so is the lung. Together all the components of the human make up one whole being!

Data Abstraction is the means by which one displays only what is required to the user. Sample - the mood of a person to a girl, a snake, a cat, a father, or a boss. Though they are all emotions, they differ based on the stimuli, and hence a portion of the whole is displayed to the person who requests it.

About Interface in Java

n the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final.

Explanation on Difference between TRUNCATE, DELETE and DROP commands?

The DELETE command is used to remove some or all rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.


SQL> SELECT COUNT(*) FROM emp;

COUNT(*)

----------

14


SQL> DELETE FROM emp WHERE job = 'CLERK';

4 rows deleted.


SQL> COMMIT;

Commit complete.


SQL> SELECT COUNT(*) FROM emp;

COUNT(*)

----------

10



TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE.



SQL> TRUNCATE TABLE emp;

Table truncated.



SQL> SELECT COUNT(*) FROM emp;


COUNT(*)

----------

0



The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.



SQL> DROP TABLE emp;

Table dropped.



SQL> SELECT * FROM emp;

SELECT * FROM emp

*


ERROR at line 1:

ORA-00942: table or view does not exist




NOTE:DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.


SQL> FLASHBACK TABLE emp TO BEFORE DROP;

Flashback complete.


PS: DELETE will not free up used space within a table. This means that repeated DELETE commands will severely fragment the table and queries will have to navigate this "free space" in order to retrieve rows.

how Class.forName() works exactly?

Dynamic loading is one of the strongest features of java,is its ability to dynamically load code given
the name of the class to load, without having to know the actual classname until runtime.

Problem facing with SQL Query, ORA-01425: escape character must be character string of length 1

select product_id from in_prod_qry_gtv where full_desc
like '%' || 'ALEX\\%DIAMOND\\%' || '%' escape '\\'


solutio i got when i googled is that "Change it to a character string of length 1."
but , still it is not resolving my problem.