Wednesday, March 24, 2021

Simple java spring boot to integrate AWS Redis Cache

  • Design
  • Configuration
  • Redis Connection
  • Implementation
Design

In this post, the cache implementation will be done through spring boot. So Im going to have spring aspect which enabled around aspect so that, itl enable us to interact with cache before and after target method execution.
For this implementation, I have already set up Redis cluster in AWS and it'l be enable us to connect to cluster through primary node.


Configuration
Add below dependency in to you pom.xml,

<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>


Redis Connection

Add below connection properties in to you Spring boot properties yaml file

spring:
   redis:
      clusterurl: {redus_cluster_url}
      timeout: 5000
   lettuce:
      pool:
         max-active: 10
         max-wait: -1
         max-idle: 50
         min-idle: 0

Create connection configuration in your application as below

@Value("${spring.redis.clusterurl}")
private String redisClusterNodes;
@Bean(value = "lettuceConnectionFactory")
@Primary
LettuceConnectionFactory lettuceConnectionFactory() {

LOGGER.info("Redis cluster url: " + redisClusterNodes); List nodes = new ArrayList<>(); nodes.add(redisClusterNodes);

LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder().useSsl().and()
.commandTimeout(Duration.ofSeconds(3)).shutdownTimeout(Duration.ZERO).build();

RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(nodes);
LettuceConnectionFactory lcf = new LettuceConnectionFactory(redisClusterConfiguration, clientConfig);

lcf.afterPropertiesSet(); return lcf;
}

Implementation

Refer the source code attached for implementation. Where ever you use the EnableCache annotation, you need to include below component scan.

@ComponentScan(basePackages = { "com.cache.redis.config"})

Enable Cache to the method

@EnableCache
public String put(String payload, Map cacheParams) {}

Make sure to pass cacheparam as a last method parameter as below

  • key - for caching key
  • cacheStore - caching store such as REDIS, MEMCACHE
  • isPut - boolean value is it get or put (create / update)
  • ttlinseconds - cache expiry time in second
Sourcode: github

Friday, December 9, 2011

Java Better Programm Certification

Design Principles Of Object Oriented Software Design Process

Design Principle Of Software
The software  design principle is set of protocol  which is used to come up for a good design of software which is stable , easy to maintain and reduce the complexity . In a nutshell to get the good design.
What is being resolved in design principle in designing software ?
According to Robert Martin , There are three common issue will be solved and some other issues also  will be solve by adhering to design principle.
Those are:
1) Rigidity
2) Fragility
3) Immobility
4) Viscosity
5) Needless Complexity
6) Needless Repetition
7) Opacity

Rigidity
Each parts of module , classes are integrated together tightly and higher dependency and coupling and low cohesion.So its so hard to change one module or part of it , because it may causes to change too many other parts of the software.
Single change causes will makes to change the dependent module.

Fragility
When you make change for one part of the software can break the other part of the software.The part of the software which is breaking due to change of the another part , never have conceptual relationship with the area that was changed.

Immobility
Its very hard to use in another application .i.e No reuse. Because,its very cost and so risk to seperate from the its original system and put in to common place. 
 
Viscosity
Is very hard to use the method which preserving by the design.

Needless Complexity

Basically this happen when the requirement couldn be identified properly. Due to that there can be method and object which aren't usefull. So it will be messy and very hard to understand due to unnecessary complexity.

Needless Repetition
The design contains repeating data & structures that could be placed in one common location as a single abstraction. And this will be make hard to understand the application with duplication code.So has to make "Dont Repeat Yourself (DRY)"

Opacity
Is the probability of the module to read and understand.Due to code does not express its intents. The code is written in very poor manner.
So when we design a software we always be very keen to avoid above mentioned issue which will be a headache in the future of maintaining of software. So lets skim in to the design principle which can eliminate of above mentioned issue in enterprise software.Since these protocols are SOLID (we can remember this as SOLID if its hard to remeber) we have to understand this solidly.

S - Single Responsibility Principle
A class should have one reason to change.
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.
In this context a responsibility is considered to be one reason to change. This principle states that if we have two reasons to change for a class, we have to split the functionality in two classes . if not it will get coupled to gethere. 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.





O - Open-Closed principle

The software entities (Classes, Modules, functions, etc..) should be open for extention, but clossed for modification.
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.

    Open For Extension,
The behavior of the module can be extended( basically you can overriding method or   subclassing       from a parent class).
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.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.
Eg: Struts 1 Action class.

 Closed For Modification
Extending behaviour of module does not resulting changes to the source code or     binary code of the module.
    Eg: You can't modify a Collection (List, Map etc.. in java ) while its being iterated.You  will end up with Concurrent modification Exception.

THE OPEN CLOSED PRINCIPLE IS THE HEART OF THE OBJECT ORIENTED SOFTWARE DEVELOPMENT


L - Liskov Substitution Principle

Is subtype must be substitutable for their base types. This principle define the OOP inheritance principle. If a client uses a base class, then it should not differentiate the base class from derived class, which mean the derived class can substitute the base class.

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.




I - The Interface Segregation Principle


Clients should not be forced to depend upon interfaces that they don't use.
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. Interfaces containing methods that are not specific to it (unnecessary methods) are called polluted or fat interfaces. This will lead to make your classe very cohesive.



D - 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 need some other module, it initializes and holds a direct reference to it. This will make the two 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.
So all object creation and resolving the dependecy are done by framework. The framework always behave in such way that "Dont call us , we will call you".

So depend on Abstractions will give some good benifit to make your module to cohesive in a way ,
1) No varible should hold a reference to a concrete class.
2) No class should derive from a concrete class.
3) No method should override an implemented method of any of its base classes.
Eg : DIP is core of the Spring framework.
 


Some term thats we should adhere when we design a software and we need to keep this in mind always to write good code.

SoC (Separation of Concerns)

SOC is a principle that is helpful to achieving high cohesion and low coupling, introduced in 1974 by Edsger W. Dijkstra in his paper "On the Role of Scientific Thought."

SoC is all about breaking the system into distinct and possibly nonoverlapping features. Each feature you want in the system represents a concern and an aspect of the system. Terms such as feature, concern, and aspect are generally considered synonyms. Concerns are mapped to software modules and, to the extent that it is possible, there’s no duplication of functionalities. SoC suggests that you focus on one particular concern at a time. It doesn’t mean, of course, that you ignore all other concerns of the system. More simply, after you’ve assigned a concern to a software module, you focus on building that module. From the perspective of that module, any other concerns are irrelevant.


LOD - Law Of Demater
which is ,
1) Principle of least knowledge - one of GRASP pattern.(http://mycrazypath-marchingtoword.blogspot.com/)
2) Only talk to you immedate friend.
3) Dont talk to a stranger.
4) Write "shy " codes.
5) Minimizing coupling.

DRY - Don't Repeat Yourself

Dont write same function with different data structer all the placeses in code base. Make thos in one single abstract class.

DBC -Design By Contract

DBC concept is developed by Betrand Meyer for language Eiffel. DBC gives us a good concept to write a robust software , even java does not support it .
In DBC basically considerings are ,

1) A contract defines rights and responsiblities between method caller and  a routing.
2) Preconditions - the routine's requirements , its the caller's responsibility to pass good data.
3) Postconditions - what the routine is guaranteed to do.
4) Class invariants - A class ensures that this condition is always true from perspective of caller.
The contract between  a routine and any potential caller can thus be read as ,
If the routine's precondtions are met by the caller, the routine shall guarntee that all postcondtions and invariants will be true when it completes.










Enjoying with Designing ! Bye from Siva
   

How to create multi page pdf with footer in pdfBox


Hi guys,

In this blog i am going to show one of example that how to create a multiple pdf page in pdf document with the footer where you generating pdf using open source java library "pdfBox". That footer should contain document name in each page , current page number and total pages in document.

First declare some constant where you can have static font size , padding size of bottom of the document.Like below code snippet.

// Hold the report font size.
private final static float FONT_SIZE = 10f;

// Hold the initial x position.
private final static float X0 = 5f;

// Hold the padding bottom of the document.
private final static float PADDING_BOTTOM_OF_DOCUMENT = 30f;

Then create a method to create document object and add some pages to that .I have created a separate method for that.Its like below code snippet.

// create empty document.
doc = new PDDocument();
// create fist page.
PDPage page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
doc.addPage(page);

Then create a PDPageContentStream Object to set the page x and y cordinates , font size and type.And also should remember is , before you write any text to page , you have to call the beginText() off the PDPageContentStream object.Its like blow code snippet.

contentStream = new PDPageContentStream(doc, page);
contentStream.beginText();
contentStream.setFont(PDType1Font.HELVETICA_BOLD, FONT_SIZE);
contentStream.moveTextPositionByAmount(5, 800);

contentStream.drawString("Siva's Test page one");
contentStream.endText();
contentStream.close();

thats it .your done . now you can save the document by specifying the file name and the location to where to save by calling the document save() method.

doc.save(new FileOutputStream(new File("C://siva//SivaTestPDfWithMultiPage.pdf")));

you can see the full code in below.

thank and enjoy the programming !!!!!!!

package com.pdf.multipage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

/**
*
* @author sivakumaran Kathamuttu
*
*
*/
public class MultipagePdfWithFooter {

// Hold the report font size.
private final static float FONT_SIZE = 10f;

// Hold the initial x position.
private final static float X0 = 5f;

// Hold the padding bottom of the document.
private final static float PADDING_BOTTOM_OF_DOCUMENT = 30f;

/**
* This method for include the footer to the each page in pdf document.
*
* @param doc
* Set the pdf document.
* @param reportName
* Set the report name.
* @throws IOException
*/
@SuppressWarnings("rawtypes")
private void addReportFooter(final PDDocument doc, final String reportName) throws IOException {

PDPageContentStream footercontentStream = null;
try {

List pages = doc.getDocumentCatalog().getAllPages();

for (int i = 0; i < pages.size(); i++) {


PDPage page = ((PDPage) pages.get(i));
footercontentStream = new PDPageContentStream(doc, page, true, true);
footercontentStream.beginText();
footercontentStream.setFont(PDType1Font.HELVETICA_BOLD, FONT_SIZE);
footercontentStream.moveTextPositionByAmount(X0,
(PDPage.PAGE_SIZE_A4.getLowerLeftY() + PADDING_BOTTOM_OF_DOCUMENT));
footercontentStream.drawString(reportName);
footercontentStream.moveTextPositionByAmount((PDPage.PAGE_SIZE_A4.getUpperRightX() / 2),
(PDPage.PAGE_SIZE_A4.getLowerLeftY()));
footercontentStream.drawString((i + 1) + " - " + pages.size());
footercontentStream.endText();
footercontentStream.close();

}
} catch (final IOException exception) {
throw new RuntimeException(exception);
} finally {

if (footercontentStream != null) {
try {
footercontentStream.close();
} catch (final IOException exception) {
throw new RuntimeException(exception);
}

}
}

}

/**
* This method created a document with 2 pages.
*
* @return Document with consist of two pages.
* @throws IOException
*/
private PDDocument createDocumentWithMultiplePage() throws IOException {

PDPageContentStream contentStream = null;
PDPageContentStream contentStream1 = null;
PDDocument doc = null;

try {
// create empty document.
doc = new PDDocument();
// create fist page.
PDPage page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
doc.addPage(page);

contentStream = new PDPageContentStream(doc, page);
contentStream.beginText();
contentStream.setFont(PDType1Font.HELVETICA_BOLD, FONT_SIZE);
contentStream.moveTextPositionByAmount(5, 800);

contentStream.drawString("Siva's Test page one");
contentStream.endText();
contentStream.close();

// Create next page.
PDPage page1 = new PDPage();
page1.setMediaBox(PDPage.PAGE_SIZE_A4);
doc.addPage(page1);

contentStream1 = new PDPageContentStream(doc, page1);
contentStream1.setFont(PDType1Font.HELVETICA_BOLD, FONT_SIZE);
contentStream1.beginText();
contentStream1.moveTextPositionByAmount(5, 800);

contentStream1.drawString("Siva's Test page Two");
contentStream1.endText();
contentStream1.close();
} catch (final IOException exception) {
throw new RuntimeException(exception);
} finally {

if (contentStream != null) {
try {
contentStream.close();
} catch (final IOException exception) {
throw new RuntimeException(exception);
}

}
if (contentStream1 != null) {
try {
contentStream1.close();
} catch (final IOException exception) {
throw new RuntimeException(exception);
}

}
}

return doc;
}

/**
* Main method
*
* @param arg
* @throws IOException
* @throws COSVisitorException
*/
public static void main(String arg[]) throws IOException, COSVisitorException {

MultipagePdfWithFooter obj = new MultipagePdfWithFooter();
PDDocument doc = obj.createDocumentWithMultiplePage();

obj.addReportFooter(doc, "Siva's Multi page with footer Test Report");
doc.save(new FileOutputStream(new File("C://siva//SivaTestPDfWithMultiPage.pdf")));
}
}

GRASP IN SOFTWARE DESIGN



What is the GRASP?

The world is dynamic. Its get changed every day or some one can say that it’s changing each and every time. But truth is, world never change but it’s modified by the adorns which some expert scientist adding on it by the out come of those peoples extreme researches. What so ever at the end people can say it’s a beautiful world? The thing we should note is how it becomes such a beautiful?
Answer is , its open and no restriction ,every people can change the world by putting so many things on it and make that so tedious since there is no restriction. But one day time had come to made a decision to restrict the things which is adding to the surface of the hearth and making to add what really necessary. Now its so beauty because it’s more organized and more compressed way every thing has been put so that is illuminating as precious stone on the galaxy.

Like world, Software also the same.

From the day beginning of the computer , so many people started to research on it and made so many remarkable out comes and put those things in to the open world. So the people who want to develop software they tried with all the softy solutions which they picking up in the world and tried to apply to the software what they tried to develop. But at the end they came up a software solution what they needed which is messy, very complex, combined the module together which is not easy to distinguishable in future if it needs. What so ever time came to make the software is very beautiful and elegant one now a days. The thing we should note is, how it becomes such a beautiful?

Answer is, since software industry is very open and no much restriction, the software developer started to pick most of the solution which is pre proven and tried to apply to the software which they tried to developed. By putting all the pattern, so many design principles, the solution which is developed was very messy and its so hard to even maintains. Why because no body knows how to unfix each component and modify since all are tightly fixed. But now time has come to make to develop the software solution which is so beauty and elegance by putting the limited predefine and designed applicable pattern on it rather putting all at to ones making a component and make it dependent and assigning a unique responsibility to each component but still those are virtually connected to each other. Generally speaking that we are Generalizing Responsibility Assignment to the Software as a Patten (GRASP).
The GRASP consists with few design principles as well as design pattern which create the set of complete methodology where software can be engineered by applying this pattern. But have to remember is, this is not completely a design pattern but its correct if any body argue that this is set of tool set which help to design a OOP software application. We good software engineers always are worrying about the designing of the software to make each component independent and oriented for one particular task.ie a responsibility. In a nutshell, the key thing to good architecture in software is assigning responsibilities to the classes correctly. So name chosen to suggest the importance of grasping fundamental principles to successfully design object-oriented software is GRASP deals exclusively with this question.
Contents of GRASP
1) Informational Expert
2) Creator
3) Controller
4) Low Coupling
5) Higher Cohesion
6) Polymorphism
7) Pure Fabrication
8) Indirection
9) Protected Variation

Informational Expert
The informational expert pattern is: The class which has more information to carry out or solve a problem in its domain context. That’s a responsibility which is to be assigned to the object that has more data to full fill the responsibility easily.
Eg: Lets say , I have responsibility like this
I want to display all java projects an engineer worked on more than one year. So how I am going to assign this responsibility to the classes. So I am going to have three classes like 1) Engineer, 2) WorkedOn 3) Project
1) First responsibility is : get the total project an Engineer worked. This is assigned to the Engineer since he has more data about the project he worked.
2) Second responsibility is : Get the period he worked in a project : This is assigned to the class Worked On ,because this class has the information of the time period about an engineer worked on a project.
3) Third responsibility is : Get all the java project an engineer worked. This responsibility is assigned to the Project class where it has the information of the project and its technology.
Like this we can give the responsibility to each class which has more information to fulfill the responsibility.
The below code snippet shows this pattern
package iExpert;

/**
*
* @author sivakumaran
*
*/
public class Engineer {

//Hold the value of total worked project.
private Integer totoalWorkedProject;

/**
* This method get the total project an engineer worked on.
* @return totoalWorkedProject.
*/
public Integer getTotalProject(){

return totoalWorkedProject;
}
}

package iExpert;

/**
*
* @author sivakumaran
*
*/
public class WorkedOn {

// hold the valeu of period.
private Integer period;

/**
* This method get the time period of the the project worked.
*
* @param eId
* set the engineer id
* @param pId
* set the project id
* @return period
*/
public Integer getTimePeriod(final Integer eId, final Integer pId) {

return period;
}
}

package iExpert;

import java.util.List;

/**
*
* @author sivakumaran
*
*/
public class Project {

// hold the list of project
private List project;

public List getProject() {

return project;
}

public void setProject(List project) {
this.project = project;
}

/**
* This method get all the java project of an emplyee
*
* @param eId
* set the employee id
* @param technolgy
* set the technology eg:: java.c#
* @return list of the project
*/
public List getAllJavaProject(final Integer eId, final String technolgy) {

return getProject();
}
}

Creator
In this, the main responsibility is to be assigned is who should create object of other classes. This is measured by few criteria as below. If one of criteria is match, then that particular class is more vital to create required object.
Let’s assume that, a responsibility has been assigned to the Book class to create the Page class.
1. Book contains or compositely aggregates Page
2. Book records Page
3. Book closely uses Page
4. Book has initializing data for Page that will be passed to Page when its created.
Thus Book has more information about page so that Book is expert to create the Page.

Eg :
package creator;

/**
*
* @author sivakumaran
*
*/
public class Page {

//Hold the value of page title value.
private String pageTitle;

//Hold the value of page contents value.
private String pageContents;

/**
* constructor
* @param pageTitle
* @param pageContents
*/
public Page(final String pageTitle, final String pageContents){

this.pageTitle = pageTitle;
this.pageContents = pageContents;
}
}

package creator;

import java.util.List;

/**
*
* @author sivakumaran
*
*/
public class Book {

//Hold the value of the totoal pages in book
private List numberOfPages;

//Hold the value of the page contents
private String pageContents;

//Hold the value of the page title
private String pageTitle;


public void createPage(){

Page pageObj = new Page(pageTitle, pageContents);
numberOfPages.add(pageObj);
}

public Page getPage(){

return numberOfPages.get(0);
}

}

Controller
Basically this pattern is assigned the responsibility to the object to receiving or handling the system event. That’s UI events. A Controller object is a non-user interface object responsible for receiving or handling a system event.
These events are being handled in two ways.
1 Represent the overall system like façade pattern.
2 Represent a use case scenario where system event occurs.(log when DAO object creates).
Basically these controller most probably not doing much work but delegate it others

Eg: ActionServlet of the Struts framework

Low Coupling
Coupling in the software arena is, what is the weight of dependencies of one object to other. So each designer of the software application , design it in a way as make low dependences to other objects. That’s make that low coupling. Why we need to have low coupling is, its maintainability. That’s we can modify the code later on with low effect of other classes.
So our problem is in GRASP is how to assign the responsibility that may remain low or can complete it without remain. So design module to keep lower dependency to other.

Higher Cohesion
Cohesion is a measure of “relatedness”. High Cohesion says elements are strongly related to one another. Low Cohesion says elements are not strongly related to one another.
Designs with low cohesion are difficult to maintain and reuse. One of the fundamental goals of an effective design is to achieve high cohesion with low coupling. So this is in GRASP context is Assign a responsibility so that cohesion remains high.

Polymorphism
Polymorphism can be talked about in numerous ways. One is - using polymorphism to extend your applications and make them more pluggable. That is the point of the GRASP Pattern and usually the point of all books on object-oriented programming.
Polymorphism in this context entails creating polymorphic methods in base classes / interfaces that are overridden / implemented in concrete or derived classes. In brief - How to handle alternative behavior based upon type.

E.g. Who is responsible for authorizing different types of payments in sale order Domain. So each payment will authorized it self.

package Polimorphism;

/**
*
* @author sivakumaran
*
*/
public class Payment {

/**
* Authorising the payment
*/
public void authorize(){

}
}


class CashPayment extends Payment {

@Override
public void authorize() {
// TODO Auto-generated method stub
super.authorize();
}
}

class CreditPayment extends Payment {

@Override
public void authorize() {
// TODO Auto-generated method stub
super.authorize();
}
}


class CheckPayment extends Payment {

@Override
public void authorize() {
// TODO Auto-generated method stub
super.authorize();
}
}



Pure Fabrication
Sometimes, during design, responsibilities need to be assigned that are not naturally attributable to any of the conceptual classes. Create an artificial class that does not represent anything in the problem domain. There are situations in which assigning responsibilities only to domain classes lead to poor cohesion or coupling or low reuse potential. So assign a highly cohesive set of responsibilities to an artificial class - a fabrication.
What we expect from this is , A class should be designed with high potential of reuse - responsibilities are small and cohesive. This will create a function-centric object. Part of the high-level object-oriented service layer in architecture.
Eg : Most of the GoF patterns involve fabricating new classes like observer,adapter, abstract factory, etc.These are only for process centric and responsible for its task .eg: factory is used for create objects.

Indirection
This pattern basically involve to make object decouple.So in GRASP how this is happen is , assign responsibility to an intermediate object to mediate between other components so that they are not directly coupled.
Eg: All proxy classes.

Protected Variation
This pattern has the responsibility to answer the question of how to minimize the impact of change due to variations or instability of certain objects, subsystems and systems?.
Identify points of predicted variation or instability and assign responsibilities to create a stable interface (or protection mechanism) around them and applying data encapsulation, interfaces, polymorphism and indirection design patterns.
Service Lookup is an example of protected variations because clients are protected from changes in the location of services using the lookup service. Also externalizing properties in a property file.

Time Format Of Cron Job Time Expressions


Hi guys ,

Today I am gonna write some important time format of cron job time expressions. In my experience , even though we know the cron job triggering time format expression, it so tendency to forget (I am always forget these expressions) to create the expression to generate the time range for trigger the cron job. So I thought to write this to quickly refer the expression format for cron job time range expression when ever we need rather put our head in to deep thinking and save our time :).

Whats cron expression,
A "Cron-Expression" is a string comprised of 6 or 7 fields separated by white space. The 6 mandatory and 1 optional fields are as follows:


Field Name
Allowed ValuesAllowed Special Characters
Seconds0-59, - * /
Minutes0-59, - * /
Hours0-23, - * /
Day-of-month1-31, - * ? / L W C
Month1-12 or JAN-DEC, - * /
Day-of-Week1-7 or SUN-SAT, - * ? / L C #
Year(Optional) empty, 1970-2099, - * /


The '*' character is used to specify all values.
Example, "*" in the minute field means "every minute".
The '?' character is allowed for the day-of-month and day-of-week fields. It is used to specify 'no specific value'. This is useful when you need to specify something in one of the two fields, but not the other.
The '-' character is used to specify ranges
For example "10-12" in the hour field means "the hours 10, 11 and 12".
The ',' character is used to specify additional values.
Example "MON,WED,FRI" in the day-of-week field means "the days Monday, Wednesday, and Friday".
The '/' character is used to specify increments.
Example "0/15" in the seconds field means "the seconds 0, 15, 30, and 45". And "5/15" in the seconds field means "the seconds 5, 20, 35, and 50".
Specifying '*' before the '/' is equivalent to specifying 0 is the value to start with. Essentially, for each field in the expression, there is a set of numbers that can be turned on or off.
For seconds and minutes, the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to 31, and for months 1 to 12. The "/" character simply helps you turn on every "nth" value in the given set. Thus "7/6" in the month field only turns on month "7", it does NOT mean every 6th month, please note that subtlety.
The 'L' character is allowed for the day-of-month and day-of-week fields.
This character is short-hand for "last", but it has different meaning in each of the two fields. For example, the value "L" in the day-of-month field means "the last day of the month" - day 31 for January, day 28 for February on non-leap years. If used in the day-of-week field by itself, it simply means "7" or "SAT". But if used in the day-of-week field after another value, it means "the last xxx day of the month" - for example "6L" means "the last Friday of the month". When using the 'L' option, it is important not to specify lists, or ranges of values, as you'll get confusing results.
The 'W' character is allowed for the day-of-month field.
This character is used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify "15W" as the value for the day-of-month field, the meaning is: "the nearest weekday to the 15th of the month". So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you specify "1W" as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not 'jump' over the boundary of a month's days. The 'W' character can only be specified when the day-of-month is a single day, not a range or list of days.
The 'L' and 'W' characters can also be combined for the day-of-month expression to yield 'LW', which translates to "last weekday of the month".
The '#' character is allowed for the day-of-week field.
This character is used to specify "the nth" XXX day of the month. For example, the value of "6#3" in the day-of-week field means the third Friday of the month (day 6 = Friday and "#3" = the 3rd one in the month). Other examples: "2#1" = the first Monday of the month and "4#5" = the fifth Wednesday of the month. Note that if you specify "#5" and there is not 5 of the given day-of-week in the month, then no firing will occur that month.
The 'C' character is allowed for the day-of-month and day-of-week fields.
This character is short-hand for "calendar". This means values are calculated against the associated calendar, if any. If no calendar is associated, then it is equivalent to having an all-inclusive calendar. A value of "5C" in the day-of-month field means "the first day included by the calendar on or after the 5th". A value of "1C" in the day-of-week field means "the first day included by the calendar on or after sunday".
The legal characters and the names of months and days of the week are not case sensitive.

Saturday, June 19, 2010

Layerd Architecture of Software


Software architecturing is in a nutshell ,organizing software component which is specific for a one functionality in a system, ie.an architectured system will have multiple component each specific for one kind of functionality. But each component should be very independent from other component and also consistent on its own context.

In term of software development , there are few software architectural methodology available which has been identified by software professionals.So we are in a lucky stage that we can use it without thinking as crazily to identify the proper architecturing framework for our own application.The below appearing some of architecturing methodology which software professional now days using to develop theirs own application.

Most popular software architectural methodologies

  • Client–server model (2-tier, n-tier, peer-to-peer, cloud computing all use this model)
  • Database-centric architecture (broad division can be made for programs which have database at its center and applications which don't have to rely on databases, E.g. desktop application programs, utility programs etc.)
  • Distributed computing
  • Event-driven architecture
  • Front end and back end
  • Implicit invocation
  • Monolithic application
  • Peer-to-peer
  • Pipes and filters
  • Plugin
  • Representational State Transfer
  • Rule evaluation
  • Search-oriented architecture (A pure SOA implements a service for every data access point.)
  • Service-oriented architecture
  • Shared nothing architecture
  • Software componentry
  • Space based architecture
  • Structured (module-based but usually monolithic within modules)
  • Three-tier model/Layerd Architecture (An architecture with Presentation, Business Logic and Database tiers)
in this article I am going to talk about my favorite architecture methodology ie. Three-tier model/Layerd Architecture in details and its pros and cone.

Three-tier model/Layerd Architecture (An architecture with Presentation, Business Logic and Database tiers)

A software layer is a common layer for J2EE application, where each layer is specific for one section of functionality of the system.The layers are organized in the system in such way that providing support and base functionality for other layers.

For example, lets talk about a ferry service system, when a ferry service need to handle the travels , it needs vessel details which is going to be traveled ,passenger or cargo type which going to be load kind of details.These details are basic details which ferry business service needs handle the travel.So those details are given by ferry data access layer.

Layering is not new concept for software industry.For example if you take the network protocols, it has been using this for years.For instant, FTP,Telnet and browse are services which depends on TCP/IP layer of network, so that if you need to modify or technology advancess, you can do it without affecting to the FTP or Tel net configuration.

So in a nutshell we are keep apart the each layer with distinct functionality in a system.The below table outlines the layers which we can identify in a typical layerd architected software application.


Below is layers and its roles

Data Access Object layer - Manage reading ,writing, updating, and delete stored data,Commonly contains JDBC , Hibernate ,IBatis or some other Database connectivity code.

Business logic layer- Mange business processing tool and logic

Value Object Layer - Lightweight structures for related business information These are some times referred to as data transfer object

Deployment layer - Publishes business object capabilities.

Presentation layer - Control display the end user

Architectural component layer - Generic application utilities.Often these objects are good candidates for enterprise side user
The below immage articulate the tipical layerd architechering methodology with component.

Software Layers for J2EE Application
















So lets go the each layer in details.

Data Access Layer.

Data access layer is specific for handling persistent unit of the application.Basically database SRUD operation.It manage access to persistent storage of some type.Simply the persistent storages are relational database,data xml file and data files.
The primary reason to separate the data access from rest of application is . that's easy to switch data sources and share DAOs between application.
A couple of patterns for data objects are most common.The simplest pattern has each persistent object represent as a DAO .The more complex and but more flexible pattern in common use is a factory base pattern.

Value Object Layer

Every applicaion has data items that logically belongs and typically are used togather. Its programmatically canvenient and with enterprise beans performance enhancing to treat this logical group of data items as a seperate object.

Business Logical layer

Object in the business logic layer combine data with business rules, constraints and activities. Business objects should be separated from DAOs, VOs, and deployment layer, such as enterprise beans to maximize the possibility of reuse.Business objects often use and coordinate the activities of multiple data object.

Deployment layer

Object in the deployment layer called deployment wrappers, are the heart of J2EE achitecture.Deployment wrappers publish business object functionality to java classes that could be on separate machine.

Presentation layer

The presentation layer is the section of application responsible for everything end users physically see in the end user interface.This layer can be build using JSP,Servelet,Html,javascrip etc.

Architectural component Layer

Ideally all general utilities and components would be provided JDK.But accordingly your requirement , you will need to use third party libraries and component.All those component are reside in this layer.

Finally this is all about layered architecture.Next blog i will show coding project example for the Layered architecture.