Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save rajavijaysingh/9356575cefcd251856f1e35c7b0d4d13 to your computer and use it in GitHub Desktop.

Select an option

Save rajavijaysingh/9356575cefcd251856f1e35c7b0d4d13 to your computer and use it in GitHub Desktop.

Revisions

  1. @behrangsa behrangsa created this gist Mar 31, 2014.
    51 changes: 51 additions & 0 deletions LinkShortnerTransformer.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    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);
    }
    }