How to trim all strings in a bean (pojo/value object) in Java

One of my favourite frameworks is webfirmframework

Forms are used everywhere in a web/desktop/other applications. In these forms, the user may enter values starting and/or ending with spaces. But we may not need theses spaces at the starting and ending, so we may want to trim it. As we know, we may simply use a trim() method to trim a string. But, what if we want to trim all strings in a bean/pojo/value object. Suppose, consider a form having some fields, first name, last name, address etc... The user may enter the values as

First Name :

Last Name :

Address : 

The values have spaces in the beginning and ending. So, to write code to trim every string separately is a kind of messing sometimes.

Here is a method which can trim all strings in a bean/pojo/value object (Only the strings will be trimmed, so it doesn't matter if it contains data types other than strings). Before that let us make a value object (POJO/bean) for these fields.
Consider it as a profile information :

So


package com.company.project.valueobjects;

import java.io.Serializable;


public class Profile implements Serializable {


private static final long serialVersionUID = 6378955155265367593L;

private String firstName;
private String lastName;
private String address;
private double latitude;
private double longitude;

public String getFirstName() {

return firstName;
}

public void setFirstName(String firstName) {

this.firstName = firstName;
}

public String getLastName() {

return lastName;
}

public void setLastName(String lastName) {

this.lastName = lastName;
}

public String getAddress() {

return address;
}

public void setAddress(String address) {

this.address = address;
}

public double getLatitude() {

return latitude;
}

public void setLatitude(double latitude) {

this.latitude = latitude;
}

public double getLongitude() {

return longitude;
}

public void setLongitude(double longitude) {

this.longitude = longitude;
}
}


And the utility class is as follows :


package com.company.project.common.helpers;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 
 * <b>File Name :</b> <i>BeanUtils.java</i> <br>
 * <b>Description :</b>
 * <p>
 * This class contains the activities of skill program. <br/>
 * <br/>
 * <b>Copyright :</b> Copyright© yyyy description
 * </p>
 * <h1>Version History :</h1>
 * 
 * Date : 20-06-2013<br/>
 * Description : First Draft
 * 
 * @version 1.0.0.1
 * @since 1.0.0.0.1
 * @author visruth
 * 
 */
public class BeanUtils implements Serializable {

/**
* This method trims all String variables defined in the bean if they have
* corresponding getter setter methods. <br/>
* Eg : BeanUtils beanUtils=new BeanUtils();<br/>
* StudentVO studentVO=new StudentVO();<br/>
* studentVO.setName("   foo   ");<br/>
* studentVO.setAddress("   bar   ");<br/>
* beanUtils.trimAllStrings(studentVO);<br/>
* System.out.println(studentVO.getName());//prints foo<br/>
* System.out.println(studentVO.getAddress());//prints bar<br/>

* @param beanObject
* @throws Exception
*             If a variable has its getter method defined but not setter
*             method will throw NoSuchMethodException instance as
*             Exception.
* @author visruth
*/
public void trimAllStrings(Object beanObject) throws Exception {
Exception noSuchMethodException = null;
boolean throwNoSuchMethodException = false;
if (beanObject != null) {

Method[] methods = null;

try {
methods = beanObject.getClass().getMethods();
} catch (SecurityException e) {
throw new Exception(e);
}

if (methods != null) {

for (Method method : methods) {

String methodName = method.getName();

if (!methodName.equals("getClass")) {

String returnType = method.getReturnType().toString();
String commonMethodName = null;

if (methodName.startsWith("get")
&& "class java.lang.String".equals(returnType)) {

commonMethodName = methodName.replaceFirst("get",
"");
String returnedValue = null;

try {
returnedValue = (String) method
.invoke(beanObject);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw e;
} catch (InvocationTargetException e) {
e.printStackTrace();
throw e;
}

if (returnedValue != null) {

StringBuilder setterMethodName = new StringBuilder();
setterMethodName.append("set");
setterMethodName.append(commonMethodName);
Method setterMethod = null;

try {
setterMethod = beanObject
.getClass()
.getMethod(
setterMethodName.toString(),
String.class);
if (setterMethod != null) {
setterMethod.invoke(beanObject,
(returnedValue.trim()));
}
} catch (SecurityException e) {
e.printStackTrace();
throw e;
} catch (NoSuchMethodException e) {
e.printStackTrace();
if (!throwNoSuchMethodException) {
noSuchMethodException = e;
}
throwNoSuchMethodException = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw e;
} catch (InvocationTargetException e) {
e.printStackTrace();
throw e;
}
}
}
}
}
}
}

if (throwNoSuchMethodException && noSuchMethodException != null) {
throw noSuchMethodException;
}
}

/**
* converts an Object to String

* @param object1
* @return String
* @author visruth
*/
public String toString(Object object) {
if (object != null) {
return object.toString();
} else {
return null;
}
}

}

To test :


public static void main(String[] args) {
BeanUtils beanUtils = new BeanUtils();

ProfileVO profileVO = new ProfileVO();

profileVO.setFirstName("      Visruth         ");
profileVO.setLastName("       CV              ");
profileVO.setAddress("        Address         ");

System.out.println(profileVO.getFirstName());
System.out.println(profileVO.getLastName());
System.out.println(profileVO.getAddress());

try {
beanUtils.trimAllStrings(profileVO);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println(profileVO.getFirstName());
System.out.println(profileVO.getLastName());
System.out.println(profileVO.getAddress());
}


And the output : 


      Visruth         
       CV              
        Address         
Visruth
CV
Address


Please share if you know any other utility methods which is not available as a ready-made component....









Comments

Popular posts from this blog

Why Should You Use Pure JavaScript for UI instead of third party js libraries

Which is the best framework for generating html from java code