Google

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: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home