Pages

Monday, October 28, 2013

Bundling single or multiple ear using assembly plug-in - How to use maven dependency set

Our application consists of multiple EAR's online, batch etc.
We faced a situation where we need to bundle multiple ear's, db scripts and property
files to make a delivery. I searched for creating an assembly descriptor but could not
find exact details on how to do it. After couple of days of browsing and trial and
error I figured out a way.

For example your application contains appl-1-ear (version - 1.0),appl-2-ear (version 2.0),
db-scripts.zip (0.0.1), properties.zip (0.0.10). You need to create a pom file which contains the
versions you want to include in your final delivery.

The advantage of this approach is, you can deliver your compoents and just declare the versions in
your delivery pom to create a final delivery. Even if it is not multiple ear's, but you have to
bundle various versions of db scripts with different versions of application this approach will
come handy.

You need to create a pom file something like below. Here declaring the type as ear is important because
by default maven searches for Jar extension for the given version number.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ravi</groupId>
    <artifactId>appl-delivery</artifactId>
    <version>0.0.2-SNAPSHOT</version>
    <packaging>pom</packaging>
<dependencies>
    <dependency>
<groupId>com.ravi.presentation</groupId>
<artifactId>appl-1-ear</artifactId>
<version>1.o</version>
<type>ear</type>
    </dependency>
   <dependency>
<groupId>com.ravi.batch</groupId>
<artifactId>appl-2-ear</artifactId>
<version>1.0</version>
<type>ear</type>
    </dependency>
<dependency>
<groupId>com.ravi.properties</groupId>
<artifactId>properties</artifactId>
<version>0.0.10</version>
<classifier>archive</classifier>
<type>zip</type>
</dependency>
<dependency>
<groupId>com.ravi.dbscripts</groupId>
<artifactId>db-scripts</artifactId>
<version>0.0.1</version>
<classifier>archive</classifier>
<type>zip</type>
</dependency>
  </dependencies>
 <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2-beta-2</version>
                <executions>
                    <execution>
                        <id>bundle-project-sources</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <descriptors>
<descriptor>assembly.xml</descriptor>
 </descriptors>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

your assembly descriptor will look something like this

<assembly>
    <id>archive</id>
    <formats>
        <format>tar.gz</format>
    </formats>
    <dependencySets>
    <dependencySet>
        <includes>
            <include>com.ravi.batch:*:EAR</include>
<include>com.ravi.presentation:*:EAR</include>
<include>com.ravi.properties:*:zip</include>
<include>com.ravi.dbscripts:*:zip</include>
        </includes>
        <!--<useProjectArtifact>true</useProjectArtifact>-->
        <outputDirectory>bin</outputDirectory>
<outputFileNameMapping>
                ${artifact.artifactId}.${artifact.extension}
         </outputFileNameMapping>
        <unpack>false</unpack>
    </dependencySet>  
</dependencySets>
</assembly>

Monday, October 21, 2013

Step by step guide to create a Spring Message Driven Pojo - Spring MDP

In your spring application you may have a requirement to listen to the incoming messages. This can be easily achieved by Spring MDP (Spring Message Driven Pojo). When you are doing for the first time, you will face few issues and it will take some time. I went through that problem so thought of documenting it.

Create a sample message listener class which implements the MessageListener interface. This interface has the onMessage method which has to be implemented by the class. Here it is just simply prints a message to the console.

import javax.jms.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SampleMessageListener implements MessageListener {
 private static final Logger logger = LoggerFactory
   .getLogger(SampleMessageListener .class);
 @Autowired
 MessageHandler Handler;
 public void onMessage(Message message) {

  logger.info("Message received ..");
  try {
System.out.println("Message received..");
  } catch (Exception ccEx) {
   logger.error("Processing  failed :" + ccEx);
   throw new RuntimeException(ccEx);
  }
 }
}

Next the spring context file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jms="http://www.springframework.org/schema/jms" 
 xmlns:jee="http://www.springframework.org/schema/jee" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/jms
                           http://www.springframework.org/schema/jms/spring-jms.xsd
                           http://www.springframework.org/schema/jee
                           http://www.springframework.org/schema/jee/spring-jee-3.0.xsd>

 <context:component-scan base-package="com.ravi.jms" />
 <context:annotation-config />

 <!-- JMS config -->
 <bean id="sampleMessageListener" class="com.ravi.jms.SampleMessageListener" />
 <jee:jndi-lookup id="sampleConnectionFactory" resource-ref="true" jndi-name="jms/Sample_CF" />
 <jee:jndi-lookup id="sampleQueueName" resource-ref="true" jndi-name="jms/sampleIncomingQ" />

 <bean id="sampleMessageListenerContainer"
  class="org.springframework.jms.listener.DefaultMessageListenerContainer">
  <property name="connectionFactory" ref="sampleConnectionFactory" />
  <property name="destination" ref="jms_acknack_queueName" />
  <property name="messageListener" ref="recievedAckNackMessageListener" />
  <property name="sessionTransacted"  value="true"></property>
  <property name="recoveryInterval" value="300000"></property>
 </bean>
</beans>

Web.xml of the application. The resources (Queue connection factory and queue) has to be defined here.

<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <display-name>Sample Application</display-name>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
 </context-param>
 
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <servlet>
  <servlet-name>MyDispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>MyDispatcherServlet</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 
 <resource-ref id="ResourceRef_001">
  <description>The QueueConnectionFactory for the service</description>
  <res-ref-name>jms/Sample_CF</res-ref-name>
  <res-type>javax.jms.QueueConnectionFactory</res-type>
  <res-auth>Container</res-auth>
  <res-sharing-scope>Shareable</res-sharing-scope>
 </resource-ref>
 
 <resource-ref id="ResourceRef_002">
  <description>The Queue for the service</description>
  <res-ref-name>jms/sampleIncomingQ</res-ref-name>
  <res-type>javax.jms.Queue</res-type>
  <res-auth>Container</res-auth>
  <res-sharing-scope>Shareable</res-sharing-scope>
 </resource-ref>
</web-app>


If you are deploying in websphere you need the ibm-bnd.xmi file also.

<?xml version="1.0" encoding="UTF-8"?>
<webappbnd:WebAppBinding xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"
xmlns:webappbnd="webappbnd.xmi" xmi:id="WebAppBinding_1238927070062"
virtualHostName="default_host">

  <webapp href="WEB-INF/web.xml#WebApp_ID"/>

  <resRefBindings xmi:id="ResourceRefBinding_001" jndiName="jms/Sample_CF">
    <bindingResourceRef href="WEB-INF/web.xml#ResourceRef_001"/>
  </resRefBindings>

  <resRefBindings xmi:id="ResourceRefBinding_002" jndiName="jms/sampleIncomingQ">
    <bindingResourceRef href="WEB-INF/web.xml#ResourceRef_002"/>
  </resRefBindings>  
</webappbnd:WebAppBinding>

Spring - Eclipse - Mavens - Issues and How to Resolve them

Issue - Spring Application not loading/starting in Eclipse Tomcat

Sometimes for strange reason, your Spring application won't be loaded by Tomcat. If you start the tomcat server, instead of loading the spring context file configured in the web.xml, the server just starts and you wont see anything specific to your application in the log file.

The issue is because of Maven configuration. Just select the web project, right click and then Select Maven. In Maven you will find the option to Update project. Just do that. Now the application should be starting like a charm in Eclipse. Select the project > Maven > Update Project


Issue - Where Eclipse keeps/explodes the Web application

It is very handy to know when you install the application on the Tomcat running in Eclipse, where exactly it
explodes the war file. Some times, you deployed the application but still the application not starting properly or you are facing some weird issues during the start-up like class not found exception when you know for sure the jar is there in the class path. Sometimes it is problem with exploding the application. You can go and see what is the problem in exploding the application.

Double click on the server where you installed the application and it should bring the overview screen of the server. There you can see the server path something like this .metadata\.plugins\org.eclipse.wst.server.core\tmp1. You should append your work space location. For example if your workspace is c:\1\workspace then the server explodes your application content in c:\1\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps. You can see your application folder in this location. You can go and see in your application lib directory you have the jar file you are looking for.

Sunday, October 13, 2013

Step by step guide to setup Cassandra and cqlsh in windows

Today I started to play with Cassandra by installing it in my windows machine. Though the instructions in the cassandra download site is clear and precise, I faced few issues in setting it up. So I thought of sharing the information for fellow developers.

Step 1: Download Cassandra from http://cassandra.apache.org/download/. The current latest version is 2.0.1. It is a tar.gz file. Download and extract it in some location in your machine. For example C:\3\apache-cassandra-2.0.1

Step 2: You can start cassandra server by calling cassandra.bat available with in the bin directory. It should startup the Cassandra server (Note: You should have Java home environment variable set to start the server)

Step 3: Now to interact with Cassandra database you need the cqlsh interactive command tool. Here is the small twist. There is none in the cassandra download package. So there is a work around we should do before adding records to the database.

3a) Download python from the below location http://www.python.org/download/releases/. Be careful here. Though the python latest version is 3.x, there is problem with installing thrift library with the latest version of Python. So download and install 2.7 version of Python.
3b) Install Thrift library by downloading it from the below location http://pypi.python.org/pypi/thrift. Install thrift module by executing the below command python setup.py install

If the python version not supported you may get this error . Revert back to version 2.7.x version of Python and then it should run like a charm

Step 4 : Now you should install cql module for python which is available with in cassandra download.  The setup.py file is available in the below location C:\3\apache-cassandra-2.0.1\pylib. Again run the command python setup.py install. 

Step 5:  Now you can run the command python cqlsh localhost 9160 and it will start the cql interactive command.  Here you can start issuing the commands llike keyspace creation etc.

CREATE KEYSPACE mykeyspace WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };

CREATE TABLE users (user_id int PRIMARY KEY,  fname text,  lname text);

INSERT INTO users (user_id,  fname, lname) VALUES (1745, 'john', 'smith');
INSERT INTO users (user_id,  fname, lname)  VALUES (1744, 'john', 'doe');
INSERT INTO users (user_id,  fname, lname)  VALUES (1746, 'john', 'smith');


Sunday, September 1, 2013

Big data - how do organizations choose

Big data is the recent buzz word in the market and many organizations are looking at it to understand what kind of benefits it can provide to their business. Logically speaking, the amount of data generated by any business is huge and analyzing that should provide more insights in to data about your business.

It is important to understand and create use cases relevant to your business before you start embarking on the big data journey as every vendor has a big data product and charging hefty license fees for using the software. Initially big data came in to the picture when search engine providers like google, ask.com needed to store vast amount of web page information to enable searching. When social media started to become mainstream websites like Facebook, twitter & you tube started generating terabytes of data and to store that kind of information some different type of databases were needed. That is how big data came in to prominence and now it is an important technology to solve many different types of issues.

The typical use cases for big data

Big data alone can't do anything apart from providing an infrastructure to store huge amount of data but together with analytics solutions, it can make a big impact. The typical usecases i saw are

For Retail segment

How customers use the business website. For example, websites like amazon.com, continuously monitor how the users use their website and if the customer quit the buying process they need to know why & what happened. So they track each and every user, the demographic area of the user, the browsing history for their website etc and this information is analyzed to see the trend. Say for example, more people are getting in to the buying process after seeing a promo on shoes on the first page but during payment, they are not able to pay with Visa card so they are quitting the process. So amazon can find this out by capturing, storing and analyzing this information.

Personalized content

By tracking the customer usage of the website, they can change the content, look and feel of the website to customer's preference. For example, if customer is searching for books mainly in the website, when he visits the site next time, all the books promos will be made visible to the user so that he can be enticed to buy the books.

Cross selling and up selling

Cross selling is selling different type of products to the customer related to the one he already bought. For example, if the customer is searching for TV and bought it, showing all the accessories related to TV (for example, TV stand, DVD's etc) and making the customer to look at them by providing compelling cost reductions.

For Banking and Financial segments

The above use cases mentioned for retail segment also applicable for banking and financial sector as well. However I am not really convinced that we can bring same kind of impact like a retail business because many of the banking products has to be still bought in branch and not in online. However I do see the below use cases

Risk assessment and fraud detection

Banks generate huge volumes of transaction data and for fraud detection it is important to analyse this data. The current model is to use standard data ware house based solution but with increase in data volumes it will become necessary to use different type of technology and big data and analytic for sure is going to be the future technology stack for this kind of analysis.

How to choose big data vendor or solution provider

This field is still emerging and there is no set of standard best practices on choosing a big data vendor. These are the points I think should be considered for selecting a big data solution provider. The important consideration is always about the licensing costs and support.  The other factors to consider are

1) Define the important use cases for the business and check ability to support these use cases
2) Maturity of the solution stack
3) How easy is to integrate with other technology investments
4) Case studies and other implementations
5) Future road map and support
6) Ability to support multi channel and integration with social media


Saturday, August 17, 2013

Learnings of the first time scrum master

Agile is becoming the de facto standard for enterprise application development. I also decided to join the band wagon so I joined a agile project as a developer with only theoretical knowledge about the agile programming. The team had 3 more developers, 2 testers, 2 BA's (one of them appointed as the product owner by the business) and a project manager. The scrum master managed some other projects as well so he could not spend enough time on this project and I was asked to do scrum master role which I accepted very reluctantly because no one in the team knows agile but for organizational reasons the project is called agile project.

From the beginning the project had many issues. We have used JIRA to track user stories but since the product owner had no idea about agile or how to use JIRA, his user stories tend to be one liners like implement security, implement web service, etc. We had user requirements documents for front end (which details the various requirements, screen mock ups, validations etc), requirements for batch process,
interface specs for web services in word documents etc. Worst of all, we had very tight dead line 6 months as well for the project development. The project manager is a good guy but very soft and also don't know about agile so we had very hard time deciding the scope of the sprint, implementing it and demoing it. After some time it became clear the project is not going well and we are not going to meet the deadlines.
The issue has been escalated to the program manager and he stepped in. The project became smooth in couple of sprints.

He didn't do anything magical but some how he brought the project back on track.

Determine the size of the project:

Determining the size of the project is very important activity. We didn't know how to do it because the requirements catered in various places (JIRA, various requirements documents, white boards, excel sheets, as defects in QC). The first activity to be done is consolidate everything in one excel sheet by listing down all the requirements and creating sub tasks where possible for each requirement. If you don't know the sub-task leave it as it is. Then do a T-shirt planning. You give size for each requirement in terms of small, medium, large, XL, XXL. Take a well known and well understood requirement and give a size for that requirement. For example, creating a web service could be medium sized requirement. Relative to this requirement
decide the size of other requirements. At the end of the exercise, you will have number of requirements of various sizes. For example 10 small, 5 medium, 10 large, 2 extra large and 1 XXL. See the team size and amount of time left to complete the activities and you will get a clear idea when you can finish the project. It will give you insight of the actual size of the project. We found out that,with the current strength it will take 8 months to finish the project (we found this 4 months after the project start) So clear indication that team size has to be increased.

The team:

A very important factor for successful agile project. The team should be cross functional and should be able to handle various functional and technical tasks. The team I worked with, compartmentalized things (I will work only in front end, I will work only in the back end) and wont touch the technical items (like deployment, solving complex technical issues) etc

Politics:

IT projects are not always about technical capability but it is also about organizational politics, background and culture of the team and the challenges it brings to the project. In our case the team is mixture of developers from two different vendors so there was some tension, also the PM and Product owner are internal employees of the organization so they were not too much worried too much about the project status.

Decision Making:

The major hurdles in any IT project is also about the decision making. The stakeholders take too much time to take decisions.Technical architect thinking about whether to use Queue's or Web services, business owners thinking this way or that way. Decisions has to be made after careful considerations but there should be deadline for every decision. If the project manager or scrum master is not able to force the decisions it impacts the team velocity and at the same time, affects the morale of the team because there are simply too many loose ends and too many user stories not completed and pending in various stages. The scrum
master should be able to speed up the decision making and if not possible escalate to the right level to get things moving. Same process applicable for other dependencies (environments set up, services to external systems) deadlines have to be agreed and if not honored has to be escalated and get it done for smooth progress.

Honest feedback to the team members:

The team members though senior people, still make mistakes in terms of creating quality code, solving technical issues. One of the team members code is very bad in terms of quality, no junits & too many defects. Other team member took too much time to solve even trivial issues which should be very simple for a developer with 10 years experience. As a scrum master and with different cultural background, I tend not to discuss the issues with them but try to solve the issues by myself which turned out to be very difficult after some time. After the new scrum master came in, this developer was kicked out immediatly and the
other developer was warned. I should have spoke to these guys and asked them to improve or move out. I didn't have the confidence to do the same. I have spent long nights trying to correct the mistakes others did which is not good in the long term.

The summary of the learning's

1) Set up a good team with good technical people. Strong manager and strong scrum master is essential for team success.
2) Understand the size of the project using appropriate methods (T shirt planning for example) and see whether the team has the capacity to meet the deadlines
3) In agile team though every one is equal, The scrum master and project manager are more equal than the rest of team. They should
1) Control the team and give honest feed back to the team
2) If team member not improving, don't hesitate to replace the team members
3) Identify the impediments and resolve the impediments in reasonable time frames
4) escalate to the right levels and get the impediments out of the way on time for the team to continue
4) Understand the underlying organizational politics and subtle issues and make sure that is not impacting the velocity of the team. If not resolved
1) Teams will be divided and each one will be working as silos not knowing what others are doing
2) Team not jelled well, take more time to complete the tasks because of communication issues
3) Dont hesitate to change the team in case above approaches not working.








Saturday, June 29, 2013

Spring MVC - Utility Project To Download files - Access log files from restricted environments

In development as well as maintenance projects you may have to access the log files to see what went wrong. However in some environments the developers may not have access to these log files. The developers has to request for these log files and it is a time consuming process. So if accessing log files implemented as part of the application itself it will save lot of time for the development team members.

However please note, this functionality should be used only when it is appropriate.

Technologies & Tools used

1. STS
2. Maven

Step 1:

Create Spring MVC project using the steps given here

Step 2:

Add showLogs and handleFileDownload method as shown below.

1:  package com.ravi.springmvc;  
2:  import java.io.File;  
3:  import java.io.FileInputStream;  
4:  import java.text.DateFormat;  
5:  import java.util.Date;  
6:  import java.util.Locale;  
7:  import javax.servlet.http.HttpServletResponse;  
8:  import org.slf4j.Logger;  
9:  import org.slf4j.LoggerFactory;  
10:  import org.springframework.stereotype.Controller;  
11:  import org.springframework.ui.Model;  
12:  import org.springframework.util.FileCopyUtils;  
13:  import org.springframework.validation.BindingResult;  
14:  import org.springframework.web.bind.annotation.ModelAttribute;  
15:  import org.springframework.web.bind.annotation.RequestMapping;  
16:  import org.springframework.web.bind.annotation.RequestMethod;  
17:  import org.springframework.web.servlet.ModelAndView;  
18:  /**  
19:   * Handles requests for the application home page.  
20:   */  
21:  @Controller  
22:  public class HomeController {  
23:       private static final Logger logger = LoggerFactory  
24:                 .getLogger(HomeController.class);  
25:       @ModelAttribute("logFile")  
26:       public LogFile getLogFile() {  
27:            return new LogFile();  
28:       }  
29:       /**  
30:        * Simply selects the home view to render by returning its name.  
31:        */  
32:       @RequestMapping(value = "/", method = RequestMethod.GET)  
33:       public String home(Locale locale, Model model) {  
34:            logger.info("Welcome home! The client locale is {}.", locale);  
35:            Date date = new Date();  
36:            DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,  
37:                      DateFormat.LONG, locale);  
38:            String formattedDate = dateFormat.format(date);  
39:            model.addAttribute("serverTime", formattedDate);  
40:            return "home";  
41:       }  
42:       @RequestMapping("/showlogs")  
43:       public ModelAndView showLogs() {  
44:            return new ModelAndView("logs", "command", new LogFile());  
45:       }  
46:       @RequestMapping(value = "/logs")  
47:       public void handleFileDownload(@ModelAttribute("log") LogFile log,  
48:                 BindingResult result, HttpServletResponse res) throws Exception {  
49:            try {  
50:                 String fn = log.getLogFileLocation();  
51:                 File f = new File(fn);  
52:                 System.out.println("Loading file " + fn + "(" + f.getAbsolutePath()  
53:                           + ")");  
54:                 if (f.exists()) {  
55:                      res.setContentType("application/text");  
56:                      res.setContentLength(new Long(f.length()).intValue());  
57:                      res.setHeader("Content-Disposition",  
58:                                "attachment; filename=Test.log");  
59:                      FileCopyUtils.copy(new FileInputStream(f),  
60:                                res.getOutputStream());  
61:                 } else {  
62:                      System.out.println("File" + fn + "(" + f.getAbsolutePath()  
63:                                + ") does not exist");  
64:                 }  
65:            } catch (Exception e) {  
66:                 System.out.println(e.getMessage());  
67:                 throw e;  
68:            }  
69:       }  
70:  }  

Step 3

Add the JSP file which allows the user to download to specific log file.

1:  <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
2:  <html>  
3:  <head>  
4:       <title>Spring 3 MVC - Log Manager</title>  
5:  </head>  
6:  <body>  
7:  <h2>Log Manager</h2>  
8:  <form:form method="post" action="logs.html">  
9:       <table>  
10:       <tr>  
11:            <td><form:label path="logFileLocation">Log File Location</form:label></td>  
12:            <td><form:input path="logFileLocation" /></td>   
13:       </tr>  
14:       <tr>  
15:       </tr>  
16:       <tr>  
17:            <td colspan="2">  
18:                 <input type="submit" value="Fetch Log"/>  
19:            </td>  
20:       </tr>  
21:  </table>       
22:  </form:form>  
23:  </body>  
24:  </html>  

Step 4

Run the application and the application can be accessed in the url http://localhost:8080/springmvc/showlogs


Step 5

Your log files will be downloaded as shown below.










This tutorial is for illustration purposes only. Do not use this in real life scenario without adding specific security measurements as this application will allow you to download all the files for which the user has access to.
 
Blogger Templates