Java 8 Default Methods

Java8-LogoInterfaces in Java always contained method declaration not their definitions (method body). There was no way of defining method body / definition in interfaces. This is because historically Java didn’t allow multiple inheritance of classes. It allowed multiple inheritance of interfaces as interface were nothing but method declaration. This solves the problem of ambiguity in multiple inheritance. Since Java 8 it is now possible to add method bodies in interfaces.

Java 8 has a new feature called Default Methods. It is now possible to add method bodies into interfaces!

package com.javainsider.java8.defaultmethods;

public interface DefaultMethod {
int addNumber(int num1, int num2);
default int multiplyNumber(int num1 , int num2){
return num1 * num2;
}
}

In above DefaultMethod interface we added a method multiplyNumber with actual method body.

Why we need Default Methods?

Why would one want to add methods into Interfaces? We’ll it is because interfaces are too tightly coupled with their implementation classes. i.e. it is not possible to add a method in interface without breaking the implementor class. Once you add a method in interface, all its implemented classes must declare method body of this new method.

Since Java 8, things started getting ugly. A new feature Lambda was introduce which is cool. However it is not possible to use this feature in existing Java libraries such as java.util package. If you add a single method in interface List, it breaks everything. You need to add its implementation in every class that implements List interface. Imagine in real world how many custom classes would change.

So for backward compatibility, Java 8 cleverly added Default Methods.

Virtual Extension Methods

It added a new concept Virtual extension methods, or as they are often called defender methods, can now be added to interfaces providing a default implementation of the declared behavior. So existing interfaces can be augmented without compromising backward compatibility by adding extension methods to the interface, whose declaration would contain instructions for finding the default implementation in the event that implementors do not provide a method body. A key characteristic of extension methods is that they are virtual methods just like other interface methods, but provide a default implementation in the event that the implementing class does not provide a method body.

Consider following example:

package com.javainsider.java8.defaultmethods;

public interface Person {

default void sayHello() {
System.out.println(“Hello…..”);
}

public void sayGoodby();

}

 

package com.javainsider.java8.defaultmethods;

public class JavaPerson implements Person {

@Override
public void sayGoodby() {
System.out.println(“Goodby Java person……”);
}
}

 

package com.javainsider.java8.defaultmethods;

public class TestJavaPerson {

public static void main(String[] args) {
JavaPerson javaPerson = new JavaPerson();

// calling sayHello method calls the method defined in interface
javaPerson.sayHello();

// calling sayGoodby- method calls the method implemented in JavapPerson
javaPerson.sayGoodby();
}

}

Output:

Hello……

Goodby Java person……

In above code we added a defender method sayHello() in Person interface. So it was ok for class JavaPersonto avoid declaring this methods body.

What about Multiple Inheritance?

Adding method definitions in interfaces can add ambiguity in multiple inheritance. isn’t it? Well, it does. However Java 8 handle this issue at Compile type. Consider below example:

package com.javainsider.java8.multipleinheritance;

public interface Person {

default void sayHello() {
System.out.println(“Hello…”);
}
}

 

package com.javainsider.java8.multipleinheritance;

public interface Female {
default void sayHello() {
System.out.println(“Hello Ms….”);
}
}

 

package com.javainsider.java8.multipleinheritance;

public interface Male {

default void sayHello() {
System.out.println(“Hello Mr….”);
}
}

 

package com.javainsider.java8.multipleinheritance;

public class Martin implements Person, Male{

@Override
public void sayHello() {
//Male.super.sayHello();
System.out.println(“Hello… I am Martin here….”);
}

}

It is also possible to explicitly call method from child class to parent interface. Consider in above example you want to call sayHello method from Male interface when Martin.sayHello is called. You can use super keyword to explicitly call the appropriate method or you can write your own implementation.

You can access the code from GIT repo:  https://github.com/javainsider/java8features

 

Happy Coding!

 

 

 

Install MongoDB On Mac OS X

Easy spets to nstall MongoDB on Mac OS X ( I have used MAC OS – Mavericks)

Image

Step 1: Download MongoDB:

Download MongoDB for MAC OS from official MongoDB site:

http://www.mongodb.org/downloads

Step 2: Install MongoDB:

$ cd ~/Download
$ tar xzf mongodb-osx-x86_64-2.6.1.tar
$ sudo mv mongodb-osx-x86_64-2.6.1 /usr/local/mongodb

 

Step 3: Create MongoDB Data Directory:

By default, MongoDB write/store data into the /data/db folder, you need to create this folder manually and assign proper permission as given below:

$ sudo mkdir -p /data/db
$ whoami
garnaik
$ sudo chown garnaik /data/db

Step 4: Set you PATH on Bash Profile for MongoDB:

Create a ~/.bash_profile file if not exists else update, and assign /usr/local/mongodb/bin to $PATH environment variable, so that you can access MongoDB on commands easily.

$ cd ~
$ pwd/Users/garnaik
$ touch .bash_profile
$ vim .bash_profile
 
exportMONGO_PATH=/usr/local/mongodb
exportPATH=$PATH:$MONGO_PATH/bin
 
##restart terminal
 
$ mongo -version
MongoDB shell version: 2.6.1

Step 5: Setting for auto start MongoDB:

To auto start yor installed mongoDB, create a launchd job on your Mac OS.

$ sudo vim /Library/LaunchDaemons/mongodb.plist

And add the following content to “/Library/LaunchDaemons/mongodb.plist”

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>mongodb</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/mongodb/bin/mongod</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>WorkingDirectory</key>
  <string>/usr/local/mongodb</string>
  <key>StandardErrorPath</key>
  <string>/var/log/mongodb/error.log</string>
  <key>StandardOutPath</key>
  <string>/var/log/mongodb/output.log</string>
</dict>
</plist>

Save the file and load the above job:

$ sudo launchctl load /Library/LaunchDaemons/mongodb.plist

$ ps -ef | grep mongo
    0    12     1   0  4:06PM ??         0:20.29 /usr/local/mongodb/bin/mongod
  501   542   435   0  4:37PM ttys000    0:00.00 grep mongo

Now restart your MAC OS.

Step 6: Start MongoDB:

If you already have added the above steps then MongoDB will start by the time your MAC OS started.

 

Otherwise you have to start MongoDB by using the below command:

$ mongod

Now ready to use MongoDB,

 

$ mongo
> mongod -version 
MongoDB shell version: 2.6.1
> show dbs
Local (empty)

Proxy Design Pattern (GOF)

ProxyWhen to use this pattern?
Proxy pattern is used when we need to create a wrapper to cover the main object’s complexity from the client.

  • Provide a surrogate or placeholder for another object to control access to it.
  • Use an extra level of indirection to support distributed, controlled, or intelligent access.
  • Add a wrapper and delegation to protect the real component from undue complexity.

Problem:
You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.

What are the usage scenarios?

  1. Virtual Proxy – Imagine a situation where there is multiple database call to extract huge size image. Since this is an expensive operation we can possibly use the proxy pattern which would create multiple proxies and point to the huge size memory consuming object for further processing. The real object gets created only when a client first requests/accesses the object and after that we can just refer to the proxy to reuse the object. This avoids duplication of the object and hence saving memory.
  2. Remote Proxy – A remote proxy can be thought about the stub in the RPC call. The remote proxy provides a local representation of the object which is present in the different address location. Another example can be providing interface for remote resources such as web service or REST resources.
  3. Protective Proxy – The protective proxy acts as an authorisation layer to verify if the actual user has access to appropriate content. An example can be thought about the proxy server which provides restrictive internet access in office. Only the websites and contents which are valid will be allowed and the remaining ones will be blocked.
  4. Smart Proxy – A smart proxy provides additional layer of security by interposing specific actions when the object is accessed. An example can be to check if the real object is locked before it is accessed to ensure that no other object can change it.

Participants:

  1. Subject – This object defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
  2. Proxy – It maintains a reference to the RealSubject so that Proxy can access it. It also implements the same interface as the RealSubject so that Proxy can be used in place of RealSubject. Proxy also controls the access to the RealSubject and can create or delete this object.
  3. RealSubject – This refers the main object which the proxy represents.

 

Code Example: –  Virtual Proxy Example:

As mentioned earlier virtual proxy is useful to save expensive memory resources. Let’s take a scenario where the real image contains a huge size data which clients needs to access. To save our resources and memory the implementation will be as below:

– Create an interface which will be accessed by the client. All its methods will be implemented by the ProxyImage class and RealImage class.
– RealImage runs on the different system and contains the image information is accessed from the database.
– The ProxyImage which is running on a different system can represent the RealImage in the new system. Using the proxy we can avoid multiple loading of the image.

Image.java:

public interface Image {
public void showImage();
}

 

RealImage.java:

public class RealImage implements Image {

private String fileName = null;
public RealImage(String strFileName){
this.fileName = strFileName;
}
@Override
public void showImage() {
System.out.println(“Show Image:” +fileName);

}
}

 

 

ProxyImage.java:

public class ProxyImage implements Image {
private RealImage img= null;
private String fileName = null;

public ProxyImage(String strFileName) {
this.fileName = strFileName;
}
/*
* (non-Javadoc)
* @see com.proxy.virtualproxy.Image#showImage()
*/
@Override
public void showImage() {
if(img == null){
img = new RealImage(fileName);
}
img.showImage();
}
}

Client.java:

public class Client {
public static void main(String[] args) {
final Image img1 = new ProxyImage(“Image***1”);
final Image img2 = new ProxyImage(“Image***2”);
img1.showImage();
img2.showImage();
}
}

Benefits:

  •  One of the advantages of Proxy pattern as you have seen in the above example is about security.
  •  This pattern avoids duplication of objects which might be huge size and memory intensive. This in turn increases the performance of the application.
  •  The remote proxy also ensures about security by installing the local code proxy (stub) in the client machine and then accessing the server with help of the remote code.

 

Drawbacks/Consequences:

This pattern introduces another layer of abstraction which sometimes may be an issue if the RealSubject code is accessed by some of the clients directly and some of them might access the Proxy classes. This might cause disparate behaviour.

Rules of thumb:
– There are few differences between the related patterns. Like Adapter pattern gives a different interface to its subject, while Proxy patterns provides the same interface from the original object but the decorator provides an enhanced interface. Decorator pattern adds additional behaviour at runtime.

– Proxy used in Java API:  java.rmi.*;

 

 

MVP – Minimum Viable Product Strategy

Not all good ideas turn out into great products.  There are quite a few products that fail in the market due to a variety of reasons.  But does it stop us from investing in the Products? How do we find out if a Product is going to be a hit in the market?  And more importantly how do we find that out by investing the minimum amount possible.  Enter MVP – The Minimum Viable Product.
The concept of MVP is getting acceptance throughout in the area of Product Development.  It is a concept largely used by start ups.  And it will immensely help new product design and development in larger organizations.
What is an MVP?
Our objective with a Minimum Viable Product is to provide a mechanism for maximum learning about the target audience or the target market with the minimum effort.  Does it mean that we only ship 3 out of the 10 features that is required to hit the market at the earliest.  No.  The concept is beyond just the product features.  A Minimum Viable Product takes into account the Product idea, how it generates interest among the users, what features that the customers or the market really wants, demand for the product, etc.  It is a strategy that is used for learning about the customers early into the product life cycle, so that they can make the changes for the good.
 MinimumViableProduct
Strategies for MVP
  • A survey for the likely features of the product
  • An email campaign to see the interest generated for the product
  • A website which shares videos, articles about the features and the benefits to the customers
  • Continuous Deployment (An Agile Practice, which can add more value to the business incrementally providing more learning)
  • A prototype / demo version of the product featuring the critical features
  • A closed beta for only very few customers
Why do we need MVP?
  • We do not have endless budget to build products
  • We want to cut the risk of a worst case scenario.  What if the product fails after 2 years of hard work?
  • We want to stay in the business yet not stop experimenting for potential opportunities
Benefits of MVP
  • Maximum learnings from minimum efforts
  • Early feedback about the product
  • Ability to realize the true value / demand of a product more quickly
  • More energy into the product development as we see some real demands
Demerits of MVP
  • Difficult to conceptualize the apt minimum.  There is no pre-defined rules for coming up with a minimum, it is pretty much judgemental.
  • Need to alter the product road map according to the feedback / learning which might be possible only with teams that are Agile.
The concept of MVP is ideal for start-ups and new R&D products/ideas, where your feedback cycle needs to be really fast.  It is better for a start-up to fail with a product idea in 3 months than 1 year.  The time and effort that is saved due to a MVP strategy is a big boon for start-ups and even larger organizations trying for new R&D product/ideas.

SAX vs DOM Parser – Concept Revisited

Image

 

Both SAX and DOM Parser’s are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.

SAX: Is a stream-based processor. You only have a tiny part in memory at any time and you “sniff” the XML stream as it passes. It uses almost no memory, but you can’t do “DOM” stuff, like use xpath or traverse trees.

DOM: You load the whole thing into memory – it’s a massive memory hog. You can blow memory with even medium sized documents. But you can use xpath and traverse the tree etc.

 

SAX:

  • Parses node by node
  • Doesn’t store the XML in memory
  • We cant insert or delete a node
  • SAX is an event based parser
  • SAX is a Simple API for XML
  • doesn’t preserve comments
  • SAX generally runs a little faster than DOM

DOM:

  • Stores the entire XML document into memory before processing
  • Occupies more memory
  • We can insert or delete nodes
  • Traverse in any direction.
  • DOM is a tree model parser
  • Document Object Model (DOM) API
  • Preserves comments
  • SAX generally runs a little faster than DOM

If we need to find a node and doesn’t need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Read More on SAX:

http://en.wikipedia.org/wiki/Simple_API_for_XML

Categories: Uncategorized Tags: , , ,

Solutions Architect ~ An Overview

solution-architecting-expectationsThe Solutions Architect is a very experienced architect with cross-domain, cross-functional and cross-industry expertise. He/she outlines solution architecture descriptions, then monitors and governs their implementation.

The Solutions Architect is responsible for the development of the overall vision that underlies the projected solution and transforms that vision through execution into the solution.

To be effective the Solutions Architect must have experience on multiple Hardware and Software Environments and be comfortable with complex heterogeneous systems environments.

 

 

 

Involvement and Responsibility:

  1. Involved with a project at the time of inception.
  2. Involved in the Functional analysis (FA) of developing the initial requirements.
  3. Remain involved throughout the balance of the project.
  4. Should have hands-on experience in multiple industries and across several disciplines
  5. They can master a variety of hardware platforms including distributed platforms, desktops, and mobile devices.
  6. A broad and deep understanding of Databases is also required.
  7. Akin to that they should also possess skill and understanding of a variety of Operating Systems
  8. Solutions Architects decide which technologies to use.
  9. They work very closely with developers to ensure proper implementation.
  10. They are the link between the needs of the organization and the developers.
  11. A solutions architect must have a balanced mix of technical and business skills.

Solution Architecture in larger organization:

Solution Architects in large organizations often act as the bridge between Enterprise Architects and Application Architects.

  • An enterprise architect’s deliverable s are usually more abstract than a solution architect’s deliverable s. But that is not always the case, and the main distinction between enterprise architect and solution architect lies in their different motivations.
  • The enterprise architect is primarily employed in the design, planning and governance of strategic and cross-organizational rationalization or optimization of an enterprise’s services, processes or components.
  • The solution architect is primarily employed to help programmer and project managers in the design, planning and governance of implementation projects of any kind.

When the solution architect starts and stops depends on the funding model for the process of solution identification and delivery.
E.g. An enterprise may employ a solution architect on a feasibility study, or to prepare a solution vision or solution outline for an Invitation to Tender. A supplier may employ a solution architect at “bid time”, before any implementation project is costed or resourced. Both may employ a solution architect to govern an implementation project, or play a leading role within it.

Next I will be posting what exactly the role and responsibility of a Java Solution Architect and what are the skills he/she should.

 

Categories: Software Solutions

INSTALL ORACLE JAVA 7 IN UBUNTU 12.10

To install Java in Ubuntu/Linux  open Terminal (Press Ctrl+Alt+T) and copy the following commands in the Terminal:

  • sudo mkdir -p /usr/local/java

For 32-bit users:

  • wget -O jre-32bit.tar.gz http://goo.gl/5UycT
  • wget -O jdk-32bit.tar.gz http://goo.gl/YPKJz
  • sudo -s cp -r jre-32bit.tar.gz /usr/local/java
  • sudo -s cp -r jdk-32bit.tar.gz /usr/local/java
  • cd /usr/local/java
  • sudo -s tar xvzf jre-32bit.tar.gz
  • sudo -s tar xvzf jdk-32bit.tar.gz

For 64-bit users:

  • wget -O jdk-64bit.tar.gz http://goo.gl/MSzBj
  • wget -O jre-64bit.tar.gz http://goo.gl/yZgjI
  • sudo -s cp -r jre-64bit.tar.gz /usr/local/java
  • sudo -s cp -r jdk-64bit.tar.gz /usr/local/java
  • cd /usr/local/java
  • sudo -s chmod a+x jre-64bit.tar.gz
  • sudo -s chmod a+x jdk-64bit.tar.gz
  • sudo -s tar xvzf jre-64bit.tar.gz
  • sudo -s tar xvzf jdk-64bit.tar.gz

Now you need to enter these command (both 32-bit and 64-bit users):

  • sudo nano /etc/profile

Add the following lines at the end of file:

JAVA_HOME=/usr/local/java/jdk*
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
JRE_HOME=/usr/local/java/jre*
PATH=$PATH:$HOME/bin:$JRE_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

Copy above lines and to paste in terminal (Press Ctrl+Shift+V) and to save file using nano (Press Ctrl+O) then (Press Ctrl+X) to exit from file.

Now enter following commands one by one in terminal:

  • sudo update-alternatives –install “/usr/bin/java” “java” “/usr/local/java/jre1.7.0_12/bin/java” 1
  • sudo update-alternatives –install “/usr/bin/javac” “javac” “/usr/local/java/jdk1.7.0_12/bin/javac” 1
  • sudo update-alternatives –install “/usr/bin/javaws” “javaws” “/usr/local/java/jre1.7.0_12/bin/javaws” 1
  • sudo update-alternatives –set java /usr/local/java/jre1.7.0_12/bin/java
  • sudo update-alternatives –set javac /usr/local/java/jdk1.7.0_12/bin/javac
  • sudo update-alternatives –set javaws /usr/local/java/jre1.7.0_12/bin/javaws
  • . /etc/profile

Check installed java version:

  • java -version

 

That’s it, Enjoy!!!

 

 

Categories: Java, JDK7, LINUX, UBUNTU
%d bloggers like this: