Skip to content

Instantly share code, notes, and snippets.

@behrangsa
Created March 31, 2014 11:22
Show Gist options
  • Save behrangsa/9890191 to your computer and use it in GitHub Desktop.
Save behrangsa/9890191 to your computer and use it in GitHub Desktop.
A custom Sling Transformer for Adobe CQ 5 (AEM) that converts long URLs to short URLs
public class LinkShortnerTransformer extends AbstractSAXPipe implements Transformer {
private static final Logger log = LoggerFactory.getLogger(SitesmartRewriterTransformer.class);
private SlingHttpServletRequest httpRequest;
private static final String ATT_NAME = "href";
private static final String EL_NAME = "a";
public SitesmartRewriterTransformer() {
}
public void dispose() {
this.httpRequest = null;
}
public void init(ProcessingContext context, ProcessingComponentConfiguration config) throws IOException {
this.httpRequest = context.getRequest();
log.info("Transforming request {}.", httpRequest.getRequestURI());
}
@Override
public void startElement(String nsUri, String localname, String qName, Attributes attrs) throws SAXException {
/* copy the element attributes */
AttributesImpl linkAttrs = new AttributesImpl(attrs);
/* Only interested in EL_NAME elements */
if (EL_NAME.equalsIgnoreCase(localname)) {
/* iterate through the attributes of the element and act only on ATT_NAME attributes */
for (int i = 0; i < linkAttrs.getLength(); i++) {
if (ATT_NAME.equalsIgnoreCase(linkAttrs.getLocalName(i))) {
String pathInLink = linkAttrs.getValue(i);
log.info("Path in link: {}", pathInLink);
/* use the resource resolver of the http request to reverse-resolve the path */
String mappedPath = httpRequest.getResourceResolver().map(httpRequest, pathInLink);
log.info("Transformed {} to {}.", pathInLink, mappedPath);
/* update the attribute value */
linkAttrs.setValue(i, mappedPath);
}
}
}
/* return updated attributes to super and continue with the transformer chain */
super.startElement(nsUri, localname, qName, linkAttrs);
}
}
@rohitgulati607
Copy link

Hi..
Can you Please share the SitesmartRewriterTransformer file also.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment