Created

May 07, 2013

My favourite CQ5 util classes

Posted by Feike Visser

In this blogpost I want to give you an overview of my favourite CQ5 util classes.

Some of these classes might already be known to you, hopefull you will find a new one that will help you during your CQ5 development work.

With every class I will give a small code example on how you can use it.

// checks if the resource exists
ResourceUtil.isNonExistingResource(myResource);

// always gets a ValueMap from a Resource
ResourceUtil.getValueMap(myResource);
//check if the Resource is an Asset
DamUtil.isAsset(myResource);
//formats the Calendar into ISO8601 format
ISO8601.format(calendar);
// creates a valid JCR-name
JcrUtil.createValidName(myCustomName);
// if the folder doesn't exist, it will be created
JcrUtils.getOrAddFolder(parent, name);
// gets a boolean property when starting an OSGi-component

@Activate
protected void activate(ComponentContext context) {
	PropertiesUtil.toBoolean(context.getProperties().get("myproperty"), false);
}

// gets the references to services loaded in the OSGi-container
serviceTracker.getServiceReference()
// creates a full path, with autosave if needed
JcrResourceUtil.createPath(... )
// gets the SlingRequest/SlingResponse when you are creating custom tags

PageContext pageContext = (PageContext) getJspContext();

SlingHttpServletRequest slingRequest = TagUtil.getRequest(pageContext);
SlingHttpServletResponse slingResponse = TagUtil.getResponse(pageContext);

// check to see if a real user is logged in

boolean realuser = ! UserPropertiesUtil.isAnonymous(request);