Monday, December 8, 2014

Design pattern Quick Guide

Observer Pattern :  Behavioral pattern

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Real Life example:
  • RSS feeds.  When I want to get updates from a particular feed, I add it to my feed reader. Any time that the RSS feed has an update, it will appear in my reader automatically.  This is the Observer pattern in action, a publisher/subscriber relationship with one source having many subscribers 
  • The whole concept of listeners is based on this pattern.
Adapter Pattern : Structural pattern


Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Real Life Example:
  • The best example for the adapter pattern is based around AC power adapters.
Downside:
Adapter pattern is just a fix for a badly designed system, which didn't consider all possibilties. While this is a fair point, it is an important part of a pluggable architecture.  It can also add a level of complexity to your code, making debugging more difficult.

The Facade pattern  : Structural pattern

Provide a unified interface to a set of interfaces in a subsystem. Fa├žade defines a higher-level interface that makes the subsystem easier to use.

Real Life Example:
  • Concept behind facade is to simplify an interface, service oriented architectures make use of the facade pattern. For example, in web services, one web service might provide access to a number of smaller services that have been hidden from the caller by the facade.
Downside:
 By introducing the Facade into your code, you will be hardwiring subsystems into the Facade. This is fine if the subsystem never changes, but if it does, your Facade could be broken. Therefore, developers working on the subsystem should be made aware of any Facade around their code.

Factory method pattern : Creational pattern

Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses

Real Life Example:
  • The idea behind the Factory Method pattern is that it allows for the case where a client doesn't know what concrete classes it will be required to create at run-time, but just wants to get a class that will do the job. The FactoryMethod builds on the concept of a simple Factory, but lets the subclasses decide which implementation of the concrete class to use.  You'll see factories used in logging frameworks, and in a lot of scenarios where the client doesn't need to know about the concrete implementations. It's a good approach to encapsulation.
Abstract Factory Pattern : Creational pattern
Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Strategy Pattern : Behavioral pattern
Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour

Real Life Example:
  • Compression algorithm
Visitor Pattern : Behavioral pattern
Allows for one or more operation to be applied to a set of objects at runtime, decoupling the operations from the object structure.

Mongo sharding example


### To Start config server instance (config server port: 27019)
mongod.exe --configsvr --dbpath ../../configdb --port 27019

### To start mongos instance (router) (router port: 27017)
mongos.exe --configdb localhost:27019

###Adding a shard
First start mongoDb instance
mongod.exe --config ../../mongo.cfg
mongod.exe --config ../../mongo1.cfg

Config file content:
##store data here
dbpath=C:\poc\mdb\data

##all output go here
logpath=C:\poc\mdb\log\mongo.log

##log read and write operations
##diaglog=3

###Auth detail admin/admin
auth=false


##Port binding
port=27020


###Open a new instance and add above mongodb instance in cluster:
mongo.exe --host localhost --port 27017 
once mongos console connected:
 sh.addShard("localhost:27020")
 sh.addShard("localhost:27021") 

sh.enableSharding("ankur")
use config
db.databases.find()

###Insert bulk data
for (var i = 1; i <= 1000; i++) db.test_collection.insert( { x : i } )

###To know the shard status
sh.status()
 
###To shard a collection
 sh.shardCollection("ankur.records",{"zip":1, "name":1})
 
###Data insertion
{
db.records.insert( { zip : 60111 , name: "ankur"})
db.records.insert( { zip : 60111 , name: "goel"})
db.records.insert( { zip : 50111 , name: "ankur"})
db.records.insert( { zip : 50111 , name: "goel"})
db.records.insert( { zip : 70111 , name: "dr"})
} 

###To know chunk distribution
db.records.getShardDistribution()


Source: http://docs.mongodb.org/manual/reference/method/#sharding

A day with Maven

POM: Project Object Model

Maven has three life cycle:
  • Clean
  • default (build)
  • Site

Clean Life cycle has following phases:
  • Pre-Clean
  • Clean
  • Post-Clean
Build(or Default) life cycle has following phase(primarily used) sequence. (Build Life cycle has 23 phases):
  • prepare-resources
  • compile
  • package
  • Install
Site life-cycle has following phases:
  • pre-site
  • site
  • post-site
  • site-deploy

Syntax for life-cycle and phase:
mvn <life-cycle> : <phase>
ex: mvn clean:clean

Syntax for activating profile:
mvn <life-cycle>/<phase>   -P<profile>
ex: mvn clean -P phix


When a phase is called via Maven command, for example mvn compile, only phases upto and including that phase will execute.

In Maven terminology, a repository is a place i.e. directory where all the project jars, library jar, plugins or any other project specific artifacts are stored and can be used by Maven easily.

Maven repository are of three types
Maven is actually a plugin execution framework where every task is actually done by plugins.

A plugin generally provides a set of goals and which can be executed using following syntax:
mvn <plugin-name>:<goal-name>

Maven provided two types of plugin:
  • Build plugins (They execute during the build and should be configured in the <build/> element of pom.xml)
  • Reporting plugins (They execute during the site generation and they should be configured in the <reporting/> element of the pom.xml)

Dependency Management:
The dependency management section is a mechanism for centralizing dependency information. When you have a set of projects that inherits a common parent it's possible to put all information about the dependency in the common POM and have simpler references to the artifacts in the child POMs.

For parent:
<dependencyManagement>
   <dependencies>
     <dependency>
       <groupId>test</groupId>
       <artifactId>a</artifactId>
       <version>1.2</version>
     </dependency>
   </dependencies> 
</dependencyManagement>


For child: If below code is not copied in child then no dependency will be included in child project from parent. Need to define all required dependency in child project.
  <dependencies>
    <dependency>
      <groupId>group-a</groupId>
      <artifactId>artifact-a</artifactId>
    </dependency>
 </dependencies> 
 

Friday, October 10, 2014

Windows 8 MongoDB in secure mode

  • add auth=true in mongo.cfg file
  • Start mongod.exe in console or use windows service configured in (http://devsuggestion.blogspot.com/2014/10/mongodb-windows8-installation.html)
  • Start mongo.exe in another console
  • use admin
  • db.addUser("user","password")
  • use test
  • db.auth("user","password")
  • db.addUser("testuser","testpassword")
  • Now test db is accessible using username/password only

Thursday, October 9, 2014

Java code to generate BigDecimal Random value

To generrate BigDecimal between 0 to defined range use following code:

private BigDecimal randomNo(int range) {

        BigDecimal rangeInBD = new BigDecimal(range);
        BigDecimal randomNoGeneration = new BigDecimal(Math.random()); // between 0 to < 1.0
        BigDecimal actualRandonNo = randomNoGeneration.multiply(rangeInBD);
        return actualRandonNo.setScale(2, BigDecimal.ROUND_HALF_UP);

    }

Wednesday, October 8, 2014

MongoDB windows 8 installation

  • Download from https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-2.6.4-signed.msi?_ga=1.92201882.1006826747.1412750869
  • Install downloaded msi
  • Move installed directory from default location C:\Program Files\MongoDB 2.6 Standard to your user defined location, something without space in naming convention, this is a good practice. Copying the installed folder to another location will not create any issue as MongoDB is self-contained and does not have any other system dependencies. For example: C:\poc\mdb\MongoDB_2.6_Standard
  • Create a  mongo.cfg file with content:
##store data here (make sure you have manually created following directory)
dbpath=C:\poc\mdb\data

##all output go here (make sure you have manually created following directory)
logpath=C:\poc\mdb\log\mongo.log
  • Open command prompt (WIN +X ) and open Comman Prompt (Admin)
  • Type following:
sc.exe create MongoDB binPath= "\"C:\poc\mdb\MongoDB_2.6_Standard\bin\mongod.exe\" --service --config=\"C:\poc\mdb\mongod.cfg\"" DisplayName= "MongoDB_2.6_Standard" start= "auto" 
  • MongoDB service is successfully installed if you see following msg:
[SC] CreateService SUCCESS
  • Start MongoDB service:
net start MongoDB
  • To stop MongoDB service:
net stop MongoDB
  • To delete MongoDB service
sc.exe delete MongoDB

Source: http://www.mongodb.org

Tuesday, September 30, 2014

Maven Tips

  • Maven Overlays are used to share common resources across multiple web applications. The dependencies of a WAR project are collected in WEB-INF/lib, except for WAR artifacts which are overlayed on the WAR project itself.
  • Maven Overlays can be achived simply by using adding dependency
  • If you want more control on  Overlay, like inclusion/exclusion/target overlay location then you need to use maven-war-plugin and overlay tag in configuration
  • Maven Overlays are applied with a first-win strategy (hence if a file has been copied by one overlay, it won't be copied by another)
  • In Maven overlay configuration by default, the source of the project (a.k.a the current build) is added first (e.g. before any overlay is applied). The current build is defined as a special overlay with no groupId, artifactId. If overlays need to be applied first, simply configure the current build after those overlays.
  • To support external dependency not available in maven repository, for ex: any paid lib. GroupID and ArtifactID should be same, scope should be system and systempath should be relative to project location.
       <dependency>
         <groupId>ojdbc14</groupId>
         <artifactId>ojdbc14</artifactId>
         <scope>system</scope>
         <version>1.0</version>
         <systemPath>${basedir}\jar\ojdbc14.jar</systemPath>
      </dependency>

Sources: http://maven.apache.org

Wednesday, May 28, 2014

Same tomcat context file serving multiple workspace

In development we encounter a common scenario of working on multiple branches @ a same time. For this we generally keep multiple copies of context file for each branch.
Ex: We have two branch, that has code in workspace_one and workspace_two, so for running code from each branch we need two context file like below
<Context docBase="F:\workspace\workspace_one\xyz\target\endpoint-1.0.0-SNAPSHOT" >
</Context>
<Context docBase="F:\workspace\workspace_two\xyz\target\endpoint-1.0.0-SNAPSHOT" >
</Context>
Similarly if we are working on n no of  branches then there will be  n no of context files.

Solution:
-DAPP_PATH="F:\workspace\workspace_one"  set this in VM arguments either from command line from where you are running tomcat or in eclipse configuration under VM arguments.
Modified the single copy of context file:
<Context docBase="${APP_PATH}\xyz\target\endpoint-1.0.0-SNAPSHOT" >
 </Context>
So each time you just need to make change in VM arguments before starting the tomcat only. No need to switch all context files.

Tomcat Resource Config

For multiple application sharing common resource, instead of defining resource in each context xml can be defined globally to share with all context in same tomcat container.
Pro/Cons: Change @ one place will reflect in all application context
Steps:
  • Define resource in <tomcat-home>/conf/server.xml
<GlobalNamingResources>
<!--
other resources
-->
<Resource name="jdbc/hcentivePHIXDS" global="jdbc/hcentivePHIXDS" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="25" maxWait="10000"
username="username" password="password" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl" factory="org.apache.commons.dbcp.BasicDataSourceFactory" />

</GlobalNamingResources>
  • Define resource link in <tomcat-home>/conf/context.xml
<context>
<!--
other elements
-->
<ResourceLink type="javax.sql.DataSource"
name="jdbc/hcentivePHIXDS"
global="jdbc/hcentivePHIXDS"/>
</context>

Hibernate General Exceptions

Common exceptions that we encountered in hibernate:

  • Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing:
Solution: This is caused by not using Cascade type while defining mapping.