Showing posts with label apache commons. Show all posts
Showing posts with label apache commons. Show all posts

Using Apache commons to truncate a string

Truncate a string and add ellipsis as necessary.

import org.apache.commons.lang.StringUtils;

StringUtils.abbreviate(str, maxLength);

Using Apache commons PropertyUtils

The beanutils package contains a very useful class, PropertyUtils, that you can use to access member values. So in the code below if request was an HTTP request object and the propertyPath was 'request.attribute(myBean).myBeanValue'. The PropertyUtils class would obtain the myBean object from the request attribute map and then call its getter method for the myBeanValue member.


import org.apache.common.beanutils.PropertyUtils

Object obj = PropertyUtils.getNestedProperty(request, propertyPath)

Using Apache commons string substitutor, StrSubstitutor


import org.apache.commons.lang.text.StrSubstitutor;

Map map = new HashMap();
map.put("DAYS", "2");
map.put("HOURS", "8");
String str = "${DAYS} days and ${HOURS} hours to go";

StrSubstitutor sub = new StrSubstitutor(map);
String resolvedString = sub.replace(str);