Is static method in Util Class ThreadSafe?

July 29, 2016 at 3:40 am | Posted in Java | Leave a comment

Recently one person ask me this question and my obvious answer was “OK, This should not be any problem to Threads…”. I am from old school and believed that most of time all thread related problems will run away if you stick to local variables. Am I correct?

Continue Reading Is static method in Util Class ThreadSafe?…

Spring Boot – 1

July 16, 2016 at 2:30 am | Posted in Java, Spring | 1 Comment

Unfortunately I never get any hands-on Spring Boot, (although I worked on various Spring based projects) so I started my own project in Spring Boot. I am sharing my experiences here in this blog.

Continue Reading Spring Boot – 1…

EclipseLink Weaving Feature

June 6, 2014 at 7:56 am | Posted in Uncategorized | Leave a comment

     Weaving is a technique of manipulating the byte-code of compiled Java classes. EclipseLink uses weaving to enhance both JPA entities and Plain Old Java Object (POJO) classes for such things as lazy loading, change tracking, fetch groups, and internal optimizations.

This weaving is used for performance optimization. This weaving is extremely important if one want to enable feature of Lazy Loading.

Weaving can be performed either dynamically at runtime, when Entities are loaded, or statically at compile time by post-processing the Entity .class files. By default, EclipseLink uses dynamic weaving whenever possible. This includes inside an Java EE 5/6 application server and in Java SE when the EclipseLink agent is configured. Dynamic weaving is recommended as it is easy to configure and does not require any changes to a project’s build process.

Dynamic Weaving: For enabling Dynamic Weaving we have to follow above steps: 

  1. (For J2SE) Modify your application JVM command line to include the above: -javaagent:eclipselink.jar
  2. Ensure that eclipselink.jar is in your classpath. While running test I found that it complains about eclipselink though the jar file in classpath. For override this I gave whole path of eclipselink.jar. In J2EE container class loader should able to find eclipselink. So we can put eclipselink in classpath or in EAR. 
  3. Package and Deploy application.

Identify Weaving is enabled:

First make sure that your persistance.xml contains logging “eclipselink.logging.level” as a “FINEST”. This not necessary for production but just need to check if weaving applied or not.

Your log file you can find following values :

property=eclipselink.orm.throw.exceptions; default value=true
property=eclipselink.weaving.changetracking; default value=true
property=eclipselink.weaving.lazy; default value=true
property=eclipselink.weaving.eager; default value=false
property=eclipselink.weaving.fetchgroups; default value=true

Now here a word of caution. in your “persistence.xml”  we have to give

<property name=”eclipselink.weaving.internal” value=”false”/>

This is because of a defect which try to store Integer in Double in the case when DB had NULL values.  This is closed on 31 Jan 2012.But I guess we are still using early build which do not have this fix. Bug 313023



Identify Differences between two DB’s

April 6, 2012 at 4:01 pm | Posted in Java | Leave a comment

In any project, developers came across 2 – 3 different DB environments. Mostly DEV, TEST, STAGE and some times PROD. Now most of the times, there is process for adding or changing any DB related stuff to keep smooth transition between DEV, TEST and STAGE. Some of the projects apply DB changes for all DB’s at the same time when application moves from DEV to TEST.

Though there are x processes to keep DB’s same at specific interval of time we came across situations where some of changes did not push to targeting environments. In such situations we feel that there should be some utility which will show you difference between two Databases.

Recently I came across one of such utility which gives you differences between data base schema’s. I got one tool known as MAD for DB (Migration ADvisor for Databases)

It analyzes the differences between two database schema’s. It automatically finds out which changes require individual migration effort and advises migrator which concrete data-sets need fixing. The main benefit of the tool is to quickly filter out database changes which are not relevant for the task of data migration, automatically verify existing data if it matches new constraints and provide a summary sorted by severity of the change.

The only problem, I faced that this includes DB Sanity Report which checks the existing data matches with new constraint takes too much time. If this check is optional then it will be great.

For using this, one need to have two property files each pointed to one DB place in bin directory of mad4db and one should copy your jdbc driver jar file into lib of mad4db.

Property Files: <db / your name>

Property file name should end with  =>  This property file should contains DB related details.


db_driver=<e.g. for oracle => oracle.jdbc.OracleDriver>




For running one should go to bin folder from command prompt:

mad4db db1 db2

For extra information please visit

Following Reports get generated by this mad4db. Hope you like this.

Severity Report:

The severity report lists changes ordered by their severity, explaining which risk results from a change and what user action is necessary:

Diff View:

The diff view provides an element comparison view over two levels of detail, first a schema diff with a table summary:

For each table, a table view is available which lists all details of the table. For changed tables, a detail diff view is available:

DB Sanity Report

For new constraints on existing data structures (or constraints made more restrictive), Mad For DB uses DB Sanity to check if the existing data matches the new constraint:

Formatting and Parsing Currency

March 31, 2011 at 8:12 pm | Posted in Java | 4 Comments

Suppose you are developing an application in java; may be Web Apps or Standalone App and you have to display Currency Internationalization according to locale. How one can implement it ? May be we can get the numerical data attached Currency Symbol. Am I right ? You might wrong. Because Currency Internationalization is not so simple.

Generally we only look to the currency format but in case of Currency Internationalization there are various factors like rounding, grouping, group separators, fractional separators, currency placement, symbol etc. Generally we need to be consistence to the presentation format of corresponding locale.

Instead of going to each thing I just pick up Grouping Separator.

Grouping Separator : The Integer portion of a number often split into groups by Grouping Separator.

  • Western Numbers generally separate numbers into thousands or groups of 3 digits.
  • Chinese & Japanese Number Systems separate numbers into 10 thousands or groups of 4 digits.
  • While Indian Format groups the lowest order 3 digits (Thousand) & then every 2 digits after that.
  • Grouping Examples
    Culture Example Notes
    British 1,234,567,890.12 Groups of 3
    12 3456 7890.12

    12 3,456 7,890.12
    Groups of 4, separated by ideographic characters and optionally a thousands separator.
    Indian 1,23,45,67,890.12 One group of 3, then groups of 2
    German 1.234.567.890,12 Groups of 3, separator is full-stop
    Swiss 1’234’567’890,12 Groups of 3, separator is apostrophe1
    French 1 234 567 890,12 Groups of 3,
    separator is a thin non-breaking space2 or “une espace fine insécable”.

    While one has to code currency symbols in UNICODE. One can find the table related to symbol & according unicode

    Currency Symbol Examples
    Currency Unicode Value Notes
    dollar sign U+0024 $
    pound sign U+00A3 £
    yen sign U+00A5 ¥
    yen character U+5186
    euro sign U+20AC
    thai baht sign U+0E3F ฿
    french franc sign U+20A3
    lira sign U+20A4
    korean won sign U+20A9

    Now how one can embed the whole logic related to Separator, currency symbol, position etc. ?

    Here in Java NumberFormat class comes to rescue us. By using only 2 methods we can achieve this.

    NumberFormat.getCurrencyInstance : NumberFormat class provides the functionality for formatting and parsing currency. NumberFormat class also provides methods for defining which locales have currency formats.

    NumberFormat.format() : This method returns a format string of a currency.

    Above one can find code :

    import java.text.*;
    import java.util.*;

    class CurrencyFormatExample {
    public void currencyFormat(Locale currentLocale) {
    Double currency = new Double(9843.21);

    NumberFormat currencyFormatter;
    String currencyOut;

    currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
    currencyOut = currencyFormatter.format(currency);
    System.out.println(currencyOut + " " + currentLocale.toString());

    public static void main(String args[]) {
    Locale[] locales = new Locale[]{new Locale("fr", "FR"), new Locale("de", "DE"),
    new Locale("ca", "CA"),new Locale("rs", "RS"),new Locale("en", "IN")

    CurrencyFormatExample[] formate = new CurrencyFormatExample[locales.length];

    for (int i = 0; i < locales.length; i++) {

    Output :

    9 843,21 € fr_FR

    9.843,21 € de_DE

    CAD 9.843,21 ca_CA

    RSD 9,843.21 rs_RS

    Rs.9,843.21 en_IN

    Ref :

    Identify Mobile

    January 12, 2011 at 6:54 pm | Posted in Java | Leave a comment

    Now a days GPRS & 3G is very common. Anybody can browse internet by mobiles / smartphones. Most of the times mobile users gets annoyed because of large images, flash objects etc. So generally companies launch different version mobile-friendly website having domain “.mobi”  or having sub-domain “.m”.

    Now what happens if mobile user comes to the classic web page. User has to bear large images / flash scripts etc. And on footer (s)he might find a link for mobile version. 🙂

    In this web2.0+ world ( I am not sure this is web 3.0 or in between ) we should detect mobile-user to give rich user experience.  By identifying mobile user we can redirect user to mobile friendly  website. Normally  this can be identified by using UserAgent  header values. This header values depend upon embedded browser & make of device. When I searched user-agents for mobile then I found 70+ different user-agent signatures. Hard code all these signatures is pretty straightforward option but having  heavy maintenance 🙂 .
    While searching for  better or smart option I came across one open source project WURFL : Wireless Universal Resource File. The WURFL is XML Configuration file which contains information about capabilities & features of many mobile devices. WURFL supports JAVA, PHP and .NET API and Tera-WURLF supports MySQLDB instead of XML Configuration file.

    Later surprisingly I come to know Spring also having some initiative related to mobile. Spring having two projects :

    1. Spring Android : It is Android Client
    2. Spring Mobile : Detecting device

    While viewing source code of Spring Mobile I realized Spring implement both approaches for detecting device : HardCoded (lite) & WURFL.

    I think Using Spring Mobile with WURFLDevice will be good option if you are using Spring framework. As spring provides light wrapper above WURFL API to integrate in Spring Framework.

    Still I have question how we can change size & resolution of images depend upon the device? The best bet is remove all images. The other options I found in same project under utilities section

    1. GAIA Image Transcoder (
    2. Image Server (

     Worth to look WURFL project !!!

    Usage Of Varargs

    February 22, 2010 at 12:40 pm | Posted in Java | Leave a comment

    In our day to day work we can use variable arguments. This feature gets introduced in J2SE 5.0. In my case I used this to build strings for logger.

         * Builds the string.
         * @param addSpace the add space
         * @param variableStrings the variable strings
         * @return the string
        public static String buildString(boolean addSpace, String… variableStrings) {
            StringBuilder sb = new StringBuilder();
            if (null != variableStrings) {
                for (String arg : variableStrings) {
                    if (isEmpty(arg)) {
                        arg = CommonConstantsIF.STR_UNDERSCORE;

                    if (addSpace) {
            return sb.toString().trim();

    Now while calling this method you can pass array of strings or comma separated String. Yes it works…

         * Test build strig.
        public void testBuildStrig() {
            String buildString = “”;
            buildString = StringUtil.buildString(true, “Nikhil”, “Suhas”, “Sidhaye”, “:”, “Project”);
            Assert.assertTrue(“Nikhil Suhas Sidhaye : Project”.equals(buildString));

    Here I pass comma separated Strings similarly one can pass String array too… So when you are going using Varargs feature ?

    Create Sitemap by GSA

    February 18, 2010 at 10:50 am | Posted in GSA, Java | Leave a comment
    Tags: ,

    From Google Search Appliance we can generate sitemap.xml.
    Unfortunately this option is not well documented & find one of the api documentation. Following is process of creating sitemap.xml

    Here I am describing process for Google Search Appliance 5.0 (GSA 5.0) but similar step should be applicable for GSA 5+. This option is not working for GSA 4.x

    One should login to admin console of GSA by http://<YourGSABox&gt;:8000/EnterpriseController Go to Status & Reports –> Crawl Diagnostics.

    Now one should select URL display mode as List Format. By default it is Tree Format. After that export all pages to a file.

    Now here is word of caution given by Google that one should exclude all errors otherwise sitemap.xml will contains URL having 404 & other errors.

    For exporting limit is 30,000 URL or 10MB file size. If you have more URLs then one should use collection wise or filter by “URLs starting with” option for export sitemap.

    Please have a look on attached image to get more clarity.

    GSA Sitemap

    TestNG Annotations Problem

    November 25, 2009 at 2:43 pm | Posted in Java | 2 Comments
    Tags: , ,
    Yesterday one of my colleague come to my desk saying some problem in configuring TestNG in Eclipse. I was surprise because I am using TestNG more than 2 years & never ran into any problem.

    RunInfo] Adding method selector: org.testng.internal.XmlMethodSelector@13f5d07 priority: 10
    [TestNGClassFinder] SKIPPING CLASS class com.test.TestController no TestNG annotations found
    [SuiteRunner] Created 1 TestRunners
    [TestRunner] Running test com.test.TestController on 0  classes,  included groups:[] excluded groups:[]
    [TestRunner] ===
    [TestRunner] Found 0 applicable methods

    This problem is strange to me. Even I used my test classes to my colleagues’ machine, problem not get solved.

    When we started from scratch we observed that in run / debug configurations annotation compliance level is javadoc instead of jdk.

    Because of this setting TestNG enable to read annotations & throws error no TestNG annotations found.

    annotation eclipse Settings for TestNG

    The above image will clarify problem more.

    FindBugs Part 1

    November 23, 2009 at 9:48 pm | Posted in Java | Leave a comment
    Tags: , , , , ,

    FindBugsTM : static code analysis tool

    FindBug is a static code analysis tool that examines your class or JAR files looking for potential problems by matching your byte-code against a list of bug patterns. With static code analysis tool, you can analyze software(s) without actually running the program.

    Getting started with FindBugs:

    To run FindBugs, you will need a Java Development Kit (JDK), version 1.4 or higher. One should download the latest release of FindBugs — currently 1.3.9. After downloading the zip or tar, unzip it into a directory of your choice. That’s it — the install is finished.

    Running FindBugs:

    Like most tools these days, you can run FindBugs in multiple ways — from a GUI, from a command line, using Ant, as an Eclipse plug-in and using Maven.

    Using the FindBugs UI:

    Using the FindBugs UI is straightforward, but a couple of points deserves some elaboration. One of the advantages of using the FindBugs UI is the description provided for each type of detected problem. Descriptions are provided for each bug pattern, which is extremely useful when you’re first becoming acquainted with the tool. Equally useful is the Source code tab in the lower pane of the window. If you tell FindBugs where to find your source, it will highlight the offending line of code when you switch to the appropriate tab.

    It’s also important to mention that if you choose xml as your output option when running FindBugs as an Ant task or from the command line, you can load the results of a previous run into the UI. Doing so is a great way to leverage the advantages of the command-line-based tooling and the UI tooling at the same time.

    For day to day activity developers find Eclipse plug-in is more suitable. But for this blog we will stick to ant as it gives us variety of reports depending upon the provided style sheets.

    Integrate with Ant:

    In build.xml we need to write the following code

    <!– =================================

    target: findbugs

    ================================= –>

    <target name=”findbugs” depends=”compile” description=”description”>

    <taskdef name=”FindBugs” classname=”edu.umd.cs.findbugs.anttask.FindBugsTask”>


    <pathelement location=”${findbugs.home}/lib/findbugs-ant.jar” />



    <FindBugs home=”${findbugs.home}” output=”html” outputFile=” findbug-report.html”  jvmargs=”-Xms60m -Xmx250m” stylesheet=”default.xsl|fancy.xsl|fancy-hist.xsl|plain.xsl|summary.xsl”>

    <class location=”${webinf.dir}/classes” />

    <sourcePath path=”JavaSource” />



    Let’s take a closer look at what’s going on in this code.

    Target: Notice that the target depends on the compile. It’s important to remember that FindBugs works on class files, not source files, so making the target depend on the compile target ensure that FindBugs will be running across the up-to-date class files. FindBugs is flexible about what it will accept as input, including a set of class files, JAR files, or a list of directories.

    Taskdef: Here we define task def name. This is general ANT Practice.

    FindBug.home: One should mention directory that contain findbugs.


    Output: The optional attribute output specifies the output format that FindBugs will use for its results. The possible values are xml, text, or emacs. If no output File is specified, then FindBugs prints to standard out. The XML format has the added advantage of being viewable within the UI.

    jvmargs: In large projects it is tend to get OutOfMemoryException. To take care of such situation we should pass max and minimum memory by jvmargs. This is optional one.

    Stylesheet: It specifies stylesheet to be used if output is html. This is optional attribute.

    Class / ClassRegex: The class element is used to specify which set of JARs, class files, or directories you want FindBugs to analyze. To analyze multiple JARs or class files, specify a separate class element for each. The class element is required unless the project File element is included. See the FindBugs manual for more details.

    AuxClasspath: You list your application’s dependencies by using the nested element auxClasspath. These are classes that your application needs, but you don’t want FindBugs to analyze. If you don’t list your application’s dependencies, FindBugs will still analyze your classes as well as it can, but it will complain when it is unable to find one of the missing classes. as with the class element, you can specify multiple auxClasspath elements in the FindBugs element. The auxClasspath element is optional.

    SourcePath: If the sourcePath element is specified, the path attribute should indicate a directory that contains your application’s source code. Specifying the directory allows FindBugs to highlight the source code in error when viewing the XML results in the GUI. This element is optional.

    Different Bugs identified by FindBugs:

    • Use Long.valueOf(…) instead of new Long(…)
    • Need to replace things like

    int num = (int) (100000 * Math.random());
    Random r = new Random();

    • concatenation with + , use String Buffer or String Builder
    • change key set by entry set

    Bug categorization:

    FindBug categorize the bugs in following categories

    •  Bad practice Warnings
    • Correctness Warnings
    • Malicious code vulnerability Warnings
    • Multithreaded correctness Warnings
    • Performance Warnings
    • Dodgy Warnings


    Next Page »

    Create a free website or blog at
    Entries and comments feeds.