April 1, 2020
Estimated Post Reading Time ~

Invalidate Cache After some time / CQ Scheduler Example

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import com.day.cq.jcrclustersupport.ClusterAware;

/**
* Shceduler run every 1 minute from master instance
* By Yogesh Upadhyay
*/

@Component(immediate=true,metatype=true,label="Cache Invalidator")
@Service(value={com.day.cq.jcrclustersupport.ClusterAware,java.lang.Runnable})
@Properties(value = {
@Property(name="service.description", value="CQ Cache Invalidator"),
@Property(name="scheduler.period", value="60", type="Long"),
@Property(name="scheduler.expression", value="* 0,6,12,18 * * * ?"),
@Property(name="scheduler.concurrent", value="false", propertyPrivate=true)
})

public class DispatcherCacheInvalidator implements Runnable,ClusterAware {

private static final Logger log = LoggerFactory.getLogger(DispatcherCacheInvalidator .class);
private static HttpClient client;
//Give server name here. For example yourserverName.com:80
//You can define multiple server by defining this property as String array

@Property(label="server name", description="Server Name" value="localhost:80"
private static final String SERVER_NAME = "server.name";

private String serverName = "";

//Give set of path. You can use OSGI configuration for this
//You can add multiple invalidation path by defining this property as string array

@Property(label="invalidate path", description="Path that needs invalidation" value="/test"
private static final String INVALIDATE_PATH = "invalidate.path";

private Set<String> invalidatePath = new HashSet<String>();
boolean isMaster = false;

public ApacheCacheInvalidator () {
client = new HttpClient();

//You can add multiple paths
//this.invalidatePath.add("Add your path here");
}

public void run() {
//ClusterAware clusterAware;

if(this.isMaster){
for(String path:invalidatePath){
log.debug("******* I am invalidating *******"+path);
this.invalidatePage(serverName,path);
}
}
}

/** invalidatePage(server, pageurl)
* server - Apache webserver host and port
* pageurl - CQ page handle
*
*/

private boolean invalidatePage(String server, String pageurl) {
boolean retFlag=false;
PostMethod method=null;

if(server==null || pageurl==null)return false;
String url="http://"+server+"/dispatcher/invalidate.cache";

try {
method = new PostMethod(url);
method.addRequestHeader("CQ-Action", "Activate");
method.addRequestHeader("CQ-Handle", pageurl);
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
log.error("ApacheCacheInvalidator Exception:"+statusCode+" "+method.getStatusLine());
return false;

}

BufferedReader sbr = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

String curLine = null;
StringBuffer retStr = new StringBuffer();
while ((curLine = sbr.readLine()) != null) {
retStr.append(curLine);

}

retFlag=true;

}catch(Exception e){
log.error("ApacheCacheInvalidator Exception:"+e.getMessage());
retFlag=false;
} finally {
method.releaseConnection();
}

return retFlag;
}
public void bindRepository(String repositoryId, String clusterId, boolean isMaster) {
this.isMaster = isMaster;

}

public void unbindRepository() {
log.info("No Repository is bound or Repository is unbound in ClusterService");
}

protected void activate(org.osgi.service.component.ComponentContext context){
log.debug("Activating Cache invalidator");
final Dictionary<String, Object> props = context.getProperties();

if(log.isDebugEnabled()) {
java.util.Enumeration<String> propKeys = props.keys();
while(propKeys.hasMoreElements()) {
String nextKey = propKeys.nextElement();
Object nextProp = props.get(nextKey);
String clazz = nextProp!=null ? " Instance of " + nextProp.getClass().getName() + "." : "";
log.debug("SCR prop {} = {}." + clazz, nextKey, nextProp);
}
}

Object prop = props.get(SERVER_NAME);
if(prop!=null){
this.serverName=prop.toString().trim();
}

prop = props.get(INVALIDATE_PATH);
this.invalidatePath.clear();

if(prop != null) {
String authIds[] = prop instanceof String[] ? (String[]) prop : prop.toString().split("\\s+");

for(String id : authIds) {
this.invalidatePath.add(id);

}
}
}


/**
* Deactivates the service.
*
* @param componentContext The component context
*/

protected void deactivate(org.osgi.service.component.ComponentContext componentContext) {
log.debug("Cache invalidator service service shut down");
}
}


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.