A Linux Guy

أسألك أن تدعو الله لي دعوه بظهر الغيب

23 April 2009

My Programming Skills

While going through friend's blogs, I found this post.
In this post I found a tests about Programmer Personality Type , I took the quiz and here's the rest ;


Your programmer personality type is:

PHTB

You're a Planner.
You may be slow, but you'll usually find the best solution. If something's worth doing, it's worth doing right.


You like coding at a High level.
The world is made up of objects and components, you should create your programs in the same way.


You work best in a Team.
A good group is better than the sum of it's parts. The only thing better than a genius programmer is a cohesive group of genius programmers.


You are a liBeral programmer.
Programming is a complex task and you should use white space and comments as freely as possible to help simplify the task. We're not writing on paper anymore so we can take up as much room as we need.

27 March 2009

Java Job Interview questions in Object Oriented Programming

In the name of ALLAH,

One of the most important part of the Jobs Interview questions I found is the object-oriented programming, so I decided to write in this important topic.
Most of us know about Object-Oriented programming basics which are Encapsulation, Inheritance and Polymorphism and Abstraction. We will talk further about them and about other topics such as abstract classes, interfaces, multiple inheritance and many more in this post, and will continue our discussion in other posts.
In my point of view, Object orientation divided over 3 layers on understanding, first level of understanding is that you know about what object is, what is a method, what is a class, what is abstraction, encapsulation, inheritance and polymorphism but this level is not enough to know actually on how to uses such great programming methodology, but you should go further one level higher to hear about Object-Oriented principles; Object-oriented principles are principles that helps you to use object-oriented basics you learned from the first level the best usage. Example for these principles are : Program to interface not to implementation and also You Class (Design) should be opened for extension, closed for modifications and You low level component shouldn't relay on higher level ones and many more (1) . Myself found these principles more interesting that the third level which are the famous Design Patterns.
Design patterns(2) are applying for object oriented principles and basics and reuse for other expertises in order to make best usage from the object oriented designing methodology.
In this discussion we will talk about Basic Object oriented programming methodology what is object, class, interface, abstract class, final ( steal) steal class and many more.

So, lets start by the most famous questions in interviews,

Question) What is the deference between Abstract class and Interface ?
Abstract class is a class that have properties and methods that can be one of these two cases : class that represent abstract concept in the real domain such as the java.lang.Number class in the Java JDK. second case that when I have a domain problem such as I have many classes that shares common functionality and I want share these functionality and make the subclasses provide their own functionality in this case I made a super class an abstract and provide implementation for the share method and non-shared method I do it as abstract methods.
Example :
class Shape {
void calculateArea (){
// do some thing
// c...
}
abstract void display(); // share by name only, each subclass has its own implementation
}
class Rectangle extends Shape{
void display(){
// do some stuff....
//c.
}
}

Note that, an abstract class cannot be instantiated ( take an instance from It ) but can be subclassed (i.e. inherited ) as an opposite for the final class ( steal in MS.net terms ) that final class can be instantiated but cannot be inherited.
Abstract class is a regular class that have a constructor, methods and fields zero ore more of its methods are abstract. An abstract method should reside in an abstract class.
Interfaces:
interface is other thing than abstract classes, interface found in Java for three reasons.
First to be such class that defined in .h files that found in C++, if you know about C++ you could remember that for a given class, there where two files for that class, a .h file and a .cpp file, the .h file is a file that define the interface of that class without any code implementations at all, first usage for the interfaces in Java is to be just an interface for a particular class for the programmer to implement. For an Employee class, there is an Employee interface that contains the prototype for its method.
The second usage is to be used as a contract, ( the interfaces are allows do that), for a class to have a particular service, he should fulfill that contract (implement that interface). Some service could be delivered just by adding the word implements InteraceXYZ (marker interfaces) and others by implementing complex methods.
Examples for the first type is the java.io.Serializable and java.lang.Clonable interfaces that provide services for your classes just be adding the implements keyword behind class declaration.
The other type requires you to provide an implementation for certain methods ( i.e. all methods in that interface ).
example : We have a store that contains items to be sold, these items are of different types, and we want to make sure that the buyer can bye them , here is the method of the buyer class :
public void buyProduct (Buyable product ){
// c....
/...........
double price = product.getPrice();
}

so for your products to get bought, all should implement the Buyable interface so that the the buyer can use the buying capabilities found is this product.
Public interface Buyable {
double getPrice(); // public abstract by default
}

each class who want sold, should impalements the getPrice method so the buyer can use to buy this product.
public class Computer implements Buyable {
///
////
public double getPrice(){
// c
//////..................
}
}
Third usage is that the interface provides multiple interface (non-implementation ) inheritance.
Where a class can implement more than interface in case that the interfaces cannot have method impalement, so no confusion can come in you class.





------------------------------------------------------------------
(1) see O'Reilly Head First Design patterns
(2) see Design Patterns Reusable software components and O'Reilly Head First Design patterns

10 March 2009

Managing user Transaction in Hibernate

In the name of ALLAH,

Today we will talk about an important topic in doing Databases, User Transactions.

There are two types of transactions found in any Database application, Database Transactions and User(Application) Transactions. 

Database Transactions are transactions that executed as a serious of SQL statements sequentially, once completed, the transaction commits ( or rolled back ).

example of DB Transaction when a Bank Client what to transfer funds form his first account to his second account, that will be done in two stages, first decrement his first account with the amount he specified, second, add to his second account the amount he wishing transfer.

In such scenario, if one stage fails, the other should fail.

So if we implement these two stages as ordinary two SQL update statements, the DB couldn't ensure that the two will be committed or rolled back together, so the solution in Transactions.

In DB Transaction, the Transaction either committed or rolled back as a whole.

The Database Management System (DBMS) itself who ensure the Atomicity, Consistency , Isolation and Durability of these transactions (ACID).

So what ACID ??

ACID is a certain operations granted  to be executed by the database against DB Transaction.

Atomicity means : single unit of work ( either the transaction committed or rolled back at all )

Isolation means : no changes cannot made to the data used in the transaction, the transaction is isolated from other transaction and database changes (i.e. if another user want to change the data under transaction, he can't ).

Consistency means : the transaction shouldn't leave the data in non-consistent state.

Durability means : once the transaction committed, all changes during it, make persisted in the database.

But, what happened if the Transaction should be span multiple User Sessions ( not hibernate Session interface ) ?

In another meaning, suppose we have an Enterprise-based web application (Web Application), the user makes changes that are related and occurs in subsequent request-response cycle.

What if the user should change his bank account in 2 or more requests to the server ??

in this case, we cannot relay on Database Transactions, So here's the User (Application) Transaction arises .

User Transactions

We will take about user transaction in a context of a simple example, suppose we have an e-commerce web application, we have more that one administrator that can change the price of the products according to some criteria, what happens when two Administrators want to change the price of one product at the same time, the first administrator will change the price based on the original price say he changed the price of a laptop computer from 4000 L.E to 3800 L.E. And the other administrator change the price from also 4000L.E. ( he still didn't see the new changes of the database ) to 4200 L.E. ??

the second administrator thought that he changes the price from 4000 to 4200, but really he will change the price from 3800 ( that changed be the other administrator will he opened the changing page and not yet decided to change the price ) to 4200, the Owner never permit that a product be increased in price by 400 L.E. A once !!

So we have three choices as system implementers ..

1)      override the first administrator by the second administrator and set the price to 4200 ( violate the business rules )

2)      not to allow the second administrator to commit his changes saying that another administrator at the same time has already changed the price

3)      not to allow the second administrator to commit his changes and showing him the changes made by the other administrator.

Solution 2 & 3 are more reasonable, in first solution, hibernate have nothing to do, neither you.

In the second and third solution Hibernate come and get a solution to such a concurrency problems by using “Managed Versioning” .

In managed versioning, you will add a new column in the database called version ( for example ), and add a new property for the object to be persisted called version.

So far so good, the new thing is to add a tag called version immediately after the identifier property that reassemble :

< version name="version" column="version" >

that is all about, when hibernate is going to update the column it will issue a SQL statement looks like this :

UPDATE products p SET p.price = “4200” AND version = 1

WHERE p.id = 123  AND version = 0

if another transaction updated that column at the same time, the version id shouldn't contain the value 0, so the update statement will never executed and hibernate throws exception of type org.hibernate.StaleObjectStateException

26 February 2009

Application Layers

Today I want to talk About an important Programming concept, Application Layers.

All of us know that there might be in your layered application some common layers such as Database layer, Business layer and Presentation layer, but most of us do not exactly know the responsibility of each layer, so lets talk about Layers in our Layered Applications.

In any modern J2EE ( and non-Java ) layered application we have Four layers in our applications, three in our programming code and one outside it, it represented in the Database.

These layers are ( from top to bottom ) Presentation layer, Business layer and Integration layer .

We will define each layer and give common technologies used to implemented that layer.


Presentation Layer :

presentation layer is the layer that the end-user sees and interacts with, this is mostly implemented as Web Interface or Desktop interface or even as Mobile-application interface.

Common technologies:

mostly the presentation layer implemented in JSF, Struts, Oracle ADF, Apache Coccon, JSP/Servlet for Web-based presentation layers and Swing, AWT for Desktop-based presentation layers

Business Layer :

The business Layer ( also known as Application Layer )  is the most important layer in your application, it represents the core application modules implemented, the more clearer and design patterns involved, the best your application in both flexibility and ability to be maintained on the long run.

Mostly implemented in your native Java code as Objects that represents your domain business model or in Large applications,  it is implemented as EJB Session Beans and MDBs.

Again, this layer is the most important one cause it decides whether you application design and coding is good or bad.

It depends on the developers experience in solving business problems.

Integration Layer :

Also known as Data Access Layer, It is the layer responsible for getting the data back and forth from and to the database.

It is mainly responsible for Making data access processes for you Business layer also it makes your application independent from the underlaying database technology.

Common technologies:

Also many developers implement this layer using regular JDBC code, there are many frameworks and technologies found in this area, for frameworks there are Hibernate, Oracle Toplink, iBATS and OJB that is an implementation for JDO technology.

In this layer there is a common Design patten arise in J2EE applications that make the implementation of this layer an easy and organized task , that is DAO pattern (Data Access Objects). ( see this post for more info about DAO pattern)

The last layer is the Database layer that stores the data of your applications, also there are many DBMS found as Oracle Database, MySQL, HSQL, the windows-only MS SQL Server and many more.

01 February 2009

Data Access Object (DAO), a J2EE Design pattern

DAO is a famous J2EE Design pattern, really it provides many services to your design as it brings more flexibility to your system, but also brings complexity.

It's the story; the more flexible is your system, the more complicated it is.

Let's discuss briefly the DAO design pattern and its associated patterns:




The class pattern is shown as CustomerDAO
CustomerBO implements Business Object J2EE pattern
Customer implements ValueObject (Data Transfer Object ) J2EE pattern

As shown, the DAO pattern isolate between the Buisness layer ( Customer BO ) and the underlying implementation of the Datasource.
The Buisness layer calls the DAO objects that depend on the underlying datasource, so the only portion of code we need to change when changing the datasource implementation mechanism (useing ORM instead of JDBC , or uses OODBMS instead of RDBMS )

Basic DAO implementation:
public class CustomerDAO extends AbstractDAO {

Customer customer;
DBCommon dbManager;

public CustomerDAO(Customer customer, DBCommon dbManager)throws DBException {
this();
this.customer = customer;
this.dbManager = dbManager;
}

public CustomerDAO(Customer customer)throws DBException {
this();
this.customer = customer;
}

public CustomerDAO(DBCommon dbManager)throws DBException {
this();
this.dbManager = dbManager;
}
public void delete() throws DBException {

boolean result = false;

try {
result = dbManager.deleteRecord("Customers", " cust_id = " + customer.getId());

}catch (DBException e) {
e.printStackTrace();
throw new ObjectNotDeletedException("cannot delete customer");
}finally {
dbManager.close();
}

if ( !result )
throw new ObjectNotDeletedException("cannot delete customer");
}
public Customer load(long identityKey) throws DBException {
//
}

//reset of CRUD methods
}
From the preceding sample we get that DAO objects in its simplest form is an object that implement basic CRUD (Create – Read- Update- Delete ) operations in its simplest fom.

There are more sophisticated techniques to create DAO objects using GoF patterns (Factory method and Abstract Factory patterns) (refer to Core J2EE Patterns : Best practice and Design strategies by Deepak Alur et. al. )

Value Objects
These are basic POJOs ( javabeans object ) used to transfer data between layers, between the application layer and the business layer for example.

This pattern uses along with DAO pattern to transfer data between the DAO layer ( data access layer or integration layer) and Business layer

Business Objects
Is the objects that depends on DAO objects to execute Business functions of the system.

09 January 2009

Enabling Arabic in Java web applications (JSP apps and Struts apps )


Enabling Arabic in Java web applications (JSP apps and Struts apps )

One of the most big problems you can face as a java web developer is how
to make you web application accepts Arabic (non-ISO-8859-1 characters)
characters from the users in the input text boxes.

In JSP/Servlet applications, a small googling can solve the problem, but
with a framework such as Struts, the matter differ somewhat.

If your web application uses the Database ( the most if not all does )
you should insure that the problem is not in the Database itself that cannot
save Arabic characters, you should try hand-entering Arabic words in varchar
and nvarchar fields, if it accepts Arabic characters, then the problem is in
the JSP/Servlet or Struts and you will find the solution here.

For pure JSP/Servlet Applications :

Two steps and every thing well be done.

First: in each JSP page write this tag at the top of the page :

<%@page language="java" contentType="text/html; charset=UTF-8"%>

Second : in each Servlet that works as the controller for you JSPs, write these two statements at the top of your service()/doGet()/doPost() methods.

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

That’s all about Enabling Arabic character acceptation in your JSP forms

For Struts Applications:

Also two steps :
First: in each JSP page write this tag at the top of the page :

<%@page language="java" contentType="text/html; charset=UTF-8"%>

Second: write a Filter class the wraps your org.apache.struts.action.ActionServlet class and put these two statements in its doFilter() method

request.setCharacterEncoding("UTF-8");

response.setCharacterEncoding("UTF-8");

example filter :

public class ArabicEncodingFilter implements Filter {

private void doBeforeProcessing(ServletRequest request, ServletResponse response)

throws IOException, ServletException {

request.setCharacterEncoding("UTF-8");

response.setCharacterEncoding("UTF-8");

}

private void doAfterProcessing(ServletRequest
request, ServletResponse response)
throws IOException, ServletException {

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {

doBeforeProcessing(request, response);

Throwable problem = null;

try {

chain.doFilter(request, response);

} catch(Throwable t) {

problem = t;

t.printStackTrace();

}

doAfterProcessing(request, response);

}}}

And then wrap all your Servlets with you Filter by putting this in web.xml :

<filter>

<filter-name>EncodingFilter</filter-name>

<filter-class>ArabicEncodingFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>EncodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

13 December 2008

How to iterate over a collection using struts logic taglib

Among struts Tag libararies there's a taglib called logic, it aims to do logical operation especially values and strings comparison using its tags such as Equa, NotEqaul, present, notPresent, greaterThan and more.

Among theses tags, there is a very handy tag that used to iterate over collection, it remembers me with the JSTL forEach tag, but it provides more funcationality.

We can use this tag to display the model data as it appears in the next view in very easy-to-use way :

lets illustrate it, assume we have an abject called EmployeeBO that wrap and Employee object of four attributes : ssn, firstname, lastname and age.

The EmployeeBO object contains a method called getAllEmployees that returns an array list of employees objects.
The following code is the code of the action class, it inserts the result of "getAllEmployees" in the session to get it back again in the view from the session:

package org.daz;

import javax.servlet.http.*;
import java.util.*;
import org.apache.struts.action.*;

public class GetAllEmployeesAction extends org.apache.struts.action.Action {

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

ActionForward forward = null;

EmployeeBO emps = new EmployeeBO();
List empList = emps.getAllEmployees();

HttpSession session = request.getSession();
session.setAttribute("empList", empList);

forward = mapping.findForward("success");

return forward;
}
}


and this is the code of the jsp page:

<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>

<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>

<html:html>

<head>

<html:base />

</head>

<body>

<table border="1" width="50%">

<tr>

<td>serial</td>

<td>SSN</td>

<td>First name</td>

<td>Last name</td>

<td>Age</td>

</tr>

<logic:iterate id="employee"
name="empList" indexId="id" offset="${param.offset}" length="5">

<tr>

<td>${id }</td>

<td>${employee.ssn }</td>

<td>${employee.firstname }</td>

<td>${employee.lastname }</td>

<td>${employee.age }</td>

</tr>

</logic:iterate>

</table>

<html:link href="showemps.jsp?offset=${id - 9}"> previous </html:link>

<html:link href="showemps.jsp?offset=${id+1}"> next </html:link>

</body>

</html:html>

The logic tag appears in red, it takes more than one attribute;

id: an page-scoped object that will store the current iteration object

name : the name of the scopped bean to iterate over

indexId : an page-scoped object that will store the current iteration number

offset : the index of the collection to start from

length : the number of rows to display on a page