Wednesday, September 10, 2014

Oracle ATG commerce integration with Endeca search

     Exploring new software and tool is always exciting and fun way to learn new stuff. With ATG Commerce v11 Oracle has replaced ATG Search with Endeca search.  I have tried to list out all the steps involved in this integration and focused to highlight the issues/errors I faced with their resolutions. So lets dive in -  

   Installation requirements with download links –
a.      Download and install Java 7 or higher,  I am using jdk 7 update 45 , set the environment variable ( JAVA_HOME = D:\Java\jdk1.7.0_45 )
b.     Install application server of your choice – I have used JBoss Enterprise Application Platform - Version 6.1.0.GA  , you can Download from Jboss site.

c.      Installing Oracle XE 11g  - Download from Oracle website and accept all the default settings.
After you install Oracle XE then create following schemas which will be used at the time of ATG configuration via CIM.

create user crs_switching_a identified by crs_switching_a;
grant connect, resource, dba to crs_switching_a;

create user crs_switching_b identified by crs_switching_b;
grant connect, resource , dba to crs_switching_b;

create user crs_publishing identified by crs_publishing;
grant connect, resource,dba to crs_publishing;

create user crs_production identified by crs_production;
grant connect, resource,dba to crs_production;

commit;

You also need JDBC driver jar , this will be needed later when we do Database configuration in CIM. You can download the jar from Oracle site. I am using ojdbc6.jar , you can use higher versions as well.

d.     Go to https://edelivery.oracle.com and download ATG frameworks and Endeca frameworks (version 11.1)
Downloads for ATG –
Oracle Commerce Platform 11.1
Oracle Commerce ReferenceStore 11.1

Downloads for Endeca search –
Oracle Endeca MDEX Engine 6.5.1
Oracle Endeca Platform Services 11.1.0
Oracle Endeca Tools and Frameworks 11.1.0
Oracle Endeca Content Acquisition System 11.1.0

     Installing Endeca Commerce with Experience Manager  -
Goto http://docs.oracle.com/cd/E51272_02/Common.110/pdf/GettingStarted.pdf  and follow instructions given in chapter 3 and chapter 5 in this guide for Endeca installation and configuration.
Please note we are installing Endeca first as its not dependent on ATG installation. We want to make sure Endeca is working fine before moving to ATG installation and configuration.
You can avoid Developer studio installation as its not needed for this integration.

After a successful installation you can see following services installed. Make sure all 3 Endeca services are started as shown below.



You will also see following folders in your d:\Endeca folder after all Endeca related installation.



Time to validate our Endeca installation – If you have followed all the instructions then your Discover Electronics reference is ready to validate.
Visit - http://localhost:8006/discover/  and you should see the below page


Note: To see workbench screen goto http://localhost:8006/

Installing ATG commerce and reference st -
Now we need to install ATG platform first and then reference store . Visit this link http://docs.oracle.com/cd/E41069_01/CRS.11-0/ATGCRSInstall/html/s0101introduction01.html   for step by step installation guide. 

During installation setup will ask for Jboss and Java path – Specifiy your local folder path where you have installed them. Please note the port I have used here is 8180. 


Just to mention, I have avoided using 8080 as Oracle XE is listening to this port so avoid using.
I am using following ports throughout all installations and configurations here.
8180 for Store
8280 for Publishing
8380 for SSO

Dont forget to set environment variable DYNAMO_HOME = D:\ATG\ATG11.1\home

 Configuring ATG environment using CIM  -
Once ATG platform and CRS installation is completed in step # 3 then we need to launch CIM.  Open a command prompt , navigate to D:\ATG\ATG11.1\home\bin  and run cim.bat
Here mainly you are going to configure following items – I suggest you follow CIM response given in any of the two links provided in the Reference section below. It has all the detailed CIM responses.
  • Set the Administrator Password
  • Product Selection – select 9 as it will select all essentials items to install. further  in AddOns choose *** Single Sign On (SSO)  ***
  • Database Configuration
  • Configure OPSS Security
  • Application Assembly and Deployment

After all the above configurations we are left with following –

a.     Start all the server instance like store , publishing and SSO. Use below commands

               D:\jboss-eap-6.1\bin>standalone.bat --server-config=ATGProduction.xml -b 0.0.0.0
               D:\jboss-eap-6.1\bin>standalone.bat --server-config=ATGPublishing.xml -b 0.0.0.0
               D:\jboss-eap-6.1\bin>standalone.bat --server-config=ATGSSO.xml -b 0.0.0.0

b.      You need to perform a full deployment in BCC – follow direct link for this task here - http://docs.oracle.com/cd/E41069_01/CRS.11-0/ATGCRSInstall/html/s0213configuringandrunningafulldeploy01.html
              If you face issues in accessing BCC then check below troubleshoot section for help.

c.       Ideally after successful full deployment the system should build the index. To verify goto http://localhost:8280/dyn/admin/nucleus/atg/commerce/endeca/index/ProductCatalogSimpleIndexingAdmin
and check the indexing job status. If its in PENDING or CANCELLED state then you need to manually invoke “Baseline Index”


d.      Once index is completed we finally need to promote the commerce reference store content . please follow instructions here to invoke promote_content - http://docs.oracle.com/cd/E41069_01/CRS.11-0/ATGCRSInstall/html/s0215promotingthecommercereferencesto01.html

e.     Its time now to finally hit the store URL and explore CRS store - http://localhost:8180/crs/storeus



 Common errors troubleshoot –

  • If you get following error while accessing BCC then read solution –  
      Error /atg/portal/framework/PortalObjectResolver      No root community folder for portal 'default' 
      Solutions – Its due to missing BIZUI data, follow below url and see the last section about 
  • You may encounter ORA-01658 error -
       Error - ORA-01658: unable to create INITIAL extent for segment in tablespace LARGE_ 
       Solution - Its due to the fact that Oracle failed to find sufficient contiguous space to allocate   
       INITIAL extent for segment being created. Visit this link for solution -    
  • If you encounter any connection related error - 
       Error - Caused by: java.sql.SQLException: Listener refused the connection with the following  
        error: ORA-12519, TNS:no appropriate service handler found 
       Solution - I increased timeout setting in the pulishing server configuration, also make sure your  
        DB is up and running.
  • You may not be able to login to BCC until you login to SSO (http://localhost:8380/sso/login) . Make sure you run the SSO instance like you start your store or publishing servers.

           References  -
a.      http://iam-saminda.blogspot.co.uk/2013/06/oracle-ecommerce-atg-102.html  - One of the best written blog which details ATG 10 integration with Endeca search.
b.     http://internetmarketing-readme.pricemaniacs.com/oracle-commerce-v11-step-by-step-cim-responses  - Blog lists all the CIM response for ATG environment configuration using CIM.

Bonus -

> How to check the status of the Endeca Log Server -
Visit - http://localhost:15010/stats

If the Log Server is running, above URL returns a confirmation message containing the file name, number of log entries and number of errors.
If it is not running, you will see browser’s default error message.

OUTPUT -
Endeca log server is running.
log file: D:\Endeca\apps\Discover\logs\logserver_output\LogServer.2014_09_10.17_45_40
number of log entries: 9
number of errors: 0

> Anatomy of an Oracle Commerce Experience Manager Site


Sunday, December 08, 2013

Emerging languages series - Scala



Although my experience in Scala language is limited but in last couple of weeks have read a lot about Scala and its growth over recent years. Coming from Java background and recent demand for Scala has forced me to dig deeper to explore the potential and features of the language.

Scala overview  –
Scala is an acronym for “Scalable Language”. Scala is a statically typed, object oriented functional language, merging two popular programming approaches into one
In other words we can say when Object-Oriented meets Functional then the result is known as Scala. It was built by Martin Odersky at EPFL, launched in 2003.
Scala runs on the JVM. Java and Scala classes can be freely mixed, no matter whether they reside in different projects or in the same.
Java libraries, frameworks and tools are all available. Build tools like ant or maven, IDEs like Eclipse, IntelliJ, or Netbeans, frameworks like Spring or Hibernate all work seamlessly with Scala. Scala runs on all common JVMs and also on Android.
Already used by Twitter, LinkedIn, Yammer, Foursquare, eBay, Amazon , Guardian newspaper and many others

Key features of Scala language  – Scala has a set of features which differ from Java. Some of these are:
All types are objects
Type inference
Functions are objects
Anonymous function
Curried function
Closures
Traits
Domain specific language (DSL) support
Concurrency support inspired by Erlang

Scala comes with an interactive interpreter, the REPL (for Read, Evaluate, Print Loop). After installing Scala, you can start the REPL by entering the command scala in a command prompt or shell window. Visit the Scala download page here. 

You can type statements and expressions at the prompt, and the REPL will evaluate these and print the results. The REPL is a useful tool for experimenting with Scala language features. The REPL understands a number of special commands that start with a colon. Type the command :help to see an overview. Type :quit to exit the REPL.

Compiling and running Scala code –
Before getting into any example please remember you can Compile Scala source files using the Scala compiler, scalac. When you use Scala as a compiled language your code must be organized a little differently than when using it as a scripting language. You’ll need to create a Scala object with a main method, as in the following example.

// HelloWorld.scala
object HelloWorld {
def main(args: Array[String]) {
 println(“Hello World!”)
}
}

Save this in a source file named HelloWorld.scala. Compile it with: scalac HelloWorld.scala and run it with: scala HelloWorld. Note that in this last command, you supply the name of the object (HelloWorld) rather than the name of the source file (HelloWorld.scala) or the compiled class file (HelloWorld.class).


Scala features By Example

Values and variables -
val name: Type = expression    // use to define an immutable value
var name: Type = expression   // use to define a mutable variable

val myVal : Int = 1;
var name = "Sajid"

Tuples -
Tuples are type-safe containers for multiple values. They useful if you want to return more than one value from a method. They are different from collections;
each element in a tuple has its own type, whereas in collections all elements in the collection usually have the same type.

// Defines a tuple with a String and an Int
val tup = (“Hello”, 123)
// The elements of a tuple are named _1, _2 etc.
println(tup._1)
println(tup._2)

// Method that returns a Tuple with two Ints
def div(a: Int, b: Int): (Int, Int) = (a / b, a % b)

// Call the method, use pattern matching to extract the values from the result, throw away the second value
val (x, _) = div(20, 7)


Methods
def name[TypeParams](ParamList1)(ParamList2)(...): ReturnType = {
// Statements and expressions
}

// Here you see return type is inferred and “return” keyword is optional
def add(x:Int, y:Int) = {
  x + y
println(add(42,13))


Default parameters
Parameters may have a default value that is used if a value is not supplied when calling the method.
def greet(name: String = “there”) {
println(“Hello “ + name)
}

Return multiple variables - It is possible to return multiple variables using Tuple
def swap(x:String, y:String) = (y, x) 
val (a,b) = swap("hello","world") 
println(a, b)


Functions –
The difference between a function and a method is that a function is a value (an object) while a method is not. A function is an instance of one of the traits Function0, Function1 etc., depending on the number of parameters that the function takes.

def add(a:Int, b:Int):Int = a + b
val m:Int = add(1, 2)
println(m)

You can convert a method to a function by assigning it to a val or var. However, to avoid ambiguity, you have to either explicitly specify the type of the val or var, or put an underscore after the method name to indicate that you want to treat it as a function.
// A method
def succ1(x: Int) = x + 1
// Explicitly specify the type of succ2
val succ2: Int => Int = succ1
// Or put an underscore after the method name
val succ2 = succ1 _


Higher order functions –
def identity(x: Int) = x
def sqr(x: Int) = x * x
def cube(x: Int) = x * x * x

def sum(f: Int=>Int, a: Int, b: Int): Int =
if (a == b) f(a) else f(a) + sum(f, a + 1, b)

println(sum(identity, 1, 10))
println(sum(sqr, 1, 10))
println(sum(cube, 1, 10))

"sum" is now a "higher order" function, It's first parameter is a function which maps an Int to an Int

The type "Int" represents a simple Integer value. The type Int => Int represents a function which accepts an Int and returns an Int.


Anonymous functions –
A method that requires a function as a parameter  the function's type is (Int,Int) => Int

def sum(f: Int=>Int, a: Int, b: Int): Int =
if (a == b) f(a) else f(a) + sum(f, a + 1, b)
println(sum(x=>x, 1, 3))
println(sum(x=>x*x, 1, 3))
println(sum(x=>x*x*x, 1, 3))

We can create "anonymous" functions on the fly. x => x*x is a function which takes an "x" and returns x*x


Curried functions –
Currying allows to turn a function that expects two arguments into a function that expects only one, and that function returns a function that expects the second argument. Creating basically a chain of functions.

def addA(x: Int, y: Int): Int =
x + y
def addB(x: Int):Int=>Int =
y => x + y
val a = addA(10, 20)
val b = addB(10)(20)
println(a)
println(b)

You can take any function of multiple arguments and curry it.


Traits –
trait Name[TypeParams] extends ClassOrTrait with Trait1 with Trait2 with ... {
// Constructor statements and trait members
}

A trait can extend one class and multiple other traits. A trait can have a constructor (you can put statements in the body of the trait that are executed as part of its constructor), but it cannot have constructor parameters.

Traits are like Java interfaces, except that a trait can be partially implemented. Like a Java interface, a trait cannot be directly instantiated even if it is fully implemented.

trait Car {
  val brand: String
}

trait Shiny {
  val shineRefraction: Int
}

One class can extend several traits using the with keyword:
class BMW extends Car with Shiny {
  val brand = "BMW"
  val shineRefraction = 12
}


Closure –
A "closure" is a function which carries with it references to the environment in which it was defined.
Alternately we can say that closure is a function, whose return value depends on the value of one or more variables declared outside this function. Consider the following piece of code with anonymous function

object Test {
   def main(args: Array[String]) {
      println( "muliplier(1) value = " +  multiplier(1) )
      println( "muliplier(2) value = " +  multiplier(2) )
   }
   var factor = 3
   val multiplier = (i:Int) => i * factor
}

Here  factor has a reference to a variable outside the function but in the enclosing scope.


Functions are ObjectsYes you read it correct J
Probably it might be little difficult to digest it if you coming from Java background. Don’t worry, here comes a golden rule of thumb. The key to scala is that everything is an object. Since every value is an Object in Scala, Functions are Objects, too!

Every Function you’ll ever define in Scala, will become an instance of an Implementation which will feature a certain Function Trait. There is a whole bunch of that Function Traits, ranging from Function1 up to Function22. Wow, and why are there so many? Since Functions are Objects in Scala and Scala is a statically typed language, it has to provide an appropriate type for every Function which comes with a different number of arguments. If you define a Function with two arguments, the compiler picks Function2 as the underlying type. If you define a Function with seven arguments, you’ll end up with Function7. And since there is a maximum up to Function22, that means you can’t define a Function which will accept 23 arguments or more.

new Function1[Int, Int] {
 def apply(x: Int): Int =
 x + 1
}


Patten matching –
Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy.
Here is a small example which shows how to match against an integer value:

object MatchTest1 extends Application {
  def matchTest(x: Int): String = x match {
    case 1 => "one"
    case 2 => "two"
    case _ => "many"
  }
  println(matchTest(3))
}

The block with the case statements defines a function which maps integers to strings. The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object.

Here is a second example which matches a value against patterns of different types:
object MatchTest2 extends Application {
  def matchTest(x: Any): Any = x match {
    case 1 => "one"
    case "two" => 2
    case y: Int => "scala.Int"
  }
  println(matchTest("two"))
}

The first case matches if x refers to the integer value 1. The second case matches if x is equal to the string "two". The third case consists of a typed pattern; it matches against any integer and binds the selector value x to the variable y of type integer.


Finally some of the key benefits of Scala –
  • Scala's case classes and pattern-matching make for very clean code, for example, and Scala traits (like interfaces with implemented methods) can be a very powerful and simple way to "inherit" behaviour without the pain of OO inheritance.
  • Scala's powerful type inference also combines the benefits of a strictly typed language with some of the benefits of dynamic typing in terms of having to write less code yourself.
  • Maintainability e.g. Scala code is often much more concise than Java (with all that boilerplate) and fewer LOC often means fewer places to screw up and less maintenance in the longer term.
  • Access to great Scala libraries e.g. for Collections, as well as to Java's existing libraries.
  • Scalability e.g through the use of Actors for (asynchronous) concurrency instead of threads, or through greater use of immutable data, functional programming etc.
  • Scala's hybrid ability to take advantage of FP and/or OOP as required for the task in hand.
Most people are using Scala on the server, because that's where you can gain the benefit of its scalability. Obviously, you can mix Scala with Java on a JVM server, and use your preferred client-side technology for browser interfaces etc. Scala is also the basis for version 2 of the lightweight Play! framework for web applications (although my understanding is that version 2.x is not currently Java EE compatible). My impression is that there is a growing trend towards looking at using the right language for specific purposes rather than a monolithic "one size fits all" approach.
Twitter is a prominent user and promoter of Scala, while LinkedIn also uses Scala for some applications.

Resources
Download Typesafe Reactive Platform for Scala - http://typesafe.com/platform/getstarted
Scala IDE for Eclipse - http://scala-ide.org/

Java 8 vs Scala: A Feature Comparison

Here’s a nicely written article on InfoQ which goes deep into this comparison and list out some of the key findings. Just to mention Java 8 is going to provide a variety of new language features, with the potential to fundamentally change the way we write applications. Especially the functional programming constructs, such as lambda expressions, can be considered a paradigm shift. This shift provides great new possibilities for more concise, compact and easy to understand code.
If you want to try them out then explore early builds of Java 8 on most platforms.

The best way to find out what a language can do for you is probably to try it out, and best way would be to sign up and learn about Functional Programming Principles In Scala from the language's creator Martin Odersky of EPFL at Coursera. Just check and register for any future date for free course.

Sunday, November 24, 2013

Hybris commerce suite - Insight

Recently started exploring Hybris commerce suite 5.0.4 and have some of the interesting facts to share. So let’s start with basics.

What is [y] Hybris ?
Hybris is one of the upcoming agile and comprehensive commerce suite. Hybris platform is simple and based on open standards like Spring, ZK, SOLR/Lucene, ANT, Groovy, Apache Commons. The hybris commerce suite is engineered for expansion, extension and scale.

How’s the [y] Hybris architecture ?
From business standpoint the hybris Commerce Suite is divided into individual packages, such as Commerce, Content, Channel and Orders. These packages are bundles of functionality assembled for a certain range of business functionality.

From a technical point of view, packages consist of individual modules (aka extensions).
Extensions written by hybris provide standardized functionality and are supported and maintained by hybris.


hybris Commerce Suite is run in a Java Virtual Machine on a Servlet Container or a J2EE-compliant application server (such as IBM Websphere or Oracle WebLogic) and connects to an external database (MySQL, Oracle DB, Microsoft SQL Server). Internal caching and persistence mechanisms allow the hybris Commerce Suite to run on a Servlet Container. A full-fledged J2EE-compliant application server can be used, but is not necessary.


















What are the key Hybris commerce capabilities and features which comes out of the box  ?

General Storefront Capabilities - Language selection , Country selection , Currency selection , SEO frienddly URLs
Product Search - Solr-based product search with Keyword Search , Keyword Autocomplete , Spelling suggestions , Faceted browsing and more
Merchandising
Personalization and Promotion
Catalog Navigation
Product Display
Cart
Checkout
Hosted Payment
Customer Account
Store Location
Content Management
Data Import / Export
Google Local / Google Shopping
Content Pages and Templates
Organization Management
Jirafe Customer Intelligence
Google Analytics
Quote Negotiation
Order Approval
Order Management (OMS)
Store Locator
Device Detection

Lets dig deeper into some of the other concepts which is essential to know –

Hybris Cockpit framework –
The hybris Cockpit framework offers a large number of highly configurable components which can be used to build a new cockpit for your customers needs, such as for example workflow and comments.

The hybris Cockpit framework is the foundation for all hybris Cockpits. It offers a large number of highly configurable components, which can be used to build a Graphical User Interface (GUI) to support high-level business use cases, allowing users to perform all their common tasks quickly and intuitively. The hybris Cockpit framework complements the functionality offered by the hMC, which provides lower-level control over all the data in the hybris system.

The hybris Cockpit framework is based on ZK, a rich internet application (RIA) framework that enables desktop-like GUIs within a web browser. The ZK Framework is also well supported by Spring. ZK delivers a rich set of user interface (UI) components, making it easy and quick for developers to deliver a rich front end experience.

The major features of the hybris Cockpit framework include:
  • Security infrastructure based on Spring security
  • Ready to use front end template
  • Base configuration as a starting point for new applications, based on Spring
  • Reusable front end components in addition to existing ZK components
  • Generic abstraction of persisted items in the front end layer via the Type Service
  • GenericSearch providers
  • Highly customizable front end
  • Automatically stored user interface configuration at application run time
  • Drag and drop functionality
Here’s the key Hybris cockpits listed with brief description -

Hybris Administration Console -  The hybris Administration Console is an administration Web page provided by the hac extension. It provides functionality for administration, monitoring, and configuration of the hybris Commerce Suite.
Hybris Management Console (hMC) - hMC is the administration tool of the hybris Commerce Suite. As part of the hybris Commerce Suite, it runs in web browsers. Using the hMC, you can manage business objects of the hybris Commerce Suite such as products, customer data, orders.

Product Cockpit - The hybris Product Cockpit enables organizations to manage and structure product information and catalogs in high-volume and collaborative environments. Product managers can visualize their input from multiple perspectives and make product management processes more efficient

WCMS Cockpit - The hybris WCMS Cockpit enables you to manage data of a website. For efficient management of information on your online shop, you can use both the catalog perspective and live edit perspective. Each of them provides you with different ways of data management.
In the hybris WCMS Cockpit you can easily do the following:
·         Create and update website pages and content components
·         Check and change website pages status
·         Synchronize catalog versions of your website
·         Create collections of chosen pages
·         Search for website pages, according to advanced criteria

Admin Cockpit - At present, the hybris Administration Cockpit is used for the manipulation of: Data Validation constraints and Instances of types

Customer service Cockpit - The hybris Customer Service Cockpit enables you to quickly and efficiently manage the customer and orders in the call-center environment. 

Report Cockpit - The hybris Reporting Module adds Report Cockpit in which users can create and manage personal Dashboard containing rich graphical report widgets.

Print Cockpit - The hybris Print Cockpit enables you to create the publication structure and to manage the publication data for in an intuitive and user-friendly way. Linked with Adobe InDesign, it is a unique and powerful application.

Lets take closer look at some technical bits –

Adding a new page in Hybris –
  • Create a new page using the cmscockpit and with the available templates(we can also create new templates using the hmc as per the requirement).
  • Add components to the content slots available
  • Create a controller to handle the user requests for the newly created page.
  • Get the request mapping from the request, perform the business logic and return the model and view

Adding a new component in Hybris –
  • Create own item in items.xml file as below
            jaloclass="de.hybris.platform.endeca.jalo.cms2.components.OurComponent">
           //necessary attributes go here.....
  •  Create a new controller OurComponentController.java
      Note: The name of controller is important and should be created as follows: Component Type +"Controller" (in       our case OurComponentController). Beside that we also have to create a representation of our component           ourComponent.jsp

      All the controllers  are defined the way we define beans in Spring MVC in the spring-servlet.xml file as                 mentioned below
  •  Perform the business logic and return the model and view.


Creating new extensions --
The hybris Commerce Suite comes with an extension generator system called extgen located in the ${HYBRIS_BIN_DIR}/platform/extgen/ directory. Using extgen, you can create new extensions based on extension templates.

The hybris Commerce Suite comes with the following extensions, which you can use as a template for new extensions:

yempty
ycockpit
yaddon
ybackoffice
yacceleratorstorefront
yacceleratortest
ycommercewebservices
yinstoreinitialdata
yacceleratorcore
yacceleratorfacades
yacceleratorinitialdata

Extgen prompts you to specify:
  • The extension's name.
  • The extension's Java package.
  • The extension template to use.
After you have provided the prompted values, extgen does the following:
  1. Copying the extension template to a temporary directory.
  2. Modifying the extension template to reflect the specified values.
  3. Copying the new extension from the temporary directory to the directory specified by  the extgen.extension.path property in the project.properties file.
To create a new extension we follow following steps -
  1. Optionally: Modify default values for the extension generation process.
  2. Create a new extension.
  3. Reference the new extension in localextensions.xml file.
  4. Rebuild the hybris Commerce Suite.
  5. Update the hybris Commerce Suite.
Afterwords, you can start implementing your business logic in the new extension.

How to get started with Hybris ?
Best to register at https://wiki.hybris.com and get started. As of now they only allow certain partner companies to register so please check with your organization.
Once you registered at their wiki then you can access the product documentation.

I would highly recommend doing the Hybris core and commerce Trails. They are logically sequenced and it helps to understand overall product features and capabilities. Make sure you are good with Spring framework fundamentals , Annotations and ant commands.



Final thoughts ... No deny that Hybris has put great efforts to bring a light weight agile commerce framework which seems very promising. Best part is it cuts lot of development time to build some of the common features in a commerce site in no time, Their modular approach and open stack also gives you enough choice to pick and chose as per your need. It will be interesting to see how their future releases fair. I am yet to see how it scales and perform in a high volume and high transaction environments.

Sunday, November 10, 2013

Emerging languages series - Groovy

Our favorite Java is getting some serious competition in recent years , It seems there are more than 200 languages that target Java platform.
There is growing interest in languages like Scala, Groovy , Clojure , JRuby, Jython for their features and simplicity. Out of this lot we will take a close look at Groovy today as its getting wide attention in the market over recent years.

Why Groovy ?
  • Groovy is more or less a superset of Java
  • Builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
  • Could seamlessly switch back and forth between Java and Groovy 
  • Considered simpler and easier to learn over Jython and JRuby
  • Groovy has Java-like syntax and hence the learning curve is not steep.
  • Simplifies testing by supporting unit testing and mocking out-of-the-box

Once you install Groovy, you could straightaway start programming in Groovy,  just put your Groovy jar file along with your application and get the program working in any machine.
There are many online editors and IDE plugin available to compile and run your Groovy code.

So what is Groovy ?
James Strachan conceived the idea of Groovy language and started development in 2003.
Groovy is a dynamic language that dynamically compiles the code to the Java platform. It is popular as a scripting language and also widely used for unit testing Java code. Groovy is open source (Apache v2 license) and is backed by VMware.
The current stable release is Groovy 2.2. You can use Groovy in most common operating systems like Linux, Windows, and Mac. 

Let’s see how Groovy looks better Java with few examples –

Hello World Example –

// Java
class HelloWorld {
public static void main(String []args) {
System.out.println("Hello world");
}
}

// Groovy
println("hello world")


More Detailed Examples –

Let’s take a look at collection (map) processing example. Lets create a map and do some processing in both Java and Groovy.

// Java
Map worldCapitals = new HashMap<>();
worldCapitals.put("England", "London");
worldCapitals.put("Japan", "Tokyo");
worldCapitals.put("France", "Paris");
worldCapitals.put("Italy", "Rome");
worldCapitals.put("USA", "Washington");
for(Map.Entry capital : worldCapitals.entrySet()) {                       
System.out.printf("%s => %s \n", capital.getKey(), capital.getValue());
}

// Groovy
def worldCapitals =   [ "England" : "London",
"Japan" : "Tokyo", 
"France" : "Paris",
"Italy" : "Rome",
"USA" : "Washington" ]
worldCapitals.each {
key, value ->  
println "$key = $value" 
}

In this case Groovy provides a simple array-like syntax for the Map data structure. See how use of each() method closure makes it simple to write the code.

We all know how we write custom code to sort a map by value in Java but the same can be achieved in a line with Groovy. See below -

def sortedMap = worldCapitals.sort { it.value }
sortedMap.each {
key, value ->  
println "$key => $value" 
}

In above Groovy code, we just passed the it.value (current iterator’s value) to the sort method. With the power of closures, the code became much simple and readable.
Groovy provides a higher-level abstraction to this functionality, and hence the code is much simpler.

Tip - The soon to be released Java 8 has also introduced concept of closures in form of  "lambda expressions". It will be interesting to see how Java is incorporating these new age language features in their new release. I will write separate post to cover Java 8 features and capabilities soon.

XML Generation Example -
In general it’s very common to generate structured output like HTML , XML or JSON in Java code. So let’s see one example around this piece.

// java
PrintWriter pw = new PrintWriter(new FileWriter("/capitals.xml"))
pw.println("");
for(Map.Entry capital : worldCapitals.entrySet()) {                  
pw.printf("\t \n \t\t '%s' \n \t \n", capital.getKey(), capital.getValue());
}
pw.println("
");


// Groovy
def capitals =   [ "England" : "London",
"Japan" : "Tokyo", 
"France" : "Paris",
"Italy" : "Rome",
"USA" : "Washington" ]

xmlbuilder = new groovy.xml.MarkupBuilder()
xmlbuilder.worldcapitals {
capitals.each {
key, value ->
country(name:key) { capital(value) }
}
}

Now just see how simple it is to do the same thing with Groovy with lot of readability. Groovy supports builders (based on Builder design pattern) for creating HTML and XML files.

Take away from this comparison -
  • Traversing a data structure is easy in Groovy - you can use “closures” instead of plain loops and use each() method. 
  • Groovy is high on meta-programming and regular expression handling capabilities.
  • Groovy builders are fabulous if you dealing with HTML , XML , JSON etc.
  • Better for productivity and code readability for sure
  • Being a dynamic language Groovy is an excellent candidate for creating DSLs (Domain Specific Languages)

We have just tried to explore few basic features of Groovy here. You should explore further programming improvements such as automatic check for nulls, helper methods, embedded expressions in strings, and operator overloading. One should also explore its meta-programming and regular expression handling capabilities.
You’ll find Grails web framework and Groovy Server Pages (GSP) interesting if you are a serious web-developer. If you are an admin, you may find Gradle build automation framework useful. Grails framework (that is similar to Ruby on Rails) is built on top of powerful and popular frameworks such as Spring and Hibernate.
Resources to learn further –
Programming Groovy 2 - Dynamic Productivity for the Java Developer, By Venkat Subramaniam
Groovy in Action, By Dierk Koenig, Andrew Glover, Paul King, Guillaume Laforge, Jon Skeet

If you are a developer, tester or script guru, you have to love Groovy. So keep grooving and have fun with it !!

Popular Posts