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

Thursday, 17 March 2016

Simple Xpath Expression Evaluator

Guys These days I am struggling with simple XPath expression evaluator. I perplexed with many solution suggested in different blogs.

but Finally I end up my own way of simple class will do the work pretty much.

If you provide the expression and Actual xml then it will return you the value of Node/Attribute.

I also added assertXMLEquals  which u can use in your work of testing .

How to use 
 1. XpathEvaluator.assertXMLEquals(expected, expression, xml, "prefix", "https://test.host.com/xsd")

Download from here...

Tuesday, 23 February 2016

How to create Webservices in Eclipse


How to start Webservices Project in Eclipse ?
How to create WSDL from java beans ?


It is a quick reference .


Steps to follow in Eclipse:
  1. Setup Tomcat to Eclipse ( you google this easily)
  2. File>new Project>web> dynamic web project
  3. Provide name of project when it asks for you.
  4. Now we have project.
  5. Create a java bean class.
  6. Add WSDL generated packages/libraries like APACHE CXF, AXIS2…etc
  7. Set up in Project >Webservices>AXIS2 Home
  8. Set up in Project >Webservices>CXF Home
  9. Right Click on Implementation Class and Webservices>generate
  10. Follow steps to create WSDL as screen directs you.

Wednesday, 27 January 2016

Two classes have the same XML type name {http://camel.apache.org/schema/spring}propertyDefinition.

Two classes have the same XML type name {http://camel.apache.org/schema/spring}propertyDefinition.



Problem:
 org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [behaviour.Error.xml]
Offending resource: class path resource [Config/behaviour/behaviour.TP2.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Failed to create the JAXB binder; nested exception is javax.xml.bind.JAXBException: Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
Two classes have the same XML type name "{http://camel.apache.org/schema/spring}propertyDefinition". Use @XmlType.name and @XmlType.namespace to assign different names to them.
 this problem is related to the following location:
  at org.apache.camel.model.config.PropertyDefinition
  at private java.util.List org.apache.camel.model.config.PropertiesDefinition.properties
  at org.apache.camel.model.config.PropertiesDefinition
 this problem is related to the following location:
  at org.apache.camel.model.PropertyDefinition
  at private java.util.List org.apache.camel.model.PropertiesDefinition.properties
  at org.apache.camel.model.PropertiesDefinition
  at private org.apache.camel.model.PropertiesDefinition org.apache.camel.spring.CamelContextFactoryBean.properties
  at org.apache.camel.spring.CamelContextFactoryBean
Two classes have the same XML type name "{http://camel.apache.org/schema/spring}propertiesDefinition". Use @XmlType.name and @XmlType.namespace to assign different names to them.
 this problem is related to the following location:


 Solution:
 Different Version of camel jars are loaded , so please check recently edited/added build files with camel version.

Tuesday, 22 December 2015

Restrict Logging of StackTrace in Java


Problem :
we have a requirement of restricting the logging of full stacktrace due to many reasons.

Solution:
we have two ways to control this printing of stakctrace.
one solution fits for application which is in devlopement stage and second one is for production stage.

1. Application in DEV STAGE :
so we have option to customize the printing of stack trace.
please go through this method .

public String customizeStackTrace(Throwable e, int maxLines)
    {
       
        StringBuilder newStackStrace = new StringBuilder(e.getMessage()+"\n"); 
        StackTraceElement[] elements = e.getStackTrace();
        for (int i = 0; i < maxLines; i++)
        {
            newStackStrace.append(elements[i]).append("\n");
        }
        return newStackStrace.toString();
    }



2. Application in PROD STAGE:
 so we have to control using log4j .
If you are using log4j version lessthan 1.12.16 then you need to upgrade to 1.2.16 or more.
and use layout as
<layout class="org.apache.log4j.EnhancedPatternLayout">
            <param name="ConversionPattern" value=" %d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1}: %m%n %throwable{10}" />
        </layout>




I think you found right information here. see you soon with new issue i found..

Wednesday, 15 July 2015

Eclipse Code Template


I came across importing same stuff frequently. I thought of creating the shortcut for this.
Then I found eclipse is good in providing this kind of stuff.

The stuff  I want to import are Logger from SLF4J, for this we have to import slf4j and lo4j api in our class.Which is irritating stuff to type everytime while creating new class.

Eclipse already have code templates which some of them are shown below:










Now we will  create a code template which will show as above

Solution:

Window->Preferences->Java -> Editor -> Templates
 
 
you Will see below :






Click on "New" 



Enter template Name as "slf4j" 
Write description
Add Patteren given below in the box.

Click OK.


For SLF4J:

${:import(org.slf4j.Logger,org.slf4j.LoggerFactory,org.slf4j.Logger,org.slf4j.Logger)}
private static final Logger LOGGER = LoggerFactory.getLogger(${enclosing_type}.class);


For Log4J:

${:import(org.apache.log4j.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);



Now you will see the slf4j code template in your eclipse .
 Start Typing sl and CTRL+SPACE. you will...like this..:-)