All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.hmtools.jsManager.JavascriptManagerDefault Maven / Gradle / Ivy

There is a newer version: 0.3.1
Show newest version
package top.hmtools.jsManager;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import javax.annotation.PostConstruct;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import top.hmtools.autoConfiguration.JsCssAutoConfiguration;

/**
 * 缺省的javascript文件管理者
 * @author HyboJ
 * 创建日期:2017-9-26下午9:42:56
 */
@Component
public class JavascriptManagerDefault implements IJavascriptManager{
	
	protected final Logger logger = LoggerFactory.getLogger(JavascriptManagerDefault.class);
	
	@Autowired
	private JsCssAutoConfiguration jsCssAutoConfiguration;
	
	/**
	 * javascript文件缓存库
	 */
	private static Map JS_REPERTORY = new HashMap();
	
	private List filePaths = new ArrayList<>();
	
	private String encoding = "UTF-8";

	@Override
	@PostConstruct
	public void init() {
		//初始化文件路径集合与文件编码格式,用于刷新
		String jsFilesPathStr = this.jsCssAutoConfiguration.getJsFilesPaths();
		this.logger.info("监控js的磁盘路径有:{}",jsFilesPathStr);
		String[] pathsArr = jsFilesPathStr.split(",");
		List pathList = Arrays.asList(pathsArr);
		for(String path:pathList){
			this.filePaths.add(new File(path));
		}
		
		this.encoding = this.jsCssAutoConfiguration.getEncoding();
		
		//尝试加载当前运行工程classpath中的javascript文件
		URL resource = this.getClass().getClassLoader().getResource("");
		
		try {
			String resourceStr = resource.toString();
			if(resourceStr.startsWith("jar:file")){
				try {
					this.logger.info("尝试读取当前工程jar{}中的静态资源文件 javascript  ####################################",resourceStr);
					resourceStr = resourceStr.replaceFirst("jar:", "");
					int indexOf = resourceStr.indexOf("!/");
					resourceStr = resourceStr.substring(0, indexOf)+"/";
					URL url = new URL(resourceStr);
					File file = new File(url.toURI());
					JarFile jar = new JarFile(file);
					Enumeration entries = jar.entries();
					while(entries.hasMoreElements()){
						JarEntry nextElement = entries.nextElement();
						String name = nextElement.getName();
						if(name.endsWith(".js")){
							this.logger.info(name);
							JarEntry jarEntry = jar.getJarEntry(name);
							InputStream inputStream = jar.getInputStream(jarEntry);
							String content = IOUtils.toString(inputStream, this.encoding);
							JS_REPERTORY.put(FilenameUtils.getName(name), content	);
						}
					}
				} catch (Exception e) {
					this.logger.error("从当前工程jar中读取文件失败:"+e.getMessage(),e);
				}
			}else{
				File classPath=new File(resource.toURI());
				this.logger.info("当前工程的classpath路径为:"+classPath+"    ###############################################");
				this.filePaths.add(classPath);
			}
		} catch (URISyntaxException e) {
			this.logger.error("从classpath中加载javascript失败:"+e.getMessage(),e);
		} 
		
		//将指定文件夹中的所有js文件内容读取到缓存
		String[] extensions = {"js"}; 
		for(File pathTmp:filePaths){
			try {
				if(!pathTmp.isDirectory()||!pathTmp.exists()){
					continue;
				}
				Collection jsFilesTmp = FileUtils.listFiles(pathTmp, extensions, true);
				for(File fileTmp:jsFilesTmp){
					String fileName = fileTmp.getName();
					String fileContent = FileUtils.readFileToString(fileTmp, encoding);
					JS_REPERTORY.put(fileName, fileContent);
				}
			} catch (Exception e) {
				logger.error("获取"+pathTmp.getAbsolutePath()+"目录下的js文件失败"+e.getMessage(),e);
			}
		}
	}

	@Override
	public void destory() {
		if(JS_REPERTORY != null){
			JS_REPERTORY.clear();
		}
	}

	@Override
	public String getJs(String jsNames) {
		if(jsNames != null && !"".equals(jsNames)){
			String[] jsNamesArr = jsNames.split(",");
			return this.getJs(jsNamesArr);
		}else{
			return ";";
		}
	}

	@Override
	public String getJs(List jsNames) {
		if(jsNames != null && jsNames.size()>0){
			String[] jsNamesArr = jsNames.toArray(new String[0]);
			return this.getJs(jsNamesArr);
		}else{
			return ";";
		}
	}

	@Override
	public String getJs(String[] jsNames) {
		StringBuffer sb_result = new StringBuffer(";");
		if(jsNames != null && jsNames.length>0){
			for(String fileName:jsNames){
				String js_content_tmp = JS_REPERTORY.get(fileName.trim().toLowerCase());
				if(js_content_tmp == null || "".equals(js_content_tmp)){
					continue;
				}
				sb_result.append(js_content_tmp+";");
			}
			return sb_result.toString();
		}else{
			return ";";
		}
	}

	@Override
	public boolean refresh() {
		boolean result = false;
		try {
			this.destory();
			this.init();
			result=true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return result;
	}

	@Override
	public List listJsFilenames() {
		List result = new ArrayList();
		if(JS_REPERTORY != null){
			Set keySet = JS_REPERTORY.keySet();
			result.addAll(keySet);
			Collections.sort(result);
		}
		return result;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy