Getting error while trying to refer OSGi Service or ResourceResolverFactory inside Custom Sling Rewriter class

Avatar

Avatar

Hemalatha

Avatar

Hemalatha

Hemalatha

11-08-2020

Hi all,

 

I am writing a custom sling rewriter which implements Transformer Class. Usually, we will use it to parse the html and rewrite the needed tag elements. In my case, I have to get some dynamic values by accessing JCR and need to rewrite them as URLs. I am not able to Refer OSGi service or ResourceResolverFactory inside transformer class. It gives me either 500 error or null pointer exception.

 

When I checked on samples in the web, they did a static rewrite. Could anyone help me to confirm whether shall I use OSGi services inside Custom Sling rewriter class.

 

Regards,

Hema

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar

Vijayalakshmi_S

MVP

Avatar

Vijayalakshmi_S

MVP

Vijayalakshmi_S
MVP

11-08-2020

Hi @Hemalatha,

Create a custom implementation for TransformerFactory and reference the desired OSGI service there. 

In the createTransformer() method of TransformerFactory, invoke your custom Transformer class (Passing the referenced OSGI service via Parameterized constructor)

Below sample skeleton for reference. (Haven't tried for actual implementation, below is just the sample structure)

CustomTransformerFactory.class

import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.rewriter.Transformer;
import org.apache.sling.rewriter.TransformerFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

@Component(service = TransformerFactory.class, property = { "pipeline.mode=global",
		"pipeline.paths=/content/learnings", "pipeline-type=linkrewriter" }, immediate = true)
public class CustomTransformerFactory implements TransformerFactory {

	@Reference //if this is not working try bind/unbind reference
	private ResourceResolverFactory rescFactory;

	@Override
	public Transformer createTransformer() {
		return new CustomTransformer(rescFactory);
	}

}

CustomTransformer.class

public class CustomTransformer implements Transformer {
	
	private ResourceResolverFactory rescFactory; // This instance variable is initialized in the below constructor(as invoked from Factory) can then be used in the overridden methods of Transformer.

	public CustomTransformer(ResourceResolverFactory rescFactory) {
		this.rescFactory = rescFactory; 
	}
}

 

Answers (1)

Answers (1)

Avatar

Avatar

Arun_Patidar

MVP

Total Posts

2.9K

Likes

1.0K

Correct Answer

831

Avatar

Arun_Patidar

MVP

Total Posts

2.9K

Likes

1.0K

Correct Answer

831
Arun_Patidar
MVP

11-08-2020

I think it should work, It is just like another osgi services

 

@component(service = TransformerFactory.class, name = "Custom Link Transformer", immediate = true,
property = {
		"pipeline.type=append-version",
		"pipeline.mode=global"
})

 

please let us know if it does not work.