Wednesday 21 January 2015

Get authorable field in Transformer

import java.io.IOException;
import org.apache.cocoon.xml.sax.AbstractSAXPipe;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.apache.sling.rewriter.ProcessingComponentConfiguration;
import org.apache.sling.rewriter.ProcessingContext;
import org.apache.sling.rewriter.Transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap;
import com.day.cq.wcm.api.Page;

@Component(immediate = true, metatype = true, label = "Random Custom Link Transformer")
@Service
public class RandomLinkTransformer extends AbstractSAXPipe implements Transformer {

private final Logger log = LoggerFactory.getLogger(this.getClass());
private SlingHttpServletRequest httpRequest;
private SlingBindings bindings;
@Property(name = "Path", label = "Path Level", description = "Link Path Level", unbounded = PropertyUnbounded.DEFAULT)
private String path;
private String internalURL = "";
private String[] domainsList = null;
public RandomLinkTransformer() {
log.debug("[CUSTOM TRANSFORMER] ************ CUSTOM TRANSFORMER CREATED");
}

public void init(ProcessingContext context, ProcessingComponentConfiguration config) throws IOException {
this.httpRequest = context.getRequest();
this.bindings = (SlingBindings) httpRequest.getAttribute(SlingBindings.class.getName());
checkCurrenturl();
}

private void checkCurrenturl() {
org.osgi.service.cm.Configuration conf;
int level = 3;
if (bindings != null) {
try {
SlingScriptHelper sling = bindings.getSling();
conf = sling.getService(org.osgi.service.cm.ConfigurationAdmin.class).getConfiguration("com.Random.transformer.RandomLinkTransformer");
if (conf.getProperties() != null) {
String configPath = (String) conf.getProperties().get("path");
level = Integer.parseInt(configPath);
}

} catch (IOException e) {
log.error("Error in Random Custom Link Transformer" + e.getMessage());
}
String currentURL = httpRequest.getPathInfo();
log.error(" **** currentURL : " + currentURL + " Level:" + level);

if (level == 1 && currentURL.contains("/content/Random")) {
internalURL = currentURL.substring(nthOccurrence(currentURL, '/', level + 1), nthOccurrence(currentURL, '/', level + 2) + 1);
} else {
internalURL = currentURL.substring(0, nthOccurrence(currentURL, '/', level) + 1);
}
String countryCode = "";
if (internalURL.contains("/content/Random/")) {
countryCode = StringUtils.substringAfter(internalURL, "/content/Random/");
countryCode = StringUtils.substringBefore(countryCode, "/");
} else {
countryCode = StringUtils.substringAfter(internalURL, "/");
countryCode = StringUtils.substringBefore(countryCode, "/");
}

if (StringUtils.isNotBlank(countryCode)) {
ResourceResolver resourceResolver = bindings.getSling().getRequest().getResourceResolver();
Page page = resourceResolver.getResource("/content/Random/" + countryCode +"/index").adaptTo(Page.class);
Resource rsc = page.getContentResource();
if(rsc!=null){
HierarchyNodeInheritanceValueMap valueMap=new HierarchyNodeInheritanceValueMap(rsc);
if(valueMap!=null){
domainsList = valueMap.getInherited("iparHeader/header/domainsList", String[].class);
}
}
}
log.error(" **** internalURL : " + internalURL);
}
}

public void startElement(final String uri, final String name, final String raw, final Attributes attrs) throws SAXException {

final AttributesImpl attributes = new AttributesImpl(attrs);
final String href = attributes.getValue("href");

if (name.equals("a") && raw.equals("a") && href != null && !href.isEmpty()) {

String newURL = href;
boolean isInternalLink = false;
boolean isVideo = isVideoPath(attributes, newURL);
if (!isVideo) {
if (domainsList != null) {
for (String domain : domainsList) {
if (newURL.contains(domain)) {
isInternalLink = true;
}
}
}
if (!isInternalLink) {
if (newURL.startsWith("http://")) {
if (!newURL.contains("Random.com" + internalURL)) {
// this case will never come in author
enableLinkTransformer(attributes, href);
}
} else if (!newURL.contains(internalURL) && !newURL.equals("#") && !newURL.equals("javascript:void(0);")) {
enableLinkTransformer(attributes, href);
}
}
}
}

super.startElement(uri, name, raw, attributes);
}

private boolean isVideoPath(final AttributesImpl attributes, final String href) {
boolean isVideo = false;
for (int i = 0; i < attributes.getLength(); i++) {
if ("rel".equalsIgnoreCase(attributes.getQName(i))) {
if (attributes.getValue("rel").equals("#overlay")) {
isVideo = true;
}
}
}
return isVideo;
}

private void enableLinkTransformer(final AttributesImpl attributes, final String href) {

boolean classNotFound = true;
for (int i = 0; i < attributes.getLength(); i++) {
if ("class".equalsIgnoreCase(attributes.getQName(i))) {
attributes.setValue(i, rewriteLink(attributes.getValue("class")));
classNotFound = false;
}
}
if (classNotFound) {
attributes.addAttribute("", "class", "class", "String", "warnAndleave");
}
}

public void dispose() {
// TODO Auto-generated method stub
}

private String rewriteLink(String classname) {
log.info("rewriteLink called......");
String rewrittenclass = classname + " warnAndleave";
log.info("[CUSTOM TRANSFORMER] ************ REWRITING LINK");
return rewrittenclass;
}

public static int nthOccurrence(String str, char c, int n) {
int pos = str.indexOf(c, 0);
while (n-- > 0 && pos != -1)
pos = str.indexOf(c, pos + 1);
return pos;
}

public void setDocumentLocator(Locator locator) {
// TODO Auto-generated method stub
contentHandler.setDocumentLocator(locator);
}

public void startDocument() throws SAXException {
// TODO Auto-generated method stub
contentHandler.startDocument();
}

public void endDocument() throws SAXException {
// TODO Auto-generated method stub
contentHandler.endDocument();
}

public void startPrefixMapping(String prefix, String uri) throws SAXException {
// TODO Auto-generated method stub
contentHandler.startPrefixMapping(prefix, uri);
}

public void endPrefixMapping(String prefix) throws SAXException {
// TODO Auto-generated method stub
contentHandler.endPrefixMapping(prefix);
}

public void endElement(String uri, String localName, String qName) throws SAXException {
// TODO Auto-generated method stub
contentHandler.endElement(uri, localName, qName);
}

public void characters(char[] ch, int start, int length) throws SAXException {
// TODO Auto-generated method stub
contentHandler.characters(ch, start, length);
}

public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
// TODO Auto-generated method stub
contentHandler.ignorableWhitespace(ch, start, length);
}

public void processingInstruction(String target, String data) throws SAXException {
// TODO Auto-generated method stub
contentHandler.processingInstruction(target, data);
}

public void skippedEntity(String name) throws SAXException {
// TODO Auto-generated method stub
contentHandler.skippedEntity(name);
}

public void setContentHandler(ContentHandler handler) {
// TODO Auto-generated method stub
this.contentHandler = handler;
}
}  

No comments:

Post a Comment