Friday, July 12, 2013

1 How decorator pattern works

Decorator is a structural pattern that adds additional responsibility to the object at run time. This pattern adds responsibility to a particular object not on the class. As a result different object of same type can have different responsibilities.

I would explain a real life example from my experience. I am a biker. Every morning I go to office riding on my bike. When I bought this bike the seller just sold the standard bike to me. They didn't provide any tail light, head light, mud guard and even the kickstand with the bike. Later I added or decorated my bike by adding a tail light, mud guard and with a kickstand. So, functionality of each of this component is different. I added them with my bike and they are responsible for additional functionalities. This can be thought of as a decorator pattern example. Here first I have the bike with standard installation. Then I decorated it with other component.

Participants in a decorator pattern are
  • Component interface
  • a Concrete implementation of Component
  • An abstract decorator
  • One or more concrete decorator that will extend abstract decorator
Basic class diagram is as follows. Later I will add the bike example decorator

Figure 1: Decorator pattern
Here ConcreteDecorator is the standard component that has to be decorated. In my example it is my bike. Decorator abstract class contains a reference of component. Each of the concrete decorator adds additional responsibility to the standard object. Now lets dive to the bike example. Participants for this example are

Bike as the Component
StandardBike as the ConcreteComponent
BikeDecorator as the abstract Decorator
TailLightDecorator as the ConcreteDecorator

So, the diagram for bike example is as follows
Figure 2: Diagram of bike decorator

The code for each of the component are given below

Bike interface is as follows

public interface Bike {
  public String ride();

public class StandardBike implements Bike{
 public String ride(){
  return " This is a standard bike";

public abstract class BikeDecorator implements Bike{

 protected Bike bike;
 public BikeDecorator(Bike pBike){ = pBike;
 public String ride(){
  return bike.ride();

public class TailLightDecorator extends BikeDecorator {

 public TailLightDecorator(Bike pBike) {

 public String ride() {
  return bike.ride() + turnOnLight();

 public String turnOnLight() {
  return " + tail light";

public class MudGuardDecorator extends BikeDecorator {

 public MudGuardDecorator(Bike pBike) {

 public String ride() {
  return bike.ride() + preventMud();

 public String preventMud() {
  return "+ mud guard";

public class Client {

 public static void main(String [] args){
  MudGuardDecorator md = new MudGuardDecorator(new TailLightDecorator(new StandardBike()));

Tuesday, July 2, 2013

0 How to query for tweets using twitter4j

Twitter has killed their API 1.0 on June 11, 2013. Now you cannot do a search query without authentication. Twitter4j is an excellent library for java developers to implement twitter things. You can update status, get a timeline, query for tweets using this library. Here I am going to show you how to query using twitter4j library

Twitter twitter = new TwitterFactory().getInstance();

        AccessToken accessToken = new AccessToken("You-Access-Token-Key", "Your-Access-Token-Secret-Key");
        twitter.setOAuthConsumer("Your-Consumer-Token-Key", "Your-Consumer-Token-Secret-Key");

        try {
            Query query = new Query("#Shahbag");
            QueryResult result;
            result =;
            List tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
        catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());

Monday, September 7, 2009

9 Oracle Export, Import using sqlplus

I will write here about oracle export,import using sqlplus. I assumed that you have basic idea about oracle, sql.

There may situation like follows:-
  • You want to copy some tables from one schema to another schema
  • You want to copy a schema into another database
  • You want to copy table rows from one schema to another schema
You can do this using oracle export, import facilities. These two facilities are really powerful to smooth data transfer. Usually I do this using sqlplus command facilities.

ExportProcess :
At first you need to create dump file. Enter command prompt then type exp in the prompt. It will ask for userid and password of the schema. Suppose your schema is ab and listener name is biis and password is ab. Then type mak@iis and then password makiis.

Then choose the dump file location. You may choose default directory by just entering file name or choose any other location say c:\\ab.dmp. The dump file will be stored in C drive. There are some dump options that is
  1. dump full database
  2. dump a user
  3. dump tables
Here we dump all object(tables,grants,constraints,function,procedures,view,materialized view etc) under user ab. sqlplus will ask for U for user, T for tables and E for entire database. Then enter other options such as export grants, export table data, compress extend etc. After entering all the options export will start and if you see a message at the end stating that "Export terminated successfully without warnings" then dump is 100% successful.

Import Process:
Now you import all objects of ab to another user say xyz. For this purpose
  1. First create the user xyz.
  2. Then enter in cammand prompt and type imp.
  3. Then type username and password of the user on which you want to import objects.
  4. Then type location of dump file (c:\\ab.dump)
  5. Enter dump options
All objects from ab to xyz will be imported successfully.

I accepted the default dump options for import and export.

For any queries plz contact me at

Wednesday, July 22, 2009

12 Custom Request Processor in Struts

I assume that you know the basics of struts and you are using lower version than that of struts 2.0.

Struts is a powerful MVC framework which can be extended to do some excellent work. There may be situations where you need some regular works at every actions. Such as validating the user, checking his/her roles, log user activities etc. Struts provides a way for that. ActionServlet is the only servlet in Struts. Before redirecting to the programmer's action, ActionServlet creates an object of RequestProcessor. The RequestProcessor class in the Struts distribution provides a default implementation for each of the request-processing steps. That means you can override only the methods that interest you, and use default implementations for rest of the methods. The processPreprocess method in RequestProcessor can be overridden to do some common tasks such as

1. Validating User Session
2. Validating User Role
3. Putting Action Form's Data Into User Log Table.

You have to do two things to implement custom request processor in struts.
1. Configure struts-config.xml. You can configure this way

Be sure to put above lines after the ending of action-mappings.

2. Create a class for example MyRequestProcessor extending class RequestProcessor and override the method processPreprocess for example. You can override any other method. The processPreprocess always return true. Returning false from this method will abort request processing. For example if user is not valid for the requested action then you may return false.
Before going to details let us see the sequence of processing a request in struts. Suppose user is requesting the action UserAction.

user request----> ActionServlet--->RequestProcessor --if processPreprocess return true-->UserAction

If you are overriding processPreprocess of RequestProcessor using your MyRequestProcessor then you can control user access.

Here is the sample code for MyRequestProcessor

public class MyRequestProcessor
extends RequestProcessor {
  protected boolean processPreprocess (
      HttpServletRequest request,
      HttpServletResponse response) {
      HttpSession session = request.getSession(false);
  //If user is trying to access login page
  // then don't check
  if( request.getServletPath().equals("/")
      || request.getServletPath().equals("/") )
      return true;
  //Check if userName attribute is there is session.
  //If so, it means user has allready logged in
  if( session != null &&
  session.getAttribute("userName") != null){
      return true;
//if user session is valid then check user requesting action is valid or not.
//you can check this from your database table or any other way. I assumed that user
//actions is saved in database.
boolean validRole = checkUserRoleFromDB(session.getAttribute("userName")
); // not implemented

return true;

          //If no redirect user to login Page
      }catch(Exception ex){

  return false;


Sunday, February 22, 2009

4 Preventing Duplicate Form Submission in Struts using TOKEN

Duplicate form submission may occur in the following situations:-
  • Using Refresh button
  • Using the browser back button to traverse back and resubmit form
  • Using Browser history feature and re-submit form.
  • Malicious submissions to adversely impact the server or personal gains
  • Clicking more than once on a transaction that take longer than usual
What happens in form submission? Suppose you have a form named adduser.jsp and an Action named So, on clicking submit in the adduser.jsp page struts finds the mapping and redirect to this url. So, in the browser url you will find /app/
and when you click on refresh same url is called and same form is submitted again. Struts provides several ways to protect this.
  • HTTP redirect after form submission
  • using TOKEN
HTTP redirect

Suppose form submission result is shown in a page called success.jsp. So, if redirect is set true in forward of action in struts.config URL in the URL bar becomes /app/success.jsp. So, if you refresh on again the success.jsp is called not the /app/ So, in this way we can protect against refresh. But, unfortunately this does not protect against goint to back button of browser and submit the form again.


This method generates a Token using session id, current time and messagediagest and save this token to session. The action responsible for rendering the form save the token using saveToken method. So, the session is saved in session and a hidden field name token with the value is set to html form. If you view the source of html form page you will find the hidden form as follows

<input type="hidden" name="org.apache.struts.taglib.html.TOKEN"value="some value">
When client submit the form this hidden field also submitted. Struts check the two TOKEN (token from session and token submitted). We can check the two token using isTokenValid method. If they are equal this method returns true and the form is submitted for the first time. If not equal then duplicate form submission. Checking code is shown below:-

request.setAttribute("brtcerror","Duplicate Form Submission Error");
return mapping.findForward("error");

resetToken method is used to clear the Token set for this action. Because if you have multiple form you must clear the Token. Other wise for new form you will always find duplicate form submission error. Suppose action addUser renders adduser.jsp page. So, you have to save token in addUser corresponding class by calling saveToken(request) method. You should validate this token in the submit action which is here.

Saturday, December 20, 2008

4 jQuery Autocomplete

Autocomplete using jQuery is quite easy. jQuery made this cumbersome work easy for programmers.

So what is needed for autocomplete feature in your page
  1. jquery.js
  2. jquery.autocomplete.js
  3. jquery.autocomplete.css file
Just include these three files in header. Ad the following script to your header

function showItem(row) {
return row[0];

$(document).ready(function() {
  max: 200,
  scrollHeight: 180,
Let us depicts about the above code segments. Here #category means the category id on which you want autocomplete feature. and "getcategory.php" is the server side file which will provide result for autocomplete.

Now let us discuss about the parameters.
minChars: minimum character in the input to call autocomplete
max: maximum item in the list. No more items exceeding this value will not be displayed. Its default value is 10
scrollHeight: this is actually list height. If result is large scroll is needed.
formatItem: if you want to format data you can use this parameter.

Now how server will deliver data. Let us see the content of getcategory.php file

$categories = array('IT', 'Software', 'Semantec', 'Hardware', 'Intel',
 'AMD', 'Politics', 'Economics', 'Business', 'Travel',
 'Psychology', 'Medical', 'Sports');

$q = strtolower($_GET["q"]);
$results = array();
// search categories
foreach($categories as $cat)
 if( strpos(strtolower($cat), $q) === 0 )
  echo "$cat\n";

Now create a textbox with id "category". If you type you can view the autocomplete effect. It will display data matching to your input. If you want multiple item in your text box just set "multiple: true" in the autocomplete parameter list. By deafult data is separated by comma. But you can change using multipleSeparator parameter.

View the Demo.

Friday, November 28, 2008

2 Various Web Layouts (Fixed, Elastic, Liquid)

Web designers basically have three layouts based on CSS. They are :-
1. Fixed
2. Elastic
3. Liquid

All of the above has its own advantages and disadvantages. I will describe here details of these three.

1. Fixed LayoutFixed layout websites looks same in all container. Whatever the monitor size, pixel it is always same. Because of its rigidity it is also called ice layout. Developer can organize elements any way he/she likes. If you set the width of your design to be 720 pixels wide, it will always be 720 pixels. If you then want a branding image spanning the top of your design, you know it needs to be 720 pixels wide to fit.

This layout cannot utilize space available. They are always same what ever the window size is. A site made for 800 600 screen resolution looks tiny in a higher resolution screen and in vice versa a site made for 1024 760 screen will cause scrolling in lower resolution. A reader with a mobile phone or a handheld computer will have to scroll laterally; a reader with a high-resolution monitor will see a narrow strip in the middle of the screen; when printing, the right-hand side can end up off-page. Besides, when the reader increases the text size, the text will sooner or later break out of a narrow column and we have an overlap that can render the page unreadable.
2. Elastic Design LayoutActually elastic design mainly works on websites text. An elastic layout scales with users’ text size. Elastic design uses em values for all elements. Ems are a relative size, written like this: 1em, 0.5em, 1.5em etc. Ems can be specified to three decimal places like so: 1.063em.
  1. They are calculated based on the font size of the parent element. E.g. If a
    has a computed font size of 16px then any element inside that layer —a child— inherits the same font size unless it is changed. If the child font size is changed to 0.75em then the computed size would be 0.75 × 16px = 12px.
  2. If the user increases (or decreases) text size in their browser, the whole interface stretches (or shrinks.)
DisadvantagesIt has same disadvantages like liquid design except that it doesn't break because of changes in text size.

3. Liquid/Fluid Layout
Liquid layout specify width height using percentage instead of px or em. For web designers the monitor screen does not have fixed width or height because these variables change, at times in unpredictable ways. People might have larger buttons, toolbars such as Yahoo or Google, they open the Favorites page on the left, they have a double task bar and so on.Therefore the width and height of the screen is different from user to user. By the name liquid this type of design implies that what ever the container that is monitor or browser the layout will be furnished according to the space. So, high, low resulution is not a problem for liquidly designed site. Main point about liquid design is accessibility. Liquid design eliminates irritating design flows such as much white space, disapperance of certain sections etc.

Too much content required for this type of layout. Too much content can confuse user.The lines of text become way too long on a large monitor Overlap is hard to avoid in small windows when a column becomes too narrow to contain long words. CSS provides a solution for both problems (max-width and min-width), but Internet Explorer doesn't support any of those.


Mohammad Abul Khaer Copyright © 2011 - |- Template created by O Pregador - |- Powered by Blogger Templates