welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ群:162333776 邮箱:admin@xlongwei.com

minifier 静态文件压缩


分类 Java   关键字 分享   标签 java   web   algorithm   ourjs   发布 hongwei  1478070437714
注意 转载须保留原文链接,译文链接,作者译者等信息。  
ourjs项目里有minifier.js,封装了cssshrink和uglify-js功能,于是在此基础上封装了java接口。

ourjs.js,由于不擅长nodejs,因此只是简单地调用utility.minifier方法
webSvr.url('/minifier', function(req, res) {
var query = url.parse(req.url, true).query;
var from = query.from, to = query.to;
console.log("minifier from: "+from+" to "+to);
if(from && from.length>3 && to && to.length>3 && from.slice(-3)==to.slice(-3) && (from.slice(-3)==".js" || from.slice(-4)==".css")){
var dir = uploads_file+"minifier/";
try{
utility.minifier(dir+from, dir+to);
res.send(200, "ok");
}catch(e){
res.send(500, "internal error")
}
}else{
res.send(401, MESSAGES.NOPERMISSION)
}
})

ServiceHandlerMinifier封装了java接口,参数支持url网址、js|css上传、js|css文本内容
String dir = GlobalConfig.getProperty(UploadUtil.uploads_file)+"minifier/";
File from = null, to = null;
String url = getParam("url", params, body);
if(StringUtil.isUrl(url)) {
JSONObject cached = DownloadUtil.cached("minifier", url);
if(cached != null) return cached;
if(!url.endsWith(".js") && !url.endsWith(".css")) return null;
from = new File(dir, new File(url).getName());
if(!from.exists() || FileUtil.lastModified(url) > from.lastModified()) FileUtil.down(url, from);
}
if(from == null || !from.exists()) {
MultipartFile file = DownloadUtil.getFile(request, "file");
if(file != null) {
//处理js或css上传
}
}
if(from == null || !from.exists()) {
String content = getParam("js", params, body);
//处理js或css文本内容
}
if(from == null || !from.exists()) return null;
to = new File(dir, FileUtil.getFileName(from)+".min."+FileUtil.getFileExt(from));
UploadUtil.direct("minifier", from); //minifier接口在www.xlongwei.com主机,java接口可能在多台主机上,因此需要上传from文件
ServiceRequester.get(service, StringUtil.params("from",from.getName(),"to",to.getName()), null); //调用主机/minifier接口
FileUtil.down(domain+to.getName(), to); //下载to文件到本机
if(to.exists()) {
if(StringUtil.isUrl(url)) CacheUtil.set("minifier", url, GlobalConfig.getProperty(UploadUtil.uploads)+",minifier/"+to.getName());
return JSONUtil.convert(StringUtil.params("domain",GlobalConfig.getProperty(UploadUtil.uploads),"path","minifier/"+to.getName()));
}
return JSONUtil.convert(StringUtil.params("error","failed to minifier "+from.getName()));

java接口调用:minifier