Saturday 13 December 2014

Transformers





Create Transformer Factory
package com.Random.transformer;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.rewriter.Transformer;
import org.apache.sling.rewriter.TransformerFactory;
@Service
@Component(immediate=true, metatype = true, label = "Random Custom Link Transformer Factory", description = "(Transformer Factory) Change links from global to locale based links")
@Properties(value={
@Property(name="service.ranking", intValue=200),
@Property(name="pipeline.mode", value="global")
})
public class RandomLinkTransformerFactory implements TransformerFactory {
    @Property( value = "customlinktransformer", propertyPrivate = true)
    private static final String PIPELINE_TYPE = "pipeline.type";
    //@Reference
    //private URLAdapter urlAdapter;
   // A class with one method that replaces ".html" with "/", given a URL.
    public final Transformer createTransformer() {    
        return new RandomLinkTransformer();
    }
}

Create Transformer
package com.Random.transformer;
import java.io.IOException;
import javax.jcr.Node;
import javax.jcr.Session;
import org.apache.cocoon.xml.sax.AbstractSAXPipe;
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.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;
@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;
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());
}
public void startElement(final String uri, final String name,
final String raw, final Attributes attrs) throws SAXException {
// TODO Auto-generated method stub
final AttributesImpl attributes = new AttributesImpl(attrs);
final String href = attributes.getValue("href");
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) {
// TODO Auto-generated catch block
log.error("Error in Random Custom Link Transformer"+e.getMessage());
}

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

String currentURL = httpRequest.getPathInfo();
   String internalURL = currentURL.substring(0,nthOccurrence(currentURL,'/',level)+1);
String newURL = href;
String output="";
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("#")){
enableLinkTransformer(attributes, href);
   }
}
}
super.startElement(uri, name, raw, attributes);
}

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