Friday, July 28, 2017

Java - Calculate Total Time Elapsed using Java5 or higher

Java - How to calculate the total Time elapsed for a java method.

It is a standard requirement in a lot Java components/applications to find out the total time a method has taken to execute the call.

Though there are several 3rd party libraries (Spring MethodInterceptor,  java-InvocationHandler/DynamicProxy, and AspectOrientedProgramming) that offer method interceptor feature where the time can can be tracked.
Looking at greater need of this requirement of calculating precise time (NanoSeconds..) that a method spent on, Java5 has introduced a new TimeUnit class.

Please see below example for reference

public static String calculateTotalTimeElapsed(long startNanoSec, long endNanoSec) {
long difference = endNanoSec - startNanoSec;
String totalTimeString = String.format("%d Hours, %d Min, %d Sec, %d Millis, %d Micro, %d Nano",
TimeUnit.NANOSECONDS.toHours(difference), TimeUnit.NANOSECONDS.toMinutes(difference),
TimeUnit.NANOSECONDS.toSeconds(difference), TimeUnit.NANOSECONDS.toMillis(difference),
TimeUnit.NANOSECONDS.toMicros(difference), TimeUnit.NANOSECONDS.toNanos(difference));
return totalTimeString;

       public static void main(String args[]){ 
               long timeBefore1 = System.nanoTime();
               //TODO: call any other function (db or resource intensive)
               String timeString = calculateTotalTimeElapsed(timeBefore1, System.nanoTime());
              System.out.println("Method has taken  "+timeString);

o Hours, 1 Min, 2 Sec, 400 Millis, 298 Micro, 12345 Nano.

Thursday, May 4, 2017

My Desktop background

Recently I've been thinking to come up with collection of best quotes that can keep reminding and motivating me everyday at work.

As Health, Finance and Career are my current priorities, I've come up with the following collection.

Feel free to use if you like.

Thursday, April 13, 2017

My view on Microservices Architecture (MSA)

It is a new architectural pattern to Design & Develop application(s) into smaller and manageable modular services that can be built using APIs/services with modern languages/frameworks. 

Though this is more popular and fashionable idea, is not a very new in Architects and Designers world when creating large and monolithic application. They have been contemplating to adopt this to build more scalable and maintainable solutions. Their thoughts were always limited by the availability of tools and technologies for implementation and new operational complexities.

Why MSA and What is the reason behind the popularity?
  • The emergence of lightweight REST integration (API Management) over popular SOAP (SOA-ESB) systems.
  • The emergence of new languages/technologies/frameworks that allow a few solutions can be developed with modern languages/frameworks. The replacement of these solutions can also be built more quickly if they are not addressing the requirements.
  • DevOps: Advancement in hardware where a software (Hypervisor) can be used to automate infrastructure, scaling the instances as needed and utility computing. 
  • Virtualization and Docker/Container management.
  • Change in how systems are communicated with Datastore, As there are more reads of data over writes; the gaining popularity of CQRS (Command Query Responsibility Segregation) with Event Sourcing over CRUD (Create Read Update and Delete) operations.
  • Emergence of new DBMS systems (RDBMS, SQL, NO-SQL, Graph SQL) etc..
  • Different interfaces (Desktops, Hand held devices with Mobility) to access the solutions with different user experience built on the same back-end solutions.
  • Growing popularity in Systems working on Distributed Architecture.
The API brings standardization of service development and its accessibility.
It promotes to develop, build and deploy the pieces (modules) of software independently and also offers scalability in deployment.
It is also a new architecture & design style to migrate Monolithic application (one big single application with lot of components without modularity) into more smaller services that are designed, developed, built and deployed independently.
It offers re-usability of these smaller modules (services) as this is essential to Enterprise with shared services organization.
It prefers BASE (BasicallyAvailable, SoftState and Eventually Consistent) transactions over ACID (Atomicity,Consistency,Isolation, Durability) in Distributed Architecture.
It prefers CQRS (Command Query Responsibility Segregation) with ES (Event Sourcing) over CRUD operations as there are more Reads than Writes.

Problems of Monolithic:
Code complexity and maintainability
Deployment becomes the bottleneck
Fear to change once the asset is grown big enough to make changes and regression-impacts.
Lack of ownership as it is
One size doesn’t fit all (ex: relational DB)
Hard to scale out, though limited scale up is possible.

Benefits of Microservices:
  • Speed
    • Faster development and deployment
    • Polyglot
  • Innovation
    • Autonomy of teams, culture of change
    • Ownership and DevOps culture
  • Quality
    • Reusability & more maintainable code
    • Better scaling and optimizations
    • Failure Isolation and Resilience
  • Overhead or Complexity of Communication in Development, Deployment and Operational Management. Some Cloud vendors (AWS) have addressed some of these solutions with tools.
  • Fairly new concept. Challenges in Finding experienced resources in market and Enterprise adoption.
  • Change of mindset is required to adopt to realize the benefit on ease of doing.
  • Technology stack is evolving fast: Determining when they are ready for Enterprise.
  • Investment overhead of both new API and ESB in large enterprises.
Though the Tier-1 technology companies (ex. FAANG) which can repeatedly re-invest in re-writing their popular solutions on new and modern architectures to offer new experience to customers, it is fair to say that the Tier-2 and organizations where IT is supporting the other business would mostly wait and see until the tools and practices are stable and technology becomes enterprise ready.

The startups and smaller organization can always venture into as their size, existing and limited investments would allow them to invest in these new areas.

Thursday, March 23, 2017

Plan for TOGAF9.1

Plan for TOGAF 9.1

Preparation Resources:
  1. Read preparation plan at
  2. Read others experience from
  3. Read preparation from
  1. Materials  from    
  3. Read the 'ADM cheat sheet' of 'Scott Duffy'  PDF.  Sign up for free PDF at
  4. Cheat sheets (2) from    a.
  5. Go through
  6. Check Resources  section/table at
  7. TOGAF input/output PDF at
  8. Read the TOGAF official document from OpenGroup.
  9. Read Exam study Guide at
  10. Go through
  11. Go through
  14. Read the MindMap 
  15. Buy the PART 1 course at and download all Videos.
  16. Buy the PART 2 course at and download all Videos.
Mock Exams:
  1. Mock Exam at
  2. Mock Exams at
  3. Mock exams at
  4. Mock exams at

  5. Sample Exams from
  6. Go through TOGAF 9 Scenario questions:
  7. Go through TOGA 9 sample questions at

Private Repositories, Not available to Public
 Modeling Tools:
  1. EA  at
  4. Abacus at

Friday, December 9, 2016

Explaining the World Economy in Pictures

I found an interesting article on explaining how current economy works.
Please read below.
Explaining the World Economy in Pictures

Tuesday, October 18, 2016

Short notes on DevOps


Integrates Developers and Operations teams in order to improve collaboration and productivity by Development of systems or application and automating infrastructure, deployment and monitoring performance.

Traditional approach and pitfalls:
Initially Developers(Application developers with programming skills and QA engineers) and Operations (Skills of configuring Networking/Firewall, Installing Windows/Unix/Linux/Database and other products, Deployment and monitoring of applications) are two different roles/groups.
The implementation of application would always start by Developers in their local boxes, where developer is responsible for Planning, Architecting, Designing, Implementing, Testing, Building, Packaging and Deploying in his local machine or in less capable environment or sandbox.

When it is decided by IT management or Business teams to take it to higher environments ( Functional Automation Testing, Performance Testing, User Acceptance Testing and finally into Production), an engagement of Infrastructure & Operations (I&O) team is required to create these environments on right infrastructure and with firewall configuration to isolate internal/external access.

By this time, I&O team has no clue about application release and has to find out the capacity to support this asset in all desired environments. The team may also needs to plan to upgrade H/W and change number of instances/clusters and increase disk space and RAM to make the asset more stable in production environment.

The turnaround time to promote a smallest change from conceptual to working solution is huge and the business may fall behind if the speed to market and attract/retain end customers is a very important part of Business Strategy.
This clearly shows the IT is falling behind the Business strategy.

New Approach:
If both Developers and Operations teams work together from the beginning of building the Application by following new standards,  the amount of time that will take to promote/release the asset into higher environments can be reduced.

How is this possible now?

The innovation and advancement of concepts in Hardware and software to manage the hardware has opened for following new practices to emerge.

a. Virtualization / Containerization (Docker)
 Allowing software to run multiple operating systems at the same time on same Hardware.
The software (Ex. Hypervisors) offers layer of abstraction, and allow to install many Guest OS and work with shared Hardware, Memory and other hardware resources.
b. Cloud (Utility) Computing.
c. Automating Infrastructure with scripts (Chef, Puppet, Saltstack and Ansible) and Vagrant for creating portable environments to run any other OS/Host.
d. The new concepts and practices are being evolved continuously and watch out or new disrupting concepts....

How do we engage this?
There are several vendors offering a complete suite of tool-chain to help IT organizations to realize the benefits of DevOps.  Mixing the other standards or methodologies (Agile/XP) of software development will take the complete Software Development and Delivery process to new level so that IT organization can immediately meet and align with Business priorities.

Other Benefits:
a. Innovate faster
b. Speed to market and get the feedback faster to improve the product.
c. Code little, build, test (Automated functional and performance, regression scripts) and release/deploy (using CI and CD practices) into all (including Prod) env in Iterative manner in collaboration with Operations team
d. Automate everything (Building, Automated Functional Testing, Automated Performance Testing, Regression Testing and  Release into Infrastructure),
e. Keep configuration of all (Dev, QA, PerfT, UAT and Prod) environments same to avoid surprises.
f. Monitor the application performance

Emphasizes a  Continuous Development (Developers) and Deployment (Operations/Administrators) using Agile practices. It is a cultural shift to IT teams (Software Engineering, Quality Assurance and Infrastructure Operations).

Automates the software delivery and infrastructure operations (i&o) in very collaborated manner very often and repeatedly.The following are key stages of DevOps.
Please refer to spreadsheet.DevOps Phases and Tools

DevOps Tools:  GitHub (source code management), Jeninks/Hudson (Continuous Integration & Deployment), Chef/Puppet (Infrastructure as code), Docker-Container, Hyper (vagrant), NewRelic (Application peformance monitoring of Logs) and SiteScope for alerts, Openshift

Wednesday, September 28, 2016

Enabling Apache Velocity UI Editor in Eclipse IDE

Adding Velocity UI Editor Plugin to Eclipse IDE

1. Download 'org.apache.velocity_1.7.0.2.jar'  and 'org.vaulttec.velocity.ui_1.0.5.jar'   or other latest versions from
Also refer to

2. Copy them into <Eclipse Installation Location>\plugins  directory.
3. Restart the Eclipse
4. Add new File associations (*.vtl and *.vm and *.vsl) in Eclipse settings at 'Windows>Preferences>General>Editors>File Associations'
5. Notice that a new entry (Velocity UI) can be seen under 'Windows>Preferences>' as the result of installing new JAR files.
6. Optional: Change the settings of 'Velocity UI' if needed.
7. Open a VTL file to see the settings are reflected in editor.

Thursday, September 15, 2016

 Pass by Value or Pass by Reference in Java?

Before coming to conclusion let's look at the example.

class Person {
private String name = null;

public Person() {

public String getName() {

public void setName(String newName) { = newName;

class Manager {
public Person changePersonName1(Person p) {
if (p != null) {
// just change only name
p.setName("I'm changed by Manager in changePersonName1()");
return p;

public Person changePersonName2(Person p) {
if (p != null) {
// just change only name
p.setName("I'm changed by Manager in changePersonName2()");
// create new Person instance, which means you no longer making any
// changes to the argument 'p' but on new Person instance
p = new Person();
p.setName("I'm recreated as new Person by Manager in changePersonName2()");
return p;

public class JavaPassByValueOrReference {
public static void main(String[] args) {
// Create a person
Person p1 = new Person();
p1.setName("I'm in p1 instance");

// Create a Manager
Manager mgr = new Manager();
System.out.println("0: Person p1 name = " + p1.getName());

//1-change name 
System.out.println("1: Person p1 name = " + p1.getName());

//2-change name
System.out.println("2: Person p1 name = " + p1.getName());
0: Person p1 name = I'm in p1 instance
1: Person p1 name = I'm changed by Manager in changePersonName1()
2: Person p1 name = I'm changed by Manager in changePersonName2()

  1. In Main(..) method the 'Name' of Person is defaulted to "I'm in p1 instance".
  2. When Manager instance (mgr) changed the Person's name using  changePersonName1(..), the 'Name' of Person is changed from "I'm in p1 instance" to "I'm changed by Manager in changePersonName1()"
  3. When Manager instance (mgr) changed the Person's name using  changePersonName2(..), the 'Name' of Person is changed from "I'm changed by Manager in changePersonName1()" to "I'm changed by Manager in changePersonName2()"  instead of "I'm recreated as new Person by Manager in changePersonName2()"
The reason is in changePersonName2(Person p) of Manager class, the input argument (p) is reassigned to new Person instance (p = new Person()), changes to done on newly created instance are not returnable to or visible to Caller.

A copy of an object is made and passed to a function. On returning from the function, the copy is again copied back to the original passed object. So, the value set in the function is copied back.

In short 'Java is Pass the Reference By Value" or 'Pass the copy of Pointer(Reference) by Value'  or 'References are passed by Value' .

Wednesday, September 14, 2016










C:/Program Files/Java/jdk1.8.0_102/bin/javaw.exe




















Wednesday, September 7, 2016

Java Enum example

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

public class EnumExample{
 public static void main(String args[]){
  // To Get the 'Day' by Abbreviation: 
  System.out.println("1 ="+Day.get("Su"));
  System.out.println("2 ="+Day.findByAbbr("Su"));
  // To get 'Day' name in String:
  System.out.println("3 ="+Day.valueOf("SUNDAY").toString());
  // To Get the Abbreviation by 'Day': 
  System.out.println("4 ="+Day.SUNDAY.getAbbreviation());
  System.out.println("5 ="+Day.valueOf("SUNDAY").getAbbreviation());  

 * Usage: 
 * 1. To Get the 'Day' by Abbreviation: Day.get("Su"))<br/>
 * 2. To Get the Abbreviation by 'Day': <br/>
 *    Day.SUNDAY.getAbbreviation();<br/>
 *        OR <br/>
 *    Day.valueOf("SUNDAY").getAbbreviation(); <br/>
 * 3. To get 'Day' name in String:<br/>
 *    Day.valueOf("SUNDAY").toString();
 enum Day {
 //Enum types

 //internal state
 private final String abbreviation;

 // Reverse-lookup map for getting a day from an abbreviation
 private static final Map<String, Day> lookup_0 = new HashMap<String, Day>();
 // Populate the lookup table on loading time
 static {
  for (Day d : Day.values()) {
   lookup_0.put(d.getAbbreviation(), d);
 //Alternative way populating lookup table
 static {
  for (Day d : EnumSet.allOf(Day.class)) {
   lookup_0.put(d.getAbbreviation(), d);

 private Day(final String abbreviation) {
  this.abbreviation = abbreviation;

 public String getAbbreviation() {
  return abbreviation;
 // This method can be used for reverse lookup purpose
 public static Day get(String abbreviation) {
  return (Day)lookup_0.get(abbreviation);
 public static Day findByAbbr(String abbreviation){
     for(Day d : values()){
         if( d.abbreviation.equals(abbreviation)){
             return d;
     return null;

Tuesday, May 31, 2016

Eclipse connectivity issue with Corporate Proxy


Some applications we use need to access the web through the Corporate proxy and pull in content. In many cases what happens is the request fails as the application is unable to negotiate the connection using the NTLM protocol. Examples of this are the Marketplace in Eclipse Luna or installing packages with npm.
Cntlm is a tool that will work around this problem by proxying these requests locally and talking to the Corporate proxy to establish a connection. From the project website: "Cntlm is an NTLM / NTLMv2 authenticating HTTP/1.1 proxy. It caches auth'd connections for reuse, offers TCP/IP tunneling (port forwarding) thru parent proxy and much much more."

Setup Instructions

  1. Download and install cntlm from
  2. Edit C:\Program Files (x86)\Cntlm\cntlm.ini and make the following changes (make sure you are running your text editor as administrator​):​
    a. Add your Corporate username
    Username <corporate proxy server login>

    b. Comment out domain (we don’t need it)
    # Domain    corp-uk

    c. Change Proxy and Add additional NoProxy
    Proxy           <HTTPPROXYNAME>:<PORT>
    NoProxy         localhost, 127.0.0.*

    d. Get password hash from the command line
    > cd "C:\Program Files (x86)\Cntlm\"
    > cntlm -H -c cntlm.ini

    e. Paste the resulting 3 lines, which contain hashes of your password, back into your config.ini:
    PassLM          <HASH>
    PassNT          <HASH>
    PassNTLMv2      <HASH>    # Only for user <USERNAME>, domain '<HTTP PROXY NAME>'

    f. Comment out clear text password parameter
    # Password <fake password>

    g. Start CNTLM
    See instructions in README.txt (in the cntlm installation directory)

    h. Test CNTLM from the comand line
    > cntlm -M

    After entering your Corporate password when prompted, you should see a response similar to the following (the HTTP 200 response indicating a success):

    Config profile  1/4... OK (HTTP code: 200)
    ----------------------------[ Profile  0 ]------
    Auth            NTLMv2
    PassNTLMv2      <your password hash>
  3. Reboot your computer.  CNTLM will be installed and will run as a windows service and you won't have sto start it again manually unless of course you stop it manually.
After configuring and starting cntlm, applications should be able to access the web with no further action needed.

Changing CNTLM Password After CORPORATE Password Reset

  1. Get password hash from the command line
    > cd "C:\Program Files (x86)\Cntlm\"
    > cntlm -H -c cntlm.ini
  2. Copy the resulting 3 lines, which contain hashes of your passwordPassLM <HASH>
    PassNT <HASH>
    PassNTLMv2 <HASH> # Only for user <USERNAME>, domain '<HTTPPROXYHOST>'
  3. Open the cntlm.ini (configuration setting file) and replace (paste) the information from step two into your cntlm.ini file.
  4. Save, stop then start cntlm.  Information on how to do that can be found in the "Starting/Stopping CNTLM Manually" section below.

Starting/Stopping CNTLM Manually

  1. To start stop CNTLM manually open a command prompt as an Administrator
  2. To stop CNTLM type
    1. net stop cntlm
  3. To start CNTLM type:
    1. net start cntlm

Further info

Cntlm technical manual

How to Configure Eclipse Proxy Settings

Note: If installing from an external site hangs at “calculating requirements and dependencies” after following the instructions here, try unchecking the "Contact all update sites during install" box.
Beginning with Eclipse version 4.4 (Luna), special steps are needed in order for Eclipse to contact external sites (e.g. to install updates or plugins).
If when attempting to install plugins or open the Eclipse Marketplace, you receive an error stating "Proxy Authentication Required", this article is for you.


The cause of the proxy error is a new set of HTTP client libraries that Eclipse uses beginning with v4.4. Removing those libraries, along with configuring Eclipse to talk to the proxy, will cause Eclipse to fall back on the JRE HTTP client libs. This should resolve the issue.

Part A: Configure Eclipse's Proxy Settings

First, you must configure Eclipse to play nice with the proxy by doing the following:
  1. In Eclipse go to Window>Preferences>General>Network Connections
  2. Choose Manual for the Active Provider
  3. For both HTTP and HTTPS, enter the following settings:
    • Host: <PROXY HOST>
    • Port: <PROXY PORT>
    • User: <PROXY USERID>
    • Password <PROXY USER PASSWORD>
    Note you will need to update this each time you change your password.
  4. Click OK to save your settings.

Part B: Remove Problematic Libraries

With Eclipse not running, go to Eclipse's plugins directory (e.g. C:\Program Files\Eclipse\plugins) and delete or rename the following three .jar files:


After performing parts A and B above, Eclipse should be able to contact external update sites without any issues.    Notes
This information was compiled from this StackOverflow question and this bug report comment on the Eclipse bug tracker.

In addition to above 2 parts, see if helps or
configure the following in eclipse.ini file.

Thursday, May 12, 2016

Best way to create a Singleton Pattern.

The Singleton Design Pattern is one of the Creational (creation of instance in best possible way) patterns.

The usage of enum, a new feature from Java5, allows safe way to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in memory (JVM).

This singleton instance is accessible from anywhere since Java Enum values are globally accessible.

The drawback is that the enum type is somewhat inflexible as it does not allow lazy

package org.comp.core;
public enum MyEnumSingleton {

       private MyEnumSingleton(){}

  public static void method1(){

//Do something 

  public static List buildStateCodeList(){
              final List<String>  stateCodeList = new ArrayList<String>();
             return stateCodeList ;

From Caller:
List<String> stateCode_USA_List = MyEnumSingleton.INSTANCE.buildStateCodeList();

The following is more appropriate in  Distributed environment.   

package org.comp.core;
public class MySerializedSingleton implements Serializable{
private static final long serialVersionUID = -12345678923456789123L;
// Private/default constructor
private MySerializedSingleton(){}
//Inner static class to create instance (A safer way)
private static class MySingletonHelper{
private static final MySerializedSingleton instance = new MySerializedSingleton();

//Return singleton instance
public static MySerializedSingleton getInstance(){
return MySingletonHelper.instance;

* Implement the readResolve() method to avoid creating a new instance in 'Deserialization'            scenario.  
protected Object readResolve() {
return getInstance();


Thursday, October 8, 2015

Testing - Glossary

Functional Testing:  (Iteration Testing) Testing the application against business requirements by testing a slice of functionality of the whole system ensuring that the software has all the required functionality that’s specified. 
System Testing:  Testing conducted on a complete, integrated system to evaluate the system’s compliance with its specified requirements, functional testing is also included in this phase.
Regression Testing: Software testing that seeks to uncover bugs in existing functional and non-functional areas after changes have been made to the system.
User Acceptance Testing: This is not System Testing, but rather ensures that the solution will work for the user. Testing is normally done by a subject-matter expert and is one of the final stages of a project often before a client or customer accepts the changes to the system.
Performance Testing: Testing performed to determine how the system performs in terms of responsiveness and stability under a particular workload. It can also serve to investigate, measure, validate or verify other quality attributes of the system, such as scalability, reliability and resource usage.
Beta Testing: Testing of a rerelease of a software product conducted by customers
Ad Hoc Testing: A testing phase where the tester tries to 'break' the system by randomly trying the system's functionality. Can include negative testing as well.
Testing a system or an Application on the fly, i.e just few tests here and there to ensure the system or an application does not crash out.

Thursday, August 7, 2014

Grails in Websphere - Not loading/working static resources in cluster env.

It is observed that the Grails application was working fine in local (tomcat) developer box and not behaving the same when deployed into Websphere cluster.

If you are using grails resources plugins then use the plugins in the following order.
        // Manually update the resoures plugin to resolove websphere look up errors
        runtime ":resources:1.2"
        runtime ":cached-resources:1.0"
        //runtime ":zipped-resources:1.0"
        compile ":cache-headers:1.1.5"