com.alogic.cache.loader.ScriptBatch Maven / Gradle / Ivy
package com.alogic.cache.loader;
import com.alogic.cache.CacheObject;
import com.alogic.load.Loader;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.Script;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.*;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import org.w3c.dom.Element;
/**
* 通过脚本实现批量热加载
* @since 1.6.12.17
*/
public class ScriptBatch extends Loader.Hot{
/**
* 加载事件脚本
*/
protected Logiclet onLoad = null;
protected static final String ID_LOADER = "$cache-loader";
protected static final String ID_LAST_SCAN_TIME = "$lastScanTime";
protected long lastScanTime = 0;
@Override
public void configure(Properties p){
super.configure(p);
}
@Override
public void configure(Element e, Properties p) {
Properties props = new XmlElementProperties(e,p);
Element onLoadElem = XmlTools.getFirstElementByPath(e, "on-load");
if (onLoadElem != null){
onLoad = Script.create(onLoadElem, props);
}
configure(props);
}
@Override
protected synchronized void doLoad(boolean first) {
if (onLoad != null){
LogicletContext logicletContext = new LogicletContext(Settings.get());
try {
logicletContext.setObject(ID_LOADER,this);
logicletContext.SetValue(ID_LAST_SCAN_TIME,String.valueOf(this.lastScanTime));
XsObject doc = new JsonObject("root",new HashMap());
onLoad.execute(doc,doc, logicletContext, null);
lastScanTime = System.currentTimeMillis();
}finally{
logicletContext.removeObject(ID_LOADER);
}
}
}
/**
* 发现一个缓存对象
*/
public static class CacheFound extends Segment {
/**
* 缓存id
*/
protected String $id = "";
/**
* 当前节点的上下文id
*/
protected String cid = "$cache-object";
public CacheFound(String tag, Logiclet p) {
super(tag, p);
}
@Override
public void configure(Properties p){
super.configure(p);
$id = PropertiesConstants.getRaw(p, "id", "");
cid = PropertiesConstants.getString(p,"cid", cid,true);
}
@Override
protected void onExecute(XsObject root,XsObject current, LogicletContext ctx,
ExecuteWatcher watcher) {
ScriptBatch loader = ctx.getObject(ID_LOADER);
if (loader != null){
String id = PropertiesConstants.transform(ctx,$id,"");
if (StringUtils.isNotEmpty(id)){
CacheObject obj = new CacheObject.Simple(id);
try {
ctx.setObject(cid, obj);
super.onExecute(root, current, ctx, watcher);
loader.add(id,obj);
}finally{
ctx.removeObject(cid);
}
}
}
}
}
}