Google

Oct 23, 2014

Debugging and working like a pro with a Java application tutorial with eclipse IDE

Often you get to work on a fully functional Java application that is already in production to fix production issues or to enhance its existing functionality. As a new Java developer in the team, it is not easy to get started and contributing. The approach would be slightly different from working on a brand new project. Here are a few tips that will help you hit the road running as quickly as possible.

This post will also help you answer a common developer interview question --

Q. How will you hit the road running fast on an enhancement or a bug fix task of a large  existing application with 1000+ artifacts?
A. Key terms are: Setting up the environment, familiarizing with the app, reverse engineering, impact analysis, monitoring the logs, and collaborating  with the team members and knowledge transferring.

Step #1: Firstly, you need to get the application running locally in your development environment. So, with the help of your existing team members and online documentation provided via the internal wiki or confluence page you need to set up your development environment to run the application.
  1. Get all the Java tools required like Java, Maven, eclipse IDE, Tomcat/JBoss Server, tex editor like Notepad++, ssh emulator like putty/cygwin/mobaXterm/MSYS, tortoise SVN, etc
  2. Set up your Java and Maven locally
  3. Checkout the relevant Java projects from a code repository like Subversion (aka SVN).
  4. Set up data sources, environment variables, and .properties files.
  5. Build and deploy the Java application locally in your machine.

Step #2: Run the application locally, and get a basic familiarity as to how to navigate through the application.  Focus on the functionality you will be working with.


Step #3: A level of reverse engineering will be required to navigate through the actual user interface and then drill down into the code that is responsible for the functionality you are focusing on foxing on enhancing. Here are the tips to do that.


Step #3.1: Run the application in debug mode by modifying the log4j config file. This will print more log info like class names, method names, and stored procedure names being executed while you perform the UI navigation. You can then check the log file to get a list of relevant class names, methods, stored procedures, etc.

Step #3.1.1: Once you have the relevant class and method details, you can

Start to work like an eclipse pro to navigate through code:

You can use CTRL+SHIFT+T to search for Java class files



You can use CTRL+SHIFT+R to search for any resource files like .properties, .xml (Spring context file), .sql files, etc



Once you are within a Java class files, you can search for a particular method with CTRL+O.



You can drill down into other classes with F3 and Ctrl + left mouse click. The CTRL+ mouse click is very powerful drill down from ClassA to ClassB method invocations.



Step #3.1.2: Once you have worked out which artifacts to be modified, it is essential to perform impact analysis as to who is using these artifacts and if your fixes or enhancements going to impact any other existing functionality.

Start to work like an eclipse pro to perform impact analysis:

Highlight either a class name or a method name and press CTRL+SHIFT+G to find out from which classes and methods it is used or referenced from.


You can also highlight the class and press CTRL+H to search both Java classes and non Java type files like Spring context files, properties files, etc. This will cast a wider search where you have a number of tabs like file, Java, JavaScript, etc to search from.



Step #3.2: As an alternative to running the application in debug mode, you can also pick some labels key text on the GUI, and then use CTRL+H and then select the "File Search" tab to search for the web resources like .jsp, ,html, .xml, etc that have that search text. You can then drill down the other artifacts from there.

Step #4: When you are ready to make the code changes you can use code assist short cut keys described in  top 10 eclipse short-cut keys every Java eclipse developer must know.


Step #5: If you can't remember these short-cut keys initially, all you have to remember is

CTRL+SHIFT+L once
CTRL+SHIFT+L twice  


While unscrambling the relationship between the software functionality and code, maintain a documentation and produce high level diagrams. For example:

CashUI.jsp --> CashController.java --> CashService.java --> CashDao.java --&gt  getAvailbleCash.sql

Obviously you need to collaborate with a number of different team members to pick their knowledge, but most often team members can;t spoon feed you, and you need to hit the road running fast. This requires both good technical know how and great soft skills to get the job done.

Labels: ,

Jun 17, 2014

How to do impact analysis in Java based applications?

Performing impact analysis is a crucial software development task.

Q. What is impact analysis? Is it a trivial task?
A. Impact analysis is about being able to tell which pieces of code, packages, modules, and projects use given piece of code, packages, modules, and projects, or vice versa is a very difficult thing.


Performing an impact analysis is not a trivial task, and there is not a single tool that can cater for every scenario. You can make use of some static analysis tools like IDEs (e.g. eclipse), JRipples, X-Ray, etc. But, unfortunately applying just static analysis alone not enough, especially in Java and other modern languages whereas lots of things can happen in run time via reflections, dynamic class loading & configuration, polymorphism, byte code injection, proxies, etc.


Q. How will you go about performing impact analysis in Java?
A. You need to use a number of different tools and techniques perform impact analysis.

1. Strong emphasis on writing unit and functional test cases

One of the most important way invented in software development to analyze impact of changes is by executing unit tests and functional tests. When a change is made to software, the change will quite often have an undesirable or unintended impact on the software as a whole. So, re-executing the automated tests can identify any potential impact of a particular change. Both agile and non-agile Java projects need to have a decent unit testing coverage.

Q. What is code coverage? How do you measure it?
A. Code coverage basically tests that how much of your code is covered under tests. There are opensource and paid tools like Coverlipse, CodeCover, Cobertura and Atlassian Clover (commercial) to analyze and improve your test coverage. 

2. Making use of the IDEs' and plugins' search facility

You can use the search facility of your IDE, and additional plugins provided for the IDE.  For example,

a) In eclipse Ctrl+Shift+g can be used to search for references
b) You can perform a general "File Search" for keywords on all projects in the work-space.
c) You can use Notepad++ editor and select Search --> Find in files. You can search for a URL or any keyword  across a number of files within a folder.


There are instances where you need to perform impact analysis across stored procedures, various services, URLs, environment properties, batch processes, etc. This will require  a wider analysis across projects and repositories.


3. Search within your code repository like Subversion (SVN)


svn list -R file:///subversion/repository | grep filename


Windows:

svn list -R file:///subversion/repository | findstr filename


There are SVN tools like SVN Search or SVNQuery  which performs SVN repository indexing and searching engine


Alternatively, checkout the projects to a common folder, and use Notepad++ or other tools to do file system search.



4. Tools like FishEye can be used to search across various code repositories

FisheEye is not targeted for any special programming language. It just supports various version control systems and the concept of text files being changed over time by various people. Handy for text searches like environment based properties files to change a URL or  host name from A to B.


5. Grep the Unix/Linux environment where your application is deployed.

You can perform a search on the file system where your application(s) are deployed.

6. Conduct impact analysis sessions across cross functional and system teams and communicate the changes.

Brain storm major areas affected and document them. Have a manual test plan that covers the impact systems to be tested. Collaborate with cross functional teams and identify any gaps in your analysis. Have a proper review and sign-off process. Get more developers to do peer code reviews.


7. Have proper documentation with high level architecture diagrams and dependency graphs where possible. As the number systems grow, so does the complexity. A typical enterprise Java application makes use of different database servers, messaging servers, ERP systems, BPM systems, Work flow systems, SOA architectures, etc. Use online document management systems like Confluence or Wiki , which enables search for various documents.


8. Analyze across various log files

It is also not easy to monitor service oriented architectures. You can use tools like Splunk to trace transactions across the IT stack while being tested by the testers to proactively identify any issues related to change. Splunk goes across multiple log files.


So,in addition to using a combination of tools, you need to have a proper process in place to to maintain the knowledge of the various systems and processes. This where experience and retaining talented people with internal systems knowledge is vital. You can easily replace a quality Java developer, but cannot easily replace business and systems knowledge.

Labels:

Mar 25, 2014

Top 10 Eclipse short-cut keys every Java developer using eclipse IDE must know -- part 2

Top 10 Eclipse short-cut keys every Java developer using eclipse IDE must know - part1 covered the frequently used CTRL+ key. This will cover CTRL+SHIFT+key. If you can remember only 1 short-cut key, this post will show you which one to remember.

8. CTRL+g and CTRL+SHIFT+g

Often you need to find where a particular type or method is referenced so that you can analyze the impact of changing the referenced class or method. You also often need to find where a particular type or method is declared. Impact analysis vital in enhancing existing code base.

CTRL+G is to find declarations in workspace



Ctrl+Shift+G is to find references in workspace



9. CTRL+SHIFT+t and CTRL+SHIFT+r

Often you need to search for Java types like classes and interfaces or Java resources like spring context XML file, properties files, sql files, data files, etc. CTRL+SHIFT+t and CTRL+SHIFT+r allow you to search for types and resources respectively with wild card character like * and ?. If you do CTRL+SHIFT+r it gives you options at the bottom as to which editor you want to use to open the selected resource. You can also use these two short cuts contextually by highlighting type (E.g. class name like EclipseShortCutKeys) and then pressing the shortcut keys.

CTRL+SHIFT+t



CTRL+SHIFT+r



10. ALT+SHIFT+R

Refactoring code is a key aspect of writing quality code. For example, you might name a variable "currentTimeMillis" and use it in a number of places. But, later on decide that a better variable name would be "startCurrentTimeMillis". If you change at one spot, you want it to be propagated to all occurences of "currentTimeMillis". This works for changing method and class names as well. If you change a name of a declared method, you want all the classes that refrencing this method to change its values in the method invocations. This is achived by highligting a class, method, or a variable, and then pressing CTRL+SHIFT+R, and then change the name at the highlighted spot, and it will propagated to other locations and resources where it is used.



Do I have to remember these 10 eclipse shortcut keys? 

With practice and experience, you will remember these frequently used shortcut keys. Until then, if you have to just remember 1 shortcut key, then it is CTRL+SHIFT+L, which lists all the short-cut keys in a popup.

If you press CTRL+SHIFT+L once



If you press CTRL+SHIFT+L twice



Labels: ,

Mar 12, 2014

Top 10 Eclipse short-cut keys every Java developer using eclipse IDE must know

1. CTRL+1

Probably the most useful one. It activates the quick fix and generates lots of code for you. This means less typing.

Generating local variables: For example, if you have written a method call and you highlight it and press Ctrl+1, Eclipse will give you options to extract to local variable, assign to new local variable or assign to new field.



If you've modified a method in a abstract superclass or interface and you highlight the subclass’ name and hit Ctrl+1, you’ll get options to add unimplemented methods or make the subclass abstract.



Suppose you’ve misspelled “currentTimeMillis”, you can highlight it, press Ctrl+1 and you’ll get an option to correct the spelling.



So, Ctrl+1 is a quick fix that does the thinking for you.

2. CTRL+space

This is a type assist tool. Handy for you to search for handy utility class like DateTimeUtils from the Joda library. There are myriad of libraries used in commercial Java projects, and very handy to pick a class.



Handy to pick your own classes as well if you don't remember the exact name for your model class, but knew that it starts with "Custom".


3. CTRL+o

You have an existing class with 15+ methods defined and want to get to a method quickly, then use CTRL+o.




4. CTRL+l

Say you get a stack trace in your eclipse console or in the log file as shown below, and you want to go directly to the line in your class that caused the exception, then use CTRL+l to go to the exact line number.


1394596218303
Exception in thread "main" java.lang.NumberFormatException: null
 at java.lang.Long.parseLong(Long.java:404)
 at java.lang.Long.(Long.java:702)
 at com.writtentest11.EclipseShortCutKeys.main(EclipseShortCutKeys.java:10)

In the above code, the class is "EclipseShortCutKeys" and line number is 10.


So, use CTRL+SHIFT+T to select the class EclipseShortCutKeys by typing the first few characters to filter, and then once this class is selected use CTRL+l and type 10 to go to the exact line.



5. CTRL+7 or CTRL+/

You may now want to comment out the line causing the java.lang.NumberFormatException. You comment and uncomment with the toggle control keys either CTRL+7 or CTRL+/. Highlight the number of lines you want to comment or uncomment, and then press CTRL+/.





6. CTRL+mouse click


The CTRL short-cuts will not be complete without the most powerful navigation CTRL + mouse click. This brings up the contextual menu to navigate to other classes or interface.  Press the CTRL key first, and then hover over the method -- for example currentTimeMillis( ) on the Joda library class DateTimeUtils, util you get a contextual menu that takes you over to the actual implementation or interface.




In commercial projects, you need to navigate from service layer classes to DAO layer classes, helper classes, domain models, etc. Many different layers will collaborate with each other to implement the business use case. So, you need to rapidly move across different layer classes.


7. CTRL+h

This is a generic search pop up. You can do Java search, File search, etc. Either high-light the type, method, or variable  and then press CTRL+h or without highlighting to fill in the search criteria yourself. Very handy to search your selection, workspace, or working sets.





So far looked at very useful CTRL+. In the next post, will cover CTRL+SHIFT+. Top 10 Eclipse Short Cut Keys - Part 2. You will see in this Part 2, the only key that you must remember.

Labels: ,

Dec 17, 2013

Software developer productivity tip with Notepad++ to construct SQL clause or any other data conversion

Lets take a tutorial like scenario to demonstrate power of Notepad++ as a  developer productivity tool.

Q. How will you extract rule_name values from a tabular data shown below and convert it to an SQL query as shown below as well?

id  type  rule_nmae            bean_name
633 ALL  asx100_rule           SECURITY_VALIDATION
632 ALL  asx200_rule           SECURITY_VALIDATION
634 ALL  ETF_rule              SECURITY_VALIDATION
635 ALL  managed_fund_rule     SECURITY_VALIDATION

This data could com from an excel spread sheet, word document, or copied from a confluence or wiki page.

The SQL we need is:

Select * from rules_table where rule_name in ('asx100_rule', 'asx200_rule', 'ETF_rule', 'managed_fund_rule');

A. Let's see Notepad++ in action

Step 1:  Copy the data to Notepad++ and delete the header row by highlighting it and pressing the delete button.

id      type      rule_nmae   bean_name


Step 2: You need to now remove all the columns except rule_name column. To do this place the cursor LHS of  first 633 value and press    + keys together and highlight the columns you want to remove with the mouse. Do the same for the last column as well.



Step 3: Next step is to remove any leading or trailing spaces. Use regex based find and replace command. Pressing CTR+ F will bring the Find dialog . You can also select it from the  "Search" menu at the top.

In the pop up find dialog, select the "replace" tab. Enter the  find and replace value as shown below. Make sure the  "Regular expression" option and "Wrap around" check box are ticked.





Don't copy paste, but type.

Find What: [\s]+
Replace with: ,

Step 4: Remove the new line characters or carriage return by finding and replacing with the "Extended ..." option turned on as shown below.


Don't copy paste, but type.

Find What: \r
Replace with: 

Replace new line with nothing.

Step 5: You need to put a single quote (') around the entries for the SQL query. Regex is agin back to the rescue.



Don't copy paste, but type.

Find What: ([^,]*)(,?)
Replace with: '\1'\2

The parentheses '( )' are used to capture the values. and \1 and \2 represent both the captured values. The ' is add before \1 and \2. Where \1 is the value like "asx100_rule" and \2 is ",". The * means 0 or many, and  ? means 0 or 1.

You can now take the single line text and put it in your where clause. This is very handy when you have to work with larger data.

This tutorial is good for learning regular expression as well.



You may also like:

Labels: ,

Jun 24, 2013

Excel spreadsheet to generate SQL

When you have some data in tabular (e.g. Excel spreadsheet) format and would like to insert into a database table, you need to write an SQL insert query. Manually writing SQL query for multiple records can be cumbersome. This is where Excel spreadsheet comes in handy as demonstrated below. A single SQL query can be copied down where the formulas get copied with incrementing column numbers.

The  Excel concatenate character & is used to achieve this. The $ means fix. $a1 means fix excel column A. When you copy the formula, the row numbers will be incremented like 2,3,4, etc, but the column will remain fixed to A. In the example below
  • $A$1 = first_name
  • $B$1 = surname
  • $C$1 = age

Note: Both column and row are prefixed with $, which means both are fixed.


The Excel formula is

 

="insert into person ("&$A$1&", "&$B$1&", "&$C$1&") values ('"&$A2&"','"&$B2&"',"&$C2&")"

The above Excel expression is easier to understand if broken down as shown below where the concatenation character & plays a major role in combining static text within quotes with dynamic formulas like $A$1.

 
"insert into person ("

&

$A$1

&

", "

&

$B$1

&

", "

$C$1

&

") values ('"

&

$A2

&

"','"

&

$B2

&

"',"

&

$C2

&

")"


The generated SQL statement will be
 

insert into person (first_name, surname, age) values ('Peter','Smith',35)


This SQL can be copied down in Excel to get SQL for all rows

 

insert into person (first_name, surname, age) values ('Peter','Smith',35)    
insert into person (first_name, surname, age) values ('John','Smith ',12)    
insert into person (first_name, surname, age) values ('Eddy','Wayne',32)    




You can create other SQL statements using the above technique from a table of data for better productivity.


If you have date column, the use the following formula to convert it to a text.


TEXT($D2,"dd/mm/yyyy")


You may also like:

Labels: , ,

Jun 14, 2013

The power of regular expression and testing tools like regexpal.com

Regular expressions are also known as regex, and they are very powerful and used widely in JavaScript, Unix scripting,  development tools, monitoring tools like Tivoli, and programming languages. So, it really pays to have good knowledge of regexes. This post is about a handy tool named "regexpal.com" that helps you not only learn regex, but also to quickly verify your regexes while working on a project. If you google for "regex online validator" you will find other similar online validating tools.



Step 1: Open up a browser and type regexpal.com on the address bar. Yo will get the online validator.

Step 2: Type or copy/paste the regex at the top window and the text to apply the regex on the second window.


As indicated in the footer, use RegexBuddy for a more powerful regex testing. The regex keywords are highlighted in blue. Also the matched phrase is also highlighted. In blue for the exact match and in yellow for any other string match.

The above example matches any string followed by one of "Monitoring", "MYAPP", or "CASHFORECAST". The "|" in regex means "OR". What if you want to literally match "Monitoring|MYAPP|CASHFORECAST"? You can escape "|" with "\" as shown below.


Now, the  "|" is not highlighted in blue as it is escaped.

Change the text as shown below. The "CASHFORECAST" is changed to "TRADEFORECAST" and match is no longer found as the text is not highlighted.

Labels: ,

May 9, 2013

Notepad++ plugin for viewing JSON data and other benefits

Q. Why is Notepad++ is a very handy tool?
A.  Notepad++ is a very handy developer tool. Here are some of the productivity benefits of Notepad++.

  •  to view source code as a free and light weight source code editor that runs in Windows environment. You can also use it to view log files and other text data.
  • It can be used for syntax highlighting, line numbering, search and replace with or without regular expressions, modified file detection, file search, etc. 

Working with JSON data

Recently, I had to work a lot with JSON data, and stumbled across a very handy plugin for Notepadd++ called "JSONViewer Notepad++", which allows you to format JSON data and view them as a tree structure. Here are the simple setps to install this plugin.

Step 1: Download the plugin as a zip file from the source-forge site.

Step 2: Unzip the downloaded file and extract out the "NPPJSONViewer.dll" file.

Step 3: Copy this file to the plugins folder in your Notepad++ installation folder, and restart your Notepad++. for example "c:\myapps\Notepad++\5.9\plugins".

Step 4: When you open up your Notepad++, you will see the "JSONViewer" sub menu under the "Plugins" on the top main menu. You can format the JSON text by highlighting your text first and then clicking on Plugins --> JSON Viewer --> Format JSON.


Extracting data

If you had some tab limited data like

FirstName Surname Age
John  Smith 25
Peter  Warren 35
Lisa  Jenkins 28


and if you want to extract out all the first names, you can invoke the column mode by pressing "Alt" key and then select the "FirstName" column with the mouse selection. Alternatively, you can use the "Alt+Shift+Arrow Key" to select the column entries you need. These options are under the  "Edit --> Column Mode" on the top menu.

Finding and replacing values with Regular expressions

If you have some comma delimited data as shown below

FirstName,Surname,middlename
John,Smith 
Peter,Warren,James 
Lisa,Jenkins


where the middle name is optional, and you want to convert the comma delimited data to tab delimited data.This is where Notepad++ 's regex based find and replace comes in handy.

Step 1: Select "Search --> Find" from the top menu.
Step 2: click on "Replace" tab.
Step 3: Tick "Match case" if required and select "Regular Expression" option.
Step 4: Enter the relevant  regular expressionsfor the "Find What" and "Replace With".


Find What: ([A-Z][a-z]*),([A-Z][a-z]*)(.*)
Replace With: \1\t\2\t\3

Where \1, etc are groups and \t is for tab delimiting.




You can use the "Find In files" tab to replace multiple files. I use this feature to search for files that has certain text (i.e. grep). This is a bulk find and replace capability. It also has other bulk features like "File --> Save all" open files.


Split views, file comparisons and synchronized scrolling

Select  View -->  Move/Clone Current Document to create split views to compare two files side by side. On split views you can select Plugins --> Compare --> compare to highlight the differences or select View --> Synchronize Vertical Scrolling to scroll both views in tandem.


Language feature to highlight reserved key words

Setting the language of the file like Java, JavaScript, etc via Language --> J --> Java or JavaScript will help you easily visually distinguish between functions, reserved words, comments, text, and other types of symbols and expressions in your code.


The latest Notepad++ version should have a TextFx menu to tidy up HTML tags to be XHTML compliant. You can also automate any monotonous tasks you do repeatedly with the Macros. It can also synchronize files with  Subversion (i.e. SVN). Hence Notepad++ is a powerful open-source developer tool that makes you more productive.

Labels: ,

Apr 16, 2013

RESTClient tool to test RESTful web services

Related posts to test web services

The http://www.wiztools.org/ has some handy open source Java tools like RESTClient, Regular Expression Tester, etc. RESTClient tool is GUI based and a good alternative to the Unix command line based tool CURL and the Firefox poster plugin. SoapUI is another GUI based client for both RESTful and SOAP based web services. This blog posts shows how easy it is to get started with RESTClient tool from WizTools. The example below shows a POST request as the GET requests are easier to test. The diagrams below illustrates posting of JSON data. The RESTful web service operations GET, POST, PUT, and DELETE correlates with the database CRUD operations Read, Create, Update, and Delete respectively.

Step 1: From WizTools click on the link to RESTClient.




Step 2: Download the JAR file "restclient-cli-3.1-jar-with-dependencies.jar". Create a short cut to the jar file. Double clicking on the short cut will open the RESTClient GUI as shown below. You can type in the URL and select "POST" as the HTTP method.


Take note of the HTTP headers passed with the request.


Step 3: You need to select the "Content-Type" that you want to post. Select  "application/json" as the content-type.




The GET requests are very straight forward requiring only the URL.


The SoapUI tool requires a WADL file for the RESTFul web services. Here is an example of SOAP Web Service using the SoapUI tool.


Related posts to test web services

Labels: , , ,

Apr 10, 2013

Maven - setting up profiles and tokenizing properties file

Maven is a popular build tools and often you have a requirement to tokenize the name/value pairs in a properties file so that right values can be substituted depending on for which environment (local, dev, test, uat, prod) you are building the package for.


For example, your properties file (portal.properties) under DEV environment might look like


portal.rest.path.accounts=@PORTAL_REST_PATH_ACCOUNT_SERVICE@
portal.rest.path.tax=@PORTAL_REST_PATH_TAX_SERVICE@
portal.logout.url=@PORTAL_LOGOUT_URL@


The values within "@" are tokens that needs to be replaced at build time. The properties files reside under src/main/resources folder as per the Maven structure.Here is a sample DEV resource myapp.properties that sits under /env/dev folder.

PORTAL_REST_PATH_ACCOUNT_SERVICE=http://DEV-1:8080/accounts_service
PORTAL_REST_PATH_TAX_SERVICE=http://DEV-1:8080/tax_service
PORTAL_LOGOUT_URL=https://smlogin-dev.myapp.net/siteminderagent/ssologout/Logout.html


Next step is to configure the pom.xml file in Maven. This is done via the profiles as shown below.

<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/xsd/maven-4.0.0.xsd">

   ....

    <profiles>
  
  <profile>
   <id>dev-tomcat</id>
   <build>
    <resources>
     <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
     </resource>
    </resources>
    <filters>
     <filter>env/dev/myapp.properties</filter>
    </filters>
   </build>
  </profile>
 </profiles>
 
 ....
 
</project>


    <build>
  <resources>
   <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
   </resource>
  </resources>
 </build>


You also need to turn filtering on as shown below in the pom file.



Finally, you can invoke this profile with the -P option in the mvn command.

clean install tomcat:run -Dmaven.tomcat.port=8080 -Pdev-tomcat




There 3 types of Maven profiles.

  • Per Project profile: Defined in the pom.xml file as shown above.
  • Per User profile: Defined in Maven settings.xml file under %USER_HOME%/.m2
  • Global profile: Defined in Maven global settings.xml file under %M2_HOME%/conf/

and these profiles can be activated a number of ways

1. Via command line with -P option as shown above.

2. You can activate it via the Maven settings.xml file as shown below


<settings 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/xsd/settings-1.0.0.xsd">
   <mirrors>
      <mirror>
         <id>maven.dev.snaponglobal.com</id>
         <name>Internal Artifactory Maven repository</name>
         <url>http://repo1.maven.org/maven2/</url>
         <mirrorOf>*</mirrorOf>
      </mirror>
   </mirrors>
   <activeProfiles>
      <activeProfile>dev-tomcat</activeProfile>
   </activeProfiles>
</settings>
 
All you have to do is type mvn install and the dev-tomcat profile will be kicked off

3. Via environment variables.

<profile>
   <id>dev-tomcat</id>
   <activation>
      <property>
         <name>env</name>
         <value>dev-tomcat</value>
      </property>
   </activation>
</profile>


4. Via operating system (OS)

<profile>
   <id>test</id>
   <activation>
      <os>
         <name>Windows </name>
         <family>Windows</family>
         <arch>x86</arch>
         <version>6.1<version>
      </os>
   </activation>
</profile>

5. Based on a missing file


<profile>
   <id>test</id>
   <activation>
      <file>
         <missing>target/generated-sources/wsdl</missing>
      </file>
   </activation>
</profile>


Q. Can you give an example where you used a profile?
A. Firstly, to tokenize properties as demonstrated in the beginning of the post. Secondly, in local development you set up a datasource for your tomcat server to use as shown below.

    
 <profiles>
  <!-- Used for running tomcat locally to do application testing by substituting 
   tokenized variables from a properties file-->
  <profile>
   <id>dev-tomcat</id>
   <build>
    <resources>
     <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
     </resource>
    </resources>
    <filters>
     <filter>src/main/filters/myapp.properties</filter>
    </filters>
    <plugins>
     <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>tomcat-maven-plugin</artifactId>
      <configuration>
          <!-- define your datasource here-->
       <contextFile>src/main/resources/tomcat-maven-plugin/context.xml</contextFile>
      </configuration>
     </plugin>
    </plugins>
   </build>
  </profile>
 </profiles>


The context.xml file will look like

<?xml version="1.0" encoding="ISO-8859-1"?>
<Context>
 <Resource
  name="jdbc/myapp_ds"
  type="javax.sql.DataSource"
  driverClassName="com.sybase.jdbc3.jdbc.SybDataSource"
  auth="Container"
  username="aes_service"
  password="service1"
  url="jdbc:sybase:Tds:myserver:5500/my_db?applicationname=myapp"
  initialSize="5"
  maxActive="5"
  maxIdle="1"
  minIdle="0"
  validationQuery="my_validateQuery"
  testOnBorrow="true"
  testOnReturn="false"
  testWhileIdle="false"
  poolPreparedStatements="false"
  removeAbandoned="false"
  logAbandoned="false"
   />
</Context>


Labels: ,

Apr 4, 2013

Top 3 Core Java Third Party librararies that you use frequently in your Java projects

Q. Can you list a few third party libraries and useful methods that you frequently use in you core Java and enterprise Java development?
A. Firstly, the Apache Commons library has a number of utility methods to simplify your development with a number of proven APIs with utility methods.

Firstly, the toString(  ), equals( .. ), and hashCode( ... ) methods are very frequently used in your domain or value object classes. Here are a few handy Apache commons library methods.


import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

public Class Customer {

    private String name;

    //...getters and setters

    @Override
    public int hashCode()
    {
        return HashCodeBuilder.reflectionHashCode(this);
    }
    
    @Override
    public boolean equals(Object obj)
    {
        return EqualsBuilder.reflectionEquals(this, obj);
    }
    
    @Override
    public String toString()
    {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
 
 
    //...


The FileUtils class has a number of handy file processing methods.

import org.apache.commons.io.FileUtils;

public Class FileUtils {

    //....
    try
        {
            FileUtils.touch(lockFile);
        }
        catch (IOException e)
        {
            logger.error("Error creating a lock file: " + lockFile.getAbsolutePath(), e);
            throw new MyCustomException(e);
        }

    //....


    public void moveFile(File srcFile, File destFile) throws IOException
    {
        FileUtils.moveFile(srcFile, destFile);
    }
 
}


The StringUtils is handy for checking if a given String is blank or empty.

import org.apache.commons.lang.StringUtils;

//....

    if (StringUtils.isEmpty(feedFileMeta.getFilePath())) {
        feedFileMeta.setFilePath(defaultFilePath);
    }


The Apache commons package has so many handy methods.

import org.apache.commons.codec.binary.Base64;

public class ApacheLibBase64Example{

    public static void main(String args[]) throws IOException {
        String origStr = "original String before encoding";

        //encoding  byte array into base 64
        byte[] encoded = Base64.encodeBase64(origStr.getBytes());     
      
        System.out.println("Original String: " + origStr );
        System.out.println("Base64 Encoded String : " + new String(encoded));
      
        //decoding byte array into base64
        byte[] decoded = Base64.decodeBase64(encoded);      
        System.out.println("Base 64 Decoded  String : " + new String(decoded));

    }
}


Package org.springframework.util  has a number of handy utility classes like Assert, ClassUtils, CollectionUtils, FileCopyUtils, FileSystemUtils, ObjectUtils, StringUtils, TYpeUtils (Java 5 Generics support) and ReflectionUtils to name a few.  The Assert utility class that assists in validating arguments. Useful for identifying programmer errors early and clearly at run time. For example,

Assert.notNull(clazz, "The class must not be null");
Assert.isTrue(i > 0, "The value must be greater than zero");


The google Guava library provides a number of precondition checking utilities with the Preconditions class.

checkArgument(i >= 0, "Argument was %s but expected nonnegative", i);
checkArgument(i < j, "Expected i < j, but %s > %s", i, j);
checkNotNull(objA);


Here is an example using the Preconditions class:

@Controller
...
public void order(ProductInfo data) {
    //required in the controller to handle errors and send a sensible error back to the client
    Preconditions.checkArgument(StringUtils.hasText(data.getName()), "Empty name parameter."); //validation
    productService.order(data);
}



public class ProductInfoValidator implements Validator {

    /**
    * This Validator validates just ProductInfo  instances
    */
    public boolean supports(Class clazz) {
        return ProductInfo.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
        ProductInfo p = (ProductInfo) obj;
        if (p.getSku() < 0) {
            e.rejectValue("sku", "negativevalue");
        } else if (p.getSku() > 9999) {
            e.rejectValue("sku", "sku.out.of.range");
        }
    }
}


The Service layer needs to apply validation to promote defensive programming. The design by contract states that your methods should check for pre and post conditions and fail fast if the contract is not met.

@Service
...
public void order(ProductInfo data) {
    //fail fast and defensive programming. aka assertions and design by contract 
    Preconditions.checkArgument(StringUtils.hasText(data.getName()), "Empty name parameter.");
    productDao.order(data);
}

If you have a requirement to work a lot with the Java collections, and performance and memory usage are of utmost importance, then look at the following libraries to work with the collections.
  1. The Trove library provides high speed regular and primitive collections for Java. 
  2. PCJ (Primitive Collections for Java)
  3. Guava (from google)

In a nut shell, the Apache commons from Apache, Spring utils from Spring, and  Guava libraries from Google should make you more productive without having to reinvent the wheel. If you have heavy usage of data structures, then Trove becomes very handy. So, before you roll out your own utility methods, check if they are already provided by these libraries.


Q. What libraries or frameworks do you use to marshaling and unmarshaling  Javas POJOs to CSV, XML, EXCEL, and PDF?
A.  There are a number of libraries available.

BeanIO is an open source Java framework for reading and writing Java beans or plain old java objects (POJO's) from a flat file or stream. BeanIO is ideally suited for batch processing, and currently supports XML, CSV, delimited and fixed length file formats. It is also handy for writing automated tests using Apache Camel where test instructions can be written on a flat file and read via BeanIO. It can also be used to produce CSV and XML download files.

The Maven users can define

    <!-- BeanIO dependency -->
    <dependency>
      <groupId>org.beanio</groupId>
      <artifactId>beanio</artifactId>
      <version>2.0.0</version>
    </dependency>

    <!-- StAX dependencies for JDK 1.5 users -->
    <dependency>
      <groupId>javax.xml</groupId>
      <artifactId>jsr173</artifactId>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>com.sun.xml.stream</groupId>
      <artifactId>sjsxp</artifactId>
      <version>1.0.2</version>
    </dependency>  


OpenCSV is an alternative for working with CSV files.

Apache POI, JXLS and JExcelApi are handy for working with Excel files in Java.

To create XML, use JAXB, Stax, JiBX, JDOM, XStream, etc. 

To create PDF documents you can use a number of options listed below.
  1. iText and JasperReports.
  2. Apache PDFBox.
  3. BFO.
  4. Converting to XML and then using XSLT to XSL-FO and then render with Apache FOP.

Labels: , ,

Oct 18, 2011

Java Interview Questions and Answers on tools

Related reads:
In today's enterprise Java development, you will use plethora of tools to make your life easier and more productive. The open-ended questions described below are not to make the Hire/No Hire decision, but to judge your seniority and experience.

Q. Can you describe some real life scenarios in which tools helped you solve issues?
A. [Hint: The objective is to ascertain, if you are using the right tool for right job. This question can also be phrased differently with How would you go about ....? type of questions like How would you go about fixing a memory or resource leak in a JEE application?, etc ].

1. Debugging: The application and server logs are the first place to turn for any issues in production or during development. It is really worth understanding some of the tools that will help to obtain, analyze and search through the logs.

  • FileZilla or WinSCP to transfer files using FTP, SFTP or SCP protocols. Log files or database extract files can be transferred from a Unix machine to your sandbox (i.e. local machine) using these utilities, and explored further using text editors like Notepad++, UltraEdit, or TextPad. These text editors provide handy features like  search text highlighting, REGEX based searches, column formatting,  compare files, and many more. Notepad++ has powerful editing features, uses less CPU, and opens larger files.  
  • Cygwin, MobaXterm or MSYS to emulate Unix like environment for Windows. Many production systems are Unix/Linux based, and having a Unix/Linux environment on your local environment can make you more productive by harnessing the power of Unix commands.
          Search the log files to see if a particular user logged in.
cat /var/log/server.log | grep "login.jsp" | grep "userid"
         List all the log files that have a particular search text.
grep -l "Missing Characteristic Value" *.log* 

        You can use regular expression patterns to search.
grep -e '^import.*util.regex' *.java

        Find all occurrences of util.* packages except the util.regex package.
grep -e '^import.*util' *.java | grep -v 'regex' 

  • Remote debugging: It is increasingly essential with the globalization to be able to debug a Java application that is deployed remotely, in another country or city. You will come across scenarios where an application might be running fine in your sandbox (i.e. local desktop), but might be buggy when running in another environment or country.

    Say you want to remotely debug an application called MyApp.jar that is running remotely, you can set up your desktop to be able to debug it by enabling the remote debugging as shown below:


    java -Xdebug -Xrunjdwp:transport=dt_socket,address=888,server=y -jar MyApp.jar


    The above command tells the MyApp.jar to start a server socket on port 888, and publish the debugging messages using the jdwp, which stands for Java Debug Wire Protocol. The IDEs like eclipse can be configured to tap in to remote debugging as shown below. 

 In eclipse, select  Run --> Debug Configurations. Right click on "Remote Java Application", and select "New". Fill in the config details as shown below and apply the changes. Click on the "Debug" button to start debugging the remote application within eclipse. You will have to attach the source files from within eclipse.




The "diagnostic-core" is the project with the source files within eclipse. The "MyApp" is the remote debug configuration that can be stopped and started within eclipse. The connection properties provide information as to where to look for debug messages exposed via jdwp. 

    • Web debugging tools like Fiddler2 for IE, Firebug NET tab for Firefox, JMeter HTTP proxy server, Charles web debugging, etc act as a proxy to capture request parameters, request/response content, headers, cookies, etc for debugging purpose.

    • SQL proxy drivers like P6SPY, log4jdbc, etc to log generated SQL statements, execution times, etc.

    • Network packet sniffing tools like Wireshark, Kismet, tcpdump, etc for analyzing the network protocols & issues. Developing applications that interact with web services presents a unique set of problems like not knowing exactly what message was sent to the server, or what response was received. Some of the most difficult bugs to track down are caused by a disconnect between what you think you are sending to the server, and what is actually going across the wire. These tools are commonly called "packet sniffers" and capture all network packets that move across your network interface. Examining the contents of these packets and the order in which they were sent and received can be a useful debugging technique.


      2. Integration testing: Most applications built nowadays need to integrate with internal and external systems through SOAP or RESTful web service and messaging (e.g. JMS). There are a number of handy tools/clients to assist in development, testing, and debugging applications that integrate with other systems.

      • HermesJMS is an extensible console that helps you interact with JMS providers making it simple to publish and edit messages, browse or search queues and topics, copy messages around and delete them.
      • soapUI is a functional testing tool for SOA and Web Service testing. soapUI provides complete test coverage - from SOAP and REST-based Web services, to JMS enterprise messaging layers, databases, Rich Internet Applications, and much more.
      • Firefox poster plugin is a developer tool for interacting with web services and other web resources that lets you make HTTP requests, set the entity body, and content type. For example, you can make RESTful service calls over HTTP by posting XML. 

      3. Version control: CVS and Subversion are the two most prominent open source version control tools. TortoiseCVS and TortoseSVN let you work with files under CVS and SVN version control systems directly from Windows Explorer. With these tools you can directly check out modules, update, commit and see differences by right clicking on files and folders within Explorer. You can see the state of a file with overlays on top of the normal icons within Explorer. It even works from within the file open dialog.

      4. Performance testing: JMeter is a popular performance testing tool for testing web applications, web services (both SOAP and RESTful), and SQL query performance.JMeter Interview Questions and Answers

      5. Hot deployment tools like  JRebel, improves developer productivity by skipping the build and redeploy phases in your sandbox. JRebel is a  JVM agent, which instantly reloads your code upon change without having to restart your application server or redeploy the application. It integrates into your JVM as a classloader extension and enables reloading of classes without requiring to create a new classloader, which is usually the case when redeploying or restarting application servers.

      6. Database administration and SQL execution tools such as db-visualizer, SQuirreL SQL,  SQL Developer, DBArtisan, and Toad.There are command-line tools like iSQL for Sybase and SQLPlus for Oracle. BCP (stands for Bulk CoPy) and SQL Loader are ETL (i.e. Extract Transform and Load) tools to import data from a flat file into a database and export data from a database into a flat file.

      7. Penetration testing or "PEN test" tools like Google's Skipfish, Firefox plugin "tamperdata", etc to identify security holes in your web application.


      Q. What are some of the frequently used short-cut keys on your favorite IDE?
      A. The less you touch the mouse, the more code you can write. For example, in eclipse, the following short-cut keys are very handy and makes you more productive.

      1. CTRL + SHIFT + R to open a resource and CTRL + SHIFT + T for Java type
      2. F4 on highlighting a class or interface to open the type hierarchy.
      3. CTRL + SHIFT + O to organize imports
      4. CTRL + SHIFT + F to format text.
      5. CTRL + D to delete a row
      6. CTRL + SHIFT + / to comment out code.
      7. CTRL + 1 is probably the most useful one. It activates the quick fix.
      8. CTRL + SHIFT + G to generate getters and setters.
      9. CTRL + O to get a snapshot of the class members. You can go directly to a member (method, variable) of a huge class file with this. If you just want to jump from one member to the next (or previous), you can use Ctrl + Shift + downarrow or Ctrl + Shift + uparrow, respectively.
      10. CTRL + L to go to a particular line. Handy when the stack trace says that the error is on line 256. 
      11. CTRL + SHIFT + L to get the list of all the currently defined short-cut keys.
      12. Pressing down the CTRL key while hovering over a class, interface or a method with the mouse to invoke the contextual menu to navigate to a particular interface, implementation, or method. Very useful.


      Q. Name a feature in your favorite IDE that you discovered recently  or  find it very useful?
      A. In eclipse, the "working sets" are very handy concept to categorize resources across projects into a contextually relevant representation. Working sets are simply, as their name suggests, a sub-set of files, classes, folders or projects with the following benefits.

      • Categorize multiple projects together that may represent a single application. For example, maven multi-module projects like   myproject-core, myproject-web, myproject-batch, myproject-parent, myproject-schedule, etc can be grouped into a single working set named "myproject".

      • You can search or access resources by working sets. You can even close the whole working set.

      • If you like, you can also create working sets by layers -- Model, View, Controller, Service, DAO, etc. It is also possible to select particular packages, classes, and folder structures to be included or excluded from a given working set. This allows developers to organize code anyway they want. 

      • Very handy and useful especially in larger projects.

      You can get the production support team to email you a stack trace, and then you can copy and paste the stack trace into Eclipse's Console window for further analysis. You can then click on class names in the stack trace as if your own code had generated it.

      There are other productivity improving features described above in terms of short-cut keys, especially the ctrl-1 for quick fix.

      The "templates" are very handy for frequently used code snippets. The window --> preferences --> Java --> Editor --> Templates can be used  to add handy code snippets to improve productivity. For example, the following template to declare loggers.

      ${:import(org.apache.commons.logging.Log, org.apache.commons.logging.LogFactory)}
      private static final Log LOG = LogFactory.getLog(${enclosing_type}.class);
      
      

      You can name the above template snippet as "logger" and when you are inside your class, if you type "logger" and then ctrl+space, eclipse will generates and inserts the required code based on the saved template.

      private static final Log LOG = LogFactory.getLog(TestSpring3.class);
      
      


      Many other useful templates can be created for productivity.


      Other similar links:

      Labels:

      Oct 6, 2011

      Maven interview questions and answers - inheritance vs aggregation



      Q: How do you inherit dependencies or plugins  in Maven? How are sub modules aggregated?
      A:

      In Maven Inheritance, you will have a multi-module maven project where a centrally managed POM file contains all the “approved” versions of artifacts.  In this “parent” pom was a “dependencyManagement” section with all the preferred versions of libraries within the organization. When you build a child of this parent, Maven will retrieve this parent to merge the parent pom with the child pom. You can have a look to the entire pom.xml by running the command mvn help:effective-pom. This parent pom is also known as the reactor pom. The child modules like myproject-ui, myproject-security, etc will be inheriting the versions from the parent.

      Like "dependencyManagement" the "pluginManagement" in parent contains plugin elements intended to configure child project builds that inherit from this one. However, this only configures plugins that are actually referenced within the plugins element in the children. The children have every right to override pluginManagement definitions.

      As shown below, the child modules are aggregated. The principle is that every command that you run on on the parent (i.e. reactor pom) will also be run on all the sub-modules. The order of the modules will be defined by the Reactor, which will look at inter-modules dependencies to find which module must be built before the others. If there are no dependencies, then it will take the list of the modules as they are defined in the parent pom.xml.

      Parent pom.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <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/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>com.myproject</groupId>
       <artifactId>myproject-parent-build</artifactId>
       <packaging>pom</packaging>
       <version>${myproject.version}</version>
       <name>${project.artifactId}</name>
       <url>http://www.myorganization.com</url>
      
       <properties>
           <myproject.version>1.0.0</myproject.version>
        <seam.version>2.2.2.Final</seam.version>
        ...
       </properties>
      
       <dependencyManagement>
        <dependencies>
         <!-- jboss seam dependencies -->
         <dependency>
          <groupId>org.jboss.seam</groupId>
          <artifactId>jboss-seam</artifactId>
          <version>${seam.version}</version>
         </dependency>
         ...
        </dependencies>
       </dependencyManagement>
      
       <build>
        <plugins>
         <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.1</version>
          <configuration>
           <source>1.6</source>
           <target>1.6</target>
          </configuration>
         </plugin>
         ...
        </plugins>
      
        <pluginManagement>
         <plugins>
          <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-compiler-plugin</artifactId>
           <version>2.1</version>
           <configuration>
            <source>1.6</source>
            <target>1.6</target>
           </configuration>
          </plugin>
          ...
         </plugins>
        </pluginManagement>
       </build>
      
       ...
      
       <modules>
        <module>myproject-security</module>
        <module>myproject-content</module>
        <module>myproject-data</module>
        <module>myproject-ui</module>
        <module>myproject-analytics</module>
       </modules>
       
      </project>
      
      


      Child pom.xml . The parent tag defines the parent to inherit form.

      <?xml version="1.0" encoding="UTF-8"?>
      <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/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>com.myproject</groupId>
       <artifactId>myproject-ui</artifactId>
       <version>${myproject.version}</version>
       <packaging>war</packaging>
       <name>${project.artifactId}</name>
       <url>http://www.myorganization.com</url>
       <parent>
        <groupId>com.myproject</groupId>
         <artifactId>myproject-parent-build</artifactId>
        <version>${myproject.version}</version>
       </parent>
      
       <build>
        <finalName>cashonline</finalName>
      
        <pluginManagement>
         <plugins>
          <plugin>
           ...
          </plugin>
          ...
         </plugins>
        </pluginManagement>
       </build>
      
       <dependencies>
        <dependency>
         <groupId>org.jboss.seam</groupId>
         <artifactId>jboss-seam</artifactId>
         <exclusions>
          <exclusion>
           <groupId>javax.el</groupId>
           <artifactId>el-api</artifactId>
          </exclusion>
         </exclusions>
        </dependency>
        
        ...
      
       </dependencies>
      
       
      </project>
      


      Q. Is this inheritance of dependencies a good idea?
      A. It is a good idea when you only have say 5-10 sub modules (i.e. child modules). But, if you have 50+ child modules inheriting from the parent dependency management or plugin management will cause a re-release of anything inheriting from it. For example, if you have 20+ projects inheriting org.jboss.seam jar, and if that jar goes from 2.2.2.Final to 2.3, then you will have to re-release the 20+ projects inheriting from it. It appears that as of version 2.0.9, there is a new scope on a dependency called import to aggregate dependencies without inheriting them.

      The example below shows aggregation without the parent tag. The scope "import" aggregates the "myproject-parent-build".

      <?xml version="1.0" encoding="UTF-8"?>
      <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/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>com.myproject</groupId>
       <artifactId>myproject-ui</artifactId>
       <version>${myproject.version}</version>
       <packaging>war</packaging>
       <name>${project.artifactId}</name>
       <url>http://www.myorganization.com</url>
       
       <dependencyManagement>
              <dependencies>
                  <dependency>
                      <groupId>com.myproject</groupId>
                      <artifactId>myproject-parent-build</artifactId>
                      <version>${myproject.version}</version>
                      <type>pom</type>
                      <scope>import</scope>
                  </dependency>
                   ....
              </dependencies>
          </dependencyManagement>
       
       
       <dependencies>
        <dependency>
         <groupId>org.jboss.seam</groupId>
         <artifactId>jboss-seam</artifactId>
         <exclusions>
          <exclusion>
           <groupId>javax.el</groupId>
           <artifactId>el-api</artifactId>
          </exclusion>
         </exclusions>
        </dependency>
        
        ...
      
       </dependencies>
      
       
      </project>
      


      So, like you favor composition or aggregation over inheritance, in maven pom also favor aggregation over inheritance.


      Q. What are the different dependency scopes have you used?
      A. compile, provided, test, and import.

      Compile means that you need the JAR for compiling and running the app. For a web application, as an example, the JAR will be placed in the WEB-INF/lib directory.

      Provided means that you need the JAR for compiling, but at run time there is already a JAR provided by the environment so you don't need it packaged with your app. For a web app, this means that the JAR file will not be placed into the WEB-INF/lib directory.

      Test scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

      import scope is used to aggregate the specified POM with the dependencies in that POM's "dependencyManagement" section. This scope is only used on a dependency of type pom in the section and available only from Maven version 2.0.9.


      You could also read other Maven Interview Questions and Answers at Java build tools - why use Maven?

      Labels: , ,