Monday 25 April 2016

Currency Conversion or Formatting As per your needs in Java


How to convert Java String as per Currency Standards of ISO 4217  ?

Solution:

I spent lot of time to get this kind of logic for currencies in java.  I think it will be helpful if any one need to play with currency formats in java.
You can enable grouping and symbols if needed .

/***
*  Used to convert any amount to any currency.
* Ex: 12.3446 to 12.34 for USD
* Ex 10001.12 to 10001 for JPY
*
*/

// you can get currency using java.util.Currency

String convertToCurrency(String actual, Currency curr)
    {
       
        BigDecimal bd  = new BigDecimal(actual);
        NumberFormat nf  = NumberFormat.getCurrencyInstance();
        nf.setCurrency(curr);
        nf.setGroupingUsed(false);
        nf.setMaximumFractionDigits(curr.getDefaultFractionDigits());
        nf.setMinimumFractionDigits(curr.getDefaultFractionDigits());
        DecimalFormat formatter = (DecimalFormat) nf;
        DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
        symbols.setCurrencySymbol(""); // Don't use null.
        formatter.setDecimalFormatSymbols(symbols);
        return formatter.format(bd);
    }

Monday 11 April 2016

Apache Camel Custome Annotated Beans Access



How to do Custom Bean Annotation Process in Apache Camel?
Sol:

In Camel we always have access to Camel Context. Using camel context we can access spring context as shown below. Once we have spring context we can access all features provided by Spring like getting annotated  beans .

Steps:
  1. Add Component scan to Spring for annotated beans.
  2. Annotate the class with  intended annotation
  3. As Code show below  
  4. Java code -   Link here   Java code 



Tuesday 5 April 2016

Null check in Java 8


Now java is becoming more advanced and programmer friendly with java 8.

now to check null we no need custom classes or if conditions.

Solution:

/*{
   "one": "two",
   "key": "value"
}*/

String body= "Sample Json String Shown above";

JSONObject on = new JSONObject(body);
Map<String,String> map = new HashMap<>();
       
        Set<String> keySet = new HashSet<>();

        Optional.ofNullable(keySet).ifPresent(x-> x.forEach(z-> map.put(z, on.getString(z))));

Steps:
1. Checking null (Optional.ofNullable(keySet))
2. If not null or actual object present (ifPresent)
3. Iterate over collection (forEach)
4. Filling Map