package foundation.data.loader;
|
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.util.Set;
|
|
import org.dom4j.Document;
|
import org.dom4j.DocumentException;
|
import org.dom4j.Element;
|
import org.dom4j.io.SAXReader;
|
|
import foundation.persist.source.DataSourceManager;
|
import foundation.persist.source.NamedDataSource;
|
import foundation.server.Initializer;
|
import foundation.server.config.Configer;
|
import foundation.server.config.ServerAssembleLoader;
|
|
public class DatasuorceLoader extends Initializer {
|
|
private static final String Node_Defination = "defination";
|
private static final String Node_Defination_URL = "url";
|
private static final String Node_Defination_UserName = "username";
|
private static final String Node_Defination_Password = "password";
|
private Set<String> activeDataSourceList;
|
|
public DatasuorceLoader() {
|
activeDataSourceList = ServerAssembleLoader.activeDataSourceList;
|
}
|
|
@Override
|
public void startUp() throws Exception {
|
File path = new File(Configer.getPath_Config());
|
File[] files = path.listFiles();
|
|
for (File file: files) {
|
String name = getShortName(file);
|
|
if (!activeDataSourceList.contains(name)) {
|
continue;
|
};
|
|
loadOneFile(name, file);
|
}
|
}
|
|
@Override
|
public void shutDown() throws Exception {
|
|
}
|
|
private void loadOneFile(String name, File file) {
|
try {
|
logger.debug("load datasource file:" + file);
|
InputStream inputStream = new FileInputStream(file);
|
|
try {
|
SAXReader reader = new SAXReader();
|
reader.setValidation(false);
|
|
Document doc = reader.read(inputStream);
|
Element root = doc.getRootElement();
|
|
loadDefination(name, root);
|
|
} catch (DocumentException e) {
|
logger.error("can not load sql file: " + file);
|
logger.error(e);
|
} finally {
|
try {
|
inputStream.close();
|
} catch (IOException e) {
|
}
|
}
|
}
|
catch (Exception e) {
|
logger.error(e);
|
}
|
}
|
|
private void loadDefination(String name, Element root) throws Exception {
|
Element element = root.element(Node_Defination);
|
|
String url = element.attributeValue(Node_Defination_URL);
|
String username = element.attributeValue(Node_Defination_UserName);
|
String password = element.attributeValue(Node_Defination_Password);
|
|
NamedDataSource dataSource = new NamedDataSource(name);
|
|
dataSource.setUrl(url);
|
dataSource.setUsername(username);
|
dataSource.setPassword(password);
|
|
DataSourceManager.appendDataSource(dataSource);
|
}
|
|
private String getShortName(File file) {
|
String result = file.getName();
|
|
int pos = result.lastIndexOf(".");
|
if (pos > 0) {
|
result = result.substring(0, pos);
|
}
|
|
return result;
|
}
|
|
}
|