Introduction to Abstract Factory Design Pattern

Abstract factory design pattern provides an interface for creating families of related or dependent objects without a specifying their concrete classes.

The abstract factory design patter is very similar to factory method pattern. One difference between the two is that with the abstract factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the factory method pattern uses inheritance and relies on subclass to handle the desired object instantiation.

Actually, the delegated objects frequently factory methods to perform the instantiation.

abstract factory design pattern

Applicability

Use the abstract factory pattern in any of following situation.

  • A system should be independent of how it’s products are created, composed, and represented
  • A class can’t anticipate the class of objects it must create
  • A system must use just one of a set of families of products

A family of related product objects is designed to be used together, and you need to enforce this constraint.

 

Participants

  • AbstractFactory

o Declare a interface for operations that create abstract products objects

  • Concretefactory

o Implements the operations to create concrete product objects

  • AbstractProduct

o Declare an interface for type of product object

  • ConcreteProduct

o Define a product object to be created by the corresponding concrete factory

o Implements the AbstractProduct interface

  • Client

o Uses only interfaces declare by AbstractFactory and AbstractProduct classes

 

Collaborations

Normally single instance of ConcreteFactory class is created at run time. (This is example of Singleton Pattern) This concrete factory creates product objects having particular implementations. To create different product objects, clients should use a different concrete factory.

AbstractFactory defers creation of product objects to its ConcreteFactory

 

Example

Let see how Abstractfactory design pattern applied to charting application which generate the chart depending upon user selection like bar chart, pie chart

  • First create an interface IChart which have drawChart method take a string arg

publicinterface IChart {

public void drawChart();

}

  • Create a abstract class say ChartAbstractFactory which have abstract method as getchart which takes string arg and return the interface type

publicabstractclass ChartAbstractFactory

publicabstract IChart getChart(String ChartType);

}

 

  • Create a class say BarChart and impelmets IChart interface

publicclass BarChart implements IChart {

@Override

public void drawChart () {

System.out.println(“charting Logic”);

}

}

 

  • Create a class ChartFactory which extends the ChartAbstractFactory

publicclass ChartFactory extends ChartAbstractFactory {

@Override

public void getChart(String chartType) {

if(chartType == null){

return null;

}

if(chartType == BarChart){

return new BarChart();

}

elseif(chartType ==PieChart)

{

return new PieChart();

}

}

return null;

}

  • Crate a class say FactoryProducer to get factories by passing information such as Chart

publicclassFactoryProducer {

    public static ChartAbstractFactory getFactory(String choice)

{

If(choice==chart)

{

return new ChartFactory();

}

return null;

}

}

  • Create a Client with main method

publicclass AbstractFactoryDemo{

ChartAbstractFactory factory = FactoryProducer.getFactory(“chart”);

IChart chart = factory. getChart(BarChart);

chart.drawChart();

}

 

Muqtar Ahmed

Helical IT Solutions

INSTALL LIFERAY ON TOMCAT USING WAR

In my previous blog, I shared how to install liferay on existing tomcat using liferay source code. You can found my previous blog here http://helicaltech.com/install-liferay-existing-tomcat-7/

This blog will be talking about how to install liferay on Tomcat using WAR (existing Tomcat)

For this Section, I will refer to your tomcat’s installation folder as $TOMCAT_HOME. Before you begin, make sure that you have downloaded Liferay latest war file. If you haven’t downloaded, you can download from http://www.liferay.com/downloads/liferay-portal/additional-files (Find “Download Wars” section And portal dependencies files from “Dependencies” section).

After downloading, you will get a liferay-portal-6.1.x-<date>.war and liferay-portal-dependencies-6.1.x-<date>.zip.

If you have liferay in your machine, you don’t need to download liferay-portal-dependencies. You can use same Liferay global library as your portal-dependencies files.

Follow these steps, to install Liferay war in Tomcat:

Step-1

Create folder $TOMCAT_HOME/lib/ext.

Step-2

Extract the Liferay dependencies file to $TOMCAT_HOME/lib/ext.

The best way to get the appropriate versions of these files is, If you have liferay in your machine, then copy all .jar from $LIFERAY_HOME/lib/ext to $TOMCAT_HOME/lib/ext  (If you are going through this step, ignore Step-3 and Step-4)

or

Download the Liferay source code and get them from there. Once you have downloaded the Liferay source, unzip the source into a temporary folder and Copy the following jars from $LIFERAY_SOURCE/lib/development to $TOMCAT_HOME/lib/ext

activation.jar

jms.jar

jta.jar

jutf7.jar

mail.jar

persistence.jar

resin.jar

script-10.jar

 

Step-3

Make sure the JDBC driver for your database is accessible by Tomcat. Copy JDBC driver for your version of the database server to $TOMCAT_HOME/lib/ext.

 

Step-4

Liferay requires an additional jar to manage transactions. You may find this .jar here: http://www.oracle.com/technetwork/java/javaee/jta/index.html.

Step-5

Now, Edit $TOMCAT_HOME/conf/catalina.properties file. Change this line

common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,${catalina.home}/lib,${catalina.home}/lib/*.jar

to

common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,${catalina.home}/lib,${catalina.home}/lib/*.jar,${catalina.home}/lib/ext,${catalina.home}/lib/ext/*.jar

Step-6

Create setenv.bat in $TOMCAT_HOME/bin folder and add these lines:

if exist “%CATALINA_HOME%/jre@java.version@/win” (

    if not “%JAVA_HOME%” == “” (

       set JAVA_HOME=

    )

 

    set “JRE_HOME=%CATALINA_HOME%/jre@java.version@/win”

)

 

set “JAVA_OPTS=%JAVA_OPTS% -Dfile.encoding=UTF8 -Djava.net.preferIPv4Stack=true -Dorg.apache.catalina.loader.WebappClassLoader.ENABLE_CLEAR_REFERENCES=false -Duser.timezone=GMT -Xmx1024m -XX:MaxPermSize=256m”

 

Step-7

I am deploying liferay in $TOMCAT_HOME/webapps/ROOT folder. So we need to Create the directory $TOMCAT_HOME/conf/Catalina/localhost and create a ROOT.xml file in it. Edit this file and populate it with the following contents to set up a portal web application:

<Context path="" crossContext="true">

 
    <!-- JAAS -->
 
    <!--<Realm
       className="org.apache.catalina.realm.JAASRealm"
       appName="PortalRealm"
       userClassNames="com.liferay.portal.kernel.security.jaas.PortalPrincipal"
       roleClassNames="com.liferay.portal.kernel.security.jaas.PortalRole"
    />-->
 
    <!--
    Uncomment the following to disable persistent sessions across reboots.
    -->
 
    <!--<Manager pathname="" />-->
 
    <!--
    Uncomment the following to not use sessions. See the property
    "session.disabled" in portal.properties.
    -->
 
    <!--<Manager className="com.liferay.support.tomcat.session.SessionLessManagerBase" />-->

</Context>

 

Step-8

Now, Deploy Liferay.

If you are manually installing Liferay on a clean Tomcat server, delete the contents of the $TOMCAT_HOME/webapps/ROOT directory. This undeploys the default Tomcat home page. Then extract the liferay-portal-6.1.x-<date>.war file to $TOMCAT_HOME/webapps/ROOT.

Step-9

Start Tomcat by executing $TOMCAT_HOME/bin/startup.sh

Congratulations on successfully installing and deploying Liferay on Tomcat!

For any confusion, please get in touch with us at Helical IT Solutions

Getting Started with Mongo DB

Installation & Startup:

Download MongoDB installer for windows platform from http://www.mongodb.org/downloads and run. This simply extracts the binaries to your program files.

#Create DBPATH and log libraries:

Allocate a folder in your system that can be used for holding the mongo databases and also allocate a log file.

Ex – Allocated “C:\mongo\data\db” for databases and “C:\mongo\logs\mongo.log” as a log file.

#Starting the mongo database

Below are different ways of starting the mongodb:

1.    From the command prompt

Execute the mongod.exe present in the bin folder to start the database.

On command prompt à mongod --dbpath c:\mongo\data\db

There are other options that can also be specified alongwith dbpath. If dbpath is not provided, it looks for c:\data\db folder and gives error if not found.

To shutdown, press CTRL+C

 

2.    Starting with a config file

You can create a configuration file to define settings for the MongoDB server like the dbpath,logpath etc. Below is a sample file :

(This is a older format, for 2.6 version a new format is introduced. Older format is supported for backward compatibility)

#This is an example config file for MongoDB

dbpath = C:\Mongo\data\db

port = 27017

logpath = C:\Mongo\logs\mongo.log

Now you can use the below command –

C:\Program Files\MongoDB 2.6 Standard\bin>mongod --config mongo.conf

2014-04-15T10:27:18.883+0530 log file "C:\Mongo\logs\mongo.log" exists; moved to

"C:\Mongo\logs\mongo.log.2014-04-15T04-57-18".

As we haven’t specified “logappend” option in the config file, it allocates new file everytime you start the db. You can check the log file if you are getting errors while connecting to the db

To shutdown, use command “mongod –shutdown”

 

3.    Installing as Windows service:

Start the command prompt as administrator

You can use the below command to create the service, edit the same as per your settings:

sc create MongoDB binPath= "\"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe\" --service --config=\"C:\Program Files\MongoDB 2.6 Standard\bin\mongo.conf\"" DisplayName= "MongoDB 2.6 Standard"

Please note this is a single line of command

You can now simply start/stop the service to start/shutdown the mongo database.

 

Using Mongo command shell:

Run Mongo.exe from \bin folder and you will see the below:

MongoDB shell version: 2.6.0

connecting to: test      //This is the Default database

Welcome to the MongoDB shell.

For interactive help, type "help".

For more comprehensive documentation, see

http://docs.mongodb.org/

Questions? Try the support group

http://groups.google.com/group/mongodb-user

 

Some basic commands to get you started

> show dbs                  // show databases

admin  (empty)
local  0.078GB

> use names               // switch to a particular database/creates one if it does not exist

switched to db names

> db.mynames.insert({name: 'shraddha', email: 'shraddha@gmail'})           // Inserting document
WriteResult({ "nInserted" : 1 })

//Note that , ‘db’ points to the current database in use. Here, Collection “mynames” is automatically created when you insert a document

> show dbs

admin  (empty)
local  0.078GB
names  0.078GB

> db.mynames.find()               //query the db, select operation

{ "_id" : ObjectId("534cbfd03dfb3fbd86d8029d"), "name" : "shraddha", "email" : "shraddha@gmail" }

//One more way of inserting……

> a={"name":"test3","email":"test3.other"}

{ "name" : "test3", "email" : "test3.other" }

> b={"name":"test4",email:"test4.other"}

{ "name" : "test4", "email" : "test4.other" }

> db.othernames.insert(a)

WriteResult({ "nInserted" : 1 })

> db.othernames.insert(b)

WriteResult({ "nInserted" : 1 })

> db.othernames.insert(c)

2014-04-15T19:40:24.798+0530 ReferenceError: c is not defined

//…In all the above inserts, the “_id” which has the unique key is auto-generated..

 

> coll=db.mynames

names.mynames

> coll.find()

{ "_id" : ObjectId("534cbfd03dfb3fbd86d8029d"), "name" : "shraddha", "email" : "shraddha@gmail" }
{ "_id" : ObjectId("534d3b89f4d4b90697c205d6"), "name" : "test1", "email" : "test1.helical" }

> coll=db.othernames

names.othernames

> coll.find()

{ "_id" : ObjectId("534d3dc3f4d4b90697c205d7"), "name" : "test3", "email" : "test3.other" }
{ "_id" : ObjectId("534d3dcdf4d4b90697c205d8"), "name" : "test4", "email" : "test4.other" }

 

> coll.find({name:{$gt:"test3"}})                  //find documents where “name” is >”test3”

{ "_id" : ObjectId("534d3dcdf4d4b90697c205d8"), "name" : "test4", "email" : "test4.other" }

> coll.find({name:"test3"})

{ "_id" : ObjectId("534d3dc3f4d4b90697c205d7"), "name" : "test3", "email" : "test3.other" }

>

> coll.find({$or:[{name:{$gt:"test3"}},{name:"test3"}]})

{ "_id" : ObjectId("534d3dc3f4d4b90697c205d7"), "name" : "test3", "email" : "test3.other" }
{ "_id" : ObjectId("534d3dcdf4d4b90697c205d8"), "name" : "test4", "email" : "test4.other" }

> coll.find({$or:[{name:{$gt:"test3"}},{name:"test0"}]})

{ "_id" : ObjectId("534d3dcdf4d4b90697c205d8"), "name" : "test4", "email" : "test4.other" }

>
 
//Example - Manually inserting ObjectID field (key value)
 
> coll=db.testobjs

names.testobjs

> coll.insert({_id:1,fld1:"abc",fld2:123})

WriteResult({ "nInserted" : 1 })

> coll.insert({_id:2,fld1:"cde",fld2:345})

WriteResult({ "nInserted" : 1 })

> coll.insert({_id:2,fld1:"cde",fld2:345})       //trying to insert duplicate value in _id

WriteResult({
"Inserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: names.testobjs.$_id_  dup key: { : 2.0 }"}}

> coll.find()

{ "_id" : 1, "fld1" : "abc", "fld2" : 123 }
{ "_id" : 2, "fld1" : "cde", "fld2" : 345 }

>
 

Importing a csv file into mongodb:

Alter the below command as per your requirement and execute:

C:\Program Files\MongoDB 2.6 Standard\bin>mongoimport --db northwind --collection orders --type csv --file C:\Shraddha\Official\MongoDB\northwind-mongo-master\orders.csv --headerline

connected to: 127.0.0.1
2014-04-17T18:24:22.603+0530 check 9 831
2014-04-17T18:24:22.604+0530 imported 830 objects

 

Options used –

–db : name of the database
–collection : orders
–type : type of input file (we can also import tsv, JSON)
–file : path of the input file
–headerline : signifies that the first line in the csv file is column names

 

Shraddha Tambe

Helical IT Solutions