package com.walker.infrastructure.arguments.support; import java.io.File; import java.io.InputStream; import java.util.List; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import com.walker.infrastructure.arguments.AbstractArgumentsManager; import com.walker.infrastructure.arguments.ArgumentsException; import com.walker.infrastructure.arguments.Group; import com.walker.infrastructure.utils.StringUtils; /** * 基于文件存储的配置参数管理器默认实现 * @author shikeying * */ public abstract class FileArgumentsManager extends AbstractArgumentsManager { private String classPathFileName; /* 文件的绝对路径 */ private String filePath; /** * 返回文件的绝对路径 * @return */ public String getFilePath() { return filePath; } /** * 设置文件名称,使用classpath下的文件名,即:文件必须维护类路径中。

* 如: *
	 * myfile.xml
	 * conf/myfile.xml
	 * 
* @param fileName */ public void setClasspathFileName(String fileName){ assert (StringUtils.isNotEmpty(fileName)); // if(fileName.startsWith(AttributeUtils.CLASSPATH_PREFIX)){ // this.classPathFileName = fileName; // } else // throw new IllegalArgumentException("fileName must start with 'classpath:'."); this.classPathFileName = fileName; } /** * 设置可变参数文件的绝对文件名,如:d:/files/config.xml * @param absoluteFilename */ public void setFileSystemFileName(String absoluteFilename){ assert (StringUtils.isNotEmpty(absoluteFilename)); this.filePath = absoluteFilename; } @Override protected List load(Object source) throws Exception { // TODO Auto-generated method stub Resource variableRes = null; if(StringUtils.isNotEmpty(filePath)){ // doCheckExist(filePath); variableRes = new FileSystemResource(new File(filePath)); } else if(StringUtils.isNotEmpty(classPathFileName)){ variableRes = new ClassPathResource(classPathFileName); this.filePath = variableRes.getFile().getAbsolutePath(); } else { throw new ArgumentsException("可变参数配置文件必须设置一个文件名,可以在类路径下也可以是绝对路径!"); } InputStream input = variableRes.getInputStream(); if(input == null) throw new ArgumentsException("file not found: " + variableRes.getFilename()); return loadFile(input); } // private void doCheckExist(String filepath){ // File file = new File(filepath); // if(!file.exists()){ // // 不存在需要把默认variable.xml文件拷贝到目的路径中。 // FileCopyUtils.copy(new File(), file); // try { // file.createNewFile(); // } catch (IOException e) { // logger.error("创建可变参数配置文件出现错误", e); // throw new NestedRuntimeException(filepath); // } // } // } /** * 从文件系统加载配置文件 * @param inputStream 文件流 * @return * @throws Exception */ protected abstract List loadFile(InputStream inputStream) throws Exception; }