Commit 09b1071c by s_guodong

代码整理(日志打印,去掉注释掉的代码,if等加大括号...)

parent 2ff433cd
...@@ -18,66 +18,62 @@ import java.util.concurrent.Future; ...@@ -18,66 +18,62 @@ import java.util.concurrent.Future;
public class BatchFilter extends AbsFilter { public class BatchFilter extends AbsFilter {
@Override @Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "BatchFiter[批处理] is running." + propertySaveToContext();
// LOG_FLAG); String threadnumStr = (String) context.getVariable("threadnum");
propertySaveToContext(); String linesStr = (String) context.getVariable("lines");
String threadnumStr = (String) context.getVariable("threadnum"); String interfaceName = (String) context.getVariable("call_interface");
String linesStr = (String) context.getVariable("lines"); String transactionName = (String) context.getVariable("call_transaction");
String interfaceName = (String) context.getVariable("call_interface"); int threadNum = Integer.parseInt(threadnumStr);
String transactionName = (String) context.getVariable("call_transaction"); int eachReadLine = Integer.parseInt(linesStr);
int threadNum = Integer.parseInt(threadnumStr); List<String> contentList;
int eachReadLine = Integer.parseInt(linesStr); Object object = context.getObject();
List<String> contentList; if (object instanceof List) {
Object object = context.getObject(); contentList = (List<String>) object;
if (object instanceof List) { } else {
contentList = (List<String>) object; String filepath = (String) context.getVariable("filepath");
} else { FileInputStream fis = null;
String filepath = (String) context.getVariable("filepath"); try {
FileInputStream fis = null; fis = new FileInputStream(filepath);
try { contentList = IOUtils.readLines(fis);
fis = new FileInputStream(filepath); } catch (FileNotFoundException e) {
contentList = IOUtils.readLines(fis); throw new InterfaceException("00601", "file [" + filepath + "] not found.", e);
} catch (FileNotFoundException e) { } catch (IOException e) {
throw new InterfaceException("00601", "file [" + filepath + "] not found.", e); throw new InterfaceException("00602", "file [" + filepath + "] read error.", e);
} catch (IOException e) { } finally {
throw new InterfaceException("00602", "file [" + filepath + "] read error.", e); if (fis != null) {
} finally { IOUtils.closeQuietly(fis);
if (fis != null) }
IOUtils.closeQuietly(fis); }
} }
} String execName = "batchFilter_" + interfaceName + "_" + transactionName;
String execName = "batchFilter_" + interfaceName + "_" + transactionName; ExecutorService exec = ThreadPoolFactory.getFixedExecutor(threadNum, execName);
ExecutorService exec = ThreadPoolFactory.getFixedExecutor(threadNum, execName); int lineCount = contentList.size();
int lineCount = contentList.size(); int curLine = 0;
int curLine = 0; List<Future<ResultMsg>> resultMsgList = new ArrayList<Future<ResultMsg>>();
List<Future<ResultMsg>> resultMsgList = new ArrayList<Future<ResultMsg>>(); int count = 0;
int count = 0; while (curLine < lineCount) {
while (curLine < lineCount) { List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<String>(); for (int i = 0; i < eachReadLine; i++) {
for (int i = 0; i < eachReadLine; i++) { if (curLine >= lineCount) {
if (curLine >= lineCount) break;
break; }
list.add(contentList.get(curLine)); list.add(contentList.get(curLine));
curLine++; curLine++;
} }
Future<ResultMsg> futureResultMsg = exec.submit(new CallableClient(interfaceName, transactionName, new Object[] { list, Future<ResultMsg> futureResultMsg = exec.submit(new CallableClient(interfaceName, transactionName, new Object[]{list,
count * eachReadLine + 1, context })); count * eachReadLine + 1, context}));
count++; count++;
resultMsgList.add(futureResultMsg); resultMsgList.add(futureResultMsg);
} }
context.setObject(resultMsgList); context.setObject(resultMsgList);
// exec.shutdown(); ThreadPoolFactory.shutdown(execName);
ThreadPoolFactory.shutdown(execName); }
// logger.info( LOG_FLAG + @Override
// "BatchFiter[批处理] wish to finish running" + LOG_FLAG); public Object getFieldValue(IFieldDef fieldDef) {
} return null;
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
return null;
}
} }
...@@ -17,108 +17,70 @@ import java.util.concurrent.Future; ...@@ -17,108 +17,70 @@ import java.util.concurrent.Future;
public class BatchFilter2 extends AbsFilter { public class BatchFilter2 extends AbsFilter {
@Override @Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "BatchFiter[批处理] is running." + propertySaveToContext();
// LOG_FLAG); String threadnumStr = (String) context.getVariable("threadnum");
// System.out.println(new Date().getMinutes() + ":" + new String linesStr = (String) context.getVariable("lines");
// Date().getTime()); String interfaceName = (String) context.getVariable("call_interface");
propertySaveToContext(); String transactionName = (String) context.getVariable("call_transaction");
String threadnumStr = (String) context.getVariable("threadnum"); String filepath = (String) context.getVariable("filepath");
String linesStr = (String) context.getVariable("lines"); int threadNum = Integer.parseInt(threadnumStr);
String interfaceName = (String) context.getVariable("call_interface"); int eachReadLine = Integer.parseInt(linesStr);
String transactionName = (String) context.getVariable("call_transaction"); File f = new File(filepath);
String filepath = (String) context.getVariable("filepath"); String execName = "batchFilter2_" + interfaceName + "_" + transactionName;
int threadNum = Integer.parseInt(threadnumStr); ExecutorService exec = ThreadPoolFactory.getFixedExecutor(threadNum, execName);
int eachReadLine = Integer.parseInt(linesStr); // 文件总行数
File f = new File(filepath); int lineCount = getLinesOfFile(f);
String execName = "batchFilter2_" + interfaceName + "_" + transactionName; // 记录文件当前行数
ExecutorService exec = ThreadPoolFactory.getFixedExecutor(threadNum, execName); int curLine = 1;
// 文件总行数 List<Future<ResultMsg>> resultMsgList = new ArrayList<Future<ResultMsg>>();
int lineCount = getLinesOfFile(f);
// 记录文件当前行数
int curLine = 1;
List<Future<ResultMsg>> resultMsgList = new ArrayList<Future<ResultMsg>>();
while (curLine <= lineCount) { while (curLine <= lineCount) {
int endLine = curLine + eachReadLine; int endLine = curLine + eachReadLine;
int subThreadReadCount = eachReadLine; int subThreadReadCount = eachReadLine;
if (endLine > lineCount) if (endLine > lineCount) {
subThreadReadCount = lineCount - curLine + 1; subThreadReadCount = lineCount - curLine + 1;
Future<ResultMsg> futureResultMsg = exec.submit(new CallableClient(interfaceName, transactionName, new Object[] { filepath, curLine, }
subThreadReadCount })); Future<ResultMsg> futureResultMsg = exec.submit(new CallableClient(interfaceName, transactionName, new Object[]{filepath, curLine,
curLine = endLine; subThreadReadCount}));
resultMsgList.add(futureResultMsg); curLine = endLine;
} resultMsgList.add(futureResultMsg);
}
context.setObject(resultMsgList);
ThreadPoolFactory.shutdown(execName);
}
context.setObject(resultMsgList); @Override
// exec.shutdown(); public Object getFieldValue(IFieldDef fieldDef) {
ThreadPoolFactory.shutdown(execName); return null;
}
/* /**
* propertySaveToContext(); String threadnumStr = (String) * 快速计算文件的行数
* context.getVariable("threadnum"); String linesStr = (String) **/
* context.getVariable("lines"); String interfaceName = (String) public int getLinesOfFile(File f) {
* context.getVariable("call_interface"); String transactionName = int lines = 0;
* (String) context.getVariable("call_transaction"); int threadNum = long fileLength = f.length();
* Integer.parseInt(threadnumStr); int eachReadLine = LineNumberReader rf = null;
* Integer.parseInt(linesStr); List<String> contentList; Object object = try {
* context.getObject(); if (object instanceof List) { contentList = rf = new LineNumberReader(new FileReader(f));
* (List<String>) object; } else { String filepath = (String) if (rf != null) {
* context.getVariable("filepath"); try { contentList = rf.skip(fileLength);
* IOUtils.readLines(new FileInputStream(filepath)); } catch lines = rf.getLineNumber() + 1;
* (FileNotFoundException e) { throw new InterfaceException("00601", logger.info("文件行数为:" + lines);
* "file [" + filepath + "] not found.", e); } catch (IOException e) { rf.close();
* throw new InterfaceException("00602", "file [" + filepath + }
* "] read error.", e); } } ExecutorService exec =
* Executors.newFixedThreadPool(threadNum); int lineCount =
* contentList.size(); int curLine = 0; List<Future<ResultMsg>>
* resultMsgList = new ArrayList<Future<ResultMsg>>(); int count = 0;
* while (curLine < lineCount) { List<String> list = new
* ArrayList<String>(); for (int i = 0; i < eachReadLine; i++) { if
* (curLine >= lineCount) break; list.add(contentList.get(curLine));
* curLine++; } Future<ResultMsg> futureResultMsg = exec.submit(new
* CallableClient(interfaceName, transactionName, new Object[]{list,
* count * eachReadLine + 1})); count++;
* resultMsgList.add(futureResultMsg); }
* context.setObject(resultMsgList); exec.shutdown();
*/
// logger.info( LOG_FLAG + } catch (IOException e) {
// "BatchFiter[批处理] wish to finish running" + LOG_FLAG); logger.error(e.getMessage(), e);
} } finally {
try {
@Override rf.close();
public Object getFieldValue(IFieldDef fieldDef) { } catch (IOException e) {
return null; logger.error(e.getMessage(), e);
} }
}
/** return lines;
* 快速计算文件的行数 }
* **/
public int getLinesOfFile(File f) {
int lines = 0;
long fileLength = f.length();
LineNumberReader rf = null;
try {
rf = new LineNumberReader(new FileReader(f));
if (rf != null) {
rf.skip(fileLength);
lines = rf.getLineNumber() + 1;
logger.info( "文件行数为:" + lines);
rf.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
rf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return lines;
}
} }
...@@ -3,7 +3,6 @@ package com.brilliance.eibs.core.service.instance.impl; ...@@ -3,7 +3,6 @@ package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException; import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef; import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context; import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.impl.AbsFilter;
import com.brilliance.eibs.util.StringUtil; import com.brilliance.eibs.util.StringUtil;
import java.beans.BeanInfo; import java.beans.BeanInfo;
...@@ -20,16 +19,13 @@ public class BeanFilter extends AbsFilter { ...@@ -20,16 +19,13 @@ public class BeanFilter extends AbsFilter {
private Class<?> typeClass; private Class<?> typeClass;
private Object object; private Object object;
@Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "BeanFilter is begining to runnig." +
// LOG_FLAG);
context.setCurrentInstance(this); context.setCurrentInstance(this);
String type = getFilterDef().getType(); String type = getFilterDef().getType();
if (type.equals("out")) { if (type.equals("out")) {
// logger.info( LOG_FLAG + "BeanFilter组装" + LOG_FLAG);
String classname = getRequiredPropertyValue("classname"); String classname = getRequiredPropertyValue("classname");
try { try {
// typeClass = ClassPathUpdater.dynamicLoadClass(classname);
typeClass = Class.forName(classname); typeClass = Class.forName(classname);
} catch (Exception e) { } catch (Exception e) {
throw new InterfaceException("00701", "class [" + classname + "] not found.", e); throw new InterfaceException("00701", "class [" + classname + "] not found.", e);
...@@ -43,20 +39,17 @@ public class BeanFilter extends AbsFilter { ...@@ -43,20 +39,17 @@ public class BeanFilter extends AbsFilter {
super.execute(context); super.execute(context);
if (type.equals("out")) { if (type.equals("out")) {
context.setObject(object); context.setObject(object);
// saveToContext(filterDef.getScope(), filterDef.getTag(), object);
} else { } else {
// logger.info( LOG_FLAG + "BeanFilter解析" + LOG_FLAG);
} }
// logger.info( LOG_FLAG + "BeanFilter has finished running." +
// LOG_FLAG);
} }
@Override @Override
protected void packField(IFieldDef fieldDef, Object fieldValue) { protected void packField(IFieldDef fieldDef, Object fieldValue) {
fieldValue = dealValueByType(fieldValue, fieldDef.getType()); fieldValue = dealValueByType(fieldValue, fieldDef.getType());
String etag = (String) elParser.getExPression(context, fieldDef.getEtag(), null); String etag = (String) elParser.getExPression(context, fieldDef.getEtag(), null);
if (StringUtil.isEmpty(etag)) if (StringUtil.isEmpty(etag)) {
return; return;
}
BeanInfo beanInfo = null; BeanInfo beanInfo = null;
try { try {
beanInfo = Introspector.getBeanInfo(typeClass); beanInfo = Introspector.getBeanInfo(typeClass);
...@@ -78,18 +71,21 @@ public class BeanFilter extends AbsFilter { ...@@ -78,18 +71,21 @@ public class BeanFilter extends AbsFilter {
try { try {
if (fieldValue instanceof List && "add".equals(context.getVariable("handle_list"))) { if (fieldValue instanceof List && "add".equals(context.getVariable("handle_list"))) {
List<Object> list = (List<Object>) descriptor.getReadMethod().invoke(object, (Object[]) null); List<Object> list = (List<Object>) descriptor.getReadMethod().invoke(object, (Object[]) null);
if (list != null) if (list != null) {
list.addAll((List<Object>) fieldValue); list.addAll((List<Object>) fieldValue);
} else }
} else {
descriptor.getWriteMethod().invoke(object, args); descriptor.getWriteMethod().invoke(object, args);
}
} catch (Exception e) { } catch (Exception e) {
throw new InterfaceException("00704", "write property [" + propertyName + "] error", e); throw new InterfaceException("00704", "write property [" + propertyName + "] error", e);
} }
break; break;
} }
} }
if (j >= propertyDescriptors.length) if (j >= propertyDescriptors.length) {
throw new InterfaceException("00707", "property [" + etag + "] of class [" + typeClass + "] not exists."); throw new InterfaceException("00707", "property [" + etag + "] of class [" + typeClass + "] not exists.");
}
} }
@Override @Override
......
...@@ -10,126 +10,100 @@ import java.io.InputStream; ...@@ -10,126 +10,100 @@ import java.io.InputStream;
/** /**
* 命令行连接 * 命令行连接
* *
* @author gechengyang * @author gechengyang
*
*/ */
public class CommandConnection extends AbsConnection { public class CommandConnection extends AbsConnection {
private String type = ""; private String type = "";
private String encode = "GBK"; private String encode = "GBK";
@Override @Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "CommandConnection is running." + encode = connectionDef.getEncoding();
// LOG_FLAG); context.setCurrentInstance(this);
encode = connectionDef.getEncoding(); String command = getPropertyValue("command", false);
// 是否有返回值
type = getPropertyValue("type", true);
int success = 1;
if (!StringUtil.isEmpty(command)) {
success = executeShell(command, context);
logger.info("shell [" + command + "] invoke " + (success == 0 ? true : false));
}
if (success == 0) {
context.getResultMsg().setSuccess(true);
} else {
context.getResultMsg().setSuccess(false);
}
}
context.setCurrentInstance(this); public int executeShell(String shellCommand, Context context) {
// String command = connectionDef.getProperty("command").getValue(); shellCommand = shellCommand.trim();
// /command=getPropertyValue(command, false); shellCommand = shellCommand.replaceAll("\\s+", " ");
String command = getPropertyValue("command", false); logger.info("[command is]" + shellCommand);
// 是否有返回值 int success = 0;
type = getPropertyValue("type", true); StringBuffer stringBuffer = new StringBuffer();
int success = 1; InputStream in = null;
if (!StringUtil.isEmpty(command)) { InputStream errorin = null;
success = executeShell(command, context); int a = 0;
logger.info( "shell [" + command + "] invoke " + (success == 0 ? true : false)); try {
} Process pid = null;
if (success == 0) Runtime runtime = Runtime.getRuntime();
context.getResultMsg().setSuccess(true); if (shellCommand.contains("*")) {
else logger.debug("[command include *]");
context.getResultMsg().setSuccess(false); pid = runtime.exec(new String[]{"/bin/sh", "-c", shellCommand}, null, null);
// logger.info( LOG_FLAG + } else if (!shellCommand.contains("|")) {
// "CommandConnection has finished running." + LOG_FLAG); String[] cmdarray = shellCommand.split("\\ ");
} logger.info("[exec is ready]" + CommonFunctionUtils.toJson(cmdarray));
pid = runtime.exec(cmdarray);
} else {
pid = runtime.exec(new String[]{"/bin/sh", "-c", shellCommand}, null, null);
}
// 执行Shell命令
if (pid != null) {
in = pid.getInputStream();
errorin = pid.getErrorStream();
stringBuffer.append(loadStream(in) + "\r\n");
String error = loadStream(errorin);
logger.info("error=" + error);
stringBuffer.append(error + "\r\n");
a = pid.waitFor();
logger.info("pid flag=" + a);
} else {
stringBuffer.append("没有pid\r\n");
}
} catch (Exception ioe) {
logger.info("ioeerror", ioe);
success = 1;
stringBuffer.append("执行Shell命令时发生异常:\r\n").append(ioe.getMessage()).append("\r\n");
throw new InterfaceException("00801", "read file error.", ioe);
} finally {
String shellMsg = stringBuffer.toString().trim();
logger.info("shell mssage:" + shellMsg);
if (!StringUtil.isEmpty(type)) {
type = type.toLowerCase();
if (type.equals("string")) {
context.setObject(shellMsg);
} else if (type.equals("int")) {
context.setObject(Integer.parseInt(shellMsg));
}
}
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(errorin);
}
return success;
}
public int executeShell(String shellCommand, Context context) { public String loadStream(InputStream in) {
shellCommand = shellCommand.trim(); String str = "";
shellCommand = shellCommand.replaceAll("\\s+", " "); try {
logger.info( "[command is]" + shellCommand); str = IOUtils.toString(in, encode);
int success = 0; } catch (Exception e) {
StringBuffer stringBuffer = new StringBuffer(); logger.error("loadStream", e);
// 格式化日期时间,记录日志时使用 } finally {
// DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss "); IOUtils.closeQuietly(in);
InputStream in = null; }
InputStream errorin = null; return str;
int a = 0; }
try {
// stringBuffer.append(dateFormat.format(new
// Date())).append("准备执行Shell命令 ").append(shellCommand).append(" \r\n");
Process pid = null;
Runtime runtime = Runtime.getRuntime();
if (shellCommand.contains("*")) {
logger.debug( "[command include *]");
pid = runtime.exec(new String[] { "/bin/sh", "-c", shellCommand }, null, null);
} else if (!shellCommand.contains("|")) {
String[] cmdarray = shellCommand.split("\\ ");// 空格
logger.info( "[exec is ready]" + CommonFunctionUtils.toJson(cmdarray));
pid = runtime.exec(cmdarray);
} else {
pid = runtime.exec(new String[] { "/bin/sh", "-c", shellCommand }, null, null);
}
// 执行Shell命令
if (pid != null) {
// stringBuffer.append("进程号:").append(pid.toString()).append("\r\n");
in = pid.getInputStream();
errorin = pid.getErrorStream();
stringBuffer.append(loadStream(in) + "\r\n");
String error = loadStream(errorin);
logger.info( "error=" + error);
stringBuffer.append(error + "\r\n");
a = pid.waitFor();
logger.info( "pid flag=" + a);
} else {
stringBuffer.append("没有pid\r\n");
}
} catch (Exception ioe) {
logger.info( "ioeerror", ioe);
success = 1;
// stringBuffer.append("执行Shell命令时发生异常:\r\n").append(ioe.getMessage()).append("\r\n");
stringBuffer.append("执行Shell命令时发生异常:\r\n").append(ioe.getMessage()).append("\r\n");
throw new InterfaceException("00801", "read file error.", ioe);
} finally {
String shellMsg = stringBuffer.toString().trim();
logger.info( "shell mssage:" + shellMsg);
if (!StringUtil.isEmpty(type)) {
type = type.toLowerCase();
if (type.equals("string")) {
context.setObject(shellMsg);
} else if (type.equals("int")) {
context.setObject(Integer.parseInt(shellMsg));
}
}
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(errorin);
}
/*
* if (a != 0) throw new InterfaceException("00801", "error accured");
*/
return success;
}
public String loadStream(InputStream in) {
String str = "";
try {
str = IOUtils.toString(in, encode);
} catch (Exception e) {
logger.error( "loadStream", e);
// TODO: handle exception
} finally {
IOUtils.closeQuietly(in);
}
/*
* in = new BufferedInputStream(in); StringBuffer buffer = new
* StringBuffer(); try { while ((ptr = in.read()) != -1) {
* buffer.append((char) ptr); } } catch (IOException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } return
* buffer.toString();
*/
return str;
}
} }
...@@ -19,8 +19,7 @@ public class ExcelTempateFilter extends AbsFilter { ...@@ -19,8 +19,7 @@ public class ExcelTempateFilter extends AbsFilter {
context.setCurrentInstance(this); context.setCurrentInstance(this);
String type = getType(); String type = getType();
if (!WRITE_FLG.equals(type)) // type="out" if (!WRITE_FLG.equals(type)) {
{
throw new InterfaceException("03401", "不支持的操作类型"); throw new InterfaceException("03401", "不支持的操作类型");
} }
Object content = context.getObject(); Object content = context.getObject();
...@@ -39,23 +38,20 @@ public class ExcelTempateFilter extends AbsFilter { ...@@ -39,23 +38,20 @@ public class ExcelTempateFilter extends AbsFilter {
@Override @Override
public Object getFieldValue(IFieldDef fieldDef) throws Exception { public Object getFieldValue(IFieldDef fieldDef) throws Exception {
// TODO Auto-generated method stub
return null; return null;
} }
@Override
protected void packField(IFieldDef fieldDef, Object fieldValue) { protected void packField(IFieldDef fieldDef, Object fieldValue) {
String etag = elParser.getExPression(context, fieldDef.getEtag(), null).toString(); String etag = elParser.getExPression(context, fieldDef.getEtag(), null).toString();
boolean defaultStyle = true; boolean defaultStyle = true;
if (!StringUtil.isEmpty(fieldDef.getTag())) { if (!StringUtil.isEmpty(fieldDef.getTag())) {
defaultStyle = false; defaultStyle = false;
} }
String[] targetIndexs = etag.split(","); String[] targetIndexs = etag.split(",");
if (targetIndexs.length < 2) { if (targetIndexs.length < 2) {
throw new InterfaceException("03404", "etag坐标数据格式错误"); throw new InterfaceException("03404", "etag坐标数据格式错误");
} }
int yIndex = 0; int yIndex = 0;
int xIndex = 0; int xIndex = 0;
try { try {
......
...@@ -2,7 +2,6 @@ package com.brilliance.eibs.core.service.instance.impl; ...@@ -2,7 +2,6 @@ package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException; import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context; import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.impl.AbsConnection;
import com.brilliance.eibs.util.StringUtil; import com.brilliance.eibs.util.StringUtil;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
...@@ -11,160 +10,144 @@ import java.util.List; ...@@ -11,160 +10,144 @@ import java.util.List;
/** /**
* 文件连接,提供对文件的读取保存功能 * 文件连接,提供对文件的读取保存功能
*
* @author hujun
* *
* @author hujun
*/ */
public class FileConnection extends AbsConnection { public class FileConnection extends AbsConnection {
private static final String EXCEL_SUFFIX = "excel"; @Override
private static final String XLS_EXCEL_SUFFIX = "xls"; public void execute(Context context) {
private static final String XLSX_EXCEL_SUFFIX = "xlsx"; context.setCurrentInstance(this);
// 获取操作类型
@Override String type = getType();
public void execute(Context context) { // 获取文件路径
String path = getPropertyValue(PATH_SYMBOL);
// logger.debug( LOG_FLAG + "FileConnection is running ." + if (isRead(type)) {
// LOG_FLAG); logger.debug("读取文件[" + path + "].");
context.setCurrentInstance(this); try {
// 获取操作类型 doRead(path);
String type = getType(); } catch (IOException e) {
// 获取文件路径 throw new InterfaceException("00801", "read file error.", e);
String path = getPropertyValue(PATH_SYMBOL); }
}
if (isRead(type)) { if (isWrite(type)) {
logger.debug( "读取文件[" + path + "]."); logger.debug("保存文件[" + path + "].");
try { try {
doRead(path); doWrite(path);
} catch (IOException e) { } catch (IOException e) {
throw new InterfaceException("00801", "read file error.", e); throw new InterfaceException("00802", "write to file error.", e);
} }
} }
if (isWrite(type)) { }
logger.debug( "保存文件[" + path + "].");
try {
doWrite(path);
} catch (IOException e) {
throw new InterfaceException("00802", "write to file error.", e);
}
}
// logger.debug( LOG_FLAG + "FileConnection is finished." +
// LOG_FLAG);
}
private boolean isRead(String type) { private boolean isRead(String type) {
return READ_FLG.equals(type); return READ_FLG.equals(type);
} }
private boolean isWrite(String type) { private boolean isWrite(String type) {
return WRITE_FLG.equals(type); return WRITE_FLG.equals(type);
} }
private void doRead(String path) throws IOException { private void doRead(String path) throws IOException {
Object content = read(path); Object content = read(path);
// logger.debug("Read the contents is " + content + "."); // 读取文件写入上下文
// 读取文件写入上下文 context.setObject(content);
context.setObject(content); }
}
private void doWrite(String path) throws IOException { private void doWrite(String path) throws IOException {
// 获取需要写入的文件 // 获取需要写入的文件
File file = new File(path); File file = new File(path);
boolean append = Boolean.valueOf(getPropertyValue("append", true)); boolean append = Boolean.valueOf(getPropertyValue("append", true));
if (!file.getParentFile().exists()) { if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
} }
if (!append || !file.exists()) { if (!append || !file.exists()) {
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (IOException e) {
throw new InterfaceException("00803", "create new file error.", e); throw new InterfaceException("00803", "create new file error.", e);
} }
} }
Object obj = context.getObject(); Object obj = context.getObject();
if (obj == null || obj.toString().equals("")) { if (obj == null || obj.toString().equals("")) {
logger.warn( "No content to write."); logger.warn("No content to write.");
} }
// logger.trace("Write the contents is " + write(file, obj, append);
// System.getProperty("line.separator") + obj.toString()); }
write(file, obj, append);
}
/** /**
* 文件写入操作 * 文件写入操作
* *
* @param path * @param file 文件路徑
* 文件路徑 * @param content 文件内容
* @param content * @param isAppend
* 文件内容 * @throws IOException
* @throws IOException */
*/ private void write(File file, Object content, boolean isAppend) throws IOException {
private void write(File file, Object content, boolean isAppend) throws IOException { FileOutputStream fos = new FileOutputStream(file, isAppend);
FileOutputStream fos = new FileOutputStream(file, isAppend); try {
try { if (content instanceof byte[]) {
if (content instanceof byte[]) { logger.info("file 类型:二进制文件");
logger.info( "file 类型:二进制文件"); IOUtils.write((byte[]) content, fos);
IOUtils.write((byte[]) content, fos); logger.info("文件长度是=" + ((byte[]) content).length);
logger.info( "文件长度是=" + ((byte[]) content).length); return;
return; }
} PrintWriter pw = null;
PrintWriter pw = null; try {
try { pw = new PrintWriter(new OutputStreamWriter(fos, connectionDef.getEncoding()), true);
pw = new PrintWriter(new OutputStreamWriter(fos, connectionDef.getEncoding()), true); pw.print(content);
pw.print(content); pw.flush();
pw.flush(); } finally {
} finally { IOUtils.closeQuietly(pw);
IOUtils.closeQuietly(pw); }
} } finally {
} finally { IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(fos); }
} }
}
/** /**
* 文件读取操作 * 文件读取操作
* *
* @param path * @param path 文件路徑
* 文件路徑 * @return 文件内容
* @return 文件内容 * @throws IOException
* @throws IOException */
*/ private Object read(String path) throws IOException {
private Object read(String path) throws IOException { BufferedReader br = null;
BufferedReader br = null; FileInputStream fis = null;
FileInputStream fis = null; try {
try { String type = getPropertyValue("type", true);
String type = getPropertyValue("type", true); fis = new FileInputStream(path);
fis = new FileInputStream(path); if ("list".equals(type)) {
if ("list".equals(type)) { List<String> list = IOUtils.readLines(fis, connectionDef.getEncoding());
List<String> list = IOUtils.readLines(fis, connectionDef.getEncoding()); IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(fis); String filterLines = getPropertyValue("removeLines", true);
String filterLines = getPropertyValue("removeLines", true); if (!StringUtil.isEmpty(filterLines)) {
if (!StringUtil.isEmpty(filterLines)) { String[] lines = filterLines.split(",");
String[] lines = filterLines.split(","); for (String line : lines) {
for (String line : lines) { list.remove(Integer.parseInt(line));
list.remove(Integer.parseInt(line)); }
} }
} return list;
return list; }
} if ("byte".equals(type)) {
if ("byte".equals(type)) { File file = new File(path);
File file = new File(path); int length = (int) file.length();
int length = (int) file.length(); byte[] bytes = new byte[length];
byte[] bytes = new byte[length]; IOUtils.readFully(fis, bytes);
IOUtils.readFully(fis, bytes); return bytes;
return bytes; }
}
StringBuffer s = new StringBuffer(); StringBuffer s = new StringBuffer();
br = new BufferedReader(new InputStreamReader(fis, connectionDef.getEncoding())); br = new BufferedReader(new InputStreamReader(fis, connectionDef.getEncoding()));
int tempchar; int tempchar;
while ((tempchar = br.read()) != -1) { while ((tempchar = br.read()) != -1) {
s.append((char) tempchar); s.append((char) tempchar);
} }
return s.toString(); return s.toString();
} finally { } finally {
IOUtils.closeQuietly(fis); IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(br); IOUtils.closeQuietly(br);
} }
} }
} }
...@@ -2,7 +2,6 @@ package com.brilliance.eibs.core.service.instance.impl; ...@@ -2,7 +2,6 @@ package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef; import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context; import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.impl.AbsFilter;
import com.brilliance.eibs.util.StringUtil; import com.brilliance.eibs.util.StringUtil;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
...@@ -12,109 +11,99 @@ import java.util.Map; ...@@ -12,109 +11,99 @@ import java.util.Map;
/** /**
* Fix报文处理 * Fix报文处理
*
* @author 葛成洋
* *
* @author 葛成洋
*/ */
public class FixFilter extends AbsFilter { public class FixFilter extends AbsFilter {
String encoding; String encoding;
String FIX_VERSION_TAG = "8"; String FIX_VERSION_TAG = "8";
String FIX_VERSION_VALUE = ""; String FIX_VERSION_VALUE = "";
String BODY_LEN_TAG = "9"; String BODY_LEN_TAG = "9";
String BODY_LEN_VALUE = ""; String BODY_LEN_VALUE = "";
String FIX_TAIL_TAG = "10"; String FIX_TAIL_TAG = "10";
String FIX_TAIL_VALUE = ""; String FIX_TAIL_VALUE = "";
Map<String, Object> map = new LinkedHashMap<String, Object>(); Map<String, Object> map = new LinkedHashMap<String, Object>();
public void execute(Context context) { @Override
// logger.info( LOG_FLAG + "FixFilter is begining to runnig." + public void execute(Context context) {
// LOG_FLAG); context.setCurrentInstance(this);
context.setCurrentInstance(this); encoding = filterDef.getEncoding();
encoding = filterDef.getEncoding();
String type = getFilterDef().getType();
String type = getFilterDef().getType(); if (type.equals("in")) {
if (type.equals("in")) { Object object = context.getObject();
// logger.info( LOG_FLAG + "Fix报文解析" + LOG_FLAG); String str = null;
Object object = context.getObject(); if (object instanceof byte[]) {
String str = null; try {
if (object instanceof byte[]) { str = new String((byte[]) object, encoding);
try { } catch (UnsupportedEncodingException e) {
str = new String((byte[]) object, encoding); logger.error(e.getMessage(), e);
} catch (UnsupportedEncodingException e) { }
// TODO Auto-generated catch block } else {
e.printStackTrace(); str = (String) context.getObject();
} }
} else {
str = (String) context.getObject(); Map<String, Object> map = new HashMap<String, Object>();
} char c = 0x01;
String splitSym = String.valueOf(c);
Map<String, Object> map = new HashMap<String, Object>(); String[] tags = str.split(splitSym);
char c = 0x01; for (String tag : tags) {
String splitSym = String.valueOf(c); if (!StringUtil.isEmpty(tag)) {
String[] tags = str.split(splitSym); String keys[] = tag.split("=");
for (String tag : tags) { map.put(keys[0], keys[1]);
if (!StringUtil.isEmpty(tag)) { }
String keys[] = tag.split("="); }
map.put(keys[0], keys[1]); context.setObject(map);
} } else {
} }
context.setObject(map); super.execute(context);
} else { // 组装完后,存入上下文resource的object
// logger.info( LOG_FLAG + "FixFilter定长报文组装" + LOG_FLAG); if (type.equals("out")) {
} StringBuffer sb = new StringBuffer();
super.execute(context); char c = 0x01;
// 组装完后,存入上下文resource的object for (String key : map.keySet()) {
if (type.equals("out")) { sb.append(key + "=" + map.get(key)).append(c);
StringBuffer sb = new StringBuffer(); }
char c = 0x01; try {
// sb.append(FIX_VERSION_TAG + "=" + FIX_VERSION_VALUE).append(c); BODY_LEN_VALUE = String.valueOf(sb.toString().getBytes(encoding).length);
for (String key : map.keySet()) { } catch (UnsupportedEncodingException e) {
sb.append(key + "=" + map.get(key)).append(c); logger.error(e.getMessage(), e);
} }
try { StringBuffer allSb = new StringBuffer();
BODY_LEN_VALUE = String.valueOf(sb.toString().getBytes(encoding).length); allSb.append(FIX_VERSION_TAG + "=" + FIX_VERSION_VALUE).append(c);
allSb.append(BODY_LEN_TAG + "=" + BODY_LEN_VALUE).append(c);
} catch (UnsupportedEncodingException e) { allSb.append(sb);
e.printStackTrace(); allSb.append(FIX_TAIL_TAG + "=" + FIX_TAIL_VALUE).append(c);
} context.setObject(allSb.toString());
StringBuffer allSb = new StringBuffer(); }
allSb.append(FIX_VERSION_TAG + "=" + FIX_VERSION_VALUE).append(c); logger.info("FixFilter is finished");
allSb.append(BODY_LEN_TAG + "=" + BODY_LEN_VALUE).append(c); }
allSb.append(sb);
allSb.append(FIX_TAIL_TAG + "=" + FIX_TAIL_VALUE).append(c); @Override
protected void packField(IFieldDef fieldDef, Object fieldValue) {
context.setObject(allSb.toString()); String etag = fieldDef.getEtag();
if (StringUtil.isEmpty(etag)) {
} return;
logger.info( "FixFilter is finished"); }
} etag = elParser.getExPression(context, etag, null).toString();
if (etag.equals(FIX_VERSION_TAG)) {
protected void packField(IFieldDef fieldDef, Object fieldValue) { FIX_VERSION_VALUE = fieldValue.toString();
String etag = fieldDef.getEtag(); } else if (etag.equals(FIX_TAIL_TAG)) {
if (StringUtil.isEmpty(etag)) FIX_TAIL_VALUE = fieldValue.toString();
return; } else if (etag.equals(BODY_LEN_TAG)) {
etag = elParser.getExPression(context, etag, null).toString(); return;
if (etag.equals(FIX_VERSION_TAG)) { } else {
FIX_VERSION_VALUE = fieldValue.toString(); map.put(etag, fieldValue.toString());
}
} else if (etag.equals(FIX_TAIL_TAG)) { }
FIX_TAIL_VALUE = fieldValue.toString();
} else if (etag.equals(BODY_LEN_TAG)) { @Override
return; public Object getFieldValue(IFieldDef fieldDef) {
} else { return null;
map.put(etag, fieldValue.toString()); }
}
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
// String etag = elParser.getExPression(context, fieldDef.getEtag(),
// null).toString();
return null;
}
} }
\ No newline at end of file
...@@ -3,7 +3,6 @@ package com.brilliance.eibs.core.service.instance.impl; ...@@ -3,7 +3,6 @@ package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException; import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef; import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context; import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.impl.AbsFilter;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException; import com.google.gson.JsonSyntaxException;
...@@ -13,128 +12,88 @@ import java.util.Map; ...@@ -13,128 +12,88 @@ import java.util.Map;
/** /**
* Json报文处理 * Json报文处理
* @author xiaoyuanzhen
* *
* @author xiaoyuanzhen
*/ */
public class GsonFilter public class GsonFilter extends AbsFilter {
extends AbsFilter
{
private Object jsonObject; private Object jsonObject;
private String jsontype; private String jsontype;
@Override @Override
public void execute(Context context) public void execute(Context context) {
{ logger.info(LOG_FLAG + "GsonFilter is begining to runnig." + LOG_FLAG);
logger.info(LOG_FLAG + "GsonFilter is begining to runnig." + LOG_FLAG); context.setCurrentInstance(this);
context.setCurrentInstance(this); String type = filterDef.getType();
String type = filterDef.getType(); if (type.equals("in")) {
if (type.equals("in")) logger.info(LOG_FLAG + "GsonFilter解析" + LOG_FLAG);
{ String json = (String) context.getObject();
logger.info(LOG_FLAG + "GsonFilter解析" + LOG_FLAG); jsontype = getRequiredPropertyValue("jsontype");
String json = (String) context.getObject(); try {
jsontype = getRequiredPropertyValue("jsontype"); Object obj = jsonToObject(json, jsontype);
try context.setObject(obj);
{ logger.debug("json to " + "[" + obj.getClass() + "] :" + obj);
Object obj = jsonToObject(json, jsontype); } catch (JsonSyntaxException e) {
context.setObject(obj); throw new InterfaceException("01301", e);
logger.debug("json to " + "[" + obj.getClass() + "] :" + obj); }
} super.execute(context);
catch (JsonSyntaxException e) } else {
{ logger.info(LOG_FLAG + "GsonFilter组装" + LOG_FLAG);
throw new InterfaceException("01301", e); Object object = context.getObject();
} super.execute(context);
super.execute(context); String jsonStr = null;
Gson gson = new Gson();
jsonStr = gson.toJson(object);
context.setObject(jsonStr);
logger.debug("gson result:" + jsonStr);
}
logger.info(LOG_FLAG + "GsonFilter has finished runnig." + LOG_FLAG);
} }
else
{
logger.info(LOG_FLAG + "GsonFilter组装" + LOG_FLAG); /**
Object object = context.getObject(); * json转化为Java对象
super.execute(context); *
String jsonStr = null; * @param json
Gson gson = new Gson(); * @return
// jsonStr = gson.toJson(jsonObject); */
jsonStr = gson.toJson(object); private Object jsonToObject(String json, String jsontype) {
context.setObject(jsonStr); Class<?> beantype = null;
//saveToContext(getFilterDef().getScope(), getFilterDef().getTag(), context.getObject()); if (json.startsWith("[") || jsontype.equals("list")) {
logger.debug("gson result:" + jsonStr); beantype = List.class;
} else if (jsontype.equals("map")) {
beantype = HashMap.class;
} else {
try {
beantype = Class.forName(jsontype);
} catch (ClassNotFoundException e) {
logger.error(e.getMessage(), e);
}
}
return new Gson().fromJson(json, beantype);
} }
logger.info(LOG_FLAG + "GsonFilter has finished runnig." + LOG_FLAG);
}
/** @Override
* json转化为Java对象 public Object getFieldValue(IFieldDef fieldDef) {
* @param json return null;
* @return
*/
private Object jsonToObject(String json, String jsontype)
{
Class<?> beantype = null;
if (json.startsWith("[") || jsontype.equals("list"))
beantype = List.class;
else if (jsontype.equals("map"))
beantype = HashMap.class;
else
{
try
{
beantype=Class.forName(jsontype);
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
return new Gson().fromJson(json, beantype);
}
//解包 处理etag
@Override
public Object getFieldValue(IFieldDef fieldDef)
{
return null;
}
/** /**
* 往当前组装的对象中添加值 * 往当前组装的对象中添加值
* @param key *
* @param value * @param key
*/ * @param value
@SuppressWarnings({"unchecked", "rawtypes"}) */
private void addElement(String key, Object value) @SuppressWarnings({"unchecked", "rawtypes"})
{ private void addElement(String key, Object value) {
if (jsonObject instanceof Map) if (jsonObject instanceof Map) {
{ ((Map) jsonObject).put(key, value);
((Map) jsonObject).put(key, value); } else if (jsonObject instanceof List) {
((List) jsonObject).add(value);
}
} }
else if (jsonObject instanceof List)
{
((List) jsonObject).add(value);
}
}
//组包 @Override
@Override protected void packField(IFieldDef fieldDef, Object fieldValue) {
protected void packField(IFieldDef fieldDef, Object fieldValue)
{
/*String etag = (String) elParser.getExPression(context, fieldDef.getEtag(), null);
Object jsonValue = null;
if (fieldValue instanceof String)
{
try
{
jsonValue = jsonToObject((String) fieldValue);
}
catch (Exception e)
{}
}
if (jsonValue != null)
{
fieldValue = jsonValue;
} }
addElement(etag, fieldValue);*/
}
} }
...@@ -5,7 +5,6 @@ import com.brilliance.eibs.core.model.IConnectionDef; ...@@ -5,7 +5,6 @@ import com.brilliance.eibs.core.model.IConnectionDef;
import com.brilliance.eibs.core.model.IPropertyDef; import com.brilliance.eibs.core.model.IPropertyDef;
import com.brilliance.eibs.core.model.impl.ConnectionDef; import com.brilliance.eibs.core.model.impl.ConnectionDef;
import com.brilliance.eibs.core.service.Context; import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.impl.AbsConnection;
import com.brilliance.eibs.core.service.instance.plugin.ConnectionAdaptor; import com.brilliance.eibs.core.service.instance.plugin.ConnectionAdaptor;
import com.brilliance.eibs.core.service.instance.plugin.DBConnPool; import com.brilliance.eibs.core.service.instance.plugin.DBConnPool;
import com.brilliance.eibs.core.service.instance.plugin.JdbcExecutor; import com.brilliance.eibs.core.service.instance.plugin.JdbcExecutor;
...@@ -25,9 +24,8 @@ public class JdbcConnection extends AbsConnection { ...@@ -25,9 +24,8 @@ public class JdbcConnection extends AbsConnection {
public static final String SQL_SESSION = "__sqlSession"; public static final String SQL_SESSION = "__sqlSession";
public final String CNT = "_cnt"; public final String CNT = "_cnt";
@Override
public void execute(Context context) { public void execute(Context context) {
// logger.debug( LOG_FLAG + "JdbcConnection is running." +
// LOG_FLAG);
context.setCurrentInstance(this); context.setCurrentInstance(this);
super.execute(context); super.execute(context);
ConnectionAdaptor connectionAdator = null; ConnectionAdaptor connectionAdator = null;
...@@ -56,29 +54,26 @@ public class JdbcConnection extends AbsConnection { ...@@ -56,29 +54,26 @@ public class JdbcConnection extends AbsConnection {
context.getResource().setCntConnection(cntConnection); context.getResource().setCntConnection(cntConnection);
} }
} catch (Exception e) { } catch (Exception e) {
throw new InterfaceException("01501", e); throw new InterfaceException("01501", e);
} }
try { try {
executor = new JdbcExecutor(context, connection); executor = new JdbcExecutor(context, connection);
} catch (Exception e) { } catch (Exception e) {
try { try {
if (executor != null) if (executor != null) {
executor.close(); executor.close();
}
} catch (SQLException e1) { } catch (SQLException e1) {
throw new InterfaceException("01503", e1); throw new InterfaceException("01503", e1);
} }
throw new InterfaceException("01502", e); throw new InterfaceException("01502", e);
} }
context.getResource().setExecutor(executor);
} else { } else {
try { try {
context.setRollbackFlag(1); context.setRollbackFlag(1);
connectionDefTmp.setId(connectionDefTmp.getId() + joinedId); connectionDefTmp.setId(connectionDefTmp.getId() + joinedId);
connection = createConnectionJoined(connectionDefTmp); connection = createConnectionJoined(connectionDefTmp);
// connection.setAutoCommit(false);
context.getResource().setConnection(connection); context.getResource().setConnection(connection);
} catch (Exception e) { } catch (Exception e) {
throw new InterfaceException("01501", e); throw new InterfaceException("01501", e);
} }
...@@ -86,24 +81,21 @@ public class JdbcConnection extends AbsConnection { ...@@ -86,24 +81,21 @@ public class JdbcConnection extends AbsConnection {
executor = new JdbcExecutor(context, connection); executor = new JdbcExecutor(context, connection);
} catch (Exception e) { } catch (Exception e) {
try { try {
if (executor != null) if (executor != null) {
executor.close(); executor.close();
}
} catch (SQLException e1) { } catch (SQLException e1) {
throw new InterfaceException("01503", e1); throw new InterfaceException("01503", e1);
} }
throw new InterfaceException("01502", e); throw new InterfaceException("01502", e);
} }
context.getResource().setExecutor(executor);
} }
// logger.debug( LOG_FLAG + context.getResource().setExecutor(executor);
// "JdbcConnection has finished runnig." + LOG_FLAG);
} }
private ConnectionAdaptor createConnection(IConnectionDef connectionDefintion) throws SQLException, ClassNotFoundException { private ConnectionAdaptor createConnection(IConnectionDef connectionDefintion) throws SQLException, ClassNotFoundException {
String id = connectionDefintion.getId(); String id = connectionDefintion.getId();
ConnectionAdaptor connectionAdaptor = context.getConnectionAdaptors().get(id); ConnectionAdaptor connectionAdaptor = context.getConnectionAdaptors().get(id);
if (null == connectionAdaptor || connectionAdaptor.isClosed()) { if (null == connectionAdaptor || connectionAdaptor.isClosed()) {
connectionAdaptor = new ConnectionAdaptor(DBConnPool.getConnection(connectionDefintion, LogUtil.getLogger(context))); connectionAdaptor = new ConnectionAdaptor(DBConnPool.getConnection(connectionDefintion, LogUtil.getLogger(context)));
context.getConnectionAdaptors().put(id, connectionAdaptor); context.getConnectionAdaptors().put(id, connectionAdaptor);
...@@ -111,24 +103,7 @@ public class JdbcConnection extends AbsConnection { ...@@ -111,24 +103,7 @@ public class JdbcConnection extends AbsConnection {
return connectionAdaptor; return connectionAdaptor;
} }
private Connection createConnectionJoined(IConnectionDef connectionDefintion) throws Exception { private Connection createConnectionJoined(IConnectionDef connectionDefintion) {
/*
* String id = connectionDefintion.getId();
*
* ConnectionAdaptor connectionAdaptor =
* context.getConnectionAdaptors().get(id); Connection connection =
* connectionAdaptor.getConnection(); if (null == connectionAdaptor ||
* connectionAdaptor.isClosed()) { logger.info(
* "jdbcConnections has closed or is null"); JotmHelper jotmHelper =
* context.getJotmHelper(); if (jotmHelper == null) { jotmHelper = new
* JotmHelper(); jotmHelper.startTMService(); // jotmHelper.begin();
* context.setJotmHelper(jotmHelper); } connection =
* jotmHelper.getConnection(connectionDefintion);
*
* logger.info( "get jdbcConnections again");
* context.getConnectionAdaptors().put(id, new
* ConnectionAdaptor(connection, null)); } return connection;
*/
return null; return null;
} }
} }
...@@ -14,101 +14,96 @@ import java.util.Hashtable; ...@@ -14,101 +14,96 @@ import java.util.Hashtable;
/** /**
* 数据库连接类,使用JNDI数据源获取数据库连接 * 数据库连接类,使用JNDI数据源获取数据库连接
*
* @author xiaoyuanzhen
* *
* @author xiaoyuanzhen
*/ */
public class JndiDsConnection extends AbsConnection { public class JndiDsConnection extends AbsConnection {
/** /**
* 数据源 * 数据源
*/ */
private DataSource dataSource; private DataSource dataSource;
/**
* 是否为CNT表单独建立一个连接
*/
private boolean useCnt;
public void execute(Context context) {
// logger.info( LOG_FLAG + "JndiConnection is running." +
// LOG_FLAG);
context.setCurrentInstance(this); /**
super.execute(context); * 是否为CNT表单独建立一个连接
*/
private boolean useCnt;
Connection connection = null; @Override
JdbcExecutor executor = null; public void execute(Context context) {
String id = connectionDef.getId(); context.setCurrentInstance(this);
try { super.execute(context);
useCnt = Boolean.valueOf(getPropertyValue("use_table_cnt", true));
dataSource = getDataSource();
connection = dataSource.getConnection();
connection.setAutoCommit(false);
context.getConnectionAdaptors().put(id, new ConnectionAdaptor(connection));
context.getResource().setConnection(connection);
if (useCnt) {
Connection cntConnection = createConnection(id + "_cnt");
cntConnection.setAutoCommit(false);
context.getResource().setCntConnection(cntConnection);
}
} catch (Exception e) {
throw new InterfaceException("01501", e);
}
try {
executor = new JdbcExecutor(context, connection);
} catch (Exception e) {
try {
if (executor != null)
executor.close();
} catch (SQLException e1) {
throw new InterfaceException("01503", e1);
}
throw new InterfaceException("01502", e);
}
context.getResource().setExecutor(executor);
// logger.info( LOG_FLAG + "JndiConnection finished." +
// LOG_FLAG);
}
/** Connection connection = null;
* 获取数据源 JdbcExecutor executor = null;
* String id = connectionDef.getId();
* @return try {
* @throws Exception useCnt = Boolean.valueOf(getPropertyValue("use_table_cnt", true));
*/ dataSource = getDataSource();
private DataSource getDataSource() throws Exception { connection = dataSource.getConnection();
String providerUrl = getPropertyValue("provider_url", true); connection.setAutoCommit(false);
String initialFactory = getPropertyValue("factory", true); context.getConnectionAdaptors().put(id, new ConnectionAdaptor(connection));
String dsName = getPropertyValue("name", false); context.getResource().setConnection(connection);
Hashtable<String, String> env = new Hashtable<String, String>(); if (useCnt) {
Connection cntConnection = createConnection(id + "_cnt");
cntConnection.setAutoCommit(false);
context.getResource().setCntConnection(cntConnection);
}
} catch (Exception e) {
throw new InterfaceException("01501", e);
}
try {
executor = new JdbcExecutor(context, connection);
} catch (Exception e) {
try {
if (executor != null) {
executor.close();
}
} catch (SQLException e1) {
throw new InterfaceException("01503", e1);
}
throw new InterfaceException("01502", e);
}
context.getResource().setExecutor(executor);
}
if (!StringUtil.isEmpty(providerUrl)) { /**
env.put(javax.naming.Context.PROVIDER_URL, providerUrl); * 获取数据源
} *
if (!StringUtil.isEmpty(initialFactory)) { * @return
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, initialFactory); * @throws Exception
} */
private DataSource getDataSource() throws Exception {
String providerUrl = getPropertyValue("provider_url", true);
String initialFactory = getPropertyValue("factory", true);
String dsName = getPropertyValue("name", false);
Hashtable<String, String> env = new Hashtable<String, String>();
InitialContext ctx = new InitialContext(env); if (!StringUtil.isEmpty(providerUrl)) {
return (DataSource) ctx.lookup(dsName); env.put(javax.naming.Context.PROVIDER_URL, providerUrl);
} }
if (!StringUtil.isEmpty(initialFactory)) {
env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, initialFactory);
}
InitialContext ctx = new InitialContext(env);
return (DataSource) ctx.lookup(dsName);
}
/** /**
* 获取数据库连接 * 获取数据库连接
* *
* @param id * @param id
* @return * @return
* @throws SQLException * @throws SQLException
*/ */
private Connection createConnection(String id) throws SQLException { private Connection createConnection(String id) throws SQLException {
ConnectionAdaptor connAdaptor = context.getConnectionAdaptors().get(id); ConnectionAdaptor connAdaptor = context.getConnectionAdaptors().get(id);
if (connAdaptor == null || connAdaptor.isClosed()) { if (connAdaptor == null || connAdaptor.isClosed()) {
Connection conn = dataSource.getConnection(); Connection conn = dataSource.getConnection();
connAdaptor = new ConnectionAdaptor(conn); connAdaptor = new ConnectionAdaptor(conn);
context.getConnectionAdaptors().put(id, connAdaptor); context.getConnectionAdaptors().put(id, connAdaptor);
} }
return connAdaptor.getConnection(); return connAdaptor.getConnection();
} }
} }
...@@ -12,184 +12,160 @@ import java.util.Date; ...@@ -12,184 +12,160 @@ import java.util.Date;
/** /**
* ResultSet结果集处理过滤器,执行该过滤器之后默认的会关闭ResultSet * ResultSet结果集处理过滤器,执行该过滤器之后默认的会关闭ResultSet
*
* @author hujun
* *
* @author hujun
*/ */
public class ResultSetFilter public class ResultSetFilter
extends AbsFilter extends AbsFilter {
{
private ResultSet rs; private ResultSet rs;
@Override @Override
public void execute(Context context) public void execute(Context context) {
{ logger.info(LOG_FLAG + "ResultSetFilter数据库结果集解析处理中." + LOG_FLAG);
logger.info(LOG_FLAG + "ResultSetFilter数据库结果集解析处理中." + LOG_FLAG); context.setCurrentInstance(this);
context.setCurrentInstance(this); rs = (ResultSet) context.getObject();
rs = (ResultSet) context.getObject(); if (rs == null) {
if (rs == null) throw new InterfaceException("01901");
throw new InterfaceException("01901"); }
JdbcExecutor executor = null; JdbcExecutor executor = null;
try try {
{ executor = context.getResource().getExecutor();
executor = context.getResource().getExecutor(); super.execute(context);
super.execute(context); } finally {
} close(executor, "01902");
finally }
{ logger.info(LOG_FLAG + "ResultSetFilter has finisehd running." + LOG_FLAG);
close(executor, "01902");
} }
logger.info(LOG_FLAG + "ResultSetFilter has finisehd running." + LOG_FLAG);
}
/** /**
* 关闭ResultSet,并拋出error系统异常 * 关闭ResultSet,并拋出error系统异常
* *
* @param rs * @param executor
* @param error * @param error
*/ */
private void close(JdbcExecutor executor, String error) private void close(JdbcExecutor executor, String error) {
{ try {
try executor.closeWithoutConn();
{ } catch (SQLException e) {
executor.closeWithoutConn(); throw new InterfaceException(error, "Close resultSet and preparedStatement exception occurs.", e);
} }
catch (SQLException e)
{
throw new InterfaceException(error, "Close resultSet and preparedStatement exception occurs.", e);
} }
}
/** /**
* 获取ResultSet的记录数 * 获取ResultSet的记录数
* *
* @return * @return
* @throws SQLException * @throws SQLException
*/ */
public int getSize() public int getSize()
throws SQLException throws SQLException {
{ rs.last();
rs.last(); int num = rs.getRow();
int num = rs.getRow(); //将游标重新复位到初始
//将游标重新复位到初始 rs.beforeFirst();
rs.beforeFirst(); return num;
return num; }
}
/** /**
* 获取ResultSet当前指向记录列名为s的Double类型的数据,如果数据库记录为空,返回"" * 获取ResultSet当前指向记录列名为s的Double类型的数据,如果数据库记录为空,返回""
* *
* @param s * @param s
* @return * @return
* @throws SQLException * @throws SQLException
*/ */
public String getString(String s) public String getString(String s)
throws SQLException throws SQLException {
{ return rs.getString(s);
return rs.getString(s); }
}
/** /**
* 获取ResultSet当前指向记录列名为s的Double类型的数据,如果数据库记录为空,返回0.0 * 获取ResultSet当前指向记录列名为s的Double类型的数据,如果数据库记录为空,返回0.0
* *
* @param s * @param s
* @return * @return
* @throws SQLException * @throws SQLException
*/ */
public double getDouble(String s) public double getDouble(String s)
throws SQLException throws SQLException {
{ return rs.getDouble(s);
return rs.getDouble(s); }
}
/** /**
* 获取ResultSet当前指向记录列名为s的Date类型的数据,默认会将java.sql.Date转换成java.util.Date * 获取ResultSet当前指向记录列名为s的Date类型的数据,默认会将java.sql.Date转换成java.util.Date
* *
* @param s * @param s
* @return * @return
* @throws SQLException * @throws SQLException
*/ */
public Date getDate(String s) public Date getDate(String s) throws SQLException {
throws SQLException java.sql.Date date = rs.getDate(s);
{ if (null != date) {
java.sql.Date date = rs.getDate(s); return new Date(rs.getDate(s).getTime());
if (null != date) }
return new Date(rs.getDate(s).getTime()); return null;
return null; }
}
/** /**
* 获取ResultSet当前指向记录列名为s的int类型的数据,如果数据库记录为空,返回0 * 获取ResultSet当前指向记录列名为s的int类型的数据,如果数据库记录为空,返回0
* *
* @param s * @param s
* @return * @return
* @throws SQLException * @throws SQLException
*/ */
public int getInt(String s) public int getInt(String s) throws SQLException {
throws SQLException return rs.getInt(s);
{ }
return rs.getInt(s);
}
/** /**
* 获取ResultSet当前指向记录列名为s的数据 * 获取ResultSet当前指向记录列名为s的数据
* @param s *
* @return * @param s
* @throws SQLException * @return
*/ * @throws SQLException
public Object getObject(String s) */
throws SQLException public Object getObject(String s) throws SQLException {
{ return rs.getObject(s);
return rs.getObject(s); }
}
/** /**
* 将ResultSet的游标下移一位 * 将ResultSet的游标下移一位
* *
* @return * @return
* @throws SQLException * @throws SQLException
*/ */
public boolean next() public boolean next() throws SQLException {
throws SQLException return rs.next();
{ }
return rs.next();
}
@Override @Override
public Object getFieldValue(IFieldDef fieldDef) public Object getFieldValue(IFieldDef fieldDef) {
{ String type = fieldDef.getType();
String type = fieldDef.getType(); String arg = fieldDef.getEtag();
String arg = fieldDef.getEtag(); try {
try if (FIELD_TYPE_DATE.equals(type)) {
{ return getDate(arg);
if (FIELD_TYPE_DATE.equals(type)) }
return getDate(arg); if (FIELD_TYPE_STRING.equals(type)) {
if (FIELD_TYPE_STRING.equals(type)) try {
{ if (getString(arg) != null) {
try return new String(getString(arg).getBytes(), filterDef.getEncoding());
{ } else {
if (getString(arg) != null) return null;
return new String(getString(arg).getBytes(), filterDef.getEncoding()); }
else } catch (UnsupportedEncodingException e) {
{ throw new InterfaceException("00403");
return null; }
} }
if (FIELD_TYPE_INT.equals(type)) {
return getInt(arg);
}
if (FIELD_TYPE_DOUBLE.equals(type)) {
return getDouble(arg);
}
return getObject(arg);
} catch (SQLException e) {
throw new InterfaceException("01903", "get result of [" + arg + "] error.", e);
} }
catch (UnsupportedEncodingException e)
{
throw new InterfaceException("00403");
}
}
if (FIELD_TYPE_INT.equals(type))
return getInt(arg);
if (FIELD_TYPE_DOUBLE.equals(type))
return getDouble(arg);
return getObject(arg);
}
catch (SQLException e)
{
throw new InterfaceException("01903", "get result of [" + arg + "] error.", e);
} }
}
} }
...@@ -18,134 +18,134 @@ import java.util.Map; ...@@ -18,134 +18,134 @@ import java.util.Map;
*/ */
public class RibbonFilter extends AbsFilter { public class RibbonFilter extends AbsFilter {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public void execute(Context context) { public void execute(Context context) {
context.setCurrentInstance(this); context.setCurrentInstance(this);
Map<Object, Object> params = (Map<Object, Object>) context.getObject();// 必须得从上下文中拿到服务列表 // 必须得从上下文中拿到服务列表
List<Server> servers = servers(params.get("server")); Map<Object, Object> params = (Map<Object, Object>) context.getObject();
String anInterface = (String) params.get("interface"); List<Server> servers = servers(params.get("server"));
String transaction = (String) params.get("transaction"); String anInterface = (String) params.get("interface");
ResultMsg value = null; String transaction = (String) params.get("transaction");
boolean flag = false; ResultMsg value = null;
StringBuffer errmsg = null; boolean flag = false;
Logger log = (Logger) context.getVariable(Constants.Log_VAR); StringBuffer errmsg = null;
for (Server server : servers) { Logger log = (Logger) context.getVariable(Constants.Log_VAR);
try { for (Server server : servers) {
Map<Object, Object> tmpParams = new HashMap<Object, Object>( try {
params); Map<Object, Object> tmpParams = new HashMap<Object, Object>(params);
tmpParams.put("ip", server.getHost()); tmpParams.put("ip", server.getHost());
tmpParams.put("port", server.getPort()); tmpParams.put("port", server.getPort());
value = new Client().call(anInterface, transaction, value = new Client().call(anInterface, transaction,
new Object[] { tmpParams }, log); new Object[]{tmpParams}, log);
if (value.isSuccess()) { if (value.isSuccess()) {
flag = true; flag = true;
break; break;
} else { } else {
errmsg = new StringBuffer(); errmsg = new StringBuffer();
errmsg.append("try call "); errmsg.append("try call ");
errmsg.append(server); errmsg.append(server);
errmsg.append(" failed ,failed message:"); errmsg.append(" failed ,failed message:");
errmsg.append(value.getDescription()); errmsg.append(value.getDescription());
server.setDsp(value.getDescription()); server.setDsp(value.getDescription());
logger.error( errmsg.toString()); logger.error(errmsg.toString());
} }
} catch (Throwable e) { } catch (Throwable e) {
errmsg = new StringBuffer(); errmsg = new StringBuffer();
errmsg.append("try call "); errmsg.append("try call ");
errmsg.append(server); errmsg.append(server);
errmsg.append(" failed ,caused by :"); errmsg.append(" failed ,caused by :");
errmsg.append(e.getMessage()); errmsg.append(e.getMessage());
server.setDsp(e.getMessage()); server.setDsp(e.getMessage());
logger.error( errmsg.toString()); logger.error(errmsg.toString());
} }
} }
if (flag) { if (flag) {
super.execute(context); super.execute(context);
context.setObject(value); context.setObject(value);
} else { } else {
throw new InterfaceException("T0001", "try call all servers " + servers throw new InterfaceException("T0001", "try call all servers " + servers
+ " failed"); + " failed");
} }
} }
@Override @Override
public Object getFieldValue(IFieldDef iFieldDef) throws Exception { public Object getFieldValue(IFieldDef iFieldDef) throws Exception {
return null; return null;
} }
private List<Server> servers(Object obj) { private List<Server> servers(Object obj) {
return servers(requireNonNull(obj).toString()); return servers(requireNonNull(obj).toString());
} }
private Object requireNonNull(Object obj) { private Object requireNonNull(Object obj) {
if(obj==null){ if (obj == null) {
throw new RuntimeException("obj is null"); throw new RuntimeException("obj is null");
} }
return obj; return obj;
} }
private List<Server> servers(String str) { private List<Server> servers(String str) {
requireNonNull(str); requireNonNull(str);
List<Server> list = new ArrayList<Server>(); List<Server> list = new ArrayList<Server>();
for (String s : str.split(",")) { for (String s : str.split(",")) {
String[] split = s.split(":"); String[] split = s.split(":");
list.add(new Server(split[0], Integer.parseInt(split[1]))); list.add(new Server(split[0], Integer.parseInt(split[1])));
} }
return list; return list;
} }
class Server { class Server {
private String host; private String host;
private int port; private int port;
private String dsp; private String dsp;
public Server(String host, int port) { public Server(String host, int port) {
this.host = host; this.host = host;
this.port = port; this.port = port;
} }
public String getHost() { public String getHost() {
return host; return host;
} }
public void setHost(String host) { public void setHost(String host) {
this.host = host; this.host = host;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
} }
public String getDsp() { public String getDsp() {
return dsp; return dsp;
} }
public void setDsp(String dsp) { public void setDsp(String dsp) {
this.dsp = dsp; this.dsp = dsp;
} }
@Override @Override
public String toString() { public String toString() {
return "[host=" + host + ", dsp=" + dsp + "]"; return "[host=" + host + ", dsp=" + dsp + "]";
} }
} }
public static void main(String[] args) { public static void main(String[] args) {
List<Server> lst = new ArrayList<Server>(); List<Server> lst = new ArrayList<Server>();
RibbonFilter rf = new RibbonFilter(); RibbonFilter rf = new RibbonFilter();
Server server1 = rf.new Server("127.0.0.1", 11); Server server1 = rf.new Server("127.0.0.1", 11);
server1.setDsp("xxxx"); server1.setDsp("xxxx");
Server server2 = rf.new Server("127.0.0.2", 22); Server server2 = rf.new Server("127.0.0.2", 22);
server2.setDsp("tyyy"); server2.setDsp("tyyy");
lst.add(server1); lst.add(server1);
lst.add(server2); lst.add(server2);
System.out.println(lst); System.out.println(lst);
} }
} }
...@@ -4,7 +4,6 @@ import com.brilliance.eibs.core.exception.InterfaceException; ...@@ -4,7 +4,6 @@ import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef; import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.model.ISubfieldDef; import com.brilliance.eibs.core.model.ISubfieldDef;
import com.brilliance.eibs.core.service.Context; import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.impl.AbsFilter;
import com.brilliance.eibs.core.service.instance.plugin.MsgFormTemplate; import com.brilliance.eibs.core.service.instance.plugin.MsgFormTemplate;
import com.brilliance.eibs.core.service.instance.plugin.MsgFormTemplate.IMsgAssembleFilter; import com.brilliance.eibs.core.service.instance.plugin.MsgFormTemplate.IMsgAssembleFilter;
import com.brilliance.eibs.core.service.instance.plugin.MsgFormTemplate.IMsgParseFilter; import com.brilliance.eibs.core.service.instance.plugin.MsgFormTemplate.IMsgParseFilter;
...@@ -29,13 +28,11 @@ import java.util.*; ...@@ -29,13 +28,11 @@ import java.util.*;
public class XmlFilter extends AbsFilter { public class XmlFilter extends AbsFilter {
private Document doc; private Document doc;
@Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "XMLFilter is begining to runnig." +
// LOG_FLAG);
context.setCurrentInstance(this); context.setCurrentInstance(this);
String type = getType(); String type = getType();
if (type.equals("in")) { if (type.equals("in")) {
// logger.info( LOG_FLAG + "XMLFilter解析" + LOG_FLAG);
try { try {
// 获取传入的xml字符串,构建Document文档对象 // 获取传入的xml字符串,构建Document文档对象
String xmlstr = context.getObject().toString(); String xmlstr = context.getObject().toString();
...@@ -44,7 +41,6 @@ public class XmlFilter extends AbsFilter { ...@@ -44,7 +41,6 @@ public class XmlFilter extends AbsFilter {
throw new InterfaceException("02801", e); throw new InterfaceException("02801", e);
} }
} else { } else {
// logger.info( LOG_FLAG + "XMLFilter组装" + LOG_FLAG);
String x = getPropertyValue("doc"); String x = getPropertyValue("doc");
if (!StringUtil.isEmpty(x) && Boolean.valueOf(x)) { if (!StringUtil.isEmpty(x) && Boolean.valueOf(x)) {
try { try {
...@@ -60,16 +56,8 @@ public class XmlFilter extends AbsFilter { ...@@ -60,16 +56,8 @@ public class XmlFilter extends AbsFilter {
if (type.equals("out")) { if (type.equals("out")) {
String formatstr = format(doc); String formatstr = format(doc);
context.getResource().setObject(formatstr); context.getResource().setObject(formatstr);
// context.getResource().setObject(doc.asXML());
// context.addVariable("global",
// IExecutableInstance.AES_ENCRYPT_PACKAGE_SYMBOL,
// formatstr);
// saveToContext(getFilterDef().getScope(), getFilterDef().getTag(),
// context.getObject());
logger.trace(formatstr); logger.trace(formatstr);
} }
// logger.info( LOG_FLAG + "XMLFilter has finished running." +
// LOG_FLAG);
} }
/** /**
...@@ -81,16 +69,14 @@ public class XmlFilter extends AbsFilter { ...@@ -81,16 +69,14 @@ public class XmlFilter extends AbsFilter {
doc = DocumentHelper.createDocument(); doc = DocumentHelper.createDocument();
String encoding = getFilterDef().getEncoding(); String encoding = getFilterDef().getEncoding();
doc.setXMLEncoding(encoding); doc.setXMLEncoding(encoding);
// doc.setRootElement(DocumentHelper.createElement(root));
Map<String, String> propMap = filterDef.getCommonsPropertyMap(); Map<String, String> propMap = filterDef.getCommonsPropertyMap();
if (propMap.containsKey("xmlns")) { if (propMap.containsKey("xmlns")) {
// modified by weicong on 2018/12/12 支持动态参数 // modified by weicong on 2018/12/12 支持动态参数
doc.addElement(root, doc.addElement(root,
(String) elParser.getExPression(context, propMap.get("xmlns"), null)); (String) elParser.getExPression(context, propMap.get("xmlns"), null));
// propMap.remove("xmlns"); } else {
} else
doc.addElement(root); doc.addElement(root);
}
Iterator<String> iterator = propMap.keySet().iterator(); Iterator<String> iterator = propMap.keySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
String key = iterator.next(); String key = iterator.next();
...@@ -105,18 +91,19 @@ public class XmlFilter extends AbsFilter { ...@@ -105,18 +91,19 @@ public class XmlFilter extends AbsFilter {
/** /**
* 按指定路径和值添加xml节点 * 按指定路径和值添加xml节点
* *
* @param path * @param node
* @param value * @param value
*/ */
private void addPath(Node node, Object value) { private void addPath(Node node, Object value) {
if (null == value) if (null == value) {
value = ""; value = "";
else if (!(value instanceof Node)) { } else if (!(value instanceof Node)) {
String encoding = filterDef.getEncoding(); String encoding = filterDef.getEncoding();
try { try {
if (null != encoding && ("ISO-8859-1".equalsIgnoreCase(encoding) if (null != encoding && ("ISO-8859-1".equalsIgnoreCase(encoding)
|| "ISO8859-1".equalsIgnoreCase(encoding))) || "ISO8859-1".equalsIgnoreCase(encoding))) {
encoding = "GBK"; encoding = "GBK";
}
value = new String(value.toString().getBytes(encoding), encoding); value = new String(value.toString().getBytes(encoding), encoding);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new InterfaceException("00403", "unsupported encoding : " + encoding, e); throw new InterfaceException("00403", "unsupported encoding : " + encoding, e);
...@@ -142,6 +129,7 @@ public class XmlFilter extends AbsFilter { ...@@ -142,6 +129,7 @@ public class XmlFilter extends AbsFilter {
* *
* @param fieldDef * @param fieldDef
*/ */
@Override
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
protected void packField(IFieldDef fieldDef, Object value) { protected void packField(IFieldDef fieldDef, Object value) {
// ------------modified by weicong on 2016/3/16 ----------- // ------------modified by weicong on 2016/3/16 -----------
...@@ -166,11 +154,10 @@ public class XmlFilter extends AbsFilter { ...@@ -166,11 +154,10 @@ public class XmlFilter extends AbsFilter {
value = cache; value = cache;
} }
sbf.setTag(sbf.getKey()); sbf.setTag(sbf.getKey());
value = ((AbsFilter) context.getCurrentInstance()).valFilter(value, sbf, value = ((AbsFilter) context.getCurrentInstance()).valFilter(value, sbf, context);
context); } else {
} else value = ((AbsFilter) context.getCurrentInstance()).valFilter(value, sbf, context);
value = ((AbsFilter) context.getCurrentInstance()).valFilter(value, sbf, }
context);
if (sbf.getSubfields().size() > 0) { if (sbf.getSubfields().size() > 0) {
String rawetag = sbf.getEtag(); String rawetag = sbf.getEtag();
String nwetag = fieldDef.getEtag() + "(" + i + ")." + rawetag; String nwetag = fieldDef.getEtag() + "(" + i + ")." + rawetag;
...@@ -181,8 +168,9 @@ public class XmlFilter extends AbsFilter { ...@@ -181,8 +168,9 @@ public class XmlFilter extends AbsFilter {
String etag = fieldDef.getEtag() + "(" + i + ")." + sbf.getEtag(); String etag = fieldDef.getEtag() + "(" + i + ")." + sbf.getEtag();
Node node = getNode(etag); Node node = getNode(etag);
if (node != null) if (node != null) {
addPath(node, value); addPath(node, value);
}
} }
} }
} }
...@@ -192,8 +180,9 @@ public class XmlFilter extends AbsFilter { ...@@ -192,8 +180,9 @@ public class XmlFilter extends AbsFilter {
@Override @Override
public void assembelMsg(IFieldDef fieldDef, Object fieldValue) { public void assembelMsg(IFieldDef fieldDef, Object fieldValue) {
Node node = getNode(path); Node node = getNode(path);
if (node != null) if (node != null) {
addPath(node, fieldValue); addPath(node, fieldValue);
}
} }
}); });
} }
...@@ -214,12 +203,14 @@ public class XmlFilter extends AbsFilter { ...@@ -214,12 +203,14 @@ public class XmlFilter extends AbsFilter {
} }
createDocument(path.substring(0, index)); createDocument(path.substring(0, index));
} }
if (cur == null) if (cur == null) {
rsnode = doc.getRootElement().addElement(lasted); rsnode = doc.getRootElement().addElement(lasted);
else } else {
rsnode = cur.addElement(lasted); rsnode = cur.addElement(lasted);
if (value != null) }
if (value != null) {
addPath(rsnode, value); addPath(rsnode, value);
}
return rsnode; return rsnode;
} }
...@@ -273,11 +264,11 @@ public class XmlFilter extends AbsFilter { ...@@ -273,11 +264,11 @@ public class XmlFilter extends AbsFilter {
return mft.getFieldValue(fieldDef, new IMsgParseFilter() { return mft.getFieldValue(fieldDef, new IMsgParseFilter() {
@Override @Override
public Object parseMsg(IFieldDef fieldDef) { public Object parseMsg(IFieldDef fieldDef) {
if (XmlUtil.isXpath(fieldDef.getType())) if (XmlUtil.isXpath(fieldDef.getType())) {
return XmlUtil.getXmlNodeValueByXpath(doc, etag); return XmlUtil.getXmlNodeValueByXpath(doc, etag);
else } else {
return XmlUtil.getXmlNodeValue(doc, etag); return XmlUtil.getXmlNodeValue(doc, etag);
}
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
...@@ -306,19 +297,17 @@ public class XmlFilter extends AbsFilter { ...@@ -306,19 +297,17 @@ public class XmlFilter extends AbsFilter {
Object val = XmlUtil.getXmlNodeValue(doc, etag); Object val = XmlUtil.getXmlNodeValue(doc, etag);
val = ((AbsFilter) context.getCurrentInstance()).valFilter(val, sbf, val = ((AbsFilter) context.getCurrentInstance()).valFilter(val, sbf,
context); context);
if (val instanceof Map) if (val instanceof Map) {
rsmap.putAll((Map<? extends String, ? extends Object>) val); rsmap.putAll((Map<? extends String, ? extends Object>) val);
else } else {
rsmap.put(sbf.getTag(), val); rsmap.put(sbf.getTag(), val);
}
} }
} }
rs.add(rsmap); rs.add(rsmap);
} }
} }
return rs; return rs;
// return XmlUtil.getElementsOfListformat(doc, etag, fieldDef,
// context);
} }
}); });
} }
...@@ -364,9 +353,6 @@ public class XmlFilter extends AbsFilter { ...@@ -364,9 +353,6 @@ public class XmlFilter extends AbsFilter {
} else { } else {
Element subElement = curElement.element(layers[i]); Element subElement = curElement.element(layers[i]);
if (subElement == null) { if (subElement == null) {
// throw new InterfaceException("02802",
// "can not find sub element [" + layers[i] +
// "] in path [" + path + "]");
return 0; return 0;
} }
curElement = subElement; curElement = subElement;
...@@ -429,11 +415,11 @@ public class XmlFilter extends AbsFilter { ...@@ -429,11 +415,11 @@ public class XmlFilter extends AbsFilter {
curElement = subElement; curElement = subElement;
} else { } else {
Element subElement = null; Element subElement = null;
if (layers[i].contains(":")) if (layers[i].contains(":")) {
subElement = subElement = curElement.element(layers[i].substring(layers[i].indexOf(':') + 1));
curElement.element(layers[i].substring(layers[i].indexOf(':') + 1)); } else {
else
subElement = curElement.element(layers[i]); subElement = curElement.element(layers[i]);
}
if (subElement == null) { if (subElement == null) {
subElement = curElement.addElement(layers[i]); subElement = curElement.addElement(layers[i]);
} }
...@@ -465,7 +451,6 @@ public class XmlFilter extends AbsFilter { ...@@ -465,7 +451,6 @@ public class XmlFilter extends AbsFilter {
* @return * @return
*/ */
public Node getNode(String path) { public Node getNode(String path) {
if (doc == null) { if (doc == null) {
int index = path.indexOf('.'); int index = path.indexOf('.');
if (index == -1) { if (index == -1) {
......
...@@ -33,13 +33,12 @@ public class HttpConnection extends AbsConnection { ...@@ -33,13 +33,12 @@ public class HttpConnection extends AbsConnection {
private Map<String, Object> headMap = new HashMap<String, Object>(); private Map<String, Object> headMap = new HashMap<String, Object>();
/** /**
* @author gechengyang Http连接 满足get和post两种请求方式 * @author gechengyang
* Http连接 满足get和post两种请求方式
**/ **/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "HttpConnection is Running." +
// LOG_FLAG);
context.setCurrentInstance(this); context.setCurrentInstance(this);
super.execute(context); super.execute(context);
...@@ -48,9 +47,10 @@ public class HttpConnection extends AbsConnection { ...@@ -48,9 +47,10 @@ public class HttpConnection extends AbsConnection {
IPropertyDef headProdef = getProperty(HEAD, true); IPropertyDef headProdef = getProperty(HEAD, true);
if (headProdef != null) { if (headProdef != null) {
String head = headProdef.getValue(); String head = headProdef.getValue();
if (!StringUtil.isEmpty(head)) if (!StringUtil.isEmpty(head)) {
headMap = (Map<String, Object>) elParser.getExPression(context, head, null); headMap = (Map<String, Object>) elParser.getExPression(context, head, null);
logger.info( "head" + headMap); }
logger.info("head" + headMap);
} }
IPropertyDef isFormProdef = getProperty(ISFORM, true); IPropertyDef isFormProdef = getProperty(ISFORM, true);
...@@ -68,10 +68,8 @@ public class HttpConnection extends AbsConnection { ...@@ -68,10 +68,8 @@ public class HttpConnection extends AbsConnection {
HttpConnectionManagerParams params = httpConnectionManager.getParams(); HttpConnectionManagerParams params = httpConnectionManager.getParams();
params.setConnectionTimeout(getPropertyValueInt(HTTP_CONNECTIONTIMEOUT)); params.setConnectionTimeout(getPropertyValueInt(HTTP_CONNECTIONTIMEOUT));
params.setSoTimeout(getPropertyValueInt(HTTP_SOTIMEOUT)); params.setSoTimeout(getPropertyValueInt(HTTP_SOTIMEOUT));
params.setDefaultMaxConnectionsPerHost(getPropertyValueInt(HTTP_DEFAULTCONNPERHOST));// very params.setDefaultMaxConnectionsPerHost(getPropertyValueInt(HTTP_DEFAULTCONNPERHOST));
// important!! params.setMaxTotalConnections(getPropertyValueInt(HTTP_MAXCONNS));
params.setMaxTotalConnections(getPropertyValueInt(HTTP_MAXCONNS));// very
// important!!
client = new HttpClient(httpConnectionManager); client = new HttpClient(httpConnectionManager);
// 设置编码 // 设置编码
String conncharset = connectionDef.getEncoding(); String conncharset = connectionDef.getEncoding();
...@@ -98,16 +96,11 @@ public class HttpConnection extends AbsConnection { ...@@ -98,16 +96,11 @@ public class HttpConnection extends AbsConnection {
DocumentFragment df = DocumentFragment df =
Html2Xml.getSourceNodeByStr(contextstr, true, responseCharset); Html2Xml.getSourceNodeByStr(contextstr, true, responseCharset);
contextstr = Html2Xml.genToXml(df, responseCharset); contextstr = Html2Xml.genToXml(df, responseCharset);
logger.info( "Html to XML =" + contextstr); logger.info("Html to XML =" + contextstr);
} }
context.setObject(contextstr); context.setObject(contextstr);
} }
((MultiThreadedHttpConnectionManager) client.getHttpConnectionManager()).shutdown(); ((MultiThreadedHttpConnectionManager) client.getHttpConnectionManager()).shutdown();
// logger.info( LOG_FLAG +
// "HttpConnection has finished running." + LOG_FLAG);
} }
public String doGet() { public String doGet() {
...@@ -115,10 +108,6 @@ public class HttpConnection extends AbsConnection { ...@@ -115,10 +108,6 @@ public class HttpConnection extends AbsConnection {
GetMethod getMethod = new GetMethod(url); GetMethod getMethod = new GetMethod(url);
InputStream in = null; InputStream in = null;
// 使用系统提供的默认的恢复策略 // 使用系统提供的默认的恢复策略
// getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
// new DefaultHttpMethodRetryHandler(3, false));
// getMethod.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
// charset);
return getContent(getMethod, in); return getContent(getMethod, in);
} }
...@@ -132,7 +121,6 @@ public class HttpConnection extends AbsConnection { ...@@ -132,7 +121,6 @@ public class HttpConnection extends AbsConnection {
PostMethod postMethod = new PostMethod(url); PostMethod postMethod = new PostMethod(url);
int size = prodef.getArguments().size(); int size = prodef.getArguments().size();
// 如果参数为Map类型 Modifed By gechengyang 20150701 // 如果参数为Map类型 Modifed By gechengyang 20150701
if (size == 1) { if (size == 1) {
Object obj = Object obj =
elParser.getExPression(context, prodef.getArguments().get(0).getValue(), null); elParser.getExPression(context, prodef.getArguments().get(0).getValue(), null);
...@@ -149,7 +137,6 @@ public class HttpConnection extends AbsConnection { ...@@ -149,7 +137,6 @@ public class HttpConnection extends AbsConnection {
prodef.setArguments(list); prodef.setArguments(list);
} }
} }
// /////////////////////////
if (size > 0) { if (size > 0) {
modeparamsid = new Object[size]; modeparamsid = new Object[size];
modeparamsvalue = new Object[size]; modeparamsvalue = new Object[size];
...@@ -183,7 +170,7 @@ public class HttpConnection extends AbsConnection { ...@@ -183,7 +170,7 @@ public class HttpConnection extends AbsConnection {
String location = null; String location = null;
if (locationHeader != null) { if (locationHeader != null) {
location = locationHeader.getValue(); location = locationHeader.getValue();
logger.info( "The page was redirected to:" + location); logger.info("The page was redirected to:" + location);
doGet(location); doGet(location);
} }
} }
...@@ -193,14 +180,11 @@ public class HttpConnection extends AbsConnection { ...@@ -193,14 +180,11 @@ public class HttpConnection extends AbsConnection {
throw new InterfaceException("01402", "Http I/O error.", e); throw new InterfaceException("01402", "Http I/O error.", e);
} }
try { try {
// postMethod.releaseConnection();
String ret = postMethod.getResponseBodyAsString(); String ret = postMethod.getResponseBodyAsString();
postMethod.releaseConnection(); postMethod.releaseConnection();
return ret; return ret;
} catch (IOException e) { } catch (IOException e) {
throw new InterfaceException("01402", "Rcv ret error.", e); throw new InterfaceException("01402", "Rcv ret error.", e);
} }
} }
...@@ -211,17 +195,11 @@ public class HttpConnection extends AbsConnection { ...@@ -211,17 +195,11 @@ public class HttpConnection extends AbsConnection {
int statusCode = client.executeMethod(getMethod); int statusCode = client.executeMethod(getMethod);
if (statusCode == HttpStatus.SC_OK) { if (statusCode == HttpStatus.SC_OK) {
// 读取内容 // 读取内容
in = getMethod.getResponseBodyAsStream(); in = getMethod.getResponseBodyAsStream();
String responsecharset = getMethod.getRequestCharSet(); String responsecharset = getMethod.getRequestCharSet();
this.responseCharset = responsecharset; this.responseCharset = responsecharset;
logger.info( "http response charset=" + responsecharset); logger.info("http response charset=" + responsecharset);
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
// int a = 0;
// byte buffer[] = new byte[1024];
// while ((a = in.read(buffer)) != -1) {
// sb.append(new String(buffer, 0, a, responsecharset));
// }
InputStreamReader isr = new InputStreamReader(in, responsecharset); InputStreamReader isr = new InputStreamReader(in, responsecharset);
char[] buffer = new char[12]; char[] buffer = new char[12];
int len = 0; int len = 0;
...@@ -230,7 +208,7 @@ public class HttpConnection extends AbsConnection { ...@@ -230,7 +208,7 @@ public class HttpConnection extends AbsConnection {
} }
// 处理内容 // 处理内容
str = sb.toString(); str = sb.toString();
logger.info( "http filter str= " + str); logger.info("http filter str= " + str);
} }
} catch (HttpException e) { } catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题 // 发生致命的异常,可能是协议不对或者返回的内容有问题
...@@ -254,13 +232,6 @@ public class HttpConnection extends AbsConnection { ...@@ -254,13 +232,6 @@ public class HttpConnection extends AbsConnection {
URL realUrl = new URL(url); URL realUrl = new URL(url);
// 打开和URL之间的连接 // 打开和URL之间的连接
URLConnection conn = realUrl.openConnection(); URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
/*
* conn.setRequestProperty("accept", "application/json");
* conn.setRequestProperty("connection", "Keep-Alive");
* conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
* conn.setRequestProperty("Authorization", vo.getAuth());
*/
for (String key : map.keySet()) { for (String key : map.keySet()) {
conn.setRequestProperty(key, map.get(key).toString()); conn.setRequestProperty(key, map.get(key).toString());
} }
...@@ -281,7 +252,7 @@ public class HttpConnection extends AbsConnection { ...@@ -281,7 +252,7 @@ public class HttpConnection extends AbsConnection {
result += line; result += line;
} }
} catch (Exception e) { } catch (Exception e) {
throw new InterfaceException("01402", "发送 POST 请求出现异常!", e); throw new InterfaceException("01402", "发送 POST 请求出现异常!", e);
} }
// 使用finally块来关闭输出流、输入流 // 使用finally块来关闭输出流、输入流
finally { finally {
...@@ -293,7 +264,7 @@ public class HttpConnection extends AbsConnection { ...@@ -293,7 +264,7 @@ public class HttpConnection extends AbsConnection {
in.close(); in.close();
} }
} catch (IOException ex) { } catch (IOException ex) {
throw new InterfaceException("01402", "关闭连接异常!", ex); throw new InterfaceException("01402", "关闭连接异常!", ex);
} }
} }
return result; return result;
......
...@@ -56,8 +56,10 @@ public class HttpsConnection extends AbsConnection { ...@@ -56,8 +56,10 @@ public class HttpsConnection extends AbsConnection {
public static final String STORE_PATH = "storepath"; public static final String STORE_PATH = "storepath";
public static final String STORE_PWD = "storepwd"; public static final String STORE_PWD = "storepwd";
public static final String STORE_PRO = "storepro"; public static final String STORE_PRO = "storepro";
public static final String DEF_PRO = "TLSv1.2";//"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" /**
* "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"
*/
public static final String DEF_PRO = "TLSv1.2";
public static final String MAPPING = "mapping"; public static final String MAPPING = "mapping";
public static final String BODY = "body"; public static final String BODY = "body";
public static final String HEAD = "head"; public static final String HEAD = "head";
...@@ -67,10 +69,10 @@ public class HttpsConnection extends AbsConnection { ...@@ -67,10 +69,10 @@ public class HttpsConnection extends AbsConnection {
private Charset charset = Charset.forName("UTF-8"); private Charset charset = Charset.forName("UTF-8");
private CloseableHttpClient httpClient; private CloseableHttpClient httpClient;
@Override @Override
public void execute(Context context) { public void execute(Context context) {
params = (Map<String, Object>) context.getObject();//必须得从上下文中拿到参数列表 // 必须得从上下文中拿到参数列表
params = (Map<String, Object>) context.getObject();
context.setCurrentInstance(this); context.setCurrentInstance(this);
super.execute(context); super.execute(context);
String type = getPropertyValue(TYPE, false); String type = getPropertyValue(TYPE, false);
...@@ -81,13 +83,13 @@ public class HttpsConnection extends AbsConnection { ...@@ -81,13 +83,13 @@ public class HttpsConnection extends AbsConnection {
String proxyHost = getPropertyValue(PROXYHOST, true); String proxyHost = getPropertyValue(PROXYHOST, true);
String proxyPort = getPropertyValue(PROXYPORT, true); String proxyPort = getPropertyValue(PROXYPORT, true);
String mapping = getPropertyValue(MAPPING, false); String mapping = getPropertyValue(MAPPING, false);
String charsetLocal = getPropertyValue(CHARSET, true);//true,存在为null,则返回 String charsetLocal = getPropertyValue(CHARSET, true);
String httpRetry = getPropertyValue(HTTPRETRY, false); String httpRetry = getPropertyValue(HTTPRETRY, false);
String connectTimeout = getPropertyValue(CONNECT_TIMEOUT, false); String connectTimeout = getPropertyValue(CONNECT_TIMEOUT, false);
String readTimeout = getPropertyValue(READ_TIMEOUT, false); String readTimeout = getPropertyValue(READ_TIMEOUT, false);
String storePath = getPropertyValue(STORE_PATH, false); String storePath = getPropertyValue(STORE_PATH, false);
String storePwd = getPropertyValue(STORE_PWD, false); String storePwd = getPropertyValue(STORE_PWD, false);
String storePro = StringUtil.isEmpty(getPropertyValue(STORE_PRO, true))? DEF_PRO : String storePro = StringUtil.isEmpty(getPropertyValue(STORE_PRO, true)) ? DEF_PRO :
getPropertyValue(STORE_PRO, true); getPropertyValue(STORE_PRO, true);
HttpClientBuilder clientBuilder = HttpClientBuilder.create(); HttpClientBuilder clientBuilder = HttpClientBuilder.create();
RequestConfig.Builder requestConfig = RequestConfig.custom(); RequestConfig.Builder requestConfig = RequestConfig.custom();
...@@ -107,7 +109,7 @@ public class HttpsConnection extends AbsConnection { ...@@ -107,7 +109,7 @@ public class HttpsConnection extends AbsConnection {
try { try {
security = getSecurity(storePath, storePwd, storePro); security = getSecurity(storePath, storePwd, storePro);
} catch (Exception e) { } catch (Exception e) {
logger.error( "create SSLConnectionSocketFactory failed:", e); logger.error("create SSLConnectionSocketFactory failed:", e);
throw new InterfaceException("11001", "create SSLConnectionSocketFactory failed.", e); throw new InterfaceException("11001", "create SSLConnectionSocketFactory failed.", e);
} }
httpClient = clientBuilder httpClient = clientBuilder
...@@ -151,21 +153,21 @@ public class HttpsConnection extends AbsConnection { ...@@ -151,21 +153,21 @@ public class HttpsConnection extends AbsConnection {
throw new InterfaceException("11001", "HttpConnection status code is not 200 ,but is " + statuscode); throw new InterfaceException("11001", "HttpConnection status code is not 200 ,but is " + statuscode);
} }
} catch (IOException e) { } catch (IOException e) {
logger.error( "url " + url, e); logger.error("url " + url, e);
throw new InterfaceException("11001", "HttpConnection exception occurs.", e); throw new InterfaceException("11001", "HttpConnection exception occurs.", e);
} finally { } finally {
if (response != null) { if (response != null) {
try { try {
response.close(); response.close();
} catch (IOException e) { } catch (IOException e) {
logger.error( "close CloseableHttpResponse failed" + url, e); logger.error("close CloseableHttpResponse failed" + url, e);
} }
} }
if (httpClient != null) { if (httpClient != null) {
try { try {
httpClient.close(); httpClient.close();
} catch (IOException e) { } catch (IOException e) {
logger.error( "close httpClient failed" + url, e); logger.error("close httpClient failed" + url, e);
} }
} }
} }
......
...@@ -22,76 +22,60 @@ import org.apache.http.protocol.BasicHttpContext; ...@@ -22,76 +22,60 @@ import org.apache.http.protocol.BasicHttpContext;
import java.net.URI; import java.net.URI;
public class RestHttpConnection public class RestHttpConnection extends AbsConnection {
extends AbsConnection /**
{ * @author gechengyang
/** * RestHttp连接 满足get和post put三种请求方式
* @author gechengyang **/
*RestHttp连接 满足get和post put三种请求方式 @Override
* **/ public void execute(Context context) {
@Override logger.info(LOG_FLAG + "RestHttpConnection is Running." + LOG_FLAG);
public void execute(Context context) context.setCurrentInstance(this);
{ String username = getPropertyValue("username");
logger.info(LOG_FLAG + "RestHttpConnection is Running." + LOG_FLAG); String password = getPropertyValue("lpassword");
context.setCurrentInstance(this); String url = getPropertyValue("url");
// super.execute(context); String mode = getPropertyValue("mode");
String username=getPropertyValue("username"); DefaultHttpClient client = new DefaultHttpClient();
String password=getPropertyValue("lpassword"); StringEntity entity = null;
String url=getPropertyValue("url"); try {
String mode=getPropertyValue("mode"); URI uri = new URI(url);
client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
//获取表单数据 TODO new UsernamePasswordCredentials(username, password));
// IPropertyDef prodef = getProperty("mode"); HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), "http");
DefaultHttpClient client = new DefaultHttpClient(); AuthCache authCache = new BasicAuthCache();
StringEntity entity=null; BasicScheme basicAuth = new BasicScheme();
try authCache.put(host, basicAuth);
{ BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
URI uri = new URI(url); HttpResponse response = null;
client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()), if ("post".equals(mode)) {
new UsernamePasswordCredentials(username, password)); HttpPost post = new HttpPost(url);
HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), "http"); //发送的消息体
AuthCache authCache = new BasicAuthCache(); String sendData = (String) context.getObject();
BasicScheme basicAuth = new BasicScheme(); entity = new StringEntity(sendData);
authCache.put(host, basicAuth); post.setEntity(entity);
BasicHttpContext localcontext = new BasicHttpContext(); response = client.execute(host, post, localcontext);
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); } else if ("put".equals(mode)) {
HttpResponse response=null; HttpPut put = new HttpPut(url);
if("post".equals(mode)) //发送的消息体
{ String sendData = (String) context.getObject();
HttpPost post = new HttpPost(url); entity = new StringEntity(sendData);
//发送的消息体 put.setEntity(entity);
String sendData=(String) context.getObject(); response = client.execute(host, put, localcontext);
entity = new StringEntity(sendData); } else if ("get".equals(mode)) {
post.setEntity(entity); HttpGet get = new HttpGet(url);
response = client.execute(host, post, localcontext); response = client.execute(host, get, localcontext);
} }
else if("put".equals(mode)) String returnData = IOUtils.toString(response.getEntity().getContent());
{ context.setObject(returnData);
HttpPut put=new HttpPut(url); } catch (Exception e) {
//发送的消息体 throw new InterfaceException("01401", "HTTP error.", e);
String sendData=(String) context.getObject(); }
entity = new StringEntity(sendData); logger.info(LOG_FLAG + "RestHttpConnection has finished running." + LOG_FLAG);
put.setEntity(entity);
response = client.execute(host, put, localcontext);
}
else if("get".equals(mode))
{
HttpGet get=new HttpGet(url);
response = client.execute(host, get, localcontext);
}
String returnData= IOUtils.toString(response.getEntity().getContent());
context.setObject(returnData);
} }
catch (Exception e)
{
throw new InterfaceException("01401", "HTTP error.", e); }
}
logger.info(LOG_FLAG + "RestHttpConnection has finished running." + LOG_FLAG);
}
}
...@@ -47,7 +47,7 @@ public class HttpsService extends AbsServer { ...@@ -47,7 +47,7 @@ public class HttpsService extends AbsServer {
@Override @Override
public void run() { public void run() {
logger.info( LOG_FLAG + "starting HttpService[id:" + serviceDef.getId() + "]." + LOG_FLAG); logger.info(LOG_FLAG + "starting HttpService[id:" + serviceDef.getId() + "]." + LOG_FLAG);
try { try {
String ksttyp = getPropertyValue(Key_Store_Type, Def_Key_Store_Type); String ksttyp = getPropertyValue(Key_Store_Type, Def_Key_Store_Type);
String kmftyp = getPropertyValue(Key_Manager_Factory, Def_Key_Manager_Factory); String kmftyp = getPropertyValue(Key_Manager_Factory, Def_Key_Manager_Factory);
...@@ -77,13 +77,13 @@ public class HttpsService extends AbsServer { ...@@ -77,13 +77,13 @@ public class HttpsService extends AbsServer {
@Override @Override
public void handle(HttpExchange httpExchange) { public void handle(HttpExchange httpExchange) {
String dsturi = httpExchange.getRequestURI().getPath(); String dsturi = httpExchange.getRequestURI().getPath();
Headers header=httpExchange.getRequestHeaders(); Headers header = httpExchange.getRequestHeaders();
try { try {
String requestBody = IOUtils.toString(httpExchange.getRequestBody(), encode); String requestBody = IOUtils.toString(httpExchange.getRequestBody(), encode);
for (Map.Entry<String, String[]> entry : handleMap.entrySet()) { for (Map.Entry<String, String[]> entry : handleMap.entrySet()) {
String orguri = entry.getKey(); String orguri = entry.getKey();
if (dsturi.equals(orguri)) { if (dsturi.equals(orguri)) {
Object rtnVal = new Client().call(entry.getValue()[0], entry.getValue()[1], new Object[]{requestBody,header}).getContent(); Object rtnVal = new Client().call(entry.getValue()[0], entry.getValue()[1], new Object[]{requestBody, header}).getContent();
if (rtnVal instanceof String) { if (rtnVal instanceof String) {
response(httpExchange, (String) rtnVal, encode); response(httpExchange, (String) rtnVal, encode);
} else { } else {
...@@ -92,18 +92,18 @@ public class HttpsService extends AbsServer { ...@@ -92,18 +92,18 @@ public class HttpsService extends AbsServer {
return; return;
} }
} }
logger.warn( "当前请求没有匹配的交易处理:" + dsturi); logger.warn("当前请求没有匹配的交易处理:" + dsturi);
} catch (Exception e) { } catch (Exception e) {
logger.error( "当前请求处理异常:" + dsturi, e); logger.error("当前请求处理异常:" + dsturi, e);
} }
} }
}); });
server.start(); server.start();
} catch (Exception e) { } catch (Exception e) {
logger.error( "https server start failed:" + e.getMessage(), e); logger.error("https server start failed:" + e.getMessage(), e);
throw new InterfaceException("01410", "https server start failed", e); throw new InterfaceException("01410", "https server start failed", e);
} }
logger.info( LOG_FLAG + "HttpsService[id:" + serviceDef.getId() + "] is started." + LOG_FLAG); logger.info(LOG_FLAG + "HttpsService[id:" + serviceDef.getId() + "] is started." + LOG_FLAG);
} }
private Map<String, String[]> checkConfigValidity(String uri, String interfaceName, String transactionName) { private Map<String, String[]> checkConfigValidity(String uri, String interfaceName, String transactionName) {
...@@ -130,15 +130,15 @@ public class HttpsService extends AbsServer { ...@@ -130,15 +130,15 @@ public class HttpsService extends AbsServer {
private SSLContext getSslContext(String storePath, String storePwd, String ksttyp, String kmftyp) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException { private SSLContext getSslContext(String storePath, String storePwd, String ksttyp, String kmftyp) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {
KeyStore ks = KeyStore.getInstance(ksttyp); KeyStore ks = KeyStore.getInstance(ksttyp);
//载入证书 // 载入证书
ks.load(new FileInputStream(storePath), storePwd.toCharArray()); ks.load(new FileInputStream(storePath), storePwd.toCharArray());
//建立一个密钥管理工厂 // 建立一个密钥管理工厂
KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmftyp); KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmftyp);
//初始化工厂 // 初始化工厂
kmf.init(ks, storePwd.toCharArray()); kmf.init(ks, storePwd.toCharArray());
//建立证书实体 // 建立证书实体
SSLContext sslContext = SSLContext.getInstance(Def_SSL_Context); SSLContext sslContext = SSLContext.getInstance(Def_SSL_Context);
//初始化证书 // 初始化证书
sslContext.init(kmf.getKeyManagers(), null, null); sslContext.init(kmf.getKeyManagers(), null, null);
return sslContext; return sslContext;
} }
...@@ -155,14 +155,14 @@ public class HttpsService extends AbsServer { ...@@ -155,14 +155,14 @@ public class HttpsService extends AbsServer {
os.write(rtnmsg.getBytes(encode)); os.write(rtnmsg.getBytes(encode));
os.flush(); os.flush();
} catch (Exception e) { } catch (Exception e) {
logger.error( "response occure exception:" + e.getMessage(), e); logger.error("response occure exception:" + e.getMessage(), e);
throw new InterfaceException("01410", "response occure exception", e); throw new InterfaceException("01410", "response occure exception", e);
} finally { } finally {
if (os != null) { if (os != null) {
try { try {
os.close(); os.close();
} catch (IOException e) { } catch (IOException e) {
logger.error( "OutputStream close occure exception:" + e.getMessage(), e); logger.error("OutputStream close occure exception:" + e.getMessage(), e);
throw new InterfaceException("01410", "OutputStream close occure exception", e); throw new InterfaceException("01410", "OutputStream close occure exception", e);
} }
} }
......
...@@ -6,7 +6,7 @@ import com.brilliance.eibs.util.StringUtil; ...@@ -6,7 +6,7 @@ import com.brilliance.eibs.util.StringUtil;
/** /**
* FTP连接 * FTP连接
* *
* @author gechengyang * @author gechengyang
**/ **/
public class FtpConnection2 extends AbsConnection { public class FtpConnection2 extends AbsConnection {
...@@ -14,8 +14,9 @@ public class FtpConnection2 extends AbsConnection { ...@@ -14,8 +14,9 @@ public class FtpConnection2 extends AbsConnection {
String encoding; String encoding;
FtpClient client; FtpClient client;
@Override
public void execute(Context context) { public void execute(Context context) {
logger.info( LOG_FLAG + "FtpConnection is Running." + LOG_FLAG); logger.info(LOG_FLAG + "FtpConnection is Running." + LOG_FLAG);
encoding = connectionDef.getEncoding(); encoding = connectionDef.getEncoding();
context.setCurrentInstance(this); context.setCurrentInstance(this);
// 获取超时时间 // 获取超时时间
...@@ -33,26 +34,25 @@ public class FtpConnection2 extends AbsConnection { ...@@ -33,26 +34,25 @@ public class FtpConnection2 extends AbsConnection {
boolean deleteFlag = Boolean.valueOf(getPropertyValue("delete", true)); boolean deleteFlag = Boolean.valueOf(getPropertyValue("delete", true));
String filenameRegex = getPropertyValue("filenameregex", true); String filenameRegex = getPropertyValue("filenameregex", true);
String passiveModeStr = getPropertyValue("passivemode", true); String passiveModeStr = getPropertyValue("passivemode", true);
boolean passiveMode = StringUtil.isEmpty(passiveModeStr)?false:Boolean.valueOf(passiveModeStr); boolean passiveMode = StringUtil.isEmpty(passiveModeStr) ? false : Boolean.valueOf(passiveModeStr);
client = new FtpClient(url, port, connectTimeout); client = new FtpClient(url, port, connectTimeout);
client.login(username, password,passiveMode); client.login(username, password, passiveMode);
try { try {
if (isDownload(type)) { if (isDownload(type)) {
logger.debug("FTP begin to Download.");
logger.debug( "FTP begin to Download.");
client.download(ctlPath, ctlFilenameregex, remotepath, localpath, filenameRegex, client.download(ctlPath, ctlFilenameregex, remotepath, localpath, filenameRegex,
arc, deleteFlag); arc, deleteFlag);
context.setObject(client.getFilenames()); context.setObject(client.getFilenames());
} }
if (isUpload(type)) { if (isUpload(type)) {
logger.debug( "FTP begin to Upload."); logger.debug("FTP begin to Upload.");
client.upload(localpath, remotepath, filenameRegex, arc); client.upload(localpath, remotepath, filenameRegex, arc);
} }
} finally { } finally {
client.disConnect(); client.disConnect();
} }
logger.info( "FtpConnection is finished."); logger.info("FtpConnection is finished.");
} }
private boolean isDownload(String type) { private boolean isDownload(String type) {
......
...@@ -20,9 +20,8 @@ public class FtpConnection_beta extends AbsConnection { ...@@ -20,9 +20,8 @@ public class FtpConnection_beta extends AbsConnection {
String encoding = ""; String encoding = "";
FTPClient ftp = null; FTPClient ftp = null;
@Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "FtpConnection is Running." +
// LOG_FLAG);
encoding = connectionDef.getEncoding(); encoding = connectionDef.getEncoding();
context.setCurrentInstance(this); context.setCurrentInstance(this);
String username = getPropertyValue("username"); String username = getPropertyValue("username");
...@@ -85,7 +84,6 @@ public class FtpConnection_beta extends AbsConnection { ...@@ -85,7 +84,6 @@ public class FtpConnection_beta extends AbsConnection {
close(ftpExcutor); close(ftpExcutor);
return; return;
} }
ftp.setDataTimeout(receiveTimeout); ftp.setDataTimeout(receiveTimeout);
try { try {
ftp.setSoTimeout(soTimeout); ftp.setSoTimeout(soTimeout);
...@@ -95,21 +93,7 @@ public class FtpConnection_beta extends AbsConnection { ...@@ -95,21 +93,7 @@ public class FtpConnection_beta extends AbsConnection {
if (isDownload(type)) { if (isDownload(type)) {
logger.debug("FTP begin to Download."); logger.debug("FTP begin to Download.");
try { try {
// 解决下载文件夹时只有一个文件下载,备份出错问题 不用特殊判断,直接调用downloadDirFiles即可
// TODO modified by yangrui 20150917
// FTPFile[] ftpFiles = ftp.listFiles(new
// String(remotepath.getBytes(encoding), encoding));
// if (ftpFiles.length == 1 && ftpFiles[0].isFile())
// {
// String remote = remotepath.substring(0,
// remotepath.lastIndexOf("/") + 1);
// ftpExcutor.downSingleFile(ftpFiles[0].getName(), remote,
// localpath, arc, fileDirectorName);
// return;
// }
ftpExcutor.downloadDirFiles(fileName, remotepath, localpath, arc, fileDirectorName); ftpExcutor.downloadDirFiles(fileName, remotepath, localpath, arc, fileDirectorName);
} catch (IOException e) { } catch (IOException e) {
close(ftpExcutor); close(ftpExcutor);
throw new InterfaceException("01204", "ftp download error:", e); throw new InterfaceException("01204", "ftp download error:", e);
......
...@@ -9,6 +9,7 @@ import javax.jms.*; ...@@ -9,6 +9,7 @@ import javax.jms.*;
public class JmsFilter extends AbsFilter { public class JmsFilter extends AbsFilter {
private MessageProducer producer; private MessageProducer producer;
@Override
public void execute(final Context context) { public void execute(final Context context) {
logger.info("Running JmsFilter."); logger.info("Running JmsFilter.");
context.setCurrentInstance(this); context.setCurrentInstance(this);
...@@ -16,6 +17,7 @@ public class JmsFilter extends AbsFilter { ...@@ -16,6 +17,7 @@ public class JmsFilter extends AbsFilter {
MessageConsumer comsumer = (MessageConsumer) context.getObject(); MessageConsumer comsumer = (MessageConsumer) context.getObject();
try { try {
comsumer.setMessageListener(new MessageListener() { comsumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message m) { public void onMessage(Message m) {
try { try {
if (m instanceof TextMessage) { // 接收文本消息 if (m instanceof TextMessage) { // 接收文本消息
...@@ -41,21 +43,18 @@ public class JmsFilter extends AbsFilter { ...@@ -41,21 +43,18 @@ public class JmsFilter extends AbsFilter {
} }
handmessage(); handmessage();
} catch (JMSException e) { } catch (JMSException e) {
// TODO Auto-generated catch block logger.error(e.getMessage(), e);
e.printStackTrace();
} }
} }
}); });
} catch (JMSException e) { } catch (JMSException e) {
// TODO Auto-generated catch block logger.error(e.getMessage(), e);
e.printStackTrace();
} }
} }
@Override @Override
public Object getFieldValue(IFieldDef fieldDef) { public Object getFieldValue(IFieldDef fieldDef) {
// TODO Auto-generated method stub
return null; return null;
} }
......
...@@ -10,70 +10,46 @@ import java.util.Hashtable; ...@@ -10,70 +10,46 @@ import java.util.Hashtable;
/** /**
* mq连接器 * mq连接器
*
* @author hujun
* *
* @author hujun
*/ */
public class MQConnection extends AbsConnection { public class MQConnection extends AbsConnection {
@Override @Override
public void execute(Context context) { public void execute(Context context) {
logger.info( LOG_FLAG + "MQConnection is Running." + LOG_FLAG); logger.info(LOG_FLAG + "MQConnection is Running." + LOG_FLAG);
context.setCurrentInstance(this); context.setCurrentInstance(this);
try { try {
// MQEnvironment.port = getPropertyValueInt(PORT_SYMBOL); int port = getPropertyValueInt(PORT_SYMBOL);
// logger.debug("mq port=" + MQEnvironment.port); logger.debug("mq port=" + port);
// MQEnvironment.hostname = getPropertyValue(IP_SYMBOL); String hostname = getPropertyValue(IP_SYMBOL);
// logger.debug("mq ip=" + MQEnvironment.hostname); logger.debug("mq ip=" + hostname);
// MQEnvironment.channel = getPropertyValue(MQ_CHANNEL_SYMBOL); String channel = getPropertyValue(MQ_CHANNEL_SYMBOL);
// MQEnvironment.CCSID = getPropertyValueInt(MQ_CCSID_SYMBOL); int CCSID = getPropertyValueInt(MQ_CCSID_SYMBOL);
// String userId= getPropertyValue("userID",true); String userId = getPropertyValue("userID", true);
int port = getPropertyValueInt(PORT_SYMBOL); String password = getPropertyValue("password", true);
logger.debug( "mq port=" + port); logger.debug("mq cssid=" + CCSID);
String hostname = getPropertyValue(IP_SYMBOL); String managerName = getPropertyValue(MQ_QUEUE_MANAGER_SYMBOL);
logger.debug( "mq ip=" + hostname); addProp2Context("transaction", MQ_QUEUE_SYMBOL);
String channel = getPropertyValue(MQ_CHANNEL_SYMBOL); Object obj[] = new Object[3];
int CCSID = getPropertyValueInt(MQ_CCSID_SYMBOL); Hashtable<String, Object> options = new Hashtable<String, Object>();
String userId = getPropertyValue("userID", true); options.put("hostname", hostname);
String password = getPropertyValue("password", true); options.put("port", port);
// if(StringUtil.isEmpty(userId)) options.put("channel", channel);
// { options.put("CCSID", CCSID);
// MQEnvironment.userID =userId; if (!StringUtil.isEmpty(userId)) {
// } options.put("userID", userId);
logger.debug( "mq cssid=" + CCSID); }
String managerName = getPropertyValue(MQ_QUEUE_MANAGER_SYMBOL); if (!StringUtil.isEmpty(password)) {
// addProp2Context(MQ_QUEUE_SYMBOL); options.put("password", password);
addProp2Context("transaction", MQ_QUEUE_SYMBOL); }
Object obj[] = new Object[3]; MQQueueManager manager = new MQQueueManager(managerName, options);
Hashtable<String, Object> options = new Hashtable<String, Object>(); obj[0] = manager;
options.put("hostname", hostname); obj[1] = getPropertyValue(MQ_QUEUE_SYMBOL, true);
options.put("port", port); obj[2] = getPropertyValue(MQ_RECEIVERTIMEOUT, true);
options.put("channel", channel); context.setObject(obj);
options.put("CCSID", CCSID); } catch (MQException e) {
if (!StringUtil.isEmpty(userId)) { throw new InterfaceException("01701", e);
options.put("userID", userId); }
} logger.info(LOG_FLAG + "MQConnection is finished." + LOG_FLAG);
if (!StringUtil.isEmpty(password)) { }
options.put("password", password);
}
MQQueueManager manager=new MQQueueManager(managerName, options);
obj[0] = manager;
obj[1] = getPropertyValue(MQ_QUEUE_SYMBOL, true);
obj[2] = getPropertyValue(MQ_RECEIVERTIMEOUT, true);
// context.setObject(manager);
context.setObject(obj);
// int openOptions;
// boolean istrue=true;
// if (istrue)
// openOptions = MQConstants.MQOO_OUTPUT |
// MQConstants.MQOO_FAIL_IF_QUIESCING;
// else
// // openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF |
// MQConstants.MQOO_OUTPUT | MQConstants.MQOO_INQUIRE;
// openOptions = CMQC.MQOO_INPUT_AS_Q_DEF | CMQC.MQOO_INQUIRE;
// manager.accessQueue(queueName, openOptions);
} catch (MQException e) {
throw new InterfaceException("01701", e);
}
logger.info( LOG_FLAG + "MQConnection is finished." + LOG_FLAG);
}
} }
...@@ -10,75 +10,81 @@ import java.util.Properties; ...@@ -10,75 +10,81 @@ import java.util.Properties;
public class RocketMQOpsProducerConnection extends AbsConnection { public class RocketMQOpsProducerConnection extends AbsConnection {
@Override @Override
public void execute(Context context) { public void execute(Context context) {
logger.info( LOG_FLAG logger.info(LOG_FLAG
+ "RocketMQOpsProducerConnection is Running." + LOG_FLAG); + "RocketMQOpsProducerConnection is Running." + LOG_FLAG);
context.setCurrentInstance(this); context.setCurrentInstance(this);
Object obj = context.getObject(); Object obj = context.getObject();
if (null != obj) { if (null != obj) {
Properties producerProperties = new Properties(); Properties producerProperties = new Properties();
Producer producer = null; Producer producer = null;
String Producer_ID = ""; // 生产者ID // 生产者ID
String ACCESS_KEY = ""; // 阿里云身份验证AccessKey String Producer_ID = "";
String SECRET_KEY = ""; // 阿里云身份验证SecretKey // 阿里云身份验证AccessKey
String ONS_ADDR = ""; // 消息队列服务器地址 String ACCESS_KEY = "";
String NAMESRV_ADDR = ""; // 消息队列服务器地址 // 阿里云身份验证SecretKey
String TOPIC; // 消息主题 String SECRET_KEY = "";
String TAG; // 消息标签 // 消息队列服务器地址
String charset;// 字符集 String ONS_ADDR = "";
charset = getPropertyValue("charset", "utf-8"); // 消息队列服务器地址
Producer_ID = getPropertyValue("GroupId"); String NAMESRV_ADDR = "";
TOPIC = getPropertyValue("topic"); String TOPIC; // 消息主题
TAG = getPropertyValue("tag"); String TAG; // 消息标签
if (StringUtil.isEmpty(Producer_ID) || StringUtil.isEmpty(TOPIC) String charset;// 字符集
|| StringUtil.isEmpty(TAG)) { charset = getPropertyValue("charset", "utf-8");
throw new IllegalArgumentException( Producer_ID = getPropertyValue("GroupId");
"[GroupId],[topic],[tag]三个属性必须配置"); TOPIC = getPropertyValue("topic");
} TAG = getPropertyValue("tag");
ACCESS_KEY = getPropertyValue("AccessKey"); if (StringUtil.isEmpty(Producer_ID) || StringUtil.isEmpty(TOPIC)
SECRET_KEY = getPropertyValue("SecretKey"); || StringUtil.isEmpty(TAG)) {
ONS_ADDR = getPropertyValue("ONSAddr",""); throw new IllegalArgumentException(
NAMESRV_ADDR = getPropertyValue("NamesrvAddr",""); "[GroupId],[topic],[tag]三个属性必须配置");
producerProperties.setProperty(PropertyKeyConst.GROUP_ID, }
Producer_ID); ACCESS_KEY = getPropertyValue("AccessKey");
producerProperties.setProperty(PropertyKeyConst.AccessKey, SECRET_KEY = getPropertyValue("SecretKey");
ACCESS_KEY); ONS_ADDR = getPropertyValue("ONSAddr", "");
producerProperties.setProperty(PropertyKeyConst.SecretKey, NAMESRV_ADDR = getPropertyValue("NamesrvAddr", "");
SECRET_KEY); producerProperties.setProperty(PropertyKeyConst.GROUP_ID,
if (!StringUtil.isEmpty(ONS_ADDR)) { Producer_ID);
producerProperties.put(PropertyKeyConst.ONSAddr, ONS_ADDR); producerProperties.setProperty(PropertyKeyConst.AccessKey,
} else if (!StringUtil.isEmpty(NAMESRV_ADDR)) { ACCESS_KEY);
producerProperties.put(PropertyKeyConst.NAMESRV_ADDR, producerProperties.setProperty(PropertyKeyConst.SecretKey,
NAMESRV_ADDR); SECRET_KEY);
} else { if (!StringUtil.isEmpty(ONS_ADDR)) {
logger.error( LOG_FLAG + "不支持的接入方式." + LOG_FLAG); producerProperties.put(PropertyKeyConst.ONSAddr, ONS_ADDR);
throw new IllegalAccessError("不支持的接入方式."); } else if (!StringUtil.isEmpty(NAMESRV_ADDR)) {
} producerProperties.put(PropertyKeyConst.NAMESRV_ADDR,
try { NAMESRV_ADDR);
producer = ONSFactory.createProducer(producerProperties); } else {
producer.start(); logger.error(LOG_FLAG + "不支持的接入方式." + LOG_FLAG);
Message message = new Message(TOPIC, TAG, obj.toString() throw new IllegalAccessError("不支持的接入方式.");
.getBytes(charset)); }
SendResult sendResult = producer.send(message); try {
assert sendResult != null; producer = ONSFactory.createProducer(producerProperties);
context.setObject("SEND_OK"); producer.start();
logger.info( Message message = new Message(TOPIC, TAG, obj.toString()
new Date() + " Send mq message success! Topic is:" .getBytes(charset));
+ TOPIC + " Tag is: " + TAG + " msgId is: " SendResult sendResult = producer.send(message);
+ sendResult.getMessageId()); assert sendResult != null;
} catch (Exception e) { context.setObject("SEND_OK");
logger.error( new Date() logger.info(
+ " Send mq message failed! Topic is:" + TOPIC new Date() + " Send mq message success! Topic is:"
+ " Tag is: " + TAG); + TOPIC + " Tag is: " + TAG + " msgId is: "
context.setObject("SEND_FAILED"); + sendResult.getMessageId());
throw new InterfaceException("03501", e); } catch (Exception e) {
} finally { logger.error(new Date()
if (producer != null) + " Send mq message failed! Topic is:" + TOPIC
producer.shutdown(); + " Tag is: " + TAG);
} context.setObject("SEND_FAILED");
} throw new InterfaceException("03501", e);
logger.info( LOG_FLAG } finally {
+ "RocketMQOpsProducerConnection is finished." + LOG_FLAG); if (producer != null) {
} producer.shutdown();
}
}
}
logger.info(LOG_FLAG
+ "RocketMQOpsProducerConnection is finished." + LOG_FLAG);
}
} }
...@@ -17,7 +17,7 @@ public class RocketMQProducerConnection extends AbsConnection { ...@@ -17,7 +17,7 @@ public class RocketMQProducerConnection extends AbsConnection {
@Override @Override
public void execute(Context context) { public void execute(Context context) {
logger.info( LOG_FLAG + "RocketMQProducerConnection is Running." + LOG_FLAG); logger.info(LOG_FLAG + "RocketMQProducerConnection is Running." + LOG_FLAG);
context.setCurrentInstance(this); context.setCurrentInstance(this);
DefaultMQProducer producer = null; DefaultMQProducer producer = null;
...@@ -25,7 +25,8 @@ public class RocketMQProducerConnection extends AbsConnection { ...@@ -25,7 +25,8 @@ public class RocketMQProducerConnection extends AbsConnection {
String groupName = getPropertyValue("groupName"); String groupName = getPropertyValue("groupName");
String serverAddress = getPropertyValue("serverAddress"); String serverAddress = getPropertyValue("serverAddress");
String topic = getPropertyValue("topic"); String topic = getPropertyValue("topic");
String subExpression = getPropertyValue("subExpression", "");; String subExpression = getPropertyValue("subExpression", "");
;
// Instantiate with a producer group name. // Instantiate with a producer group name.
producer = new DefaultMQProducer(groupName); producer = new DefaultMQProducer(groupName);
...@@ -36,15 +37,16 @@ public class RocketMQProducerConnection extends AbsConnection { ...@@ -36,15 +37,16 @@ public class RocketMQProducerConnection extends AbsConnection {
Object obj = context.getObject(); Object obj = context.getObject();
if (null != obj) { if (null != obj) {
logger.debug( "send_message="+obj); logger.debug("send_message=" + obj);
String encoding = connectionDef.getEncoding(); String encoding = connectionDef.getEncoding();
Message msg = Message msg =
new Message(topic /* Topic */, new Message(topic,
(obj.toString()).getBytes(StringUtil.isEmpty(encoding) (obj.toString()).getBytes(StringUtil.isEmpty(encoding)
? RemotingHelper.DEFAULT_CHARSET ? RemotingHelper.DEFAULT_CHARSET
: encoding)); /* Message body */ : encoding)); /* Message body */
if (!StringUtil.isEmpty(subExpression)) if (!StringUtil.isEmpty(subExpression)) {
msg.setTags(subExpression); msg.setTags(subExpression);
}
// Call send message to deliver message to one of brokers. // Call send message to deliver message to one of brokers.
SendResult sendResult = producer.send(msg); SendResult sendResult = producer.send(msg);
context.setObject(sendResult.getSendStatus()); context.setObject(sendResult.getSendStatus());
...@@ -63,6 +65,6 @@ public class RocketMQProducerConnection extends AbsConnection { ...@@ -63,6 +65,6 @@ public class RocketMQProducerConnection extends AbsConnection {
} finally { } finally {
producer.shutdown(); producer.shutdown();
} }
logger.info( LOG_FLAG + "RocketMQProducerConnection is finished." + LOG_FLAG); logger.info(LOG_FLAG + "RocketMQProducerConnection is finished." + LOG_FLAG);
} }
} }
...@@ -23,7 +23,7 @@ public class RocketMQServer extends AbsServer { ...@@ -23,7 +23,7 @@ public class RocketMQServer extends AbsServer {
@Override @Override
public void run() { public void run() {
logger.info( LOG_FLAG + "RocketMQServer starting ." + LOG_FLAG); logger.info(LOG_FLAG + "RocketMQServer starting ." + LOG_FLAG);
final String interfaceName = getRequiredPropertyValue("interfaceName"); final String interfaceName = getRequiredPropertyValue("interfaceName");
final String transactionName = getRequiredPropertyValue("transactionName"); final String transactionName = getRequiredPropertyValue("transactionName");
...@@ -45,32 +45,30 @@ public class RocketMQServer extends AbsServer { ...@@ -45,32 +45,30 @@ public class RocketMQServer extends AbsServer {
// Register callback to execute on arrival of messages fetched from brokers. // Register callback to execute on arrival of messages fetched from brokers.
consumer.registerMessageListener(new MessageListenerConcurrently() { consumer.registerMessageListener(new MessageListenerConcurrently() {
@Override @Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
ConsumeConcurrentlyContext context) { ConsumeConcurrentlyContext context) {
Client client = new Client(); Client client = new Client();
client.call(interfaceName, transactionName, new Object[] {msgs}); client.call(interfaceName, transactionName, new Object[]{msgs});
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
} }
}); });
// Launch the consumer instance. // Launch the consumer instance.
consumer.start(); consumer.start();
} catch (MQClientException e) { } catch (MQClientException e) {
logger.error( LOG_FLAG + "RocketMQServer error." + LOG_FLAG, e); logger.error(LOG_FLAG + "RocketMQServer error." + LOG_FLAG, e);
close(); close();
} }
logger.info(LOG_FLAG + "RocketMQServer is finished." + LOG_FLAG);
logger.info( LOG_FLAG + "RocketMQServer is finished." + LOG_FLAG);
} }
@Override @Override
public void close() { public void close() {
if (null != consumer) if (null != consumer) {
consumer.shutdown(); consumer.shutdown();
}
} }
} }
...@@ -22,17 +22,28 @@ public class RocketMQServerOns extends AbsServer { ...@@ -22,17 +22,28 @@ public class RocketMQServerOns extends AbsServer {
public void run() { public void run() {
logger.info(LOG_FLAG + "RocketMQOnsServer starting ." + LOG_FLAG); logger.info(LOG_FLAG + "RocketMQOnsServer starting ." + LOG_FLAG);
Properties properties; Properties properties;
String CONSUMER_ID = ""; //消费者ID // 消费者ID
String ACCESS_KEY = ""; //阿里云身份验证AccessKey String CONSUMER_ID = "";
String SECRET_KEY = ""; //阿里云身份验证SecretKey // 阿里云身份验证AccessKey
String ONS_ADDR = ""; //消息队列服务器地址 String ACCESS_KEY = "";
String NAMESRV_ADDR = ""; //消息队列服务器地址 // 阿里云身份验证SecretKey
String[] TOPIC; //消息主题组 String SECRET_KEY = "";
String[] TAG; //消息标签组 // 消息队列服务器地址
int CONSUME_THREAD_NUM = 0; //消费线程数 String ONS_ADDR = "";
int MAX_RECONSUME_TIMES = 0; //消息消费失败的最大重试次数 // 消息队列服务器地址
int CONSUME_TIMEOUT = 0; //每条消息消费的最大超时时间 String NAMESRV_ADDR = "";
int SUSPEND_TIME_MILLIS = 0; //消息消费失败的重试间隔时间(只适用于顺序消息) // 消息主题组
String[] TOPIC;
// 消息标签组
String[] TAG;
// 消费线程数
int CONSUME_THREAD_NUM = 0;
// 消息消费失败的最大重试次数
int MAX_RECONSUME_TIMES = 0;
// 每条消息消费的最大超时时间
int CONSUME_TIMEOUT = 0;
// 消息消费失败的重试间隔时间(只适用于顺序消息)
int SUSPEND_TIME_MILLIS = 0;
String interfaceName = getRequiredPropertyValue("interfaceName"); String interfaceName = getRequiredPropertyValue("interfaceName");
String transactionName = getRequiredPropertyValue("transactionName"); String transactionName = getRequiredPropertyValue("transactionName");
...@@ -48,16 +59,16 @@ public class RocketMQServerOns extends AbsServer { ...@@ -48,16 +59,16 @@ public class RocketMQServerOns extends AbsServer {
MAX_RECONSUME_TIMES = getPropertyValue("MaxReconsumeTimes", 1); MAX_RECONSUME_TIMES = getPropertyValue("MaxReconsumeTimes", 1);
CONSUME_TIMEOUT = getPropertyValue("ConsumeTimeout", 15); CONSUME_TIMEOUT = getPropertyValue("ConsumeTimeout", 15);
SUSPEND_TIME_MILLIS = getPropertyValue("SuspendTimeMillis", 3000); SUSPEND_TIME_MILLIS = getPropertyValue("SuspendTimeMillis", 3000);
//校验topic和tag数量是否一致,支持多消息订阅 // 校验topic和tag数量是否一致,支持多消息订阅
checkTopicAndTag(TOPIC, TAG); checkTopicAndTag(TOPIC, TAG);
properties = new Properties(); properties = new Properties();
//消息消费者ID // 消息消费者ID
properties.put(PropertyKeyConst.GROUP_ID, CONSUMER_ID); properties.put(PropertyKeyConst.GROUP_ID, CONSUMER_ID);
//阿里云身份验证AccessKey // 阿里云身份验证AccessKey
properties.put(PropertyKeyConst.AccessKey, ACCESS_KEY); properties.put(PropertyKeyConst.AccessKey, ACCESS_KEY);
//阿里云身份验证secretKey // 阿里云身份验证secretKey
properties.put(PropertyKeyConst.SecretKey, SECRET_KEY); properties.put(PropertyKeyConst.SecretKey, SECRET_KEY);
//消息队列服务器地址 // 消息队列服务器地址
if (!StringUtil.isEmpty(ONS_ADDR)) { if (!StringUtil.isEmpty(ONS_ADDR)) {
properties.put(PropertyKeyConst.ONSAddr, ONS_ADDR); properties.put(PropertyKeyConst.ONSAddr, ONS_ADDR);
} else if (!StringUtil.isEmpty(NAMESRV_ADDR)) { } else if (!StringUtil.isEmpty(NAMESRV_ADDR)) {
...@@ -66,14 +77,14 @@ public class RocketMQServerOns extends AbsServer { ...@@ -66,14 +77,14 @@ public class RocketMQServerOns extends AbsServer {
logger.error(LOG_FLAG + "不支持的接入方式." + LOG_FLAG); logger.error(LOG_FLAG + "不支持的接入方式." + LOG_FLAG);
throw new IllegalAccessError("不支持的接入方式."); throw new IllegalAccessError("不支持的接入方式.");
} }
//设置 Consumer 实例的消费线程数,默认:64 (订阅 消费者) // 设置 Consumer 实例的消费线程数,默认:64 (订阅 消费者)
properties.put(PropertyKeyConst.ConsumeThreadNums, CONSUME_THREAD_NUM); properties.put(PropertyKeyConst.ConsumeThreadNums, CONSUME_THREAD_NUM);
//设置消息消费失败的最大重试次数,默认:16 (订阅 消费者) // 设置消息消费失败的最大重试次数,默认:16 (订阅 消费者)
properties.put(PropertyKeyConst.MaxReconsumeTimes, MAX_RECONSUME_TIMES); properties.put(PropertyKeyConst.MaxReconsumeTimes, MAX_RECONSUME_TIMES);
//设置每条消息消费的最大超时时间,超过设置时间则被视为消费失败, (订阅 消费者) // 设置每条消息消费的最大超时时间,超过设置时间则被视为消费失败, (订阅 消费者)
//等下次重新投递再次消费。每个业务需要设置一个合理的值,单位(分钟)。默认:15 // 等下次重新投递再次消费。每个业务需要设置一个合理的值,单位(分钟)。默认:15
properties.put(PropertyKeyConst.ConsumeTimeout, CONSUME_TIMEOUT); properties.put(PropertyKeyConst.ConsumeTimeout, CONSUME_TIMEOUT);
//只适用于顺序消息,设置消息消费失败的重试间隔时间 单位(毫秒) (订阅 消费者) // 只适用于顺序消息,设置消息消费失败的重试间隔时间 单位(毫秒) (订阅 消费者)
properties.put(PropertyKeyConst.SuspendTimeMillis, SUSPEND_TIME_MILLIS); properties.put(PropertyKeyConst.SuspendTimeMillis, SUSPEND_TIME_MILLIS);
try { try {
logger.info("开始创建Consumer..."); logger.info("开始创建Consumer...");
...@@ -81,8 +92,9 @@ public class RocketMQServerOns extends AbsServer { ...@@ -81,8 +92,9 @@ public class RocketMQServerOns extends AbsServer {
for (int i = 0; i < TOPIC.length; i++) { for (int i = 0; i < TOPIC.length; i++) {
String tp = TOPIC[i]; String tp = TOPIC[i];
String tg = TAG[i]; String tg = TAG[i];
if (StringUtil.isEmpty(tp)) if (StringUtil.isEmpty(tp)) {
continue; continue;
}
logger.info("订阅的Topic" + i + ":" + tp); logger.info("订阅的Topic" + i + ":" + tp);
logger.info("订阅的Tag" + i + ":" + tg); logger.info("订阅的Tag" + i + ":" + tg);
consumer.subscribe(tp, tg, new MessageListenerImpl(interfaceName, transactionName, context, logger)); consumer.subscribe(tp, tg, new MessageListenerImpl(interfaceName, transactionName, context, logger));
...@@ -104,8 +116,9 @@ public class RocketMQServerOns extends AbsServer { ...@@ -104,8 +116,9 @@ public class RocketMQServerOns extends AbsServer {
@Override @Override
public void close() { public void close() {
if (null != consumer) if (null != consumer) {
consumer.shutdown(); consumer.shutdown();
}
} }
} }
...@@ -132,7 +145,6 @@ class MessageListenerImpl implements MessageListener { ...@@ -132,7 +145,6 @@ class MessageListenerImpl implements MessageListener {
String msgId = message.getMsgID(); String msgId = message.getMsgID();
try { try {
topicTagStr = message.getTopic() + "," + message.getTag(); topicTagStr = message.getTopic() + "," + message.getTag();
logger.info("msgId=" + msgId + "当前Topic+Tag=" + topicTagStr); logger.info("msgId=" + msgId + "当前Topic+Tag=" + topicTagStr);
// 查询消息消费处理 // 查询消息消费处理
Client client = new Client(); Client client = new Client();
......
...@@ -6,46 +6,48 @@ import com.brilliance.eibs.lsocket.AliveClient; ...@@ -6,46 +6,48 @@ import com.brilliance.eibs.lsocket.AliveClient;
/** /**
* @author gechengyang socket客户端长连接 * @author gechengyang socket客户端长连接
* **/ **/
public class AliveSocketConnection extends AbsConnection { public class AliveSocketConnection extends AbsConnection {
@Override @Override
public void execute(Context context) { public void execute(Context context) {
logger.info( "Running SocketClientConnection."); logger.info("Running SocketClientConnection.");
context.setCurrentInstance(this); context.setCurrentInstance(this);
super.execute(context); super.execute(context);
setTimeOut(); setTimeOut();
AliveClient aclient = null; AliveClient aclient = null;
try { try {
setTimeOut(); setTimeOut();
String ip = getPropertyValue(IP_SYMBOL); String ip = getPropertyValue(IP_SYMBOL);
int port = getPropertyValueInt(PORT_SYMBOL); int port = getPropertyValueInt(PORT_SYMBOL);
String heartbeat = getPropertyValue(HEAR_BEAT, true); String heartbeat = getPropertyValue(HEAR_BEAT, true);
String content = (String) context.getObject(); String content = (String) context.getObject();
aclient = AliveClient.getInstance(ip, port, connectTimeout, logger); aclient = AliveClient.getInstance(ip, port, connectTimeout, logger);
aclient.setHeartbeart(heartbeat); aclient.setHeartbeart(heartbeat);
aclient.put(content); aclient.put(content);
} catch (Exception e) { } catch (Exception e) {
throw new InterfaceException("00014", "SocketClientConnection exception occurs.", e); throw new InterfaceException("00014", "SocketClientConnection exception occurs.", e);
} }
logger.info( "SocketClientConnection is finished."); logger.info("SocketClientConnection is finished.");
} }
/** /**
* 设置超时时间,包括连接超时,返回超时 * 设置超时时间,包括连接超时,返回超时
*/ */
protected void setTimeOut() { @Override
setConnectTimeOut(); protected void setTimeOut() {
} setConnectTimeOut();
}
/** /**
* 获取连接超时时间,如果为空,则使用默认时间 * 获取连接超时时间,如果为空,则使用默认时间
*/ */
protected void setConnectTimeOut() { @Override
int connectTimeout = getPropertyValueInt(CONNECT_TIMEOUT_SYMBOL, true); protected void setConnectTimeOut() {
if (connectTimeout != 0) { int connectTimeout = getPropertyValueInt(CONNECT_TIMEOUT_SYMBOL, true);
this.connectTimeout = connectTimeout; if (connectTimeout != 0) {
} this.connectTimeout = connectTimeout;
logger.debug( "Connect timeout = " + this.connectTimeout); }
} logger.debug("Connect timeout = " + this.connectTimeout);
}
} }
...@@ -15,69 +15,63 @@ import java.util.Map.Entry; ...@@ -15,69 +15,63 @@ import java.util.Map.Entry;
/** /**
* 201908 weicong 修改 * 201908 weicong 修改
*
*/ */
public class MinaClientConnection extends AbsConnection { public class MinaClientConnection extends AbsConnection {
private MinaNioClient client; private MinaNioClient client;
private String charset; private String charset;
@Override @Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "MinaClientConnection is Running." + charset = getPropertyValue("charset", Charset.defaultCharset().name());
// LOG_FLAG); MinaSocketClientAdaptor adaptor = null;
charset = getPropertyValue("charset", Charset.defaultCharset().name()); try {
MinaSocketClientAdaptor adaptor =null; setTimeOut();
try { context.setCurrentInstance(this);
setTimeOut(); int port = getPropertyValueInt(PORT_SYMBOL);
context.setCurrentInstance(this); logger.info("socket port=" + port);
int port = getPropertyValueInt(PORT_SYMBOL); String hostname = getPropertyValue(IP_SYMBOL);
logger.info( "socket port=" + port); logger.info("socket hostname=" + hostname);
String hostname = getPropertyValue(IP_SYMBOL); Map<String, String> props = new HashMap<String, String>();
logger.info( "socket hostname=" + hostname); for (Entry<String, IPropertyDef> entry : this.connectionDef.getPropertyMap().entrySet()) {
Map<String, String> props=new HashMap<String, String>(); props.put(entry.getKey(), entry.getValue().getValue());
for(Entry<String, IPropertyDef> entry:this.connectionDef.getPropertyMap().entrySet()){ }
props.put(entry.getKey(), entry.getValue().getValue()); client = new MinaNioClient(hostname, port, props);
} client.init();
client = new MinaNioClient(hostname, port,props); client.setTimeout(connectTimeout == 0 ? 1000 : connectTimeout);
client.init(); adaptor = new MinaSocketClientAdaptor(client, charset, receiveTimeout == 0 ? 2000 : receiveTimeout);
client.setTimeout(connectTimeout==0?1000:connectTimeout); client.loadPloyHandler(new NioProxyHandler(adaptor));
adaptor = new MinaSocketClientAdaptor(client,charset,receiveTimeout==0?2000:receiveTimeout); client.connect();
client.loadPloyHandler(new NioProxyHandler(adaptor)); adaptor.setSession(client.getSession());
client.connect(); context.getResource().setSocketProxy(adaptor);
adaptor.setSession(client.getSession()); } catch (Exception e) {
context.getResource().setSocketProxy(adaptor); if (adaptor != null) {
} catch (Exception e) { adaptor.close();
if(adaptor!=null){ }
adaptor.close(); throw new InterfaceException("02102", e);
} }
throw new InterfaceException("02102", e); }
}
// logger.info( LOG_FLAG + "MinaClientConnection is finished." +
// LOG_FLAG);
}
private static class NioProxyHandler extends NioProcessHandler { private static class NioProxyHandler extends NioProcessHandler {
private MinaSocketClientAdaptor adaptor; private MinaSocketClientAdaptor adaptor;
private NioProxyHandler(MinaSocketClientAdaptor adaptor) { private NioProxyHandler(MinaSocketClientAdaptor adaptor) {
this.adaptor = adaptor; this.adaptor = adaptor;
} }
@Override @Override
protected void process(IoSession session, Object message) { protected void process(IoSession session, Object message) {
adaptor.setMessage(message); adaptor.setMessage(message);
} }
@Override @Override
public void exceptionCaught(IoSession session, Throwable cause) public void exceptionCaught(IoSession session, Throwable cause)
throws Exception { throws Exception {
super.exceptionCaught(session, cause); super.exceptionCaught(session, cause);
adaptor.close(); adaptor.close();
} }
} }
} }
...@@ -12,14 +12,14 @@ import java.net.Socket; ...@@ -12,14 +12,14 @@ import java.net.Socket;
/** /**
* ProxyFilter 通信代理 * ProxyFilter 通信代理
*
* @author gechengyang
* *
* @author gechengyang
*/ */
public class ProxyFilter extends AbsFilter { public class ProxyFilter extends AbsFilter {
SocketProxy socketp = null; SocketProxy socketp = null;
SocketProxy midsp = null; SocketProxy midsp = null;
@Override
public void execute(Context context) { public void execute(Context context) {
logger.info(LOG_FLAG + "ProxyFilter is running" + LOG_FLAG); logger.info(LOG_FLAG + "ProxyFilter is running" + LOG_FLAG);
context.setCurrentInstance(this); context.setCurrentInstance(this);
...@@ -29,24 +29,25 @@ public class ProxyFilter extends AbsFilter { ...@@ -29,24 +29,25 @@ public class ProxyFilter extends AbsFilter {
logger.info(LOG_FLAG + "ProxyFilter has finished running" + LOG_FLAG); logger.info(LOG_FLAG + "ProxyFilter has finished running" + LOG_FLAG);
} }
@Override
protected void packField(IFieldDef fieldDef, Object fieldValue) { protected void packField(IFieldDef fieldDef, Object fieldValue) {
} }
@Override
public Object getFieldValue(IFieldDef fieldDef) { public Object getFieldValue(IFieldDef fieldDef) {
return null; return null;
} }
public void run() { public void run() {
Object obj[] = (Object[]) context.getResource().getObject(); Object obj[] = (Object[]) context.getResource().getObject();
if (obj == null) return; if (obj == null) {
return;
}
socketp = (SocketProxy) obj[0]; socketp = (SocketProxy) obj[0];
Socket socket = socketp.getSocket(); Socket socket = socketp.getSocket();
midsp = (SocketProxy) obj[1]; midsp = (SocketProxy) obj[1];
Socket mids = midsp.getSocket(); Socket mids = midsp.getSocket();
try { try {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int a = -1; int a = -1;
logger.info("proxyFilter belongs to " + context.getVariable("transactionName")); logger.info("proxyFilter belongs to " + context.getVariable("transactionName"));
...@@ -57,7 +58,6 @@ public class ProxyFilter extends AbsFilter { ...@@ -57,7 +58,6 @@ public class ProxyFilter extends AbsFilter {
} catch (Exception e) { } catch (Exception e) {
logger.error("socket error:", e); logger.error("socket error:", e);
throw new InterfaceException("02201"); throw new InterfaceException("02201");
} finally { } finally {
logger.info("[" + context.getVariable("transactionName") + "]sokcet is closed nomally"); logger.info("[" + context.getVariable("transactionName") + "]sokcet is closed nomally");
IOUtils.closeQuietly(socket); IOUtils.closeQuietly(socket);
...@@ -65,16 +65,9 @@ public class ProxyFilter extends AbsFilter { ...@@ -65,16 +65,9 @@ public class ProxyFilter extends AbsFilter {
try { try {
logger.info("socketProxy Map:" + SocketManagerFactoryUtil.getSocketProxyMap()); logger.info("socketProxy Map:" + SocketManagerFactoryUtil.getSocketProxyMap());
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block logger.error(e.getMessage(), e);
e.printStackTrace();
} }
/*
* if (socketp!=null&&SocketClientConnection.ali
*
* veProxys.containsKey(socketp)) SocketClientConnection.aliveProxys.remove(socketp);
*/
} }
} }
} }
...@@ -13,108 +13,109 @@ import java.net.SocketTimeoutException; ...@@ -13,108 +13,109 @@ import java.net.SocketTimeoutException;
/** /**
* Socket客户端连接器 * Socket客户端连接器
* *
* @author gechengyang * @author gechengyang
*/ */
public class ShortSocketClientConnection extends AbsConnection { public class ShortSocketClientConnection extends AbsConnection {
@Override @Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "SocketClientConnection is Running." context.setCurrentInstance(this);
// + LOG_FLAG); ISocketProxy socketProxy = null;
context.setCurrentInstance(this); try {
ISocketProxy socketProxy = null; setTimeOut();
try { int port = getPropertyValueInt(PORT_SYMBOL);
setTimeOut(); logger.info("socket port=" + port);
int port = getPropertyValueInt(PORT_SYMBOL); String ip = getPropertyValue(IP_SYMBOL);
logger.info( "socket port=" + port); logger.info("socket ip=" + ip);
String ip = getPropertyValue(IP_SYMBOL); // 是否有报文头
logger.info( "socket ip=" + ip); boolean has_head = true;
boolean has_head = true;// 是否有报文头 // 报文头长度是二进制还是十进制
String head_len_type = "";// 报文头长度是二进制还是十进制 String head_len_type = "";
int head_len = 0;// 报文头长度 // 报文头长度
boolean is_contain_head_len = false;// 报文头长度是否包含报文头 int head_len = 0;
int fill_len = 0;// 默认为0 // 报文头长度是否包含报文头
boolean is_contain_fill_len = false;// 报文头长度是否包含报文头和报文体之间数据的长度 true boolean is_contain_head_len = false;
// 默认为0
int fill_len = 0;
// 报文头长度是否包含报文头和报文体之间数据的长度 true
boolean is_contain_fill_len = false;
has_head = getPropertyValueBoolean(IServerInstance.HAS_CONTAIN_HEAD, true); has_head = getPropertyValueBoolean(IServerInstance.HAS_CONTAIN_HEAD, true);
head_len_type = getPropertyValue(IServerInstance.HEAD_LEN_TYPE, IServerInstance.HEAD_LEN_TYPE_10); head_len_type = getPropertyValue(IServerInstance.HEAD_LEN_TYPE, IServerInstance.HEAD_LEN_TYPE_10);
head_len = getPropertyValue(IServerInstance.HEAD_LEN, 0); head_len = getPropertyValue(IServerInstance.HEAD_LEN, 0);
is_contain_head_len = getPropertyValueBoolean(IServerInstance.IS_CONTAIN_HEAD_LEN, false); is_contain_head_len = getPropertyValueBoolean(IServerInstance.IS_CONTAIN_HEAD_LEN, false);
fill_len = getPropertyValue(IServerInstance.FILL_LEN, 0); fill_len = getPropertyValue(IServerInstance.FILL_LEN, 0);
is_contain_fill_len = getPropertyValueBoolean(IServerInstance.IS_CONTAIN_FILL_LEN, false); is_contain_fill_len = getPropertyValueBoolean(IServerInstance.IS_CONTAIN_FILL_LEN, false);
if (has_head) { if (has_head) {
int headLen = 0;
byte[] headLenBytes = null;
Object obj = context.getObject();
byte[] sendData = null;
if (obj instanceof String) {
sendData = ((String) obj).getBytes(connectionDef.getEncoding());
} else if (obj instanceof byte[]) {
sendData = (byte[]) obj;
}
headLen = sendData.length;
if (is_contain_head_len) {
headLen = headLen + head_len;
}
if (fill_len != 0) {
if (!is_contain_fill_len) {
headLen = headLen + fill_len;
}
}
if (head_len_type.equals(IServerInstance.HEAD_LEN_TYPE_10)) {
headLenBytes = String.format("%0" + head_len + "d", headLen).getBytes();
} else if (head_len_type.equals(IServerInstance.HEAD_LEN_TYPE_2)) {
headLenBytes = CommonFunctionUtils.intToBytes(headLen);
}
socketProxy = new SocketProxy(new InetSocketAddress(ip, port), connectTimeout, receiveTimeout, connectionDef.getEncoding(), context);
socketProxy.send(headLenBytes);
socketProxy.send(sendData);
int headLen = 0; headLenBytes = new byte[head_len];
byte[] headLenBytes = null; IOUtils.readFully(socketProxy.getSocket().getInputStream(), headLenBytes);
Object obj = context.getObject(); if (head_len_type.equals(IServerInstance.HEAD_LEN_TYPE_10)) {
byte[] sendData = null; headLen = Integer.parseInt(new String(headLenBytes));
if (obj instanceof String) { } else if (head_len_type.equals(IServerInstance.HEAD_LEN_TYPE_2)) {
sendData = ((String) obj).getBytes(connectionDef.getEncoding()); headLen = CommonFunctionUtils.bytesToInt(headLenBytes);
} else if (obj instanceof byte[]) { }
sendData = (byte[]) obj; if (is_contain_head_len) {
} headLen = headLen - head_len;
headLen = sendData.length; }
if (is_contain_head_len) { if (fill_len != 0) {
headLen = headLen + head_len; if (!is_contain_fill_len) {
} headLen = headLen + fill_len;
if (fill_len != 0) { }
if (!is_contain_fill_len) { }
headLen = headLen + fill_len; byte[] databuffer = new byte[headLen];
} IOUtils.readFully(socketProxy.getSocket().getInputStream(), databuffer);
} context.setObject(databuffer);
if (head_len_type.equals(IServerInstance.HEAD_LEN_TYPE_10)) { } else {
headLenBytes = String.format("%0" + head_len + "d", headLen).getBytes();
} else if (head_len_type.equals(IServerInstance.HEAD_LEN_TYPE_2)) {
headLenBytes = CommonFunctionUtils.intToBytes(headLen);
}
socketProxy = new SocketProxy(new InetSocketAddress(ip, port), connectTimeout, receiveTimeout, connectionDef.getEncoding(), context);
socketProxy.send(headLenBytes);
socketProxy.send(sendData);
headLenBytes = new byte[head_len]; }
IOUtils.readFully(socketProxy.getSocket().getInputStream(), headLenBytes); } catch (SocketTimeoutException e) {
if (head_len_type.equals(IServerInstance.HEAD_LEN_TYPE_10)) { closeSocket(socketProxy);
headLen = Integer.parseInt(new String(headLenBytes)); throw new InterfaceException("02101", e);
} else if (head_len_type.equals(IServerInstance.HEAD_LEN_TYPE_2)) { } catch (Exception e) {
headLen = CommonFunctionUtils.bytesToInt(headLenBytes); closeSocket(socketProxy);
} throw new InterfaceException("02102", e);
if (is_contain_head_len) { } finally {
headLen = headLen - head_len; closeSocket(socketProxy);
} }
if (fill_len != 0) { }
if (!is_contain_fill_len) {
headLen = headLen + fill_len;
}
}
byte[] databuffer = new byte[headLen];
IOUtils.readFully(socketProxy.getSocket().getInputStream(), databuffer);
context.setObject(databuffer);
} else {
} /**
* 关闭socket连接
} catch (SocketTimeoutException e) { *
closeSocket(socketProxy); * @param proxy
throw new InterfaceException("02101", e); */
} catch (Exception e) { private void closeSocket(ISocketProxy proxy) {
closeSocket(socketProxy); if (proxy != null) {
throw new InterfaceException("02102", e); proxy.close();
} finally { }
closeSocket(socketProxy); }
}
// logger.info( LOG_FLAG + "SocketClientConnection is finished."
// + LOG_FLAG);
}
/**
* 关闭socket连接
*
* @param proxy
*/
private void closeSocket(ISocketProxy proxy) {
if (proxy != null)
proxy.close();
}
} }
...@@ -15,104 +15,96 @@ import java.util.concurrent.ConcurrentHashMap; ...@@ -15,104 +15,96 @@ import java.util.concurrent.ConcurrentHashMap;
/** /**
* Socket客户端连接器 * Socket客户端连接器
* *
* @author hujun ------------modified by weicong on 2016/4/01 ----------- * @author hujun ------------modified by weicong on 2016/4/01 -----------
* 兼容sslsocket * 兼容sslsocket
*/ */
public class SocketClientConnection extends AbsConnection { public class SocketClientConnection extends AbsConnection {
/** /**
* 保存socket长连接 * 保存socket长连接
*/ */
public static Map<SocketIdentity, ISocketProxy> aliveProxys = new ConcurrentHashMap<SocketIdentity, ISocketProxy>(); public static Map<SocketIdentity, ISocketProxy> aliveProxys = new ConcurrentHashMap<SocketIdentity, ISocketProxy>();
/** /**
* @author hujun * @author hujun
* * <p>
* 用于标记标识socket长连接 * 用于标记标识socket长连接
* */
*/ private static class SocketIdentity {
private static class SocketIdentity { private String interfaceId;
private String interfaceId; private String transactionName;
private String transactionName; private String ref;
private String ref;
private SocketIdentity(String interfaceId, String transactionName, String ref) { private SocketIdentity(String interfaceId, String transactionName, String ref) {
this.interfaceId = interfaceId; this.interfaceId = interfaceId;
this.transactionName = transactionName; this.transactionName = transactionName;
this.ref = ref; this.ref = ref;
} }
private static SocketIdentity bulid(String interfaceId, String transactionName, String ref) { private static SocketIdentity bulid(String interfaceId, String transactionName, String ref) {
return new SocketIdentity(interfaceId, transactionName, ref); return new SocketIdentity(interfaceId, transactionName, ref);
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
boolean b = EqualsBuilder.reflectionEquals(this, obj); boolean b = EqualsBuilder.reflectionEquals(this, obj);
return b; return b;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this); return HashCodeBuilder.reflectionHashCode(this);
} }
} }
@Override @Override
public void execute(Context context) { public void execute(Context context) {
// logger.info( LOG_FLAG + "SocketClientConnection is Running." context.setCurrentInstance(this);
// + LOG_FLAG); ISocketProxy socketProxy = null;
context.setCurrentInstance(this); try {
ISocketProxy socketProxy = null; setTimeOut();
try { final int port = getPropertyValueInt(PORT_SYMBOL);
setTimeOut(); logger.info("socket port=" + port);
final int port = getPropertyValueInt(PORT_SYMBOL); final String ip = getPropertyValue(IP_SYMBOL);
logger.info( "socket port=" + port); logger.info("socket ip=" + ip);
final String ip = getPropertyValue(IP_SYMBOL); String alive = getPropertyValue(ALIVE_SYMBOL, true);
logger.info( "socket ip=" + ip);
String alive = getPropertyValue(ALIVE_SYMBOL, true);
SocketIdentity socketId = SocketIdentity.bulid(context.getResource().getInterfaceName(), context.getResource().getTransactionName(), SocketIdentity socketId = SocketIdentity.bulid(context.getResource().getInterfaceName(), context.getResource().getTransactionName(),
getIDef().getRef()); getIDef().getRef());
// 长连接池中获取 // 长连接池中获取
if (!StringUtil.isEmpty(alive) && Boolean.valueOf(alive)) { if (!StringUtil.isEmpty(alive) && Boolean.valueOf(alive)) {
/* socketProxy = aliveProxys.get(socketId);
* synchronized (lock) { if (null == socketProxy || !socketProxy.isConnected()) {
*/ socketProxy = new SocketProxy(new InetSocketAddress(ip, port), connectTimeout, receiveTimeout, connectionDef.getEncoding(),
socketProxy = aliveProxys.get(socketId); context);
if (null == socketProxy || !socketProxy.isConnected()) { aliveProxys.put(socketId, socketProxy);
socketProxy = new SocketProxy(new InetSocketAddress(ip, port), connectTimeout, receiveTimeout, connectionDef.getEncoding(), }
context); } else {
aliveProxys.put(socketId, socketProxy); if (null == socketProxy) {
} socketProxy = new SocketProxy(new InetSocketAddress(ip, port), connectTimeout, receiveTimeout, connectionDef.getEncoding(),
/* } */ context);
} else { }
if (null == socketProxy) { }
socketProxy = new SocketProxy(new InetSocketAddress(ip, port), connectTimeout, receiveTimeout, connectionDef.getEncoding(), context.getResource().setSocketProxy(socketProxy);
context); } catch (SocketTimeoutException e) {
} closeSocket(socketProxy);
} throw new InterfaceException("02101", e);
} catch (Exception e) {
closeSocket(socketProxy);
throw new InterfaceException("02102", e);
}
context.getResource().setSocketProxy(socketProxy); }
} catch (SocketTimeoutException e) {
closeSocket(socketProxy);
throw new InterfaceException("02101", e);
} catch (Exception e) {
closeSocket(socketProxy);
throw new InterfaceException("02102", e);
}
// logger.info( LOG_FLAG + "SocketClientConnection is finished."
// + LOG_FLAG);
}
/** /**
* 关闭socket连接 * 关闭socket连接
* *
* @param proxy * @param proxy
*/ */
private void closeSocket(ISocketProxy proxy) { private void closeSocket(ISocketProxy proxy) {
if (proxy != null) if (proxy != null) {
proxy.close(); proxy.close();
} }
}
} }
...@@ -14,87 +14,86 @@ import java.net.SocketException; ...@@ -14,87 +14,86 @@ import java.net.SocketException;
public class ChannelServer extends AbsServer { public class ChannelServer extends AbsServer {
private AsyncChannelServer server; private AsyncChannelServer server;
private ChannelListner listener; private ChannelListner listener;
public ChannelServer(Context context, IServiceDef serviceDef, ApacheEL elParser) { public ChannelServer(Context context, IServiceDef serviceDef, ApacheEL elParser) {
super(context, serviceDef, elParser); super(context, serviceDef, elParser);
} }
@Override @Override
public void run() { public void run() {
logger.info( LOG_FLAG + "ChannelServer starting ." + LOG_FLAG); logger.info(LOG_FLAG + "ChannelServer starting ." + LOG_FLAG);
int port = Integer.valueOf(getRequiredPropertyValue("port")); int port = Integer.valueOf(getRequiredPropertyValue("port"));
int destPort = Integer.valueOf(getRequiredPropertyValue("destPort")); int destPort = Integer.valueOf(getRequiredPropertyValue("destPort"));
String destIP = getRequiredPropertyValue("destIP"); String destIP = getRequiredPropertyValue("destIP");
String requestInterfaceName = getPropertyValue("request_interfaceName"); String requestInterfaceName = getPropertyValue("request_interfaceName");
String requestTransactionId = getPropertyValue("request_transactionName"); String requestTransactionId = getPropertyValue("request_transactionName");
String responseInterfaceName = getPropertyValue("response_interfaceName"); String responseInterfaceName = getPropertyValue("response_interfaceName");
String responseTransactionId = getPropertyValue("response_transactionName"); String responseTransactionId = getPropertyValue("response_transactionName");
String length = getPropertyValue("length"); String length = getPropertyValue("length");
if (StringUtil.isEmpty(length) if (StringUtil.isEmpty(length)
|| ((StringUtil.isEmpty(requestInterfaceName) || StringUtil.isEmpty(requestTransactionId)) && (StringUtil || ((StringUtil.isEmpty(requestInterfaceName)
.isEmpty(responseInterfaceName) || StringUtil.isEmpty(responseTransactionId)))) || StringUtil.isEmpty(requestTransactionId))
server = new AsyncChannelServer(port, destPort, destIP); && (StringUtil.isEmpty(responseInterfaceName) || StringUtil.isEmpty(responseTransactionId)))) {
else server = new AsyncChannelServer(port, destPort, destIP);
server = new AsyncFixedChannelServer(port, destPort, destIP, Integer.valueOf(length), requestInterfaceName, requestTransactionId, } else {
responseInterfaceName, responseTransactionId); server = new AsyncFixedChannelServer(port, destPort, destIP, Integer.valueOf(length), requestInterfaceName, requestTransactionId,
responseInterfaceName, responseTransactionId);
listener = new ChannelListner(); }
Thread t = new Thread(listener); listener = new ChannelListner();
t.setName("Asynchronous Channel '" + serviceDef.getId() + "' Server Listener"); Thread t = new Thread(listener);
t.setDaemon(true); t.setName("Asynchronous Channel '" + serviceDef.getId() + "' Server Listener");
t.start(); t.setDaemon(true);
t.start();
try { try {
server.startup(); server.startup();
} catch (IOException e) { } catch (IOException e) {
if ((e instanceof SocketException) && e.getMessage().equals("socket closed")) if ((e instanceof SocketException) && e.getMessage().equals("socket closed"))
; ;
else { else {
throw new InterfaceException("02301", e); throw new InterfaceException("02301", e);
} }
} }
logger.info( LOG_FLAG + "ChannelServer is finished." + LOG_FLAG); logger.info(LOG_FLAG + "ChannelServer is finished." + LOG_FLAG);
} }
@Override @Override
public void close() { public void close() {
listener.interrupted(); listener.interrupted();
server.close(); server.close();
} }
private class ChannelListner extends Detect { private class ChannelListner extends Detect {
private long interval = 60000; private long interval = 60000;
private ChannelListner() { private ChannelListner() {
} }
private ChannelListner(long interval) { private ChannelListner(long interval) {
this.interval = interval; this.interval = interval;
} }
@Override @Override
protected void exception() { protected void exception() {
interrupted(); interrupted();
} }
@Override @Override
protected void handle() throws IOException { protected void handle() throws IOException {
int size = server.getPool().size(); int size = server.getPool().size();
logger.info( "Connections size in [" + serviceDef.getId() + "] channel : " + size); logger.info("Connections size in [" + serviceDef.getId() + "] channel : " + size);
try { try {
Thread.sleep(interval); Thread.sleep(interval);
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.error( e.getMessage(),e); logger.error(e.getMessage(), e);
} }
} }
@Override @Override
protected void close() { protected void close() {
logger.info( "ChannelListner of [" + serviceDef.getId() + "] channel is closed."); logger.info("ChannelListner of [" + serviceDef.getId() + "] channel is closed.");
} }
}
}
} }
...@@ -23,7 +23,7 @@ public class LinkServer extends AbsServer { ...@@ -23,7 +23,7 @@ public class LinkServer extends AbsServer {
@Override @Override
public void run() { public void run() {
logger.info(LOG_FLAG + "LinkServer starting ." + LOG_FLAG); logger.info(LOG_FLAG + "LinkServer starting ." + LOG_FLAG);
String links = getRequiredPropertyValue(LINKS_SYMBOL);// 127.0.0.1:10001:10002 String links = getRequiredPropertyValue(LINKS_SYMBOL);
int headTagLen = Integer.valueOf(getRequiredPropertyValue(HEAD_TAG_LEN_SYMBOL)); int headTagLen = Integer.valueOf(getRequiredPropertyValue(HEAD_TAG_LEN_SYMBOL));
String heartbeat = getPropertyValue(HEARTBEAT_SYMBOL); String heartbeat = getPropertyValue(HEARTBEAT_SYMBOL);
String fin = getPropertyValue(FIN_SYMBOL); String fin = getPropertyValue(FIN_SYMBOL);
...@@ -52,8 +52,9 @@ public class LinkServer extends AbsServer { ...@@ -52,8 +52,9 @@ public class LinkServer extends AbsServer {
@Override @Override
public void close() { public void close() {
for (LinkDispatch dispatch : dispatchs) for (LinkDispatch dispatch : dispatchs) {
dispatch.interrupted(); dispatch.interrupted();
}
executorService.shutdownNow(); executorService.shutdownNow();
} }
......
...@@ -24,14 +24,34 @@ public class ShortSocketServer extends AbsServer { ...@@ -24,14 +24,34 @@ public class ShortSocketServer extends AbsServer {
private int timeout; private int timeout;
private IServerMode mode; private IServerMode mode;
private boolean has_head = true;// 是否有报文头 /**
private String head_len_type = IServerInstance.HEAD_LEN_TYPE_10;// 报文头长度是二进制还是十进制 * 是否有报文头
private int head_len = 0;// 报文头长度 */
private boolean is_contain_head_len = false;// 报文头长度是否包含报文头 private boolean has_head = true;
private int fill_len = 0;// 默认为0 /**
private boolean is_contain_fill_len = false;// 报文头长度是否包含报文头和报文体之间数据的长度 true * 报文头长度是二进制还是十进制
// false */
private int body_offset = 0;// 报文体位移量 默认为0, -1为减去1个长度,+1为增加1个长度 private String head_len_type = IServerInstance.HEAD_LEN_TYPE_10;
/**
* 报文头长度
*/
private int head_len = 0;
/**
* 报文头长度是否包含报文头
*/
private boolean is_contain_head_len = false;
/**
* 默认为0
*/
private int fill_len = 0;
/**
* 报文头长度是否包含报文头和报文体之间数据的长度 true
*/
private boolean is_contain_fill_len = false;
/**
* 报文体位移量 默认为0, -1为减去1个长度,+1为增加1个长度
*/
private int body_offset = 0;
private String encoding = "UTF-8"; private String encoding = "UTF-8";
......
...@@ -11,64 +11,53 @@ import java.net.DatagramSocket; ...@@ -11,64 +11,53 @@ import java.net.DatagramSocket;
/** /**
* udpserver * udpserver
*
* @author gechengyang
* *
* @author gechengyang
*/ */
public class UdpServer extends AbsServer { public class UdpServer extends AbsServer {
private boolean isOpen = true; private boolean isOpen = true;
public UdpServer(Context context, IServiceDef serviceDef, ApacheEL elParser) { public UdpServer(Context context, IServiceDef serviceDef, ApacheEL elParser) {
super(context, serviceDef, elParser); super(context, serviceDef, elParser);
} }
@Override @Override
public void run() { public void run() {
logger.info( LOG_FLAG + "UdpServer starting ." + LOG_FLAG); logger.info(LOG_FLAG + "UdpServer starting ." + LOG_FLAG);
try { try {
// 服务发布的端口 // 服务发布的端口
int port = Integer.valueOf(getRequiredPropertyValue(PORT_SYMBOL)); int port = Integer.valueOf(getRequiredPropertyValue(PORT_SYMBOL));
int buffersize = Integer.valueOf(getRequiredPropertyValue(BUFFER_SIZE)); int buffersize = Integer.valueOf(getRequiredPropertyValue(BUFFER_SIZE));
logger.info( "socketserver port=" + port); logger.info("socketserver port=" + port);
String interfaceName = getRequiredPropertyValue("interfaceName"); String interfaceName = getRequiredPropertyValue("interfaceName");
String transName = getRequiredPropertyValue("transactionName"); String transName = getRequiredPropertyValue("transactionName");
DatagramSocket server = new DatagramSocket(port); DatagramSocket server = new DatagramSocket(port);
logger.info( "server start at port: " + port); logger.info("server start at port: " + port);
while (isOpen) { while (isOpen) {
DatagramPacket dataPacket = null; DatagramPacket dataPacket = null;
byte buffer[] = new byte[buffersize]; byte buffer[] = new byte[buffersize];
dataPacket = new DatagramPacket(buffer, buffer.length); dataPacket = new DatagramPacket(buffer, buffer.length);
server.receive(dataPacket); server.receive(dataPacket);
String revs = new String(buffer, 0, dataPacket.getLength()); String revs = new String(buffer, 0, dataPacket.getLength());
logger.info( "dataPackegt.length=" + dataPacket.getLength()); logger.info("dataPackegt.length=" + dataPacket.getLength());
logger.info( "server recive:" + revs); logger.info("server recive:" + revs);
byte[] b = new byte[dataPacket.getLength()]; byte[] b = new byte[dataPacket.getLength()];
System.arraycopy(buffer, 0, b, 0, dataPacket.getLength()); System.arraycopy(buffer, 0, b, 0, dataPacket.getLength());
// new Thread(new UdpHandle(interfaceName, transName, revs, new Thread(new UdpHandle(interfaceName, transName, b, dataPacket, server)).start();
// dataPacket, server)).start(); }
new Thread(new UdpHandle(interfaceName, transName, b, dataPacket, server)).start(); close();
// byte[] sndinfo = "1234567".getBytes(); } catch (Exception e) {
// DatagramPacket dataPacket1 = new DatagramPacket(sndinfo, throw new InterfaceException("03001", e);
// sndinfo.length, dataPacket.getAddress(), } finally {
// dataPacket.getPort());
}
// server.send(dataPacket1); logger.info(LOG_FLAG + "UdpServer is finished." + LOG_FLAG);
// server.close(); }
}
close(); @Override
} catch (Exception e) { public void close() {
throw new InterfaceException("03001", e); }
} finally {
}
logger.info( LOG_FLAG + "UdpServer is finished." + LOG_FLAG);
}
@Override
public void close() {
}
} }
...@@ -10,81 +10,69 @@ import java.io.ByteArrayOutputStream; ...@@ -10,81 +10,69 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
public abstract class BaseChartBuilder public abstract class BaseChartBuilder implements IChartBuilder {
implements IChartBuilder
{
private ChartModel model; private ChartModel model;
public BaseChartBuilder( ChartModel model ) public BaseChartBuilder(ChartModel model) {
{ this.model = model;
this.model = model; }
}
protected ChartModel getModel()
{
return model;
}
protected void setModel(ChartModel model)
{
this.model = model;
}
@Override protected ChartModel getModel() {
public byte[] generate() return model;
throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
desolveMessyCode();
JFreeChart chart = createChart();
ChartUtilities.writeChartAsPNG(baos, chart, model.getWidth(), model.getHeight());
baos.close();
} }
catch (IOException e)
{ protected void setModel(ChartModel model) {
throw new IOException("Image create exception.", e); this.model = model;
} }
return baos.toByteArray();
} @Override
public byte[] generate() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
desolveMessyCode();
JFreeChart chart = createChart();
ChartUtilities.writeChartAsPNG(baos, chart, model.getWidth(), model.getHeight());
baos.close();
} catch (IOException e) {
throw new IOException("Image create exception.", e);
}
return baos.toByteArray();
}
@Override @Override
public void fillData() public void fillData() {
{ Map<?, ?> data = getModel().getDatas();
Map<?, ?> data = getModel().getDatas(); if (null != data) {
if (null != data) for (Map.Entry<?, ?> entry : data.entrySet()) {
for (Map.Entry<?, ?> entry : data.entrySet()) fillSingleData(entry);
fillSingleData(entry); }
} }
}
protected boolean isNumeric(Object o) protected boolean isNumeric(Object o) {
{ return o instanceof Integer || o instanceof Double || o instanceof Float;
return o instanceof Integer || o instanceof Double || o instanceof Float; }
}
protected boolean isNumericArray(Object o) protected boolean isNumericArray(Object o) {
{ return o instanceof Integer[] || o instanceof Double[] || o instanceof Float[];
return o instanceof Integer[] || o instanceof Double[] || o instanceof Float[]; }
}
protected abstract void fillSingleData(Map.Entry<?, ?> entry); protected abstract void fillSingleData(Map.Entry<?, ?> entry);
protected abstract JFreeChart createChart(); protected abstract JFreeChart createChart();
private void desolveMessyCode() private void desolveMessyCode() {
{ StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
StandardChartTheme standardChartTheme = new StandardChartTheme("CN"); String font = "宋体";
String font="宋体"; // 设置标题字体
// 设置标题字体 standardChartTheme.setExtraLargeFont(new Font(font, Font.PLAIN, 20));
standardChartTheme.setExtraLargeFont(new Font(font, Font.PLAIN, 20)); // 设置图例的字体
// 设置图例的字体 standardChartTheme.setRegularFont(new Font(font, Font.PLAIN, 12));
standardChartTheme.setRegularFont(new Font(font, Font.PLAIN, 12)); // 设置轴向的字体
// 设置轴向的字体 standardChartTheme.setLargeFont(new Font(font, Font.PLAIN, 12));
standardChartTheme.setLargeFont(new Font(font, Font.PLAIN, 12)); // 应用主题样式
// 应用主题样式 ChartFactory.setChartTheme(standardChartTheme);
ChartFactory.setChartTheme(standardChartTheme); }
}
} }
...@@ -4,30 +4,23 @@ import org.apache.commons.lang.reflect.ConstructorUtils; ...@@ -4,30 +4,23 @@ import org.apache.commons.lang.reflect.ConstructorUtils;
/** /**
* @author hujun * @author hujun
* * <p>
* 图表生成器工厂 * 图表生成器工厂
*/ */
public class ChartFactory public class ChartFactory {
{ public static final String CHART_IMPL_PACKAGE = "com.brilliance.eibs.core.service.chart.impl";
public static final String CHART_IMPL_CLASS_SUFFIX = "ChartBuilder";
public static final String CHART_IMPL_PACKAGE = "com.brilliance.eibs.core.service.chart.impl"; public static IChartBuilder produce(String type, ChartModel model) {
public static final String CHART_IMPL_CLASS_SUFFIX = "ChartBuilder"; try {
Class<?> clazz = Class.forName(CHART_IMPL_PACKAGE + "." + firstLetterUpper(type) + CHART_IMPL_CLASS_SUFFIX);
public static IChartBuilder produce(String type, ChartModel model) return (IChartBuilder) ConstructorUtils.invokeConstructor(clazz, new Object[]{model});
{ } catch (Exception e) {
try throw new IllegalArgumentException("Get a " + type.toLowerCase() + " chart generator failure.", e);
{ }
Class<?> clazz = Class.forName(CHART_IMPL_PACKAGE + "." + firstLetterUpper(type) + CHART_IMPL_CLASS_SUFFIX);
return (IChartBuilder) ConstructorUtils.invokeConstructor(clazz, new Object[]{model});
}
catch (Exception e)
{
throw new IllegalArgumentException("Get a " + type.toLowerCase() + " chart generator failure.", e);
} }
}
private static String firstLetterUpper(String s) private static String firstLetterUpper(String s) {
{ return s.replaceFirst(s.substring(0, 1), s.substring(0, 1).toUpperCase());
return s.replaceFirst(s.substring(0, 1), s.substring(0, 1).toUpperCase()); }
}
} }
...@@ -4,70 +4,58 @@ import java.util.Map; ...@@ -4,70 +4,58 @@ import java.util.Map;
/** /**
* @author hujun * @author hujun
* * <p>
* 图表数据模型 * 图表数据模型
*/ */
public class ChartModel public class ChartModel {
{ private String title;
private String title; private String[] label;
private String[] label; private int height = 280;
private int height = 280; private int width = 500;
private int width = 500; private Map<?, ?> datas;
private Map<?, ?> datas;
public ChartModel(String title) {
public ChartModel( String title ) this.title = title;
{ }
this.title = title;
} public int getHeight() {
return height;
public int getHeight() }
{
return height; public void setHeight(int height) {
} this.height = height;
}
public void setHeight(int height)
{ public int getWidth() {
this.height = height; return width;
} }
public int getWidth() public void setWidth(int width) {
{ this.width = width;
return width; }
}
public Map<?, ?> getDatas() {
public void setWidth(int width) return datas;
{ }
this.width = width;
} public String getTitle() {
return title;
public Map<?, ?> getDatas() }
{
return datas; public void setTitle(String title) {
} this.title = title;
}
public String getTitle()
{ public String[] getLabel() {
return title; return label;
} }
public void setTitle(String title) public void setLabel(String[] label) {
{ this.label = label;
this.title = title; }
}
public void setDatas(Map<?, ?> datas) {
public String[] getLabel() this.datas = datas;
{ }
return label;
}
public void setLabel(String[] label)
{
this.label = label;
}
public void setDatas(Map<?, ?> datas)
{
this.datas = datas;
}
} }
...@@ -4,13 +4,11 @@ import java.io.IOException; ...@@ -4,13 +4,11 @@ import java.io.IOException;
/** /**
* @author hujun * @author hujun
* * <p>
* 图表生成器接口 * 图表生成器接口
*/ */
public interface IChartBuilder public interface IChartBuilder {
{ byte[] generate() throws IOException;
byte[] generate()
throws IOException;
void fillData(); void fillData();
} }
...@@ -4,7 +4,6 @@ import com.brilliance.eibs.core.service.chart.BaseChartBuilder; ...@@ -4,7 +4,6 @@ import com.brilliance.eibs.core.service.chart.BaseChartBuilder;
import com.brilliance.eibs.core.service.chart.ChartModel; import com.brilliance.eibs.core.service.chart.ChartModel;
import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart; import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.category.CategoryItemRenderer;
...@@ -12,56 +11,47 @@ import org.jfree.data.category.DefaultCategoryDataset; ...@@ -12,56 +11,47 @@ import org.jfree.data.category.DefaultCategoryDataset;
import java.util.Map.Entry; import java.util.Map.Entry;
public class BarChartBuilder public class BarChartBuilder extends BaseChartBuilder {
extends BaseChartBuilder
{
private DefaultCategoryDataset dataset = new DefaultCategoryDataset(); private DefaultCategoryDataset dataset = new DefaultCategoryDataset();
public BarChartBuilder( ChartModel model ) public BarChartBuilder(ChartModel model) {
{ super(model);
super(model); fillData();
fillData();
}
@Override
protected JFreeChart createChart()
{
String[] labels = getModel().getLabel();
JFreeChart localJFreeChart = ChartFactory.createBarChart3D(getModel().getTitle(), labels != null && labels.length >= 1 ? labels[0]
: null, labels != null && labels.length == 2 ? labels[1] : null, dataset);
CategoryPlot localCategoryPlot = (CategoryPlot) localJFreeChart.getPlot();
CategoryAxis localCategoryAxis = localCategoryPlot.getDomainAxis();
// localCategoryAxis.setTickLabelFont(new Font("宋体",Font.BOLD, 20));
//localCategoryAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(0.3926990816987241D));
CategoryItemRenderer localCategoryItemRenderer = localCategoryPlot.getRenderer();
localCategoryItemRenderer.setBaseItemLabelsVisible(true);
BarRenderer localBarRenderer = (BarRenderer) localCategoryItemRenderer;
localBarRenderer.setItemMargin(0.2D);
return localJFreeChart;
}
@Override
protected void fillSingleData(Entry<?, ?> entry)
{
Object value = entry.getValue();
Object key = entry.getKey();
if (!isNumeric(value) || !(key instanceof String[] || key instanceof String))
throw new IllegalArgumentException("Data type of bar chart is wrong.");
if (key instanceof String)
{
String category = key == null ? "" : (String) key;
dataset.addValue(Double.valueOf(value.toString()), "", category);
} }
if (key instanceof String[])
{ @Override
String[] category = (String[]) key; protected JFreeChart createChart() {
if (category.length != 2) String[] labels = getModel().getLabel();
throw new IllegalArgumentException("Data number of bar chart is wrong."); JFreeChart localJFreeChart = ChartFactory.createBarChart3D(getModel().getTitle(), labels != null && labels.length >= 1 ? labels[0]
dataset.addValue(Double.valueOf(value.toString()), category[1] == null ? "" : category[1], category[0] == null ? "" : category[0]); : null, labels != null && labels.length == 2 ? labels[1] : null, dataset);
CategoryPlot localCategoryPlot = (CategoryPlot) localJFreeChart.getPlot();
CategoryItemRenderer localCategoryItemRenderer = localCategoryPlot.getRenderer();
localCategoryItemRenderer.setBaseItemLabelsVisible(true);
BarRenderer localBarRenderer = (BarRenderer) localCategoryItemRenderer;
localBarRenderer.setItemMargin(0.2D);
return localJFreeChart;
} }
} @Override
protected void fillSingleData(Entry<?, ?> entry) {
Object value = entry.getValue();
Object key = entry.getKey();
if (!isNumeric(value) || !(key instanceof String[] || key instanceof String)) {
throw new IllegalArgumentException("Data type of bar chart is wrong.");
}
if (key instanceof String) {
String category = key == null ? "" : (String) key;
dataset.addValue(Double.valueOf(value.toString()), "", category);
}
if (key instanceof String[]) {
String[] category = (String[]) key;
if (category.length != 2) {
throw new IllegalArgumentException("Data number of bar chart is wrong.");
}
dataset.addValue(Double.valueOf(value.toString()), category[1] == null ? "" : category[1], category[0] == null ? "" : category[0]);
}
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment