package cc.concurrent.config.client.loader;
import cc.concurrent.config.core.api.FilePublishedApi;
import cc.concurrent.config.core.model.CheckParam;
import cc.concurrent.config.core.model.FilePublished;
import com.caucho.hessian.client.HessianProxyFactory;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static com.google.common.base.Preconditions.checkState;
/**
* User: yanghe.liang
* Date: 13-11-3
* Time: 下午12:17
*/
public class RemoteLoader extends Loader {
private final static Logger logger = LoggerFactory.getLogger(RemoteLoader.class);
private final String remoteUrl;
private final String localDir;
private FilePublishedApi filePublishedService;
public RemoteLoader(String appName, String remoteUrl, String localDir) {
super(appName);
this.remoteUrl = remoteUrl;
this.localDir = localDir;
}
@Override
public void init() throws Exception {
HessianProxyFactory factory = new HessianProxyFactory();
filePublishedService = (FilePublishedApi) factory.create(FilePublishedApi.class, remoteUrl);
}
@Override
String getXml(String fileName) throws Exception {
FilePublished filePublished = filePublishedService.download(appName, fileName);
checkState(filePublished != null, "loader[%s] appName[%s] fileName[%s] download null", getClass().getSimpleName(), appName, fileName);
return filePublished.getXml();
}
public List<FilePublished> checkAndDownload(List<CheckParam> checkParams) {
return filePublishedService.checkAndDownload(appName, checkParams);
}
@Override
public void cacheXml(String fileName, String xml) {
String path = getAppDir() + "/" + fileName + ".xml";
try {
Files.write(xml, new File(path), Charsets.UTF_8);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
private String getAppDir() {
return localDir.endsWith("/") ?
localDir + appName :
localDir + "/" + appName;
}
}