e hënë, 25 qershor 2007

Implementing serializable singleton

public class MySingleton implements Serializable {
static MySingleton singleton = new MySingleton();

private MySingleton() {
}

// This method is called immediately after an object of this class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return singleton;
}
}

Deserializing an Object

try {
// Deserialize from a file
File file = new File("filename.ser");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
// Deserialize the object
javax.swing.JButton button = (javax.swing.JButton) in.readObject();
in.close();

// Get some byte array data
byte[] bytes = getBytesFromFile(file);
// see e36 Reading a File into a Byte Array for the implementation of this method

// Deserialize from a byte array
in = new ObjectInputStream(new ByteArrayInputStream(bytes));
button = (javax.swing.JButton) in.readObject();
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}

Serializing an Object.

Object object = new javax.swing.JButton("push me");

try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();

// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();

// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}

Forcing updates to a file to a disk.

try {
// Open or create the output file
FileOutputStream os = new FileOutputStream("outfilename");
FileDescriptor fd = os.getFD();

// Write some data to the stream
byte[] data = new byte[]{(byte)0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE};
os.write(data);

// Flush the data from the streams and writers into system buffers.
// The data may or may not be written to disk.
os.flush();

// Block until the system buffers have been written to disk.
// After this method returns, the data is guaranteed to have
// been written to disk.
fd.sync();
} catch (IOException e) {
}

Getting and Setting modification time of file or a directory.

File file = new File("filename");

// Get the last modified time
long modifiedTime = file.lastModified();
// 0L is returned if the file does not exist

// Set the last modified time
long newModifiedTime = System.currentTimeMillis();
boolean success = file.setLastModified(newModifiedTime);
if (!success) {
// operation failed.
}

Renaming a file or directory.

// File (or directory) with old name
File file = new File("oldname");

// File (or directory) with new name
File file2 = new File("newname");

// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}

Creating a temporary file.

try {
// Create temp file.
File temp = File.createTempFile("pattern", ".suffix");

// Delete temp file when program exits.
temp.deleteOnExit();

// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}

Copy file from one location to another location

// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}

e martë, 19 qershor 2007

JSP Scripting Elements

Scripting Elements are basically used to add contents to the HTML page dynamically.
Lets you add java code inside the HTML/JSP.

1) JSP Comments
- used to comments for user information.

2) JSP Expressions
- used to insert dynamic results to the output page.
- FORMAT - <%= expression %>
- they are printed directly to the output page.
- e.g. Thanks for ordering <%= request.getParameter("title") %>
- e.g. Current time: <%= new java.util.Date() %>
- XML SYNTAX - Java Expression

3) JSP Scriptlets
- used to insert java code into the method that handles request for the page.
- FORMAT - <% code %>
- they are inserted into the _jspservice(called by service) method of the servlet.
- they have access to implicit objects automatically.
- e.g. <% String q = request.getQueryString(); out.println("GET data: " + q);%>
- they can be used for setting response headers and status codes, invoking side effects such as writing to the server log or updating a database, or executing code that contains loops, conditionals, or other complex constructs.
- XML SYNTAX - Code

4) JSP Declaraions
- used to add methods and field declarations to the servlet that corresponds to the JSP page.
- FORMAT - <%! Java Code %>
- they are inserted to the main body of the servlet class, outside the _jspService() and called by service to process the request.
- XML SYNTAX - Code
- implicit objects wont be accessible within declarations.

Tag Library Descriptor File Format.


1.0
1.1
csajsp


A tag library from Core Java Files & Pages,
http://javablues.blogspot.com/.





prime

com.tags.PrimeTag

Outputs a random N-digit prime.

EMPTY


length
false



Components to make up Tag Library.

1) Tag Handler Class -- holds logic for the tag implementation
- need to implement Tag interface, can be achieved by extending TagSupport or BodyTagSupport class.
- some important methods
--- doStartTag() -- basic method called for tag found in JSP, called for non-attribute tags the logic can be implemented over here.
--- doEndTag()
--- can have setter/getter methods of the tag attributes, so whenever an attribute is passed from a JSP it calls setter method to set the value in Tag handler class and later be used by doStartTag() or other business/logic methods.

2) Tag Library Descriptor File -- maps XML element names to the tag implementations
- maps tag to tag handler class
- defines tag attributes (required/optional)

3) JSP file -- uses the tag
- define the taglib directive to point to tag library descriptor file.
--- <%@ taglib uri="abc\def\xyz.tld" prefix="xyz" %>
---

e hënë, 18 qershor 2007

How to handle multiple submit by user?

For multiple submit
---------------------------
1) disable the submit button,
- once the request has been submitted or started processing, user cant submit it again.

2) generate a token, when data gets committed.
- Once data is committed or token is generated, the user cant resubmit the page or the request wont be fulfilled.

3) generate a token when request processing gets started, so that user cant resubmit.
- if the commit fails, user can go to last successful page and get ActionForm, and process the request and go forward.

Define Business Delegate Pattern.

Business Delegate Pattern.
--------------------------------------

Define Transfer Object Pattern.

Transfer Object Pattern.
---------------------------------

Define Session Facade pattern.

Session Facade pattern is all about remove complexities and provide a single interface to user for business calls.

- e.g. for a amount transfer across bank accounts functionality, rather than providing all the mentioned methods in AAAAA, session facade pattern provides a single interface to users as in BBBBB.

AAAAA.
-- checkSourceAcct()
-- checkDestAcct()
-- debitAmountFromSource()
-- CreditAmountToDest()

BBBBB.
-- transferFromSourceToDestAcct()

Advantages
--------------------
- User wont have to be dragged to the complexities of the business.
- User will have to handle a single method for calling the business method, rather than a bunch of methods.

Define Front Controller Pattern.

Front Controller.
------------------------------

Define DAO Pattern.

DAO Pattern.
-----------------------------

Define Service Locator pattern.

Service Locator Pattern
-------------------------------------

Define MVC pattern.

MVC pattern differenciates all the 3 aspects of application in 3 difft tiers.

Modal
------------------
- Holds the business logic of the application.
- holds data sent betw. difft. tiers like JSP to servlet and hadler classes.

View
------------------
- handles presentation tier of the application.
- handles presentation logic, client side validation.
- e.g. HTML, JSP

Controller
------------------
- handles the flow of the application
- e.g. Servlets, Action Class in Struts, ActionServlet is using struts-config.xml as front controller to handle each request and redirect it to appropriate destination.

Advantages
----------------------
- Increases modularity of the application.
- Increases Maintainability of the application.

Define an Observer Pattern.

Observer Pattern
-------------------------------

Define Factory Pattern.

Factory Pattern
--------------------------

Define Singleton Design Pattern.

Singleton Design Pattern
-----------------------------------

Pros and Cons of Hibernate.

Hibernate
--------------------
Pros
- reduces development effort for persisting data from business tier
- developer is not required to know SQL statements

Cons
- for high data intensive applications, hibernate does not perform upto the mark.

What is a FRAMEWORK?

Framework
-------------------
Framework is
- a collection of established design patterns to solve the problems in specific way.
- defines application flow

e.g. Struts, Spring, Tiles, Portal

What is DESIGN PATTERN?

Design Pattern
---------------------------
Design Pattern is an efficient solution to certain re-occurring problem.

e.g.
Problem --> to maintain a single object in an application
Solution --> implement singleton design pattern, that ensures a single object in an application.

What is ABSTRACTION?

Abstraction
------------------------

What is DATA HIDING?

Data Hiding
---------------------------
- is all about hiding the data from outside world by encapsulating the data/methods into a single entity, class.

What is POLYMORPHISM?

Polymorphism
------------------------

What is INHERITANCE?

Inheritance
------------------------
- is one of the main characteristic of object in Object Oriented Programming.
- is all about reuse the properties/attributes of super/parent class.
- real world example is ... son/daughter can inherit the parents property.
- inheritance cant be applied at ... the certificates/degrees earned by parents cant be inherited by son/daughter.

Diff betw. JDK, JVM and Java Run Time

abcd

How to manage session in an application.

1) Cookie
- they store user information on local machine.
- this cookie is passed to browser for checking user authentication.
- some of the browsers does not provide support for cookies.

2) URL rewriting
- additional user information will be appended to the URL to pass information to the destination
- Cons - limitation is 256 chars of URL
- Cons - user data is exposed to the world

3) Hidden Variables in HTML/JSP
- user data is maintained across the HTML/JSPs using hidden fields
- and in servlets by using request.getParameter("") - by passing parameter names.

3) HttpSession class
- maintaining a session object across an active session.
- we can store diff. user objects, need to be maintained across the session.
- its a hashmap
- request.getSession(true), to get a new session if does not exist.
- overcomes limitations of cookie and URL rewriting for storing sessionID.
- set maximum lifetime of the session.

Scope/visibility of Objects in Application life cycle

1) page --> visibility of object from the declaration point to the end of page
2) request --> visibility will be till a request gets processed or a new request created.
3) session --> visibility will be till a user session/ browser session session is terminated. Or user logs out of the application.
4) application --> available throughout the application, for all users, object is set into application context.

Implicit objects in JSP

1) out
- print variable,
- PrintWriter object, to send output to client.

2) request
- scope,
- access request data by request.getParameter().
- HttpServletReequest object
- ServletRequest object for non-Http servlets

3) response
- set status codes/ response headers.
- HttpServletResponse object

4) session
- scope,
- access session data & existing session.
- created automatically

5) application
- scope,
- is ServletContext,
- = getServletConfig().getContext(),
- data is shared between all servlets.
- getAttribute(), setAttribute() for placing application level data.

6) page
- synonym for this,
- rarely used.

7) pageContext
- access page variables.

8) config
- servlet config object for this page.

Life cycle methods of Entity Beans

abcd .............

Life cycle methods of Message Driven Beans

At the start of the App. Server/ application, EJB container creates a pool of MDB instances, so on request the create() methods wont be called.

11111) DOES NOT EXIST
a) setMessageDrivenContext() --> after getting the bean instance, sets context object to the bean, to access container level information.
b) ejbCreate() --> to load start up parameters before processing a request, like DB connection.

22222) READY --> onMessage()
a) ejbRemove() --> to remove/close environment variables like DB connection, ready for garbage collection.

Life cycle methods of Stateful Session Bean

Stateful Session Bean
------------------------------------
11111) does not exist --> bean is does not exist state
a) create() --> a bean instance is created
b) setSessionContext() --> instanciates the bean object
c) ejbCreate() --> allows to perform operations after the bean instance created and before it starts processing request like create database connection.
*****Dest****> READY STATE

22222) Ready
a) ejbRemove() --> to perform certain operations before bean object is removed or garbage collected. e.g. close database connection.
b) remove() --> removes the bean instance or makes it ready for garbage collection.
*****Dest****> DOES NOT EXIST STATE

c) ejbPassivate() --> called before bean performs passivation operation on bean instance, stores bean info from memory to secondary storage (like virtual memory for ideal apps in OS) based on least-recently-used algorithm.
*****Dest****> PASSIVE STATE

33333) Passive
a) ejbActivate() --> when any business method of a bean is invoked while bean is in passive state, ejb container activates the bean, moves back to ready stage and then calls ejbActivate() method.
*****Dest****> READY STATE

Life cycle methods of Stateless Session Beans

Stateless Session Bean
------------------------------------
1) does not exist --> bean is does not exist state
a) create() --> a bean instance is created
b) setSessionContext() --> instanciates the bean object
c) ejbCreate() --> allows to perform operations after the bean instance created and before it starts processing request like create database connection.

2) Ready
a) ejbRemove() --> to perform certain operations before bean object is removed or garbage collected. e.g. close database connection.
b) remove() --> removes the bean instance or makes it ready for garbage collection.

Life cycle methods of Session Beans

Stateless Session Bean
------------------------------------
1) does not exist --> bean is does not exist state
a) create() --> a bean instance is created
b) setSessionContext() --> instanciates the bean object
c) ejbCreate() --> allows to perform operations after the bean instance created and before it starts processing request like create database connection.

2) Ready
a) ejbRemove() --> to perform certain operations before bean object is removed or garbage collected. e.g. close database connection.
b) remove() --> removes the bean instance or makes it ready for garbage collection.

Stateful Session Bean
------------------------------------
1) does not exist --> bean is does not exist state
a) create() --> a bean instance is created
b) setSessionContext() --> instanciates the bean object
c) ejbCreate() --> allows to perform operations after the bean instance created and before it starts processing request like create database connection.
*****Dest****> READY STATE

2) Ready
a) ejbRemove() --> to perform certain operations before bean object is removed or garbage collected. e.g. close database connection.
b) remove() --> removes the bean instance or makes it ready for garbage collection.
*****Dest****> DOES NOT EXIST STATE

c) ejbPassivate() --> called before bean performs passivation operation on bean instance, stores bean info from memory to secondary storage (like virtual memory for ideal apps in OS) based on least-recently-used algorithm.
*****Dest****> PASSIVE STATE

3) Passive
a) ejbActivate() --> when any business method of a bean is invoked while bean is in passive state, ejb container activates the bean, moves back to ready stage and then calls ejbActivate() method.
*****Dest****> READY STATE

Life cycle methods of JSP

1) _init()
2) jsp_service();
3) _destroy();

LIfe cycle methods of Servlet

1) init()
2) service()
3) destroy()

Diff betw. String, StringBuffer & StringBuilder

String.
-----------------------
- mutable sequence of characters
- cant append or insert char/string in existing object, a new object will be created.
- its synchronized.
- for each substring or any operation, a new object is created and given its reference.

StringBuffer
-----------------------
- an immutable sequence of characters
- allows to insert, append char/string within the existing object.
- its synchronized.

StringBuilder
-----------------------
- has been introduced in J2SE 5.0
- its un-synchronized version of StringBuffer class.
- allows insert/append operations on string.
- mutable sequence of characters they are un-synchronized.

Pros and Cons of Garbage Collector

Pros.
------------------
- it helps to recollect out of scope/session objects and reclaims memory.
- improves application performance by improving memory.

Cons.
-----------------
- its a heavy process to reclaim memory.

NOTE: for best programming practices, programming should be done in a way that program itself manages object to reclaim and out of scope objects created in minimal, so as creating minimum load on GC.

Diff. betw. DriverManager and DataSource interface implementation

DriverManager.
-------------------------------
- hampers the application performance as the connections are created/closed in java classes.
- does not support connection pooling.

DataSource
-------------------------------
- improves application performance as connections are not created/closed within a class, they are managed by the application server and can be fetched while at runtime.
- it provides a facility creating a pool of connections
- helpful for enterprise applications

e mërkurë, 13 qershor 2007

Define diff. states of Thread.

1) Not exist -- thread does not exist, to be created upon a request to create.
2) Runnable --
3) Running -- thread occupies the monitor and in running stage
4) Waiting -- some other thread is running, waiting for other thread to halt or stop execute.

Diff. between Abstract Class and Interface

1) a class can extend only one class, while can implement multiple interfaces.
2) an abstract class can have a concrete method while an interface can;t have a concrete method.
3) we can implement multiple inheritance using interface by implementing an interface at any levels of the class hierarchy, while multiple inheritance cant be achieved by extending classes in Java.

e martë, 12 qershor 2007

Diff. between HashMap and HashTable

HashTable
--------------------
1) is synchronized, thread-safe.
2) each time a thread is required to acquire a lock before using it.
3) does not allow null value as key.

HashMap
--------------------
1) is not synchronized or thread-safe.
2) lock is not required by threads.
3) allows one null value as key
4) it can be made thread-safe by using --> Collections.synchronizedMap() method.
5) better performance in single-threaded applications. -- no lock is required to acquire.
6) better performance in multi-threaded applications. -- you can implement a synchronize block at more broad level, so at each entry point lock is not required.

Diff. between ArrayList and Vector.

Vector
------------------------
1) is synchronized, thread-safe.
2) each time a thread is required to acquire a lock before using it.

ArrayList
------------------------
1) is not synchronized or thread-safe.
2) lock is not required by threads.
3) it can be made thread-safe by using Collections.synchronizedList() method.
4) better performance in single-threaded applications. -- no lock is required to acquire.
5) better performance in multi-threaded applications. -- you can implement a synchronize block at more broad level, so at each entry point lock is not required.

Diff between Thread and Runnable implementation.

1) In your application, when you are already extending your class to some base class for inheritance and want to implement threading, then will have to implement the Runnable interface, coz you can extend only one class at a time, while you can implement multiple interfaces.

2) Runnable interface has only one method -run(), so if you want to override more methods for customizing the threading implementation, you need to extend the Thread class, coz Thread class has all the methods and allows to override them.

Can we write try-finally blocks without a catch block?

Yes,

Incase we want to throw some exception from the current method that would be cought later by the calling program and perform some business operation, try-finally is written w/o a catch block.

like ...

public int getInterest() throws AException{

try{

abc ...

Throw new AException();

...
}finally{

Do ... some .... clearance operation

}
}

NOTE: try block should have catch or finally block, Only try block cant work/compile.

Read-Only Collection or unmodifiable

List stuff = Arrays.asList(new String[]{"a", "b"});

// Make a list read-only
List list = new ArrayList(stuff);
list = Collections.unmodifiableList(list);

try {
// Try modifying the list
list.set(0, "new value");
} catch (UnsupportedOperationException e) {
// Can't modify
}

// Make a set read-only
Set set = new HashSet(stuff);
set = Collections.unmodifiableSet(set);

// Make a map read-only
Map map = new HashMap();
// Add key/value pairs ...
map = Collections.unmodifiableMap(map);

Synchronize a list.

String [] str = new String("A", "B", "C", "D");
List list = Arrays.asList(str);

// sort the list
Collections.sort(list);

// synchronize the list
list = (List)Collections.synchronizedList(list);

Search/BinarySearch an object from a sorted list

// Create a list with an ordered list of strings
String [] str = new String("ant", "bat", "cat", "dog");
List sortedList = Arrays.asList();
Collections.sort(sortedList);

// Search for the word "cat"
int index = Collections.binarySearch(sortedList, "cat"); // 2

// Search for a non-existent element
index = Collections.binarySearch(sortedList, "cow"); // -4

Getting and Setting properties in a Properties File.

String string = properties.getProperty("a.b");
properties.setProperty("a.b", "new value");

Reading and Writing a Properties File.

// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("filename.properties"));
} catch (IOException e) {
}

// Write properties file.
try {
properties.store(new FileOutputStream("filename.properties"), null);
} catch (IOException e) {
}

Here is an example of the contents of a properties file:

# a comment
! a comment

a = a string
b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line \
continuation line
d.e.f = another string

Using StringTokenizer.

break string into words.
------------------------
String aString = "word1 word2 word3";
StringTokenizer parser = new StringTokenizer(aString);

while (parser.hasMoreTokens()) {
S.O.P(parser.nextToken());
}

tokenize string based on "-"
-----------------------------
String aString = "A-B-CD-DEF-G-HI-J";
StringTokenizer parser = new StringTokenizer(aString, "-");

while (parser.hasMoreTokens()) {
S.O.P(parser.nextToken());
}

How to sort an array?

// Create a list
String[] strArray = new String[] {"z", "a", "C"};
List list = Arrays.asList(strArray);

// Sort
Collections.sort(list);
// C, a, z

// Case-insensitive sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
// a, C, z

// Reverse-order sort
Collections.sort(list, Collections.reverseOrder());
// z, a, C

// Case-insensitive reverse-order sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(list);
// z, C, a

e hënë, 11 qershor 2007

Explain the life cycle methods of a Servlet.

The javax.servlet.Servlet interface defines the three methods known as life-cycle
methods of servlet.

This Servlet interface has been implemented by both GenericServlet and HttpServlet.

- public void init(ServletConfig config) throws ServletException
- public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
- public void destroy()

--> init()
For the first request for the servlet, the init() method will be called to initialize the servlet parameters. For the Servlets life cycle its called only once.

--> service()
After the servlet instance is created, for sub-sequent requests a new thread is created and service() will be called.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

--> destroy()
Before the servlet instance is removed from the server memory, destroy() is called to release unwanted resources. Its called only once in servlet's life cycle.

sendRedirect() vs. forward()

Redirect sends an http header back to the browser which causes it to issue a new request for the url indicated in the redirect. This involves an extra round-trip between the server and the browser and you lose all the request parameters unless you have appended them to the redirect url. The reason you would want to use a redirect is in situations where if the user clicks the refresh button or a back button, you would be re-executing a servlet which should not be re-executed. The classic example is an order confirmation page. If the user clicks the refresh button, you don't want to place a duplicate order. To avoid duplicate orders, the order confirmation page should always have been redirected to rather than forwarded to. Since your jsp is doing nothing, it should just forward to the servlet (redirect would be a waste).

URL encoding is used to add the session id to the url if the user's browser does not support cookies. The encodeURL and encodeRedirectURL methods of the HttpServletResponse class contain logic to determine if encoding is necessary so it doesn't hurt to call them. If a user's browser does not support cookies and you do not encode urls, each request will result in a new session.

By the way, your code should be changed to :
<%
String path = request.getContextPath() +
"/servlet/FrontController?thePage=\"index\"";
response.sendRidrect(path);
%>

Since you are already in a scriptlet (i.e. between <% %>), you don't use <%=. It should look like regular java code. Also, index/"" looks like a syntax error. If you are trying to escape the quote, it should be \" not /".