Monday, August 5, 2013

How to set chmod for a folder and all of its subfolders and files in Linux Ubuntu Terminal?

to change all the directories to 755:
    find /opt/lampp/htdocs -type d -exec chmod 755 {} \;
to change all the files to 644:
    find /opt/lampp/htdocs -type f -exec chmod 644 {} \;

Friday, January 4, 2013

PHP explode function

PHP explode function

The explode function is used to split a string by a specified string into pieces i.e. it breaks a string into an array.

The explode function in PHP allows us to break a string into smaller text with each break occurring at the same symbol. This symbol is known as the delimiter. Using the explode command we will create an array from a string. The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.

for more details please visit http://php.net/manual/en/function.explode.php

array explode ( string $delimiter , string $string [, int $limit ] )

explode function request 3 parameters, but the last one is optional. Let see what are these parameters.

$delimiter - to break a string into smaller text with each break occurring at the same symbol, this would be the symbol
$string - String that you want to split
$limit - Limit is optional param but would may be tricky. You must concern following points when you are try to use limit.
  • If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
  • If the limit parameter is negative, all components except the last -limit are returned.
  • If the limit parameter is zero, then this is treated as 1.
Let see some example codes:

<?php
$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));


Above code will output the following:
Array
(
    [0] => one
    [1] => two|three|four
)

<?php
$str = 'one|two|three|four';

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));


Above code will output the following:
Array
(
    [0] => one
    [1] => two
    [2] => three
)


<?php
$str = 'one|two|three|four';

// limit with 0 and 1 would be same
print_r(explode('|', $str, 0));



Above code will output the following:

Array
(
    [0] => one|two|three|four
)

PHP implode function

implode() Function

The implode function is used to join an elements of an array with a string.

The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice.

The implode function in PHP is easily remembered as "array to string", which simply means that it takes an array and returns a string. It rejoins any array elements and returns the resulting string, which may be put in a variable.

Let's take an example:

If you want to separate array values with a dashed (-), Following statement is just fine.

<?php

$array = array('XXX', 'TTT', '2123123');
$dash_separated = implode("-", $array);

var_dump($dash_separated);

It will output the result as follows :

string(15) "XXX-TTT-2123123"

Here are the tricky ways of implode will get naughty.

1) When try to implode with empty array.
eg:

<?php
//When using empty array it will return empty string even passed the glue 
var_dump(implode('hello', array()));


Above code will output empty string as :


string(0) ""


2) When try to implode with array with boolean.

eg:
<?php

//When imploding boolean values it will just return the values of true
var_dump(implode('',array(true, true, false, false, true)));



Above code will output only true(s) as :

string(3) "111"

Advanced usage of implode method

If you are dealing with sql functions the implode method is just perfect. try following codes:

<?php

//Quite handier with sql functions with arrays

$fields = array(
        'subject' => 'go green',
        'message' => 'i am going to take off!'
);

$sql = 'INSERT INTO table_name';
$sql .= " VALUES (`" . implode("`,`", array_keys($fields)) . "`)";
$sql .= " ('" . implode("','", $fields) . "')";

var_dump($sql);

$userIds = array(2, 32, 55, 200, 44);

$sql2 = "SELECT * FROM table_name";
$sql2 .= " WHERE 1 AND (id=" . implode(" OR id = ", $userIds) . ")";

var_dump($sql2);



Above codes will give the output as follows:


string(90) "INSERT INTO table_name VALUES (`subject`,`message`) ('go green','i am going to take off!')"
string(88) "SELECT * FROM table_name WHERE 1 AND (id=2 OR id = 32 OR id = 55 OR id = 200 OR id = 44)"

Happy coding ~

Thursday, September 13, 2012

Transactions in MySQL


Definition of a transaction

A transaction is an atomic unit of database operations against the data in one or more databases. The effects of all the SQL statements in a transaction can be either all committed to the database or all rolled back.

MySQL supports several storage engines. The InnoDB is fully ACID compliant. The ACID stands for Atomicity, Consistency, Isolation and Durability. Reliable transactions must support all these four properties.

Operations within a transaction must be atomic. This means, that either all operations succeed or fail. This is all or nothing rule. The consistency property ensures that the database is in a consistent state after the transaction is finished. The data is valid and there are no half-finished records. For example there are no customers left with no payment records or there are no payment records without customers. Isolation is the requirement that other operations cannot access data that has been modified during a transaction that has not yet completed. The question of isolation occurs in case of concurrent transactions. Without isolation, the data may end up in inconsistent state. Durability is the ability of the database system to recover the committed transaction updates against any kind of system failure.

The default transaction isolation level for MySQL is repeatable read.

mysql> SELECT @@tx_isolation;
+-----------------+
| @@tx_isolation  |
+-----------------+
| REPEATABLE-READ |
+-----------------+

The current isolation level is stored in the tx_isolation server variable.

mysql> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

mysql> SELECT @@tx_isolation;
+----------------+
| @@tx_isolation |
+----------------+
| SERIALIZABLE   |
+----------------+

We can change the isolation level with the SET TRANSACTION ISOLATION LEVEL statement.


Autocommit


MySQL also automatically commits statements that are not part of a transaction. The results of any UPDATE or INSERT statement not preceded with a START will immediately be visible to all connections.

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+

The autocommit variable is set by default.

mysql> SET autocommit=0;

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            0 |
+--------------+

The autocommit can be turned off.
Now we are going to demonstrate the autocommint variable.

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+

CREATE TABLE Test(Num INTEGER NOT NULL) engine=InnoDB;

The autocommit is set. We create a simple Test table with InnoDB storage engine, which supports transactions.

mysql> INSERT INTO Test VALUES (1), (2), (3);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
+-----+

We insert three rows into the column of the table. The values are immediately committed.

mysql> SET autocommit=0;

mysql> INSERT INTO Test VALUES (4), (5);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
|   5 |
+-----+

Now we set the autocommit variable to false. We insert two values and select all data from the table. We have now 5 rows in the table.

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
+-----+

However, the data is not permanently written to the table. With the ROLLBACK statement, we take them back.

mysql> INSERT INTO Test VALUES (4), (5);

mysql> COMMIT;

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
|   5 |
+-----+

Now we insert value 4, 5 again. This time, the rows are committed with the COMMIT statement. Subsequent rollback statement has no effect.


Starting transactions

With autocommit enabled, each single SQL statement is wrapped automatically in its own transaction. To start our own transaction, we issue the START TRANSACTION statement. The transaction is later finished with the COMMIT or ROLLBACK statements. Multiple statements may be issued in the body of the transaction. All are either committed or rolled back as one unit.

mysql> TRUNCATE Test;
Query OK, 0 rows affected (0.02 sec)

mysql> SELECT * FROM Test;
Empty set (0.00 sec)

We will work with the same Test table. We truncate the data in the table.

mysql> START TRANSACTION;

mysql> INSERT INTO Test VALUES (1), (2);

mysql> INSERT INTO Test VALUES (3), (4);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
+-----+

In the above code, we start a transaction and insert four rows into the table. The values are not yet committed. From the current connection the rows are visible.

$ mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 65
Server version: 5.1.41-3ubuntu12.9 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SELECT * FROM mydb.Test;
Empty set (0.00 sec)


However, from a different connection, the Test table is empty. We launch a new instance of a mysql client program. This is a different connection to the MySQL database. From this connection, the values are not yet visible.


mysql> COMMIT;

Finally, the COMMIT statement commits the data to the table. The rows are visible from both connections.

We start another transaction. This time the data will be rolled back.

mysql> START TRANSACTION;

mysql> INSERT INTO Test VALUES (5), (6);

mysql> INSERT INTO Test VALUES (7), (8);

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
+-----+



In the above SQL code, we start a new transaction. We insert four values into the Test table. We roll the changes back with the ROLLBACK statement. Subsequent select from the table shows that the data was not committed to the table.

Tuesday, August 28, 2012

How to find a content of a file linux

You can find content inside a file by using Linux grep command. eg : If you want to find the usage of text called "Hello". You can type as follows:

grep -r hello .

-r option means read all files under each directory, recursively
hello - means the content what you want to search
. - means the path for this scenario it means from current folder.(You can use absolute path as well eg: /home/gayan/)

Enjoy ~

Wednesday, August 1, 2012

Database Access Object Pattern using PHP


The simplest web widget to the most complex online e-commerce website have one thing in
common: they deal with data. So much of programming revolves around data access and
manipulation. With the massive proliferation of the Internet, cheaper storage devices, improved understanding of analytics, and greater expectations for information access, data is being leveraged in more interesting and unique ways. The Data Access Object Design Pattern aims to help construct objects that can work easily (transparently) with all of this data.

Programming typically can be a lot of repetition. This was especially true before more popular frameworks started being released. Most PHP programmers can count into the double digits the number of CRUD (create, read, update, delete) applications they’ve had to make. One of the major portions of repetition in the standard create/update application is the data source manipulation. For the rest of the discussion, I’m going to stop generalizing the data source and refer to it as SQL.

In the application, a SQL statement has to be written to create the entity in the database. Next, an additional SQL statement must be written in order to provide updates to any of the individual features of that entity. The repetition involved in creating these SQL statements is not only boring but also not best practice.

Code example

First create your own database and create following table

 CREATE TABLE task (  
      id INT PRIMARY KEY AUTO_INCREMENT,  
      subject VARCHAR(255),  
      description text  
 );  

Create php file called "baseDao" and put following code

 <?php  
 class baseDao  
 {  
   private $connection;  
   public function __construct() {  
     $this->connectToDb(DB_USER, DB_PASS, DB_HOST, DB_NAME);  
   }  
   public function connectToDb($user, $pass, $host, $database) {  
     $this->connection = mysql_connect($host, $user, $pass);  
     mysql_select_db($database, $this->connection);  
   }  
   public function fetch($value, $key = NULL)  
   {  
     if (is_null($key)) {  
       $key = $this->_primaryKey;  
     }  
     $sql = "SELECT * FROM {$this->_tableName} WHERE {$key} = '" . $value . "';";  
     $results = mysql_query($sql, $this->connection);  
     $rows = array();  
     while ($result = mysql_fetch_array($results)) {  
       $rows[] = $result;  
     }  
     return $rows;  
   }  
   public function update($keyedArray)  
   {  
     $sql = "UPDATE {$this->_tableName} SET ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates[] = "{$column}='" . $value . "'" ;  
     }  
     $sql .= implode(",", $updates);  
     $sql .= " where {$this->_primaryKey}='". $keyedArray[$this->_primaryKey] . "';";  
     mysql_query($sql, $this->connection);  
   }  
      public function save($keyedArray)  
   {  
     $sql = "INSERT INTO {$this->_tableName} ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates_columns[] = "{$column}";  
       $updates_values[] = "'" . $value . "'" ;  
     }  
           $sql .= "(";  
     $sql .= implode(",", $updates_columns);  
           $sql .= ")";  
           $sql .= " VALUES (";  
     $sql .= implode(",", $updates_values);  
     $sql .= ");";  
     if (!mysql_query($sql, $this->connection))  
                echo mysql_error();  
   }  
 }  

Finally you can use the dao class as follows:


 <?php  
 //DB_USER, DB_PASS, DB_HOST, DB_NAME  
 define('DB_USER', 'root');  
 define('DB_PASS', '');  
 define('DB_HOST', 'localhost');  
 define('DB_NAME', 'blog_samples');  
 //include "baseDao.php";  
 include "taskDao.php";  
 $taskDao = new taskDao();  
 $updates=array('subject' => 'testSubjectValue', 'description' => 'testDescriptionValue');  
 $taskDao->save($updates);  
 echo "<br/>Dao pattern !<br/>";  
Good luck !

Friday, July 27, 2012

Builder design pattern using php

Software complexity is an interesting thing. The requirements for software are complex as are the functionality of a software package or product. Even the code that makes up the software is complex. The focus of the Design Pattern approach is to provide maintainability, architectural 
strength and reduced complexity. With the host of complex objects making up most software repositories, solutions involving the Builder Design Pattern have their work cut out for them.

Code example

The project contains a class that creates the complex product object. This class contains three methods to completely form it. If each of these methods is not called when creating a new product object, attributes of the class will be missing and the program will halt. These methods are setType(), setColor(), and setSize(). The initial version of this code was designed to create the object followed by the execution of each of these methods.

class Product
{
    protected $type = '';
    protected $size = '';
    protected $color = '';
    protected $price = '';

    public function setColor($color)
    {
        $this->color = $color;
    }

    public function setSize($size)
    {
        $this->size = $size;
    }

    public function setType($type)
    {
        $this->type = $type;
    }


    public function setPrice($price)
    {
        $this->price = $price;
    }

    function __toString()
    {
        $text = 'Product { ';
        $text .= ":type => " . $this->type;
        $text .= ", :size => " . $this->size;
        $text .= ", :color => " . $this->color;
        $text .= ", :price => " . $this->price;
        $text .= " }";
        return $text;
    }

}


To create a complete product object, the product configurations need to be passed individually to each of
the methods of the product class:


// our product configuration received from other functionality
$productConfigs = array(‘type’=>’shirt’, ‘size’=>’XL’, ‘color’=>’red’);
$product = new product();
$product->setType($productConfigs[‘type’]);
$product->setSize($productConfigs[‘size’]);
$product->setColor($productConfigs[‘color’]);


Having to call each one of these methods when an object is created is not best practice. Instead, an object based on the Builder Design Pattern should be used to create this product instance.


The productBuilder class is designed to accept those configuration options that are required to build
the product object. It stores both the configuration parameter and a new product instance on
instantiation. The build() method is responsible for calling each of the methods in the product class to
fully complete the product object. Finally, the getProduct() method returns the completely built
product object.




class ProductBuilder
{

    protected $product = NULL;
    protected $config = array();

    public function __construct($config){
        $this->product = new Product();
        $this->config = $config;
    }

    public function build() {
        $this->product->setType($this->config['type']);
        $this->product->setColor($this->config['color']);
        $this->product->setSize($this->config['size']);
        $this->product->setPrice($this->config['price']);
    }

    public function getProduct() {
        return $this->product;
    }
}

Note that this build() method hides the actual method calls from the code requesting the new product. If the product class changes in the future, only the build() method of the productBuilder class needs to change. This code demonstrates the creation of the product object, using the productBuilder class:


$builder = new productBuilder($productConfigs);
$builder->build();
$product = $builder->getProduct();

The Builder Design Pattern is meant to eliminate the complex creation of other objects. Using the Builder Design Pattern is not only best practice but it also reduces the chances of having to repeatedly alter pieces of code if an object’s construction and configuration methods change.

Thursday, June 14, 2012

Codeigniter - Model-View-Controller



CodeIgniter is based on the Model-View-Controller development pattern. MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.

  • The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.
  • The View is the information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of "page".
  • The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.

CodeIgniter has a fairly loose approach to MVC since Models are not required. If you don't need the added separation, or find that maintaining models requires more complexity than you want, you can ignore them and build your application minimally using Controllers and Views. CodeIgniter also enables you to incorporate your own existing scripts, or even develop core libraries for the system, enabling you to work in a way that makes the most sense to you.

Wednesday, June 13, 2012

Codeigniter Installation Instructions


CodeIgniter is installed in four steps:
  1. Unzip the package. (http://codeigniter.com/downloads/)
  2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
  3. Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
  4. If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.
If you wish to increase security by hiding the location of your CodeIgniter files you can rename the system and application folders to something more private. If you do rename them, you must open your main index.php file and set the $system_folder and $application_folder variables at the top of the file with the new name you've chosen.
For the best security, both the system and any application folders should be placed above web root so that they are not directly accessible via a browser. By default, .htaccess files are included in each folder to help prevent direct access, but it is best to remove them from public access entirely in case the web server configuration changes or doesn't abide by the .htaccess.
After moving them, open your main index.php file and set the $system_folder and $application_folder variables, preferably with a full path, e.g. '/www/MyUser/system'.
One additional measure to take in production environments is to disable PHP error reporting and any other development-only functionality. In CodeIgniter, this can be done by setting the ENVIRONMENT constant, which is more fully described on the security page.
That's it!

Getting started CodeIgniter

CodeIgniter is an Application Development Framework - a toolkit - for people who build web sites using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.

CodeIgniter is right for you if:
  • You want a framework with a small footprint.
  • You need exceptional performance.
  • You need broad compatibility with standard hosting accounts that run a variety of PHP versions and configurations.
  • You want a framework that requires nearly zero configuration.
  • You want a framework that does not require you to use the command line.
  • You want a framework that does not require you to adhere to restrictive coding rules.
  • You do not want to be forced to learn a templating language (although a template parser is optionally available if you desire one).
  • You eschew complexity, favoring simple solutions.
  • You need clear, thorough documentation.


Tuesday, June 12, 2012

Can't start portgresql in F15, F16

First please login as follows in your terminal :


# su - postgres

Then type

$ pg_ctl init

---------------------------------

After execute above command try to start the server as normal way :

systemctl start postgresql.service or /etc/init.d/postgresql start

If you want to start the server from start-up please type as following in your terminal:

chkconfig postgresql on

Friday, May 11, 2012

Adapter pattern using php

Programming would be simple, but boring. Programmers would continue to build applications on top of the same technologies that they did years ago. They would never need to introduce different databases, implement new best practices, or consume different APIs. But these things do change. Luckily, programmers have the Adapter Design Pattern to help update legacy systems with new code and functionality.

The solution is to build another object, using the Adapter Design Pattern. This Adapter object works as an intermediary between the original application and the new functionality. The Adapter Design Pattern defines a new interface for an existing object to match what the new object requires.

Code Example

In the original code base of the project, an object exists that handles all of the error messages and codes called errorObject. The original programmers didn’t think their code would ever generate any errors, so they designed the system to output the errorObject’s error information directly to the console.

In this example, a 404:Not Found error is being generated. You are going to assume that the error message content and code may change, but the text will always stay in the same format.

 class ErrorObject  
 {  
   private $error;  
   public function __construct($error){  
     $this->error = $error;  
   }  
   public function getError(){  
     return $this->error;  
   }  
 }  


 class LogToConsole  
 {  
   private $errorObject;  
   public function __construct($errorObject){  
     $this->errorObject = $errorObject;  
   }  
   public function write() {  
     fwrite(STDERR, $this->errorObject->getError() . "\n");  
   }  
 }  

Here is the testing...

 include "ErrorObject.php";  
 include "LogToConsole.php";  
 /** create the new 404 error object **/  
 $error = new ErrorObject("404:Not Found");  
 /** write the error to the console **/  
 $log = new LogToConsole($error);  
 $log->write();  
How about new requirement comes that error need to output to csv format, with the code and description.
Lets look at how we going to do that with Adapter pattern.
 class LogToCsvAdapter extends ErrorObject  
 {  
   private $errorNumber, $errorText;  
   public function __construct($error)  
   {  
     parent::__construct($error);  
     $parts = explode(':', $this->getError());  
     $this->errorNumber = $parts[0];  
     $this->errorText = $parts[1];  
   }  
   public function getErrorNumber()  
   {  
     return $this->errorNumber;  
   }  
   public function getErrorText()  
   {  
     return $this->errorText;  
   }  
 }  






Here is the testing...
 include "ErrorObject.php";  
 include "LogToCsv.php";  
 include "LogToCsvAdapter.php";  
 /** create the new 404 error object adapted for csv **/  
 $error = new LogToCsvAdapter("404:Not Found");  
 /** write the error to the csv file **/  
 $log = new logToCSV($error);  
 $log-&gt;write();  




Good luck...

Wednesday, May 9, 2012

How to delete .svn files for linux

Recursively delete .svn directories


This is a simple example of a unix command, which recursively deletes subversion .svn folders. Subversion is a well-spread open-source revision control application. Every copy of source code received from subversion repository has .svn folders, which store metadata. However, if you want to use or distribute source code, these .svn folder are often not necessary.     

We use find command to find all .svn folders beginning from current directory.


eg: type : find . -type d -name .svn

It is possible to pass these directories directly to rm command, using grave accent quotes (key to left of '1')

eg: type : rm -rf `find . -type d -name .svn`

above command will remove every .svn folder beginning from current directory.

You may do not like to type each and every time so you can create shell script for that.


1) Create a file called  /usr/bin/csvn 
2) Input following codes:

#!/bin/sh
echo "recursively removing .svn folders from"
pwd
rm -rf `find . -type d -name .svn`

You may save this script to /usr/bin/csvn (or other binary folder included in path) and use later to get 'clean' project source without typing lengthy commands.

For example

$ svn checkout svn://server.com/svn/project
A    project/index.php
A    project/sourceA/a.php
A    project/sourceA/a1.php
A    project/sourceA/a2.php
A    project/sourceB/b.php
A    project/sourceB/module/lib.php
A    project/sourceC/c.php
Checked out revision 15.
$ cd project
$ csvn
recursively removing .svn folders from
/Users/anyexample/Source/project

~Good luck~

Thursday, March 29, 2012

Mercurial for first time

This is simply version control system.

Basic usage:

1). How to clone from repo?


hg clone http://www.selenic.com/repo/hello my-hello


If everything went gladly, You will see new folder in your current directory called `my-hello` . This is the directory that you have checkout from the repository.

2). How to see  revision information?

Go to your checkout folder. (my-hello). And type


hg parents



Wednesday, March 14, 2012

Libraries installation for symfony development using yum

yum install php-pdo.i686
yum install php-xml
yum install php-mbstring.i686
yum list php-pear
yum install php-pecl-apc
yum install php-process

Thursday, September 29, 2011

WILD CARDS WITH WGET



You can download all the pdf files under docs folder:


wget -r -l1 --no-parent -A.pdf http://somehost.com/docs/


Step 1
-------------


Go to linux shell


Step 2
-------------


Have the following command and hit enter


wget -r -l1 --no-parent -A.pdf http://somehost.com/docs/




It will download all the pdf files in the specified host.


Enjoy... :)

Thursday, February 3, 2011

Design Principles


What are Software Design Principles?

Software design principles represent a set of guidelines that helps us to avoid having a bad design. The design principles are associated to Robert Martin who gathered them in "Agile Software Development: Principles, Patterns, and Practices". According to Robert Martin there are 3 important characteristics of a bad design that should be avoided:

  • Rigidity - It is hard to change because every change affects too many other parts of the system.
  • Fragility - When you make a change, unexpected parts of the system break.
  • Immobility - It is hard to reuse in another application because it cannot be disentangled from the current application.

Open Close Principle


  • Software entities like classes, modules and functions should be open for extension but closed for modifications.


OPC is a generic principle. You can consider it when writing your classes to make sure that when you need to extend their behavior you don’t have to change the class but to extend it. The same principle can be applied for modules, packages, libraries. If you have a library containing a set of classes there are many reasons for which you’ll prefer to extend it without changing the code that was already written (backward compatibility, regression testing, …). This is why we have to make sure our modules follow Open Closed Principle.

When referring to the classes Open Close Principle can be ensured by use of Abstract Classes and concrete classes for implementing their behavior. This will enforce having Concrete Classes extending Abstract Classes instead of changing them. Some particular cases of this are Template Pattern and Strategy Pattern.

Dependency Inversion Principle


  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions.


Dependency Inversion Principle states that we should decouple high level modules from low level modules, introducing an abstraction layer between the high level classes and low level classes. Further more it inverts the dependency: instead of writing our abstractions based on details, the we should write the details based on abstractions.

Dependency Inversion or Inversion of Control are better know terms referring to the way in which the dependencies are realized. In the classical way when a software module(class, framework, …) need some other module, it initializes and holds a direct reference to it. This will make the 2 modules tight coupled. In order to decouple them the first module will provide a hook(a property, parameter, …) and an external module controlling the dependencies will inject the reference to the second one.

By applying the Dependency Inversion the modules can be easily changed by other modules just changing the dependency module. Factories and Abstract Factories can be used as dependency frameworks, but there are specialized frameworks for that, known as Inversion of Control Container.

Interface Segregation Principle

  • Clients should not be forced to depend upon interfaces that they don't use.

This principle teaches us to take care how we write our interfaces. When we write our interfaces we should take care to add only methods that should be there. If we add methods that should not be there the classes implementing the interface will have to implement those methods as well. For example if we create an interface called Worker and add a method lunch break, all the workers will have to implement it. What if the worker is a robot?


As a conclusion Interfaces containing methods that are not specific to it are called polluted or fat interfaces. We should avoid them.

Single Responsibility Principle


  • A class should have only one reason to change.


In this context a responsibility is considered to be one reason to change. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes.

Single Responsibility Principle was introduced Tom DeMarco in his book Structured Analysis and Systems Specification, 1979. Robert Martin reinterpreted the concept and defined the responsibility as a reason to change.

Liskov's Substitution Principle




  • Derived types must be completely substitutable for their base types.

This principle is just an extension of the Open Close Principle in terms of behavior meaning that we must make sure that new derived classes are extending the base classes without changing their behavior. The new derived classes should be able to replace the base classes without any change in the code.


Liskov's Substitution Principle was introduced by Barbara Liskov in a 1987 Conference on Object Oriented Programming Systems Languages and Applications, in Data abstraction and hierarchy

Saturday, December 4, 2010

How to create sample vaadin application with maven 2.2.1

How to create sample vaadin application with maven 2.2.1

Step one
--------

Create maven project with typing the following command on your command line.


mvn archetype:create -DgroupId=com.sample.vaadin -DartifactId=SampleVaadin -DarchetypeArtifactId=maven-archetype-webapp

Here is the sample pom.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.sample.vaadin</groupId>  
  <artifactId>SampleVaadin</artifactId>  
  <packaging>war</packaging>  
  <version>1.0-SNAPSHOT</version>  
  <name>SampleVaadin Maven Webapp</name>  
  <url>http://maven.apache.org</url>  
  <dependencies>  
   <dependency>  
    <groupId>junit</groupId>  
    <artifactId>junit</artifactId>  
    <version>3.8.1</version>  
    <scope>test</scope>  
   </dependency>  
  </dependencies>  
  <build>  
   <finalName>SampleVaadin</finalName>  
  </build>  
 </project>  

Step two
--------

Integrate jetty servlet container to vaadin project

Please update your pom.xml as follows:

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.sample.vaadin</groupId>  
  <artifactId>SampleVaadin</artifactId>  
  <packaging>war</packaging>  
  <version>1.0-SNAPSHOT</version>  
  <name>SampleVaadin Maven Webapp</name>  
  <url>http://maven.apache.org</url>  
  <dependencies>  
   <dependency>  
    <groupId>junit</groupId>  
    <artifactId>junit</artifactId>  
    <version>3.8.1</version>  
    <scope>test</scope>  
   </dependency>  
      <dependency>  
           <groupId>com.vaadin</groupId>  
           <artifactId>vaadin</artifactId>  
           <version>6.6.2</version>  
           <type>jar</type>  
           <scope>compile</scope>  
      </dependency>  
  </dependencies>  
  <build>  
   <finalName>SampleVaadin</finalName>  
      <plugins>  
        <plugin>  
          <groupId>org.mortbay.jetty</groupId>  
          <artifactId>maven-jetty-plugin</artifactId>  
     </plugin>  
           <plugin>  
                     <groupId>org.apache.maven.plugins</groupId>  
                     <artifactId>maven-compiler-plugin</artifactId>  
                     <version>2.3.2</version>  
                     <configuration>  
                          <source>1.6</source>  
                          <target>1.6</target>  
                     </configuration>  
           </plugin>  
   </plugins>  
  </build>       
 </project>  


*** You can test whether jetty is running by typing "mvn jetty:run"


Step tree
--------

Writing code under src/main/java/com/sample/vaadin/HelloVaadin.java


 /**  
 * This is the main class of the vaadin page  
 * @author gayan  
 *  
 * src/main/java/com/sample/vaadin/HelloVaadin.java  
 */  
 package com.sample.vaadin;  
 import com.vaadin.Application;  
 import com.vaadin.ui.*;  
 public class HelloVaadin extends Application {  
   @Override  
   public void init() {  
     Window mainWindow = new Window("HelloVaadin");  
     Label label = new Label("Hello Vaadin user");  
     mainWindow.addComponent(label);  
     setMainWindow(mainWindow);  
   }  
 }  

Step four
--------

Edit you web.xml file under webapp/web.xml as following

 <!DOCTYPE web-app PUBLIC  
  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
  "http://java.sun.com/dtd/web-app_2_3.dtd" >  
 <web-app version="2.5" xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance\" xmlns="[http://java.sun.com/xml/ns/javaee]" xsi:schemalocation="[http://java.sun.com/xml/ns/javaee] [http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd]">  
   <display-name>HelloVaadin</display-name>  
   <context-param>  
     <param-name>productionMode</param-name><param-value>false</param-value><description>Vaadin production mode</description>  
   </context-param>  
   <servlet>  
     <servlet-name>HelloVaadin</servlet-name>  
     <servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>  
     <init-param>  
       <param-name>application</param-name>  
                <param-value>com.sample.vaadin.HelloVaadin</param-value>  
                <description>Vaadin application class to start</description>  
     </init-param>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>HelloVaadin</servlet-name>  
     <url-pattern>/*</url-pattern>  
   </servlet-mapping>  
 </web-app>  

Final step
--------

Have commond "mvn compile jetty:run" and please have a look on http://localhost:8080 on your browser.