Wednesday, December 25, 2013

[Java] Convert to Boolean

This is an example code that returns boolean equivalent of 'Y' or 'N' to true or false.

public boolean getBooleanEquivalent(String str){
   if (str == null 
       || ("").equalsIgnoreCase(str) 
       || str.equalsIgnoreCase("N"))
   {
      return false;
   }
   else
   {
      return true;
   }

}

JUnit ANT Script

This is an example of running JUnit using ANT script.

<?xml version="1.0" encoding="UTF-8"?>

<!-- Description :This ANT script execute JUnit. -->
<project default="junit.script" name="Example JUnit script.">
<property environment="env"/>
<property name="junit.lib" value="C:/jboss-as-7.1.1.Final/standalone/cit/lib"/>
<property name="junit.reports.dir" value="C:/jboss-as-7.1.1.Final/standalone/cit/reports/junit_ws_ext"/>
<property name="test.classes.dir" value="C:/jboss-as-7.1.1.Final/standalone/cit/reports/junit_ws_ext/test_classes"/>
<property name="report.dir" value="Z:/"/>

<path id="JUNIT.lib"> 
<fileset dir="${junit.lib}"> 
<include name="**/*.jar" /> 
</fileset> 
</path>

<path id="TEST.classes"> 
<fileset dir="${test.classes.dir}"> 
<include name="**/*.jar" /> 
</fileset> 
</path>

<taskdef name="junit"  classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask">
<classpath refid="JUNIT.lib" /> 
</taskdef>

<target name="junit.ws.ext.script" depends="junit.ext.script,copy.script"/> 

<target name="junit.ext.script">
<junit fork="yes" printsummary="withOutAndErr" >
<formatter type="xml"/>
<test name="com.mago.AllTests" todir="${junit.reports.dir}"/>
<classpath refid="JUNIT.lib"/>
<classpath refid="TEST.classes"/>
</junit>
<junitreport todir="${junit.reports.dir}/junit_ws_ext_result">
<fileset dir="${junit.reports.dir}">
<include name="TEST-*.xml"/>
</fileset>
<report format="frames" todir="${junit.reports.dir}/junit_ws_ext_result"/>
</junitreport>
</target>

<target name="copy.script">
<copydir src="${junit.reports.dir}/junit_ws_ext_result"  dest="${report.dir}/junit_ws_ext"/>
</target>


</project>

[Java] Compilation ANT Script

This is an example of ANT script that compiles Java source code.

<?xml version="1.0" encoding="UTF-8"?>

<project default="compile" name="Example Compiler Script">

<!-- Default target -->
<target name="compile" depends="create.BinFolders,delete.GeneratedClasses,compile.project" />
<!-- Properties -->
<property name="checkout.project.dir" value="C:/Jenkins/.jenkins/jobs"/>
<!-- Create bin folders -->
<target name="create.BinFolders">
<echo>[START] :Creating bin folders</echo>
<mkdir dir="${checkout.project.dir}/workspace/bin"/>
<echo>[END] :Created bin folders</echo>
</target>

<!-- Delete classes -->
<target name="delete.GeneratedClasses">
<echo>[START] :Deleting generated classes</echo>
<delete>
<fileset dir="${checkout.project.dir}/workspace/javaproject/bin" includes="**/*.class"/>
</delete>
<echo>[END] :Deleted all generated classes</echo>
</target>

<!-- Compiling javaproject project -->
<target name="compile.project" description="target :compile.project">
<echo>[START] :Compiling javaproject project</echo>
<javac srcdir="${checkout.project.dir}/workspace/javaproject/src" destdir="${checkout.project.dir}/workspace/javaproject/bin">
<classpath>
<fileset dir="C:/Server/SupportJars" includes="**/*.jar"/>
</classpath>
</javac>
<echo>[END] :Finished compiling javaproject project</echo>
</target>

</project>

CheckStyle ANT Script

This is an example of CheckStyle ANT script.

<?xml version="1.0" encoding="UTF-8"?>

<!-- Description :This ANT script execute CheckStyle. -->
<project default="checkstyle.script" name="Example CheckStyle script.">
<property environment="env"/>
<property name="checkout.project.dir" value="C:/Program Files (x86)/Jenkins/jobs"/>
<property name="checkstyle.home" value="C:/checkstyle-5.6"/>
<property name="checkstyle.reports.dir" value="C:/reports"/>
<taskdef resource="checkstyletask.properties" classpath="${checkstyle.home}/checkstyle-5.6-all.jar"/>
<target name="checkstyle.run" depends="checkstyle.script"/> 
<target name="checkstyle.script">
<tstamp>
<format property="init_time" pattern="yyyy.MMM.dd ':' HH:mm:ss z" locale="en"/>
<format property="ext_time" pattern="yyyyMMMddHHmmss" locale="en"/>
</tstamp>
<move  failonerror="false" file="${checkstyle.reports.dir}/checkstyle.html" tofile="${checkstyle.reports.dir}/archives/checkstyle_${ext_time}.html"/>
<checkstyle config="${checkstyle.home}/sun_checks.xml" failureProperty="checkstyle.failure" failOnViolation="false">
<formatter type="xml" tofile="${checkstyle.reports.dir}/checkstyle.xml" />
<fileset dir="${checkout.project.dir}/workspace/src" includes="**/*.java" />
</checkstyle>
<xslt in="${checkstyle.reports.dir}/checkstyle.xml" out="${checkstyle.reports.dir}/checkstyle.html" style="${checkstyle.home}/contrib/checkstyle-noframes.xsl"/>
</target>

</project>

PMD ANT Script

This is an example of PMD ANT script.

<?xml version="1.0" encoding="UTF-8"?>

<!-- Description :This ANT script execute PMD.-->
<project default="pmd.script" name="Sample PMD script.">
<!-- Default target -->
<target name="pmd.run" depends="pmd.cit"/> 
<!-- Properties -->
<property name="checkout.project.dir" value="C:/Program Files (x86)/Jenkins/jobs"/>
<property name="pmd.home" value="C:/pmd-bin-5.0.0"/>
<property name="pmd.reports.dir" value="C:/reports"/>
<property name="pmd.rulesets" value="java-basic,java-optimizations,java-strings"/>
<path id="PMD.lib"> 
<fileset dir="${pmd.home}/lib"> 
<include name="*.jar" /> 
</fileset> 
</path>
<taskdef name="pmd"  classname="net.sourceforge.pmd.ant.PMDTask" >
<classpath refid="PMD.lib" /> 
</taskdef>
<target name="pmd.cit">
<tstamp>
<format property="init_time" pattern="yyyy.MMM.dd ':' HH:mm:ss z" locale="en"/>
<format property="ext_time" pattern="yyyyMMMddHHmmss" locale="en"/>
</tstamp>
<move  failonerror="false" file="${pmd.reports.dir}/pmd.html" tofile="${pmd.reports.dir}/archives/pmd_${ext_time}.html"/>
<pmd rulesetfiles="${pmd.rulesets}">
<formatter type="html" toFile="${pmd.reports.dir}/pmd.html" toConsole="true"/>
<fileset dir="${checkout.project.dir}/workspace/src/">
<include name="**/*.java"/>
</fileset>
</pmd>    
</target>

</project>

FindBugs ANT Script

Example script for running FindBugs. This script can be used for Continuous Integration like Jenkins.

<?xml version="1.0" encoding="UTF-8"?>

<!-- Description :ANT script for FindBugs. -->

<project default="findbugs.script" name="CIT FindBugs">
<!-- Default target -->
<target name="findbugs.execute" depends="findbugs.exec" />
<!-- Property -->
<property name="checkout.project.dir" value="C:/Program Files (x86)/Jenkins/jobs"/>
<property name="findbugs.reports.dir" value="C:/reports"/>
<property name="findbugs.home" value="C:/findbugs-1.3.9-rc1"/>
<!-- FindBugs TaskDef -->
<taskdef name="findbugs" classpath="${findbugs.home}/lib/findbugs.jar" classname="edu.umd.cs.findbugs.anttask.FindBugsTask" />
<!-- Run Findbugs -->
<target name="findbugs.exec" description="target :project.cit">
<echo>[START] :Execute FindBugs</echo>
<tstamp>
<format property="init_time" pattern="yyyy.MMM.dd ':' HH:mm:ss z" locale="en"/>
<format property="ext_time" pattern="yyyyMMMddHHmmss" locale="en"/>
</tstamp>
<move  failonerror="false" file="${findbugs.reports.dir}/findbugs.html" tofile="${findbugs.reports.dir}/archives/findbugs_${ext_time}.html"/>
<echo> Time now is ${init_time}</echo>
<echo> Ext time is ${ext_time}</echo>
<findbugs  home="${findbugs.home}"  workHard="true" output="html" outputFile="${findbugs.reports.dir}/findbugs.html" failOnError="true" errorProperty="findbugsFailure" effort="min" reportLevel="low" jvmargs="-Xmx1024M">
<sourcePath path="${checkout.project.dir}/workspace/src/**.java" />
<class location="${checkout.project.dir}/workspace/bin" />
</findbugs>
<echo>[END] :Finished running FindBugs</echo>
</target>
</project>

Email ANT Script

Example script to send email.

<?xml version="1.0" encoding="UTF-8"?>

<project default="email" name="Email Example">
<target name="email">
<mail mailhost="email-server.com" subject="Sample ANT Email">
<from address="sender@gmail.com"/>
<replyto address="sender@gmail.com"/>
<to address="receiver1@gmail.com"/>
<to address="receiver2@gmail.com"/>
<message>
Hi,
This is a sample ANT email
Thank you. 
</message>   
</mail>
</target>
</project>

Thursday, December 19, 2013

Generate EAR File Using ANT Script

In this example, I will create an ANT script that generate EAR file. The only requirement is the ANT script tool that you can download from Apache. There are only 2 files to create, i.e. build.xml and application.xml.

First is to create META-INF folder. Under this folder create application.xml file with the following entries:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN" "http://java.sun.com/dtd/application_1_3.dtd">
<application id="Application_ID">
    <display-name>MYEAR</display-name>
    <module>
        <web>
            <web-uri>dummy1.war</web-uri>
            <context-root>dummy1</context-root>
        </web>
    </module>
<module>
        <web>
            <web-uri>dummy2.war</web-uri>
            <context-root>dummy2</context-root>
        </web>
    </module>

</application>

Then create build.xml outside META-INF folder.

<?xml version="1.0" encoding="UTF-8"?>         
<project name="bankfusion" default="build">
<target name="build">
    <ear earfile="C:/folder/MyEar.ear"
         appxml="C:/folder/META-INF/application.xml">
      <fileset dir="C:/folder">
        <!-- WAR files should be copied in c:/folder -->
        <include name="*.war"/> 
      </fileset>
    </ear>
  </target>
</project>

This is the folder structure:

C:\folder
     + WEB-INF
          - application.xml
     + build.xml

To run the script, go to c:\folder then type ant.

i.e. 
c:\folder\ant

Monday, December 16, 2013

[Java] Encryption Using SHA-256

When there is a requirement to save password to a database, there is always a need for this password to be secured. One way of securing the password is to encrypt it. Below is a sample password encryption class using SHA-256.


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
import org.jboss.security.auth.spi.Util;

public class EncryptionUtil 
{
 
 private final static Logger LOG = Logger.getLogger(EncryptionUtil .class .getName()); 
 
 /**
  * Encrypt with SHA-256 and BASE64.
  * @param str String to be encrypted.
  * @return    Encrypted string.
  */
 public static String encrypt(String password) 
 {
      return Util.createPasswordHash("SHA-256", "BASE64", null, null,password);
 }

}//end class

[Java] Utility Class for Date Formatting

Sample class contains methods that parses Date object to different formats. This class can be used as utility class in converting Date object to String or Calendar.


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Logger;

public class MyDateUtility

{
private final static Logger LOGGER = Logger.getLogger(MyDateUtility.class .getName());

/**
* Parses the date from YYMMDD to yyyy-MM-dd+HH:mm format.
* @param date - cyymmdd
* @return
*/
public static String formatDate1(String date)
 {
Date d1 = null;
SimpleDateFormat df=new SimpleDateFormat("yyMMdd");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd+HH:mm");
Calendar cal = new GregorianCalendar();

try 
  {
d1 = df.parse(date);
} catch (ParseException e) 
  {
e.printStackTrace();
}
   cal.setTime(d1);
   
   return output.format(d1);

}//end method


       /**
       * Return String Date based on the toFormat parameter.
       */
public static String formatDate(String date, String currentFormat, String toFormat)
 {
Date d1 = null;
SimpleDateFormat df=new SimpleDateFormat(currentFormat);
SimpleDateFormat output = new SimpleDateFormat(toFormat);
Calendar cal = new GregorianCalendar();

try 
  {
d1 = df.parse(date);
} catch (ParseException e) 
  {
e.printStackTrace();
}
   cal.setTime(d1);
   
   return output.format(d1);
}//end method

/**
        * Return Date in Calendar format.
        */
public static Calendar getCalendarObject(String date, String format)
 {
Calendar cal = new GregorianCalendar();
SimpleDateFormat output = new SimpleDateFormat(format);
try 
  {
cal.setTime(output.parse(date));
} catch (ParseException e) 
  {
e.printStackTrace();
}

return cal;
}//end method

/**
* Format Calendar object to string based on the passed format.
* @param cal
* @param format - e.g. yyyy-MM-dd+HH:mm
* @return
*/
public static String calendarToStringFormat(Calendar cal, String format)
        {
SimpleDateFormat output = new SimpleDateFormat(format);
return output.format(cal.getTime());
}//end method

}//end class

Sunday, December 15, 2013

[Java] Splitting String using Guava API


The method below accepts the following parameters:
   1. splitLen - number of characters the string will be splitted.
   2. arrayLen - new size of a return array.
   3. str - string to be splitted.


public static String[] splitString(int splitLen, int arrayLen, String str)
{
String[] returnTokens = null;
String[] tokens = null;

Preconditions.checkArgument(splitLen > 0);
tokens =
   Iterables.toArray(
       Splitter
           .fixedLength(splitLen)
           .split(str),
       String.class
   );

returnTokens = Arrays.copyOf(tokens, arrayLen);

return returnTokens;

}//end method


This is how to call the method.

String str = "Please split the string into 5 characters each but return only the first 3.";
String[] splittedStr = splitString(5,3,str);

[Java] Caching Using XMLBeans

In this example, I will create caching service. The properties file  will be cached during start-up of application server - I used Apache Tomcat version 6. I decided to used Servlet to make caching portable. There are other ways of caching properties file based on the application server, e.g. in Websphere - Custom Service can be used but that would require update to code when application is deployed to other application server like JBoss. Lazy loading is also another way but that would impact the performance of the initial process that invoke the caching process.

Now, let us start coding the caching process...


Step 1: Create XSD for caching configuration.

What I want is to have a configuration file that I can use to define caching classes. I want it re-usable so that other Developer can define their own caching classes. Below is the schema that define the XML configuration file.

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://mago.com/cache">
  <xs:element name="CacheConfiguration">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Configuration" maxOccurs="unbounded" minOccurs="0">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="Key"/>
              <xs:element type="xs:string" name="ClassName"/>
              <xs:element type="xs:string" name="ConfigurationFile"/>
              <xs:element type="xs:string" name="Description"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>


Below is the XML equivalent which I will save in a file - cache.xml. This file can have multiple configuration entries.

<?xml version="1.0" encoding="utf-8"?>
<CacheConfiguration>
  <Configuration>
    <Key>DummyConfig</Key>
    <ClassName>com.mago.cache.example.DummyClass</ClassName>
    <ConfigurationFile>C:/dummy1.properties</ConfigurationFile>
    <Description>This is dummy cache class</Description>
  </Configuration>
</CacheConfiguration>


Step 2: Generate XSD classes using XMLBeans.

Generate XMLBeans classes using scomp command. Add generated Jar file to Eclipse project build properties.

scomp -out CacheConfiguration.jar cache-config.xsd


Step 3: Create interface class that has cache() and getCache() methods.


import java.util.Map;

public interface Cache 

{
public void cache(String propertiesFileAbsolutPath);
public Map<String,String> getCache();


}//end class


Step 4: Create cache implementation class.

import java.util.Map;

public class DummyCache implements Cache {


   private Map<String,String> map;


@Override

public void cache(String propertiesFileAbsolutPath) 
 {
Enumeration enuKeys = null; 
  map = new HashMap<String,String>(); 
  Properties properties = new Properties(); 
  try { 
    properties.load(new FileInputStream(propertiesFileAbsolutPath)); 
  } catch (FileNotFoundException e1) 
  { 
     e1.printStackTrace(); 
  } catch (IOException e1) 
  { 
    e1.printStackTrace(); 
  } 

  enuKeys = properties.keys(); 

  while (enuKeys.hasMoreElements()) 
  { 
    String key = (String) enuKeys.nextElement(); 
    String value = properties.getProperty(key); 
    map.put(key, value); 
    LOGGER.info("Caching " + value + " with key " + key); 
  }
}

@Override

public Map<String, String> getCache() 
 {
return map;
}

}//end class



Step 5: Create singleton class that reads cache.xml.

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.xmlbeans.XmlException;
import com.mago.cache.CacheConfigurationDocument;
import com.mago.cache.CacheConfigurationDocument.CacheConfiguration;
import com.mago.cache.CacheConfigurationDocument.CacheConfiguration.Configuration;


public class CacheManager {


private final Logger LOGGER = Logger.getLogger(CacheManager.class .getName()); 
private static CacheManager instance;
private static Map cacheMap;

public static CacheManager getInstance(){
if (instance == null) {
instance = new CacheManager();
cacheMap = new HashMap();
}
return instance;
}

/**
* Add objects to cache using reflection.
*/
public void cache(){
//Use reflection
Class cls = null;
Object obj = null;
Method method = null;
Class noparams[] = {};
Map<String,String> cachedItems = null;
//XMLBeans
CacheConfigurationDocument cacheConfigDoc = null;
CacheConfiguration cacheConfig = null;
//Get config file
String configurationFile = "c:/cache.config";
LOGGER.info("Configration file is " + configurationFile);
File xmlFile = new File(configurationFile); 
//Parse using xmlbeans
try {
cacheConfigDoc = CacheConfigurationDocument.Factory.parse(xmlFile);
cacheConfig = cacheConfigDoc.getCacheConfiguration();
Configuration[] configuration = cacheConfig.getConfigurationArray();
for(Configuration c : configuration){
//Load
try {
cls = Class.forName(c.getClassName());
obj = cls.newInstance();
method = cls.getDeclaredMethod("cache", new Class[]{String.class});
method.invoke(obj, c.getConfigurationFile());
method = cls.getDeclaredMethod("getCache", noparams);
cachedItems = (Map<String,String>)method.invoke(obj, null);
//Add to Map
cacheMap.put(c.getKey(),cachedItems);

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

}//end for
} catch (XmlException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}//end method

/**
* Search value base on key.
* @param objectName
* @param key
* @return
*/
public String getCacheItemValue(String objectName,String key)
 {
Map cacheItems = (Map)cacheMap.get(objectName.trim());
String cacheValue = (String)cacheItems.get(key.trim());
return cacheValue;
}

   
   /**
   * Re-cache
   */
   public void reCache()
   {
cache();
   }

}//end class




Step 6: Create Servlet class that will call CacheManager during startup.


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;
import com.mago.cache.example.CacheManager;
import java.io.IOException;


/**

 * Servlet implementation class CacheServlet
 */
public class CacheServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final static Logger LOGGER = Logger.getLogger(CacheServlet.class.getName());


    /**

     * Default constructor. 
     */
    public CacheServlet() {
    }
    

public void init() throws ServletException 

 {
CacheManager.getInstance().cache();
}//end method

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String req = request.getParameter("action");
if("recache".equalsIgnoreCase(req))
  {
CacheManager.getInstance().reCache();
}else if("getvalue".equalsIgnoreCase(req))
  {
String cache = request.getParameter("cache");
String key = request.getParameter("key");
String value = CacheManager.getInstance().getCacheItemValue(cache, key);
LOGGER.info("Value from cache is " + value);
}

}//end method


/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{

}


}//end class



Step 7: Update web.xml. Set Servlet load-on-startup to 1 - this means, Servlet will be loaded during Apache Tomcat start-up.


<?xml version="1.0" encoding="UTF-8"?>
<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>StartupService</display-name>
<servlet>
<description>
</description>
<display-name>CacheServlet</display-name>
<servlet-name>CacheServlet</servlet-name>
<servlet-class>com.mago.cache.example.CacheServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CacheServlet</servlet-name>
<url-pattern>/CacheServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>



Step 7: Start Apache Tomcat and check if the caching is successful using Servlet - http://localhost:8080/<web context>/CacheServlet?action=getValue&cache=DummyConfig&key=<key of the property>

That's it!

Note : I use BareTail to monitor log file. It is similar to the 'tail' command in Unix or Linux.