Commit 8ccb5c73 by s_guodong

init

parents
/.idea/
/target/
File added
File added
This diff is collapsed. Click to expand it.
package com.brilliance.eibs.core.service.chart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
public abstract class BaseChartBuilder
implements IChartBuilder
{
private ChartModel model;
public BaseChartBuilder( ChartModel model )
{
this.model = model;
}
protected ChartModel getModel()
{
return model;
}
protected void setModel(ChartModel model)
{
this.model = model;
}
@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
public void fillData()
{
Map<?, ?> data = getModel().getDatas();
if (null != data)
for (Map.Entry<?, ?> entry : data.entrySet())
fillSingleData(entry);
}
protected boolean isNumeric(Object o)
{
return o instanceof Integer || o instanceof Double || o instanceof Float;
}
protected boolean isNumericArray(Object o)
{
return o instanceof Integer[] || o instanceof Double[] || o instanceof Float[];
}
protected abstract void fillSingleData(Map.Entry<?, ?> entry);
protected abstract JFreeChart createChart();
private void desolveMessyCode()
{
StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
String font="宋体";
// 设置标题字体
standardChartTheme.setExtraLargeFont(new Font(font, Font.PLAIN, 20));
// 设置图例的字体
standardChartTheme.setRegularFont(new Font(font, Font.PLAIN, 12));
// 设置轴向的字体
standardChartTheme.setLargeFont(new Font(font, Font.PLAIN, 12));
// 应用主题样式
ChartFactory.setChartTheme(standardChartTheme);
}
}
package com.brilliance.eibs.core.service.chart;
import org.apache.commons.lang.reflect.ConstructorUtils;
/**
* @author hujun
*
* 图表生成器工厂
*/
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 IChartBuilder produce(String type, ChartModel model)
{
try
{
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)
{
return s.replaceFirst(s.substring(0, 1), s.substring(0, 1).toUpperCase());
}
}
package com.brilliance.eibs.core.service.chart;
import java.util.Map;
/**
* @author hujun
*
* 图表数据模型
*/
public class ChartModel
{
private String title;
private String[] label;
private int height = 280;
private int width = 500;
private Map<?, ?> datas;
public ChartModel( String title )
{
this.title = title;
}
public int getHeight()
{
return height;
}
public void setHeight(int height)
{
this.height = height;
}
public int getWidth()
{
return width;
}
public void setWidth(int width)
{
this.width = width;
}
public Map<?, ?> getDatas()
{
return datas;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String[] getLabel()
{
return label;
}
public void setLabel(String[] label)
{
this.label = label;
}
public void setDatas(Map<?, ?> datas)
{
this.datas = datas;
}
}
package com.brilliance.eibs.core.service.chart;
import java.io.IOException;
/**
* @author hujun
*
* 图表生成器接口
*/
public interface IChartBuilder
{
byte[] generate()
throws IOException;
void fillData();
}
package com.brilliance.eibs.core.service.chart.impl;
import com.brilliance.eibs.core.service.chart.BaseChartBuilder;
import com.brilliance.eibs.core.service.chart.ChartModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import java.util.Map.Entry;
public class BarChartBuilder
extends BaseChartBuilder
{
private DefaultCategoryDataset dataset = new DefaultCategoryDataset();
public BarChartBuilder( ChartModel model )
{
super(model);
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[])
{
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]);
}
}
}
package com.brilliance.eibs.core.service.chart.impl;
import com.brilliance.eibs.core.service.chart.BaseChartBuilder;
import com.brilliance.eibs.core.service.chart.ChartModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import java.util.List;
import java.util.Map.Entry;
public class LineChartBuilder
extends BaseChartBuilder
{
private XYSeriesCollection collection = new XYSeriesCollection();
public LineChartBuilder( ChartModel model )
{
super(model);
fillData();
}
@Override
protected JFreeChart createChart()
{
String[] labels = getModel().getLabel();
JFreeChart localJFreeChart = ChartFactory.createXYLineChart(getModel().getTitle(), labels != null && labels.length >= 1 ? labels[0]
: null, labels != null && labels.length == 2 ? labels[1] : null, collection, PlotOrientation.VERTICAL, true, true, false);
XYPlot localXYPlot = (XYPlot) localJFreeChart.getPlot();
localXYPlot.setDomainPannable(true);
localXYPlot.setRangePannable(true);
XYLineAndShapeRenderer localXYLineAndShapeRenderer = (XYLineAndShapeRenderer) localXYPlot.getRenderer();
localXYLineAndShapeRenderer.setBaseShapesVisible(true);
localXYLineAndShapeRenderer.setBaseShapesFilled(true);
NumberAxis localNumberAxis = (NumberAxis) localXYPlot.getRangeAxis();
localNumberAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
return localJFreeChart;
}
@Override
protected void fillSingleData(Entry<?, ?> entry)
{
Object value = entry.getValue();
Object key = entry.getKey();
if (!(value instanceof List) || !(key instanceof String))
throw new IllegalArgumentException("Data type of broken line chart is wrong.");
List<?> points = (List<?>) value;
XYSeries localXYSeries = new XYSeries((String) key);
for (Object p : points)
{
if (!isNumericArray(p))
throw new IllegalArgumentException("Data type of broken line chart is wrong.");
Object[] point = (Object[]) p;
if (point.length != 2)
throw new IllegalArgumentException("Data number of broken line chart is wrong.");
localXYSeries.add(Double.valueOf(point[0].toString()), Double.valueOf(point[1].toString()));
}
collection.addSeries(localXYSeries);
}
}
package com.brilliance.eibs.core.service.chart.impl;
import com.brilliance.eibs.core.service.chart.BaseChartBuilder;
import com.brilliance.eibs.core.service.chart.ChartModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.util.Rotation;
import java.util.Map.Entry;
public class PieChartBuilder
extends BaseChartBuilder
{
private DefaultPieDataset dataset = new DefaultPieDataset();
public PieChartBuilder( ChartModel model )
{
super(model);
fillData();
}
@Override
protected JFreeChart createChart()
{
JFreeChart localJFreeChart = ChartFactory.createPieChart3D(getModel().getTitle(), dataset, true, true, false);
PiePlot3D localPiePlot3D = (PiePlot3D) localJFreeChart.getPlot();
localPiePlot3D.setDarkerSides(true);
localPiePlot3D.setStartAngle(290.0D);
localPiePlot3D.setDirection(Rotation.CLOCKWISE);
localPiePlot3D.setForegroundAlpha(0.5F);
localPiePlot3D.setNoDataMessage("No data to display");
return localJFreeChart;
}
@Override
protected void fillSingleData(Entry<?, ?> entry)
{
Object value = entry.getValue();
Object key = entry.getKey();
if (!isNumeric(value) || !(key instanceof String))
throw new IllegalArgumentException("Data type of pie chart is wrong.");
dataset.setValue((String) key, Double.valueOf(value.toString()));
}
}
package com.brilliance.eibs.core.service.esearch;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class ElasticSearchHandler
{
private Client client;
private Logger logger;
private BulkRequestBuilder bulkRequestBuilder;
public BulkRequestBuilder getBulkRequestBuilder()
{
return bulkRequestBuilder;
}
public void setBulkRequestBuilder()
{
this.bulkRequestBuilder = client.prepareBulk();
}
public Client getClient()
{
return client;
}
public void setClient(Client client)
{
this.client = client;
}
public ElasticSearchHandler(String ipAddress, Logger logger )
{
// 集群连接超时设置
/*
* Settings settings =
* ImmutableSettings.settingsBuilder().put("client.transport.ping_timeout"
* , "10s").build(); client = new TransportClient(settings);
*/
client = new TransportClient().addTransportAddress(new InetSocketTransportAddress(ipAddress, 9300));
//client.prepareSearch("user").setTypes("tb_person0", "tb_person1", "tb_person2", "tb_person3", "tb_person4").setQuery(QueryBuilders.filteredQuery("name", "张三")).setFilter(FilterBuilders.rangeFilter("age").from(20).to(22));
// SearchRequestBuilder searchbuilder1=client.prepareSearch("user").setTypes("tb_person0", "tb_person1", "tb_person2", "tb_person3", "tb_person4");
setBulkRequestBuilder();
this.logger = logger;
}
public String toJsonData(Map<String, Object> map)
{
String jsonData = null;
try
{
// 使用XContentBuilder创建json数据
XContentBuilder jsonBuild = XContentFactory.jsonBuilder();
jsonBuild.startObject();
for (String key : map.keySet())
{
jsonBuild.field(key, map.get(key));
}
jsonBuild.endObject();
jsonData = jsonBuild.string();
logger.debug("store data=" + jsonData);
}
catch (IOException e)
{
e.printStackTrace();
}
return jsonData;
}
public void commit()
{
bulkRequestBuilder.execute().actionGet();
// bulkRequestBuilder.setRefresh(true);
}
public void close()
{
if (client != null)
client.close();
}
/**
* 建立索引,索引建立好之后,会在elasticsearch-0.20.6\data\elasticsearch\nodes\0创建所以你看
*
* @param indexName
* 为索引库名,一个es集群中可以有多个索引库。名称必须为小写
* @param indexType
* Type为索引类型,是用来区分同索引库下不同类型的数据的,一个索引库下可以有多个索引类型。
* @param jsondata
* json格式的数据集合
* @return
*/
public void createIndexResponse(String indexname, String type, String index, String jsondata)
{
// 创建索引库需要注意的是.setRefresh(true)这里一定要设置,否则第一次建立索引查找不到数据
// IndexRequestBuilder requestBuilder = client.prepareIndex(indexname,
// type).setRefresh(true);
bulkRequestBuilder.add(client.prepareIndex(indexname, type, index).setRefresh(true).setSource(jsondata));
// client.prepareIndex(indexname, type, index).setRefresh(true).setSource(jsondata).execute().actionGet();
}
public void updatebyIndex(String indexname, String type, String id,List<String[]> list)
throws IOException, InterruptedException, ExecutionException
{
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(indexname);
updateRequest.type(type);
updateRequest.id(id);
// updateRequest.doc(XContentFactory.jsonBuilder().startObject().field("name", "银花感冒颗粒").endObject()).refresh(true);
//client.update(updateRequest).get();
XContentBuilder xContentBuilder =XContentFactory.jsonBuilder().startObject();
for (int i = 0; i < list.size(); i++)
{
String []str=list.get(i);
xContentBuilder.field(str[0],str[1]);
}
updateRequest.doc(xContentBuilder.endObject()).refresh(true);
client.update(updateRequest).get();;
}
public void deleteByIndex(String indexname, String type, String id)
{
client.prepareDelete(indexname, type, id).execute().actionGet();
}
/**
* 创建索引
*
* @param client
* @param jsondata
* @return
*/
public IndexResponse createIndexResponse(String indexname, String type, String jsondata)
{
IndexResponse response = client.prepareIndex(indexname, type).setSource(jsondata).execute().actionGet();
return response;
}
/**
* 执行搜索
*
* @param queryBuilder
* @param indexname
* @param type
* @return
*/
public List<Map<String, Object>> searcher(List<String> tagList, SearchRequestBuilder searchbuilder)
{
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
SearchResponse searchResponse = searchbuilder.execute().actionGet();
SearchHits hits = searchResponse.getHits();
logger.info("查询到记录数=" + hits.getTotalHits());
SearchHit[] searchHists = hits.getHits();
if (searchHists.length > 0)
{
for (SearchHit hit : searchHists)
{
Map<String, Object> map = new HashMap<String, Object>();
for (int j = 0; j < tagList.size(); j++)
{
String key = tagList.get(j);
Object obj = hit.getSource().get(key);
map.put(key, obj);
}
list.add(map);
}
}
return list;
}
}
\ No newline at end of file
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.service.Context;
public class APIConnection
extends AbsConnection
{
/**
* API接入
**/
@Override
public void execute(Context context)
{
logger.info(LOG_FLAG + "APIConnection is running.");
context.setCurrentInstance(this);
logger.info(LOG_FLAG + "APIConnection has finished to run.");
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
public class APIFilter extends AbsFilter {
/**
* APIFilter用于API接入方式数据的处理,类似CommandConnetion和StringArrayFilter
* **/
@Override
public void execute(Context context) {
// logger.info( LOG_FLAG + "APIFIlter is running." + LOG_FLAG);
context.setCurrentInstance(this);
super.execute(context);
// logger.info( LOG_FLAG + "APIFIlter has finished running." +
// LOG_FLAG);
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
// TODO Auto-generated method stub
return null;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.lsocket.AliveClient;
/**
* @author gechengyang socket客户端长连接
* **/
public class AliveSocketConnection extends AbsConnection {
@Override
public void execute(Context context) {
logger.info( "Running SocketClientConnection.");
context.setCurrentInstance(this);
super.execute(context);
setTimeOut();
AliveClient aclient = null;
try {
setTimeOut();
String ip = getPropertyValue(IP_SYMBOL);
int port = getPropertyValueInt(PORT_SYMBOL);
String heartbeat = getPropertyValue(HEAR_BEAT, true);
String content = (String) context.getObject();
aclient = AliveClient.getInstance(ip, port, connectTimeout, logger);
aclient.setHeartbeart(heartbeat);
aclient.put(content);
} catch (Exception e) {
throw new InterfaceException("00014", "SocketClientConnection exception occurs.", e);
}
logger.info( "SocketClientConnection is finished.");
}
/**
* 设置超时时间,包括连接超时,返回超时
*/
protected void setTimeOut() {
setConnectTimeOut();
}
/**
* 获取连接超时时间,如果为空,则使用默认时间
*/
protected void setConnectTimeOut() {
int connectTimeout = getPropertyValueInt(CONNECT_TIMEOUT_SYMBOL, true);
if (connectTimeout != 0) {
this.connectTimeout = connectTimeout;
}
logger.debug( "Connect timeout = " + this.connectTimeout);
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.ResultMsg;
import com.brilliance.eibs.core.threadpool.ThreadPoolFactory;
import com.brilliance.eibs.main.client.CallableClient;
import org.apache.commons.io.IOUtils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class BatchFilter extends AbsFilter {
@Override
public void execute(Context context) {
// logger.info( LOG_FLAG + "BatchFiter[批处理] is running." +
// LOG_FLAG);
propertySaveToContext();
String threadnumStr = (String) context.getVariable("threadnum");
String linesStr = (String) context.getVariable("lines");
String interfaceName = (String) context.getVariable("call_interface");
String transactionName = (String) context.getVariable("call_transaction");
int threadNum = Integer.parseInt(threadnumStr);
int eachReadLine = Integer.parseInt(linesStr);
List<String> contentList;
Object object = context.getObject();
if (object instanceof List) {
contentList = (List<String>) object;
} else {
String filepath = (String) context.getVariable("filepath");
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
contentList = IOUtils.readLines(fis);
} catch (FileNotFoundException e) {
throw new InterfaceException("00601", "file [" + filepath + "] not found.", e);
} catch (IOException e) {
throw new InterfaceException("00602", "file [" + filepath + "] read error.", e);
} finally {
if (fis != null)
IOUtils.closeQuietly(fis);
}
}
String execName = "batchFilter_" + interfaceName + "_" + transactionName;
ExecutorService exec = ThreadPoolFactory.getFixedExecutor(threadNum, execName);
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, context }));
count++;
resultMsgList.add(futureResultMsg);
}
context.setObject(resultMsgList);
// exec.shutdown();
ThreadPoolFactory.shutdown(execName);
// logger.info( LOG_FLAG +
// "BatchFiter[批处理] wish to finish running" + LOG_FLAG);
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
return null;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.ResultMsg;
import com.brilliance.eibs.core.threadpool.ThreadPoolFactory;
import com.brilliance.eibs.main.client.CallableClient;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class BatchFilter2 extends AbsFilter {
@Override
public void execute(Context context) {
// logger.info( LOG_FLAG + "BatchFiter[批处理] is running." +
// LOG_FLAG);
// System.out.println(new Date().getMinutes() + ":" + new
// Date().getTime());
propertySaveToContext();
String threadnumStr = (String) context.getVariable("threadnum");
String linesStr = (String) context.getVariable("lines");
String interfaceName = (String) context.getVariable("call_interface");
String transactionName = (String) context.getVariable("call_transaction");
String filepath = (String) context.getVariable("filepath");
int threadNum = Integer.parseInt(threadnumStr);
int eachReadLine = Integer.parseInt(linesStr);
File f = new File(filepath);
String execName = "batchFilter2_" + interfaceName + "_" + transactionName;
ExecutorService exec = ThreadPoolFactory.getFixedExecutor(threadNum, execName);
// 文件总行数
int lineCount = getLinesOfFile(f);
// 记录文件当前行数
int curLine = 1;
List<Future<ResultMsg>> resultMsgList = new ArrayList<Future<ResultMsg>>();
while (curLine <= lineCount) {
int endLine = curLine + eachReadLine;
int subThreadReadCount = eachReadLine;
if (endLine > lineCount)
subThreadReadCount = lineCount - curLine + 1;
Future<ResultMsg> futureResultMsg = exec.submit(new CallableClient(interfaceName, transactionName, new Object[] { filepath, curLine,
subThreadReadCount }));
curLine = endLine;
resultMsgList.add(futureResultMsg);
}
context.setObject(resultMsgList);
// exec.shutdown();
ThreadPoolFactory.shutdown(execName);
/*
* propertySaveToContext(); String threadnumStr = (String)
* context.getVariable("threadnum"); String linesStr = (String)
* context.getVariable("lines"); String interfaceName = (String)
* context.getVariable("call_interface"); String transactionName =
* (String) context.getVariable("call_transaction"); int threadNum =
* Integer.parseInt(threadnumStr); int eachReadLine =
* Integer.parseInt(linesStr); List<String> contentList; Object object =
* context.getObject(); if (object instanceof List) { contentList =
* (List<String>) object; } else { String filepath = (String)
* context.getVariable("filepath"); try { contentList =
* IOUtils.readLines(new FileInputStream(filepath)); } catch
* (FileNotFoundException e) { throw new InterfaceException("00601",
* "file [" + filepath + "] not found.", e); } catch (IOException e) {
* 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 +
// "BatchFiter[批处理] wish to finish running" + LOG_FLAG);
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
return null;
}
/**
* 快速计算文件的行数
* **/
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;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.StringUtil;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.List;
/**
* JavaBean格式处理
*
* @author xiaoyuanzhen
*
*/
public class BeanFilter extends AbsFilter {
private Class<?> typeClass;
private Object object;
public void execute(Context context) {
// logger.info( LOG_FLAG + "BeanFilter is begining to runnig." +
// LOG_FLAG);
context.setCurrentInstance(this);
String type = getFilterDef().getType();
if (type.equals("out")) {
// logger.info( LOG_FLAG + "BeanFilter组装" + LOG_FLAG);
String classname = getRequiredPropertyValue("classname");
try {
// typeClass = ClassPathUpdater.dynamicLoadClass(classname);
typeClass = Class.forName(classname);
} catch (Exception e) {
throw new InterfaceException("00701", "class [" + classname + "] not found.", e);
}
try {
object = typeClass.newInstance();
} catch (Exception e) {
throw new InterfaceException("00702", "create instance of class [" + typeClass + "] error.", e);
}
}
super.execute(context);
if (type.equals("out")) {
context.setObject(object);
// saveToContext(filterDef.getScope(), filterDef.getTag(), object);
} else {
// logger.info( LOG_FLAG + "BeanFilter解析" + LOG_FLAG);
}
// logger.info( LOG_FLAG + "BeanFilter has finished running." +
// LOG_FLAG);
}
@Override
protected void packField(IFieldDef fieldDef, Object fieldValue) {
fieldValue = dealValueByType(fieldValue, fieldDef.getType());
String etag = (String) elParser.getExPression(context, fieldDef.getEtag(), null);
if (StringUtil.isEmpty(etag))
return;
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(typeClass);
} catch (Exception e) {
throw new InterfaceException("00703", "get beaninfo of class [" + typeClass + "] error.", e);
}
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
int j = 0;
for (; j < propertyDescriptors.length; j++) {
PropertyDescriptor descriptor = propertyDescriptors[j];
String propertyName = descriptor.getName();
if (propertyName.equals(etag)) {
Object[] args = new Object[1];
args[0] = fieldValue;
if (args[0] == null) {
continue;
}
logger.debug( "pack property:[" + propertyName + "],value:[" + args[0] + "]");
try {
if (fieldValue instanceof List && "add".equals(context.getVariable("handle_list"))) {
List<Object> list = (List<Object>) descriptor.getReadMethod().invoke(object, (Object[]) null);
if (list != null)
list.addAll((List<Object>) fieldValue);
} else
descriptor.getWriteMethod().invoke(object, args);
} catch (Exception e) {
throw new InterfaceException("00704", "write property [" + propertyName + "] error", e);
}
break;
}
}
if (j >= propertyDescriptors.length)
throw new InterfaceException("00707", "property [" + etag + "] of class [" + typeClass + "] not exists.");
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
String etag = (String) elParser.getExPression(context, fieldDef.getEtag(), null);
try {
return elParser.getExPression(context, "${this." + etag + "}", null);
} catch (Exception e) {
throw new InterfaceException("00706", "get bean value [" + etag + "]error.", e);
}
}
}
/**
*
*/
package com.brilliance.eibs.core.service.instance.impl;
import cmdsimix.client.core.ImixApplication;
import cmdsimix.client.core.ImixSession;
import cmdsimix.client.core.ImixSessionExistingException;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.imix.CMDSClientListener;
import com.brilliance.eibs.imix.Reconnect;
import com.brilliance.eibs.util.LogUtil;
import imix.ConfigError;
import imix.field.SubscriptionRequestType;
import imix.imix10.MarketDataRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author gechengyang
*
*/
public class CMDSListenerConnection extends AbsConnection {
private ImixSession imixSession = null;
private String username;
private String password;
private String market;
private boolean isLogon = false;
public Date createDate(String time) {
Date result = null;
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
StringBuffer sb = new StringBuffer();
sb.append("" + year);
if (month < 10)
sb.append("0" + month);
else
sb.append(month);
if (day < 10)
sb.append("0" + day);
else
sb.append(day);
sb.append(time + "00");
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
try {
result = df.parse(sb.toString());
} catch (Exception e) {
logger.error("the time of session close error", e);
}
return result;
}
public void stopSession() {
int a = 0;
if (imixSession != null) {
logger.info("now to stop on ImixSession................................");
try {
imixSession.stop();
ImixApplication.stop();
} catch (Exception e) {
a = 1;
// ImixApplication.getLogger().warn("stop imixApp error.", e);
}
isLogon = false;
}
logger.info("[" + new Date() + "]Current Process is Exited.");
System.exit(a);
}
public void checkImixSessionStarted() {
logger.info("imixSession is not Started,try to connect again");
if (imixSession != null && (!imixSession.isStarted())) {
new Reconnect(imixSession, LogUtil.getLogger(context)).reconnect();
}
}
public void createImixSession() {
try {
imixSession = new ImixSession(username, password, market);
} catch (ConfigError e) {
logger.error("config error:", e);
throw new InterfaceException("03201", "ConfigError.", e);
} catch (ImixSessionExistingException e) {
logger.error("ImixSessionExistingException error:", e);
throw new InterfaceException("03201", "ImixSessionExistingException error", e);
}
}
@Override
public void execute(Context context) {
context.setCurrentInstance(this);
String path = getPropertyValue("path");
String market = getPropertyValue("market");
this.market = market;
String userName = getPropertyValue("UserName");
this.username = userName;
String password = getPropertyValue("password");
this.password = password;
String startTime = getPropertyValue("startTime");
String endTime = getPropertyValue("endTime");
String interfaceName = getPropertyValue("interfaceName");
String transactionName = getPropertyValue("transactionName");
SimpleDateFormat timeformate = new SimpleDateFormat("HHmm");
String curTime = timeformate.format(new Date());
// int startFlag = curTime.compareTo(startTime); // 需要当前时间大于开始时间,标志大于0
int stopFlag = curTime.compareTo(endTime); // 需要当前时间小于结束时间,标志小于0
/*
* if (startFlag < 0) { logger.info("非实时汇率工作时间,小于开始时间" + startTime);
* return; }
*/
if (stopFlag > 0) {
logger.info("非实时汇率工作时间,大于停止时间" + endTime);
return;
}
// 注册一个定时器,在结束时间将session关掉,退出当前进程
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
stopSession();
}
}, createDate(endTime));
// 检查当前imixSession是否为启动
Timer timer2 = new Timer();
timer2.schedule(new TimerTask() {
@Override
public void run() {
checkImixSessionStarted();
}
}, 60000, 60000);
try {
CMDSClientListener listener = new CMDSClientListener(Thread.currentThread(), context, LogUtil.getLogger(context), interfaceName,
transactionName);
ImixApplication.initialize(listener, path);
createImixSession();
// 启动后验证后,发送广播(broadcastRequest)和刷新请求(refreshRequest)后就不要在停止。会15分钟推送报文过来
isLogon = imixSession.isStarted();
if (!isLogon && Boolean.valueOf(getPropertyValue("mac")))
isLogon = imixSession.start();
logger.info("imixSession= " + imixSession.isStarted());
if (isLogon) {
logger.info("now send broadcast request after logon...............................");
MarketDataRequest broadcastRequest = new MarketDataRequest();
broadcastRequest.set(new SubscriptionRequestType(SubscriptionRequestType.BROADCAST_REQUEST));// 3
imixSession.send(broadcastRequest);
logger.info("now send refresh request ...............................");
MarketDataRequest refreshRequest = new MarketDataRequest();
refreshRequest.set(new SubscriptionRequestType(SubscriptionRequestType.PRICE_DATA_FULL_IMAGE_REFRESH_REQUEST));// 4
imixSession.send(refreshRequest);
}
/*
* if (isLogon == false) { Thread.currentThread().interrupt(); }
* Thread.currentThread().join(); try { ImixApplication.stop(); }
* catch (Exception e) {
* ImixApplication.getLogger().warn("stop imixApp error.", e); }
*/
long sleepTime = createDate(endTime).getTime() - createDate(startTime).getTime();
Thread.sleep(sleepTime);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.chart.ChartFactory;
import com.brilliance.eibs.core.service.chart.ChartModel;
import com.brilliance.eibs.core.service.chart.IChartBuilder;
import java.util.Map;
public class ChartFilter
extends AbsFilter
{
@Override
public void execute(Context context)
{
logger.info(LOG_FLAG + "ChartFilter is running." + LOG_FLAG);
context.setCurrentInstance(this);
propertySaveToContext();
super.execute(context);
try
{
String type = (String) context.getVariable("type");
IChartBuilder builder = ChartFactory.produce(type, buildModel(type, context));
context.setObject(builder.generate());
}
catch (Exception e)
{
throw new InterfaceException("03201", "Build chart failed.", e);
}
logger.info(LOG_FLAG + "ChartFilter is finished." + LOG_FLAG);
}
private ChartModel buildModel(String type, Context context)
{
Object title = context.getVariable("title");
Object label = context.getVariable("label");
Object height = context.getVariable("height");
Object width = context.getVariable("width");
Object data = context.getVariable("data");
ChartModel model = new ChartModel(title != null ? (String) title : null);
if (null != label)
{
String[] labels = ((String) label).split(",");
model.setLabel(labels);
}
if (null != data)
model.setDatas((Map<?, ?>) data);
if (null != height)
model.setHeight(Integer.valueOf(height.toString()));
if (null != width)
model.setWidth(Integer.valueOf(width.toString()));
return model;
}
@Override
public Object getFieldValue(IFieldDef fieldDef)
throws Exception
{
return null;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.model.IModuleDef;
import com.brilliance.eibs.core.module.ISO8583Module;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.ByteUtil;
import com.brilliance.eibs.util.StringUtil;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* 8583格式处理
*
* @author xiaoyuanzhen
*
*/
public class Class8583Filter extends AbsFilter {
private String direction;
private List<String> bitmaplist = new ArrayList<String>();
String encoding = null;
ISO8583Module iso8583Module = null;
IModuleDef moduleDef = null;
byte subbyts[] = null;
String controlInfo = "";
String varInfos = "";
public void execute(Context context) {
try {
encoding = getFilterDef().getEncoding();
String type = getFilterDef().getType();
// logger.info( LOG_FLAG +
// "Mac8583Filter is begining to runnig." + LOG_FLAG);
context.setCurrentInstance(this);
propertySaveToContext();
String id = (String) context.getVariable("moduleid");
moduleDef = context.getModulesMap().get(id);
/*
* if ("in".equals(getFilterDef().getType())) { iso8583Module = new
* ISO8583Module(encoding, context.getObject(), moduleDef); }
*/
super.execute(context);
if (type.equals("out")) {
// logger.info( LOG_FLAG + "Mac8583Filter组装" +
// LOG_FLAG);
int bitmapsize = Integer.parseInt((String) context.getVariable("bitmapsize"));
if (bitmapsize == 0) {
context.setObject(controlInfo);
logger.info( "sub controlInfo=" + controlInfo);
return;
}
byte[] bitmap = new byte[bitmapsize];
for (int i = 0; i < bitmapsize; i++) {
bitmap[i] = 0x00;
}
for (int index = 0; index < bitmaplist.size(); index++) {
String etag = bitmaplist.get(index);
int sequence = Integer.parseInt(etag);
setBitmap(sequence, bitmap, true);
}
// 获取controlInfo长度
int controlLen = controlInfo.length();
int controlSize = controlLen % 8 == 0 ? controlLen / 8 : (controlLen / 8 + 1);
int lef = controlSize * 8 - controlLen;
String zero = StringUtil.repeat("0", lef);
// 完整信息
String bitinfo = controlInfo + zero;
logger.info( "bitinfo=" + bitinfo);
byte[] bittoBytebuffer = new byte[controlSize];
for (int i = 0; i < bittoBytebuffer.length; i++) {
String temp = bitinfo.substring(i * 8, (i + 1) * 8);
bittoBytebuffer[i] = ByteUtil.bit2byte(temp);
}
byte[] bodybytes = null;
if (subbyts != null) {
bodybytes = new byte[bitmapsize + subbyts.length + bittoBytebuffer.length + varInfos.getBytes(encoding).length];
System.arraycopy(bitmap, 0, bodybytes, 0, bitmapsize);
System.arraycopy(subbyts, 0, bodybytes, bitmapsize, subbyts.length);
System.arraycopy(bittoBytebuffer, 0, bodybytes, bitmapsize + subbyts.length, controlSize);
System.arraycopy(varInfos.getBytes(), 0, bodybytes, bitmapsize + subbyts.length + controlSize, varInfos.getBytes(encoding).length);
} else {
bodybytes = new byte[bitmapsize + bittoBytebuffer.length + varInfos.getBytes(encoding).length];
System.arraycopy(bitmap, 0, bodybytes, 0, bitmapsize);
System.arraycopy(bittoBytebuffer, 0, bodybytes, bitmapsize, controlSize);
System.arraycopy(varInfos.getBytes(), 0, bodybytes, bitmapsize + controlSize, varInfos.getBytes(encoding).length);
}
logger.debug( "二进制代码为=" + toBinaryString(bodybytes));
context.setObject(bodybytes);
} else {
// logger.info( LOG_FLAG + "Mac8583Filter解析" +
// LOG_FLAG);
}
// logger.info( LOG_FLAG +
// "Mac8583Filter has finished running." + LOG_FLAG);
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* byte[]转化为十六进制字符串
*
* @param bytes
* @return
*/
public String toHexString(byte[] bytes) {
String str = "";
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xff);
if (hex.length() == 1) {
hex = '0' + hex;
}
str += hex;
}
return str;
}
/**
*
* @param bytes
* @return
*/
public String toBinaryString(byte[] bytes) {
String str = "";
for (byte b : bytes) {
String hex = Integer.toBinaryString(b & 0xff);
hex = String.format("%08d", Integer.parseInt(hex));
str += hex;
}
return str;
}
/**
* 设置bitmap的sequence对应位
*
* @param seq
* @param bitmap
* @param zero
*/
public void setBitmap(int seq, byte[] bitmap, boolean one) {
byte[] ones = new byte[] { (byte) 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
byte[] zeros = new byte[] { (byte) 0x7f, (byte) 0xbf, (byte) 0xd0, (byte) 0xef, (byte) 0xf7, (byte) 0xfb, (byte) 0xfd, (byte) 0xfe };
if (one)
bitmap[seq / 8] |= ones[seq % 8];
else
bitmap[seq / 8] &= zeros[seq % 8];
}
public void setDirection(String director) {
this.direction = director;
}
public String getDirection() {
return this.direction;
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
return null;
}
protected void packField(IFieldDef fieldDef, Object value) {
// String str = (String) value;
String etag = fieldDef.getEtag();
IFieldDef dstField = moduleDef.getMap().get(etag);
fieldDef.setType(dstField.getType());
fieldDef.setSize(dstField.getSize());
int size = Integer.parseInt(fieldDef.getSize());
int val = 0;
int bitmapsize = Integer.parseInt((String) context.getVariable("bitmapsize"));
if (bitmapsize == 0) {
String bit = Integer.toBinaryString(Integer.valueOf(value.toString()));
int bitlen = bit.length();
String left = StringUtil.repeat("0", size - bitlen);
bit = left + bit;
controlInfo += bit;
return;
}
if (etag.equals("0")) {
bitmaplist.add(etag);
controlInfo += value;
return;
}
// 变长
if (dstField.getType().equals("vrString") || dstField.getType().equals("fxString")) {
String str = (String) value;
try {
val = str.getBytes(encoding).length;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (dstField.getType().equals("bit")) {
val = Integer.parseInt(value.toString());
}
if (dstField.getType().equals("vrString") || dstField.getType().equals("bit")) {
String bit = Integer.toBinaryString(val);
int bitlen = bit.length();
String left = StringUtil.repeat("0", size - bitlen);
bit = left + bit;
controlInfo += bit;
}
// 变长
if (dstField.getType().equals("vrString") || dstField.getType().equals("fxString")) {
varInfos += value;
}
/*
* if (etag.equals("0") && (value instanceof byte[])) {
* bitmaplist.add(etag); subbyts = (byte[]) value; }
*/
bitmaplist.add(etag);
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.el.CommonFunctionUtils;
import com.brilliance.eibs.util.StringUtil;
import org.apache.commons.io.IOUtils;
import java.io.InputStream;
/**
* 命令行连接
*
* @author gechengyang
*
*/
public class CommandConnection extends AbsConnection {
private String type = "";
private String encode = "GBK";
@Override
public void execute(Context context) {
// logger.info( LOG_FLAG + "CommandConnection is running." +
// LOG_FLAG);
encode = connectionDef.getEncoding();
context.setCurrentInstance(this);
// String command = connectionDef.getProperty("command").getValue();
// /command=getPropertyValue(command, false);
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);
// logger.info( LOG_FLAG +
// "CommandConnection has finished running." + LOG_FLAG);
}
public int executeShell(String shellCommand, Context context) {
shellCommand = shellCommand.trim();
shellCommand = shellCommand.replaceAll("\\s+", " ");
logger.info( "[command is]" + shellCommand);
int success = 0;
StringBuffer stringBuffer = new StringBuffer();
// 格式化日期时间,记录日志时使用
// DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
InputStream in = null;
InputStream errorin = null;
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;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.esearch.ElasticSearchHandler;
import com.brilliance.eibs.util.LogUtil;
/**
* esercher,并存入上下文
*
* @author ge
*/
public class EsearchConnection extends AbsConnection {
public void execute(Context context) {
// logger.info( LOG_FLAG + "esearchConnection is running." +
// LOG_FLAG);
context.setCurrentInstance(this);
super.execute(context);
String ip = getPropertyValue("ip");
ElasticSearchHandler es = new ElasticSearchHandler(ip, LogUtil.getLogger(context));
context.setObject(es);
// logger.info( LOG_FLAG +
// "esearchConnection has finished runnig." + LOG_FLAG);
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Excel处理
*
* @author xiaoyuanzhen
*
*/
public class ExcelFilter extends AbsFilter {
String encoding;
private String path;
private String date_pattern;
private String decimal_pattern;
private String date_default;
private String decimal_defalut;
private String filetype;
private String[] dates = null;
private String[] decimals = null;
private HSSFWorkbook hwb;
private XSSFWorkbook xwb;
private Sheet sheet;
private Workbook wb;
// private HSSFSheet hsheet;
// private XSSFSheet xsheet;
private int MAX_SHEET = 0;
public void execute(Context context) {
logger.info( LOG_FLAG + "ExcelFilter is begining to runnig." + LOG_FLAG);
context.setCurrentInstance(this);
propertySaveToContext();
encoding = filterDef.getEncoding();
// Excel报文路径
path = (String) context.getVariable("path");
logger.info( "Excel Path=" + path);
context.setCurrentInstance(this);
propertySaveToContext();
encoding = filterDef.getEncoding();
// Excel报文路径
logger.info( "Excel Path=" + path);
// 日期格式
date_pattern = (String) context.getVariable("date_pattern");
// 数值格式
decimal_pattern = (String) context.getVariable("decimal_pattern");
// 默认日期格式
date_default = (String) context.getVariable("date_default");
// 默认数值格式
decimal_defalut = (String) context.getVariable("decimal_defalut");
String type = getFilterDef().getType();
if (type.equals("in")) {
initExcel();
}
super.execute(context);
logger.info( "ExcelFilter is finished");
}
protected void packField(IFieldDef fieldDef, Object objValue) {
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
return null;
}
/**
* 初始化参数
* **/
public void initExcel() {
/*
* path = "G:/历史文件/远期信用证外债信息(部分数据).xls"; date_pattern =
* "0,7,yyyy-MM-dd|0,8,yyyy/MM/dd"; decimal_pattern =
* "0,9,####|0,10,####|0,11,####"; date_default = "yyyyMMdd";
* decimal_defalut = "####.00";
*/
if (date_pattern != null)
dates = date_pattern.split("\\|");
if (decimal_pattern != null)
decimals = decimal_pattern.split("\\|");
int i = path.lastIndexOf(".");
filetype = path.substring(i + 1);
wb = getWorkbook(path);
}
/**
* 得到Excel对象
**/
public Workbook getWorkbook(String path) {
FileInputStream is = null;
try {
is = new FileInputStream(new File(path));
// POIFSFileSystem fs = new POIFSFileSystem(is);
// logger.info( "fs=" + fs == null);
// wb = new HSSFWorkbook(fs);
// wb = new XSSFWorkbook(is);
if ("xls".equals(filetype)) {
POIFSFileSystem fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook(fs);
MAX_SHEET = wb.getNumberOfSheets();
} else if ("xlsx".equals(filetype) || "xlsm".equals(filetype)) {
wb = new XSSFWorkbook(is);
MAX_SHEET = wb.getNumberOfSheets();
}
// MAX_SHEET = wb.getNumberOfSheets();
} catch (FileNotFoundException e) {
logger.error( "file can not find");
logger.error( e.getMessage(),e);
} catch (IOException e) {
logger.error( "file io exception");
logger.error( e.getMessage(),e);
} finally {
IOUtils.closeQuietly(is);
}
return wb;
}
/**
* 得到Sheet页签
* **/
public Sheet getSheet(int sheetIndex) {
for (int i = 0; i < MAX_SHEET; i++) {
if (sheetIndex == i) {
return wb.getSheetAt(i);
}
}
return null;
}
public String getPattern(int sheet, int columns, int type) {
String pattern = null;
// 时间
String start = sheet + "," + columns;
if (type == 1) {
if (dates != null) {
for (int i = 0; i < dates.length; i++) {
String s = dates[i];
if (s.startsWith(start)) {
pattern = s.split(",")[2];
break;
}
}
}
}
// 数值
else if (type == 2) {
if (decimals != null) {
for (int i = 0; i < decimals.length; i++) {
String s = decimals[i];
if (s.startsWith(start)) {
pattern = s.split(",")[2];
break;
}
}
}
}
return pattern;
}
/**
* 加载Excel,转换成List<String[]>
* **/
public List<String[]> loadExcel(int sheetIndex, int rowOffset, int rowMax, int columnOffset, int columnCount) {
logger.info( "begin to anylyse excel");
List<String[]> list = new ArrayList<String[]>();
sheet = getSheet(sheetIndex);
int totalrow = sheet.getLastRowNum();
logger.info( "[MaxRow]=" + totalrow);
if (rowMax > totalrow) {
throw new InterfaceException("03111", "rownumber can not be bigger than the rowMax[" + totalrow + "].");
}
if (rowMax == -1) {
rowMax = totalrow;
}
int rowcolumnCount = 0;
for (int j = rowOffset; j <= rowMax; j++) {
Row r = sheet.getRow(j);
int cellnum = r.getLastCellNum();
// 修改以表头行的列数为基准 modify by cjh 20180713
if (j == rowOffset) {
if (columnCount > cellnum) {
throw new InterfaceException("03112", "cellnum can not be bigger than the celMax[" + cellnum + "].");
}
if (columnCount == -1) {
rowcolumnCount = cellnum - 1;
}
if (columnCount != -1) {
rowcolumnCount = columnCount;
}
}
int i = 0;
String[] str = new String[rowcolumnCount - columnOffset + 1];
for (int k = columnOffset; k <= rowcolumnCount; k++) {
Cell cell = r.getCell(k);
if (k == 26) {
System.out.println("");
}
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
str[i] = null;
i++;
break;
case Cell.CELL_TYPE_BOOLEAN:
str[i] = String.valueOf(cell.getBooleanCellValue());
i++;
break;
case Cell.CELL_TYPE_NUMERIC: {
// 判断是否为日期类型
String pattern = null;
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// 用于转化为日期格式
Date d = cell.getDateCellValue();
pattern = getPattern(sheetIndex, k, 1);
if (pattern == null)
pattern = date_default;
DateFormat formater = new SimpleDateFormat(pattern);
str[i] = formater.format(d);
} else {
// 用于格式化数字,只保留数字的整数部分
pattern = getPattern(sheetIndex, k, 2);
if (pattern == null)
pattern = decimal_defalut;
DecimalFormat df = new DecimalFormat(pattern);
str[i] = df.format(cell.getNumericCellValue());
}
i++;
}
break;
case Cell.CELL_TYPE_STRING:
str[i] = cell.getStringCellValue();
i++;
break;
case Cell.CELL_TYPE_FORMULA:
try {
str[i] = String.valueOf(cell.getStringCellValue());
} catch (IllegalStateException e) {
String pattern = null;
try {
str[i] = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// 用于转化为日期格式
Date d = cell.getDateCellValue();
pattern = getPattern(sheetIndex, k, 1);
if (pattern == null)
pattern = date_default;
DateFormat formater = new SimpleDateFormat(pattern);
str[i] = formater.format(d);
} else {
// 用于格式化数字,只保留数字的整数部分
pattern = getPattern(sheetIndex, k, 2);
if (pattern == null)
pattern = decimal_defalut;
DecimalFormat df = new DecimalFormat(pattern);
str[i] = df.format(cell.getNumericCellValue());
}
} catch (IllegalStateException e1) {
str[i] = null;
}
}
i++;
break;
}
} else {
str[i] = null;
i++;
}
}
list.add(str);
}
for (int j = 0; j < list.size(); j++) {
String[] ss = list.get(j);
StringBuffer sb = new StringBuffer();
for (int l = 0; l < ss.length; l++) {
sb.append(ss[l] + ",");
}
// logger.info( sb.toString());
}
return list;
}
public static void main(String[] args) {
ExcelFilter excelFilter = new ExcelFilter();
excelFilter.initExcel();
// 签约信息
List<String[]> list = excelFilter.loadExcel(0, 0, 8, 0, 18);
// List<String[]> list = excelFilter.loadExcel(1, 1, 8, 0, 9);
if (list != null) {
for (String[] strings : list) {
for (int i = 0; i < strings.length; i++) {
System.out.print(strings[i] + ", ");
}
System.out.println(".....");
}
}
}
}
\ No newline at end of file
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.StringUtil;
import org.apache.poi.ss.usermodel.*;
public class ExcelTempateFilter extends AbsFilter {
private Workbook wb;
private Sheet sheet;
private int currentLastRowIndex;
private int currentFirstCellIndex;
private CellStyle defaultCellStyle;
@Override
public void execute(Context context) {
context.setCurrentInstance(this);
String type = getType();
if (!WRITE_FLG.equals(type)) // type="out"
{
throw new InterfaceException("03401", "不支持的操作类型");
}
Object content = context.getObject();
if (content == null || !(content instanceof Workbook)) {
throw new InterfaceException("03402", "缺少poi workbook对象");
}
wb = (Workbook) content;
sheet = wb.getSheetAt(0);
currentLastRowIndex = sheet.getLastRowNum();
Row row = sheet.getRow(currentLastRowIndex);
currentFirstCellIndex = row.getFirstCellNum();
Cell cell = row.getCell(currentFirstCellIndex);
defaultCellStyle = cell.getCellStyle();
super.execute(context);
}
@Override
public Object getFieldValue(IFieldDef fieldDef) throws Exception {
// TODO Auto-generated method stub
return null;
}
protected void packField(IFieldDef fieldDef, Object fieldValue) {
String etag = elParser.getExPression(context, fieldDef.getEtag(), null).toString();
boolean defaultStyle = true;
if (!StringUtil.isEmpty(fieldDef.getTag())) {
defaultStyle = false;
}
String[] targetIndexs = etag.split(",");
if (targetIndexs.length < 2) {
throw new InterfaceException("03404", "etag坐标数据格式错误");
}
int yIndex = 0;
int xIndex = 0;
try {
yIndex = Integer.valueOf(targetIndexs[0]);
xIndex = Integer.valueOf(targetIndexs[1]);
} catch (NumberFormatException e) {
throw new InterfaceException("03403", "坐标转换数字异常", e);
}
int currentYIndex = currentLastRowIndex + yIndex + 1;
int currentXIndex = currentFirstCellIndex + xIndex;
Row row = sheet.getRow(currentYIndex);
if (null == row) {
row = sheet.createRow(currentYIndex);
}
Cell cell = row.createCell(currentXIndex);
cell.setCellValue(fieldValue.toString());
Cell styleCell = null;
if (defaultStyle) {
cell.setCellStyle(defaultCellStyle);
} else {
String tag = elParser.getExPression(context, fieldDef.getTag(), null).toString();
String[] sourceIndexs = tag.split(",");
if (sourceIndexs.length != 0 && sourceIndexs.length < 2) {
throw new InterfaceException("03404", "tag坐标数据格式错误");
}
try {
yIndex = Integer.valueOf(sourceIndexs[0]);
xIndex = Integer.valueOf(sourceIndexs[1]);
} catch (NumberFormatException e) {
throw new InterfaceException("03403", "坐标转换数字异常", e);
}
currentYIndex = currentLastRowIndex + yIndex + 1;
currentXIndex = currentFirstCellIndex + xIndex;
row = sheet.getRow(currentYIndex);
styleCell = row.getCell(currentXIndex);
cell.setCellStyle(styleCell.getCellStyle());
}
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import weblogic.wtc.jatmi.Ferror;
import weblogic.wtc.jatmi.TypedFML32;
/**
* @author gechengyang FML32报文格式转换
* ***/
public class FML32Filter extends AbsFilter {
private TypedFML32 fml32 = new TypedFML32();
@Override
public void execute(Context context) {
// logger.info( LOG_FLAG + "FML32Filter is running" + LOG_FLAG);
context.setCurrentInstance(this);
String type = getFilterDef().getType();
if ("in".equals(type)) {
// logger.info( LOG_FLAG + "FML32Filter解析" + LOG_FLAG);
fml32 = (TypedFML32) context.getObject();
}
super.execute(context);
if ("out".equals(type)) {
// logger.info( LOG_FLAG + "FML32Filter组装" + LOG_FLAG);
context.setObject(fml32);
// saveToContext(getFilterDef().getScope(), getFilterDef().getTag(),
// context.getObject());
}
// logger.info( LOG_FLAG + "FML32Filter has finished running" +
// LOG_FLAG);
}
// 解包函数
@Override
public Object getFieldValue(IFieldDef fieldDef) {
String etag = (String) elParser.getExPression(context, fieldDef.getEtag(), null);
int key = Integer.parseInt(etag);
Object object;
try {
object = fml32.Fget(key, 0);
logger.info( "parse FML32 field[" + etag + "],value[" + object + "].");
} catch (Ferror e) {
// TODO Auto-generated catch block
throw new InterfaceException("01101", "FML32解包异常", e);
}
return object;
}
// 组包函数
@Override
protected void packField(IFieldDef fieldDef, Object fieldValue) {
fieldValue = dealValueByType(fieldValue, fieldDef.getType());
String etag = (String) elParser.getExPression(context, fieldDef.getEtag(), null);
logger.info( "config FML32 field[" + etag + "],value[" + fieldValue + "].");
int key = Integer.parseInt(etag);
try {
fml32.Fchg(key, 0, fieldValue);
}
catch (Ferror e1) {
throw new InterfaceException("01102", "FML32组包异常", e1);
}
}
public static void main(String[] args) {
TypedFML32 fml32 = new TypedFML32();
try {
fml32.Fchg(167872287, 0, "12");
}
catch (Ferror e1) {
throw new InterfaceException("10018", "FML32组包异常", e1);
}
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.StringUtil;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.util.List;
/**
* 文件连接,提供对文件的读取保存功能
*
* @author hujun
*
*/
public class FileConnection extends AbsConnection {
private static final String EXCEL_SUFFIX = "excel";
private static final String XLS_EXCEL_SUFFIX = "xls";
private static final String XLSX_EXCEL_SUFFIX = "xlsx";
@Override
public void execute(Context context) {
// logger.debug( LOG_FLAG + "FileConnection is running ." +
// LOG_FLAG);
context.setCurrentInstance(this);
// 获取操作类型
String type = getType();
// 获取文件路径
String path = getPropertyValue(PATH_SYMBOL);
if (isRead(type)) {
logger.debug( "读取文件[" + path + "].");
try {
doRead(path);
} catch (IOException e) {
throw new InterfaceException("00801", "read 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) {
return READ_FLG.equals(type);
}
private boolean isWrite(String type) {
return WRITE_FLG.equals(type);
}
private void doRead(String path) throws IOException {
Object content = read(path);
// logger.debug("Read the contents is " + content + ".");
// 读取文件写入上下文
context.setObject(content);
}
private void doWrite(String path) throws IOException {
// 获取需要写入的文件
File file = new File(path);
boolean append = Boolean.valueOf(getPropertyValue("append", true));
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!append || !file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
throw new InterfaceException("00803", "create new file error.", e);
}
}
Object obj = context.getObject();
if (obj == null || obj.toString().equals("")) {
logger.warn( "No content to write.");
}
// logger.trace("Write the contents is " +
// System.getProperty("line.separator") + obj.toString());
write(file, obj, append);
}
/**
* 文件写入操作
*
* @param path
* 文件路徑
* @param content
* 文件内容
* @throws IOException
*/
private void write(File file, Object content, boolean isAppend) throws IOException {
FileOutputStream fos = new FileOutputStream(file, isAppend);
try {
if (content instanceof byte[]) {
logger.info( "file 类型:二进制文件");
IOUtils.write((byte[]) content, fos);
logger.info( "文件长度是=" + ((byte[]) content).length);
return;
}
PrintWriter pw = null;
try {
pw = new PrintWriter(new OutputStreamWriter(fos, connectionDef.getEncoding()), true);
pw.print(content);
pw.flush();
} finally {
IOUtils.closeQuietly(pw);
}
} finally {
IOUtils.closeQuietly(fos);
}
}
/**
* 文件读取操作
*
* @param path
* 文件路徑
* @return 文件内容
* @throws IOException
*/
private Object read(String path) throws IOException {
BufferedReader br = null;
FileInputStream fis = null;
try {
String type = getPropertyValue("type", true);
fis = new FileInputStream(path);
if ("list".equals(type)) {
List<String> list = IOUtils.readLines(fis, connectionDef.getEncoding());
IOUtils.closeQuietly(fis);
String filterLines = getPropertyValue("removeLines", true);
if (!StringUtil.isEmpty(filterLines)) {
String[] lines = filterLines.split(",");
for (String line : lines) {
list.remove(Integer.parseInt(line));
}
}
return list;
}
if ("byte".equals(type)) {
File file = new File(path);
int length = (int) file.length();
byte[] bytes = new byte[length];
IOUtils.readFully(fis, bytes);
return bytes;
}
StringBuffer s = new StringBuffer();
br = new BufferedReader(new InputStreamReader(fis, connectionDef.getEncoding()));
int tempchar;
while ((tempchar = br.read()) != -1) {
s.append((char) tempchar);
}
return s.toString();
} finally {
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(br);
}
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.StringUtil;
import org.apache.commons.collections.map.LinkedMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 处理文件
*
* @author ge
*
*/
public class FilelstFilter extends AbsFilter {
private static final String SPLIT_STRATEGY = "bysplit";
private static final String FIXED_STRATEGY = "fixedlen";
private static final String FIELD_STRATEGY_SYMBOL = "field_strategy";
private static final String FIELD_SYMBOL = "field";
private String fieldStrategy;
private String field;
private static final String EXCEPT = "except";
private String except;
private List<IFieldDef> list = new ArrayList<IFieldDef>();
private List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
@Override
public void execute(Context context) {
// logger.debug( LOG_FLAG + "FilelstFilter is running." +
// LOG_FLAG);
context.setCurrentInstance(this);
propertySaveToContext();
getParameter();
super.execute(context);
String type = getType();
// 解析
if (type.equals("in")) {
List<String> contextVal = (List<String>) context.getObject();
if (!StringUtil.isEmpty(except))
contextVal.remove(Integer.parseInt(except));
// 变长报文解析
if (this.fieldStrategy.equals(SPLIT_STRATEGY)) {
for (String str : contextVal) {
Map<String, Object> map = new LinkedMap();
String arrays[] = splitString(str, this.field);
// 遍历field得到每个值
for (int i = 0; i < list.size(); i++) {
IFieldDef fieldDef = list.get(i);
String val = arrays[Integer.parseInt(fieldDef.getEtag())];
map.put(fieldDef.getTag(), dealValueByType(val, fieldDef.getType()));
}
listmap.add(map);
}
} else if (this.fieldStrategy.equals(FIXED_STRATEGY)) {
for (String str : contextVal) {
Map<String, Object> map = new LinkedMap();
String leftstr = str;
// 遍历field得到每个值
for (int i = 0; i < list.size(); i++) {
IFieldDef fieldDef = list.get(i);
int index = Integer.parseInt(fieldDef.getEtag());
String val = leftstr.substring(0, index);
map.put(fieldDef.getTag(), dealValueByType(val, fieldDef.getType()));
leftstr = leftstr.substring(index);
}
listmap.add(map);
}
}
logger.info( "listmap=" + listmap);
context.setObject(listmap);
}
// 组装
else {
List<String> combineList = new ArrayList<String>();
String curline = System.getProperty("line.separator", "\n");
List<Map<String, Object>> contextVal = (List<Map<String, Object>>) context.getObject();
if (this.fieldStrategy.equals(SPLIT_STRATEGY)) {
this.field = this.field.replace("\\t", "\t");
for (Map<String, Object> map : contextVal) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
IFieldDef fieldDef = list.get(i);
Object val = map.get(fieldDef.getTag());
if (val == null)
val = "";
sb.append(i != (list.size() - 1) ? (val + this.field) : val);
}
combineList.add(sb.toString());
}
StringBuffer cs = new StringBuffer();
for (int i = 0; i < combineList.size(); i++) {
cs.append(i != (list.size() - 1) ? (combineList.get(i) + curline) : combineList.get(i));
}
context.setObject(cs.toString());
logger.info( "组装combine=" + combineList);
} else {
for (Map<String, Object> map : contextVal) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
IFieldDef fieldDef = list.get(i);
Object val = map.get(fieldDef.getTag());
int size = Integer.parseInt(fieldDef.getEtag());
if (val == null)
val = "";
else {
if (val instanceof Integer) {
int len = val.toString().length();
sb.append(StringUtil.repeat("0", size - len)).append(val);
} else if (val instanceof String) {
int len = val.toString().length();
sb.append(val).append(StringUtil.repeat(" ", size - len));
}
}
}
combineList.add(sb.toString());
}
StringBuffer cs = new StringBuffer();
for (int i = 0; i < combineList.size(); i++) {
cs.append(i != (list.size() - 1) ? (combineList.get(i) + curline) : combineList.get(i));
}
context.setObject(cs.toString());
logger.info( "组装combine=" + combineList);
}
}
// logger.debug( LOG_FLAG + "FilelstFilter is finished.");
}
/**
* 获取filter的特定parameter参数
*/
private void getParameter() {
this.fieldStrategy = (String) context.getVariable(FIELD_STRATEGY_SYMBOL);
if (SPLIT_STRATEGY.equals(fieldStrategy))
this.field = ((String) context.getVariable(FIELD_SYMBOL));
this.except = (String) context.getVariable(EXCEPT);
}
@Override
protected void packField(IFieldDef fieldDef, Object fieldValue) {
String etag = elParser.getExPression(context, fieldDef.getEtag(), null).toString();
fieldDef.setEtag(etag);
String tag = elParser.getExPression(context, fieldDef.getTag(), null).toString();
fieldDef.setTag(tag);
String type = elParser.getExPression(context, fieldDef.getType(), null).toString();
fieldDef.setType(type);
list.add(fieldDef);
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
String etag = elParser.getExPression(context, fieldDef.getEtag(), null).toString();
fieldDef.setEtag(etag);
String tag = elParser.getExPression(context, fieldDef.getTag(), null).toString();
fieldDef.setTag(tag);
String type = elParser.getExPression(context, fieldDef.getType(), null).toString();
fieldDef.setType(type);
list.add(fieldDef);
return null;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.StringUtil;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Fix报文处理
*
* @author 葛成洋
*
*/
public class FixFilter extends AbsFilter {
String encoding;
String FIX_VERSION_TAG = "8";
String FIX_VERSION_VALUE = "";
String BODY_LEN_TAG = "9";
String BODY_LEN_VALUE = "";
String FIX_TAIL_TAG = "10";
String FIX_TAIL_VALUE = "";
Map<String, Object> map = new LinkedHashMap<String, Object>();
public void execute(Context context) {
// logger.info( LOG_FLAG + "FixFilter is begining to runnig." +
// LOG_FLAG);
context.setCurrentInstance(this);
encoding = filterDef.getEncoding();
String type = getFilterDef().getType();
if (type.equals("in")) {
// logger.info( LOG_FLAG + "Fix报文解析" + LOG_FLAG);
Object object = context.getObject();
String str = null;
if (object instanceof byte[]) {
try {
str = new String((byte[]) object, encoding);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
str = (String) context.getObject();
}
Map<String, Object> map = new HashMap<String, Object>();
char c = 0x01;
String splitSym = String.valueOf(c);
String[] tags = str.split(splitSym);
for (String tag : tags) {
if (!StringUtil.isEmpty(tag)) {
String keys[] = tag.split("=");
map.put(keys[0], keys[1]);
}
}
context.setObject(map);
} else {
// logger.info( LOG_FLAG + "FixFilter定长报文组装" + LOG_FLAG);
}
super.execute(context);
// 组装完后,存入上下文resource的object
if (type.equals("out")) {
StringBuffer sb = new StringBuffer();
char c = 0x01;
// sb.append(FIX_VERSION_TAG + "=" + FIX_VERSION_VALUE).append(c);
for (String key : map.keySet()) {
sb.append(key + "=" + map.get(key)).append(c);
}
try {
BODY_LEN_VALUE = String.valueOf(sb.toString().getBytes(encoding).length);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuffer allSb = new StringBuffer();
allSb.append(FIX_VERSION_TAG + "=" + FIX_VERSION_VALUE).append(c);
allSb.append(BODY_LEN_TAG + "=" + BODY_LEN_VALUE).append(c);
allSb.append(sb);
allSb.append(FIX_TAIL_TAG + "=" + FIX_TAIL_VALUE).append(c);
context.setObject(allSb.toString());
}
logger.info( "FixFilter is finished");
}
protected void packField(IFieldDef fieldDef, Object fieldValue) {
String etag = fieldDef.getEtag();
if (StringUtil.isEmpty(etag))
return;
etag = elParser.getExPression(context, etag, null).toString();
if (etag.equals(FIX_VERSION_TAG)) {
FIX_VERSION_VALUE = fieldValue.toString();
} else if (etag.equals(FIX_TAIL_TAG)) {
FIX_TAIL_VALUE = fieldValue.toString();
} else if (etag.equals(BODY_LEN_TAG)) {
return;
} else {
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
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.plugin.FtpClient;
import com.brilliance.eibs.util.StringUtil;
/**
* FTP连接
*
* @author gechengyang
**/
public class FtpConnection2 extends AbsConnection {
String encoding;
FtpClient client;
public void execute(Context context) {
logger.info( LOG_FLAG + "FtpConnection is Running." + LOG_FLAG);
encoding = connectionDef.getEncoding();
context.setCurrentInstance(this);
// 获取超时时间
setTimeOut();
String username = getPropertyValue("username");
String password = getPropertyValue("password");
String url = getPropertyValue("url");
int port = Integer.parseInt(getPropertyValue("port"));
String type = getType();
String remotepath = getPropertyValue("remotepath");
String localpath = getPropertyValue("localpath");
String arc = getPropertyValue("arc", true);
String ctlPath = getPropertyValue("ctlPath", true);
String ctlFilenameregex = getPropertyValue("ctlFilenameregex", true);
boolean deleteFlag = Boolean.valueOf(getPropertyValue("delete", true));
String filenameRegex = getPropertyValue("filenameregex", true);
String passiveModeStr = getPropertyValue("passivemode", true);
boolean passiveMode = StringUtil.isEmpty(passiveModeStr)?false:Boolean.valueOf(passiveModeStr);
client = new FtpClient(url, port, connectTimeout);
client.login(username, password,passiveMode);
try {
if (isDownload(type)) {
logger.debug( "FTP begin to Download.");
client.download(ctlPath, ctlFilenameregex, remotepath, localpath, filenameRegex,
arc, deleteFlag);
context.setObject(client.getFilenames());
}
if (isUpload(type)) {
logger.debug( "FTP begin to Upload.");
client.upload(localpath, remotepath, filenameRegex, arc);
}
} finally {
client.disConnect();
}
logger.info( "FtpConnection is finished.");
}
private boolean isDownload(String type) {
return READ_FLG.equals(type);
}
private boolean isUpload(String type) {
return WRITE_FLG.equals(type);
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.plugin.FtpExcutor;
import com.brilliance.eibs.core.service.instance.plugin.JdkFtpExecutor;
import com.brilliance.eibs.util.StringUtil;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.net.SocketException;
/**
* FTP连接
*
* @author gechengyang
**/
public class FtpConnection_beta extends AbsConnection {
String encoding = "";
FTPClient ftp = null;
public void execute(Context context) {
// logger.info( LOG_FLAG + "FtpConnection is Running." +
// LOG_FLAG);
encoding = connectionDef.getEncoding();
context.setCurrentInstance(this);
String username = getPropertyValue("username");
logger.info("ftp username=" + username);
String password = getPropertyValue("password");
logger.info("ftp password=" + password);
String url = getPropertyValue("url");
logger.info("ftp ip=" + url);
int port = Integer.parseInt(getPropertyValue("port"));
logger.info("ftp port=" + port);
String type = getType();
String remotepath = getPropertyValue("remotepath");
logger.info("ftp remotepath=" + remotepath);
String localpath = getPropertyValue("localpath");
logger.info("ftp localpath=" + localpath);
String arc = getPropertyValue("arc", true);
String fileDirectorName = getPropertyValue("subFileName", true);
String fileName = getPropertyValue("filename", true);
String ftptype = getPropertyValue("type", true);
if (StringUtil.isEmpty(ftptype)) {
ftptype = "aph";
}
// 获取超时时间
setTimeOut();
// JDK版本
if ("sun".equals(ftptype.toLowerCase())) {
JdkFtpExecutor fu = new JdkFtpExecutor();
/*
* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器
*/
fu.connectServer(logger, url, port, username, password);
try {
if (isDownload(type)) {
if (!StringUtil.isEmpty(fileName)) {
fu.cd(remotepath);
}
fu.download(fileName, localpath);
} else if (isUpload(type)) {
fu.cd(remotepath);
fu.upload(localpath, fileName);
}
} catch (IOException e) {
throw new InterfaceException("01204", "ftp error:", e);
} finally {
try {
fu.closeConnect();
} catch (IOException e) {
throw new InterfaceException("01204", "ftp error:", e);
}
}
} else {
FtpExcutor ftpExcutor = new FtpExcutor(encoding, logger);
ftp = ftpExcutor.getFtpClient();
ftp.setConnectTimeout(connectTimeout);
ftp.setDefaultTimeout(default_timeout);
boolean b = ftpExcutor.loginFtp(url, port, username, password);
if (!b) {
close(ftpExcutor);
return;
}
ftp.setDataTimeout(receiveTimeout);
try {
ftp.setSoTimeout(soTimeout);
} catch (SocketException e1) {
throw new InterfaceException("01204", "ftp soTime Error:", e1);
}
if (isDownload(type)) {
logger.debug("FTP begin to Download.");
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);
} catch (IOException e) {
close(ftpExcutor);
throw new InterfaceException("01204", "ftp download error:", e);
}
}
if (isUpload(type)) {
logger.debug("FTP begin to Upload.");
try {
ftpExcutor.uploadDirFiles(localpath, remotepath);
} catch (IOException e) {
close(ftpExcutor);
throw new InterfaceException("01204", "ftp upload error:", e);
}
}
logger.info("FtpConnection is finished.");
}
}
private boolean isDownload(String type) {
return READ_FLG.equals(type);
}
private boolean isUpload(String type) {
return WRITE_FLG.equals(type);
}
public void close(FtpExcutor ftpExcutor) {
if (ftpExcutor.getFtpClient() != null) {
try {
ftpExcutor.closeConnections(ftpExcutor.getFtpClient());
} catch (IOException e1) {
logger.error("e1", e1);
}
try {
ftpExcutor.getFtpClient().disconnect();
} catch (IOException e1) {
logger.error("e1", e1);
}
}
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class GeTuiConnection
extends AbsConnection
{
/* static String appId = "8jY9A5v0vjAawT2UM2BXz8";
static String appkey = "u7EQpo2p6SAAM1qN4LCIN2";
static String master = "3yNDlhWPWg84GlsYz0PE82";
static String CID = "c6b2ac37fb3436c9344ab770b0a55ecf";*/
String type = "";
String appid = "";
String appkey = "";
String master = "";
String title = "";
String content = "";
List<String> cidList = new ArrayList<String>();
String host = "http://sdk.open.api.igexin.com/apiex.htm";
String info="";
/**
* @author gechengyang
*个推服务端程序
* **/
@Override
public void execute(Context context)
{
logger.info(LOG_FLAG + "GeTuiConnection is Running." + LOG_FLAG);
context.setCurrentInstance(this);
super.execute(context);
//推送类型 ToApp/ToList
type = getPropertyValue("type");
appid = getPropertyValue("appid");
appkey = getPropertyValue("appkey");
master = getPropertyValue("master");
cidList = (List<String>) getPropertyValueOfObject(getProperty("cids"));
title = getPropertyValue("title");
content = getPropertyValue("content");
info = getPropertyValue("info");
//配置返回每个用户返回用户状态,可选
System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
IGtPush push = new IGtPush(host, appkey, master);
//建立连接,开始鉴权
boolean b;
try
{
b = push.connect();
if (b)
logger.info("建立连接,开始鉴权!");
else
{
logger.info("建立连接失败!!!");
context.setObject(false);
return;
}
}
catch (IOException e)
{
throw new InterfaceException("F0001", "消息推送过程中发生异常.", e);
}
NotificationTemplate template = null;
IPushResult ret=null;
//通知透传模板
template = notificationToList();
if (type.equals("ToList"))
{
ListMessage message = new ListMessage();
message.setData(template);
//设置消息离线,并设置离线时间
message.setOffline(true);
//离线有效时间,单位为毫秒,可选
message.setOfflineExpireTime(24 * 1000 * 3600);
//配置推送目标
List targets = new ArrayList();
for (int i = 0; i < cidList.size(); i++)
{
Target target1 = new Target();
target1.setAppId(appid);
target1.setClientId(cidList.get(i));
targets.add(target1);
}
//获取taskID
String taskId = push.getContentId(message);
//使用taskID对目标进行推送
ret = push.pushMessageToList(taskId, targets);
//打印服务器返回信息
String response = ret.getResponse().toString();
Map<String, Object> map = new Gson().fromJson(response, Map.class);
logger.info("个推PushToList返回信息为:" + map);
context.setObject(map.get("result"));
}
else if (type.equals("ToApp"))
{
AppMessage message = new AppMessage();
message.setData(template);
//设置消息离线,并设置离线时间
message.setOffline(true);
//离线有效时间,单位为毫秒,可选
message.setOfflineExpireTime(24 * 1000 * 3600);
//设置推送目标条件过滤
List appIdList = new ArrayList();
List phoneTypeList = new ArrayList();
// List provinceList = new ArrayList();
//List tagList = new ArrayList();
appIdList.add(appid);
//设置机型
phoneTypeList.add("ANDROID");
phoneTypeList.add("IPHONE");
//设置省份
// provinceList.add("浙江");
//设置标签内容
//tagList.add("开心");
message.setAppIdList(appIdList);
message.setPhoneTypeList(phoneTypeList);
// message.setProvinceList(provinceList);
// message.setTagList(tagList);
ret = push.pushMessageToApp(message);
//打印服务器返回信息
String response = ret.getResponse().toString();
Map<String, Object> map = new Gson().fromJson(response, Map.class);
logger.info("个推PushToAPP返回信息为:" + map);
context.setObject(map.get("result"));
}
logger.info(LOG_FLAG + "GeTuiConnection has finished running." + LOG_FLAG);
}
public NotificationTemplate notificationToList()
{
NotificationTemplate template = new NotificationTemplate();
// 设置APPID与APPKEY
template.setAppId(appid);
template.setAppkey(appkey);
// 设置通知栏标题与内容
template.setTitle(title);
template.setText(content);
// 配置通知栏图标
template.setLogo("icon.png");
// 配置通知栏网络图标
template.setLogoUrl("");
// 设置通知是否响铃,震动,或者可清除
template.setIsRing(true);
template.setIsVibrate(true);
template.setIsClearable(true);
// 透传消息设置,1为强制启动应用,客户端接收到消息后就会立即启动应用;2为等待应用启动
template.setTransmissionType(1);
template.setTransmissionContent(info);
return template;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Json报文处理
* @author xiaoyuanzhen
*
*/
public class GsonFilter
extends AbsFilter
{
private Object jsonObject;
private String jsontype;
@Override
public void execute(Context context)
{
logger.info(LOG_FLAG + "GsonFilter is begining to runnig." + LOG_FLAG);
context.setCurrentInstance(this);
String type = filterDef.getType();
if (type.equals("in"))
{
logger.info(LOG_FLAG + "GsonFilter解析" + LOG_FLAG);
String json = (String) context.getObject();
jsontype = getRequiredPropertyValue("jsontype");
try
{
Object obj = jsonToObject(json, jsontype);
context.setObject(obj);
logger.debug("json to " + "[" + obj.getClass() + "] :" + obj);
}
catch (JsonSyntaxException e)
{
throw new InterfaceException("01301", e);
}
super.execute(context);
}
else
{
logger.info(LOG_FLAG + "GsonFilter组装" + LOG_FLAG);
Object object = context.getObject();
super.execute(context);
String jsonStr = null;
Gson gson = new Gson();
// jsonStr = gson.toJson(jsonObject);
jsonStr = gson.toJson(object);
context.setObject(jsonStr);
//saveToContext(getFilterDef().getScope(), getFilterDef().getTag(), context.getObject());
logger.debug("gson result:" + jsonStr);
}
logger.info(LOG_FLAG + "GsonFilter has finished runnig." + LOG_FLAG);
}
/**
* json转化为Java对象
* @param json
* @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
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private void addElement(String key, Object value)
{
if (jsonObject instanceof Map)
{
((Map) jsonObject).put(key, value);
}
else if (jsonObject instanceof List)
{
((List) jsonObject).add(value);
}
}
//组包
@Override
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);*/
}
}
package com.brilliance.eibs.core.service.instance.impl;
import cn.hutool.core.io.IoUtil;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.el.CommonFunctionUtils;
import com.brilliance.eibs.util.StringUtil;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
/**
* @author huwenming_saw
* @date 2020-07-22 13:36:06
*/
public class HttpConnectionBetter extends AbsConnection {
public static final String HTTP = "http://";
public static final String HTTPS = "https://";
public static final String SERVER = "server";
public static final String ROOTURL = "rootUrl";
public static final String GET = "get";
public static final String POST = "post";
public static final String PROXYSERVER = "proxyServer";
public static final String PROXYHOST = "proxyHost";
public static final String PROXYPORT = "proxyPort";
public static final String CHARSET = "charset";
public static final String HTTPRETRY = "httpRetry";
public static final String CONNECT_TIMEOUT = "connect_timeout";
public static final String READ_TIMEOUT = "read_timeout";
public static final String MAPPING = "mapping";
public static final String BODY = "body";
public static final String HEAD = "head";
private final HttpClientContext httpClientContext = new HttpClientContext();
Map<String, Object> params;
private Charset charset = StandardCharsets.UTF_8;
private CloseableHttpClient httpClient;
final int CODE = HttpStatus.SC_OK;
@Override
public void execute(Context context) {
// 必须得从上下文中拿到参数列表
params = (Map<String, Object>) context.getObject();
context.setCurrentInstance(this);
super.execute(context);
String type = getPropertyValue(TYPE, false);
String server = getPropertyValue(SERVER, false);
String rootUrl = getPropertyValue(ROOTURL, false);
String method = getPropertyValue(METHOD_SYMBOL, false);
boolean proxyServer = getPropertyValueBoolean(PROXYSERVER, false);
String proxyHost = getPropertyValue(PROXYHOST, true);
String proxyPort = getPropertyValue(PROXYPORT, true);
String mapping = getPropertyValue(MAPPING, false);
// true,存在为null,则返回
String charsetLocal = getPropertyValue(CHARSET, true);
String httpRetry = getPropertyValue(HTTPRETRY, false);
String connectTimeout = getPropertyValue(CONNECT_TIMEOUT, false);
String readTimeout = getPropertyValue(READ_TIMEOUT, false);
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
RequestConfig.Builder requestConfig = RequestConfig.custom();
SocketConfig.Builder socketConfig = SocketConfig.custom();
CookieStore cookieStore = new BasicCookieStore();
if (StringUtil.isNotEmpty(charsetLocal)) {
charset = Charset.forName(charsetLocal);
}
if (proxyServer) {
if (StringUtil.isEmpty(proxyHost) || StringUtil.isEmpty(proxyPort)) {
throw new IllegalArgumentException(proxyHost + "," + proxyPort);
}
requestConfig.setProxy(new HttpHost(proxyHost, Integer.parseInt(proxyPort), type));
}
requestConfig.setConnectTimeout(Integer.parseInt(connectTimeout)).setSocketTimeout(Integer.parseInt(readTimeout));
httpClient = clientBuilder
.setRetryHandler(new DefaultHttpRequestRetryHandler(Integer.parseInt(httpRetry), true))
.setDefaultCookieStore(cookieStore)
.setDefaultRequestConfig(requestConfig.build())
.setDefaultSocketConfig(socketConfig.build()).build();
HttpRequestBase httpRequestBase;
String url = (Objects.equals("http", type) ? HTTP : HTTPS) + server + rootUrl + mapping;
if (GET.equals(method)) {
httpRequestBase = new HttpGet(url);
} else if (POST.equals(method)) {
HttpPost httpPost = new HttpPost(url);
if (params.containsKey(BODY)) {
Object obj = params.get(BODY);
if (obj instanceof String) {
httpPost.setEntity(new StringEntity((String) obj, charset));
} else {
httpPost.setEntity(new StringEntity(CommonFunctionUtils.toJson(obj), charset));
}
}
httpRequestBase = httpPost;
} else {
throw new UnsupportedOperationException(method);
}
if (params.containsKey(HEAD)) {
Map<Object, Object> head = (Map<Object, Object>) params.get(HEAD);
setHead(head, httpRequestBase);
}
String read;
try (CloseableHttpResponse response = httpClient.execute(httpRequestBase, httpClientContext)) {
StatusLine statusLine = response.getStatusLine();
int statuscode = statusLine.getStatusCode();
if (CODE == statuscode) {
read = IoUtil.read(response.getEntity().getContent(), charset);
context.setObject(read);
} else {
throw new InterfaceException("11001", "HttpConnection status code is not 200 ,but is " + statuscode);
}
} catch (IOException e) {
logger.error("url " + url, e);
throw new InterfaceException("11001", "HttpConnection exception occurs.", e);
} finally {
if (Objects.nonNull(httpClient)) {
try {
httpClient.close();
} catch (IOException e) {
logger.error("close httpClient failed" + url, e);
}
}
}
}
private void setHead(Map<Object, Object> parameters, HttpRequestBase httpRequestBase) {
for (Map.Entry<Object, Object> entry : parameters.entrySet()) {
httpRequestBase.setHeader(entry.getKey().toString(), entry.getValue().toString());
}
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.el.CommonFunctionUtils;
import com.brilliance.eibs.util.StringUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
public class HttpsConnection extends AbsConnection {
public static final String HTTPS = "https://";
public static final String SERVER = "server";
public static final String ROOTURL = "rootUrl";
public static final String GET = "get";
public static final String POST = "post";
public static final String PROXYSERVER = "proxyServer";
public static final String PROXYHOST = "proxyHost";
public static final String PROXYPORT = "proxyPort";
public static final String CHARSET = "charset";
public static final String HTTPRETRY = "httpRetry";
public static final String CONNECT_TIMEOUT = "connect_timeout";
public static final String READ_TIMEOUT = "read_timeout";
public static final String STORE_PATH = "storepath";
public static final String STORE_PWD = "storepwd";
public static final String STORE_PRO = "storepro";
public static final String DEF_PRO = "TLSv1.2";//"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"
public static final String MAPPING = "mapping";
public static final String BODY = "body";
public static final String HEAD = "head";
final int CODE = HttpStatus.SC_OK;
private final HttpClientContext httpClientContext = new HttpClientContext();
Map<String, Object> params;
private Charset charset = Charset.forName("UTF-8");
private CloseableHttpClient httpClient;
@Override
public void execute(Context context) {
params = (Map<String, Object>) context.getObject();//必须得从上下文中拿到参数列表
context.setCurrentInstance(this);
super.execute(context);
String type = getPropertyValue(TYPE, false);
String server = getPropertyValue(SERVER, false);
String rootUrl = getPropertyValue(ROOTURL, false);
String method = getPropertyValue(METHOD_SYMBOL, false);
boolean proxyServer = getPropertyValueBoolean(PROXYSERVER, false);
String proxyHost = getPropertyValue(PROXYHOST, true);
String proxyPort = getPropertyValue(PROXYPORT, true);
String mapping = getPropertyValue(MAPPING, false);
String charsetLocal = getPropertyValue(CHARSET, true);//true,存在为null,则返回
String httpRetry = getPropertyValue(HTTPRETRY, false);
String connectTimeout = getPropertyValue(CONNECT_TIMEOUT, false);
String readTimeout = getPropertyValue(READ_TIMEOUT, false);
String storePath = getPropertyValue(STORE_PATH, false);
String storePwd = getPropertyValue(STORE_PWD, false);
String storePro = StringUtil.isEmpty(getPropertyValue(STORE_PRO, true))? DEF_PRO :
getPropertyValue(STORE_PRO, true);
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
RequestConfig.Builder requestConfig = RequestConfig.custom();
SocketConfig.Builder socketConfig = SocketConfig.custom();
CookieStore cookieStore = new BasicCookieStore();
if (StringUtil.isNotEmpty(charsetLocal)) {
charset = Charset.forName(charsetLocal);
}
if (proxyServer) {
if (StringUtil.isEmpty(proxyHost) || StringUtil.isEmpty(proxyPort)) {
throw new IllegalArgumentException(proxyHost + "," + proxyPort);
}
requestConfig.setProxy(new HttpHost(proxyHost, Integer.parseInt(proxyPort), type));
}
requestConfig.setConnectTimeout(Integer.parseInt(connectTimeout)).setSocketTimeout(Integer.parseInt(readTimeout));
SSLConnectionSocketFactory security = null;
try {
security = getSecurity(storePath, storePwd, storePro);
} catch (Exception e) {
logger.error( "create SSLConnectionSocketFactory failed:", e);
throw new InterfaceException("11001", "create SSLConnectionSocketFactory failed.", e);
}
httpClient = clientBuilder
.setRetryHandler(new DefaultHttpRequestRetryHandler(Integer.parseInt(httpRetry), true))
.setDefaultCookieStore(cookieStore)
.setDefaultRequestConfig(requestConfig.build())
.setDefaultSocketConfig(socketConfig.build())
.setSSLSocketFactory(security).build();
HttpRequestBase httpRequestBase;
String url = HTTPS + server + rootUrl + mapping;
if (GET.equals(method)) {
httpRequestBase = new HttpGet(url);
} else if (POST.equals(method)) {
HttpPost httpPost = new HttpPost(url);
if (params.containsKey(BODY)) {
Object obj = params.get(BODY);
if (obj instanceof String) {
httpPost.setEntity(new StringEntity((String) obj, charset));
} else {
httpPost.setEntity(new StringEntity(CommonFunctionUtils.toJson(obj), charset));
}
}
httpRequestBase = httpPost;
} else {
throw new UnsupportedOperationException(method);
}
if (params.containsKey(HEAD)) {
Map<Object, Object> head = (Map<Object, Object>) params.get(HEAD);
setHead(head, httpRequestBase);
}
String read;
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpRequestBase, httpClientContext);
StatusLine statusLine = response.getStatusLine();
int statuscode = statusLine.getStatusCode();
if (CODE == statuscode) {
read = IOUtils.toString(response.getEntity().getContent(), charset);
context.setObject(read);
} else {
throw new InterfaceException("11001", "HttpConnection status code is not 200 ,but is " + statuscode);
}
} catch (IOException e) {
logger.error( "url " + url, e);
throw new InterfaceException("11001", "HttpConnection exception occurs.", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error( "close CloseableHttpResponse failed" + url, e);
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
logger.error( "close httpClient failed" + url, e);
}
}
}
}
private void setHead(Map<Object, Object> parameters, HttpRequestBase httpRequestBase) {
for (Map.Entry<Object, Object> entry : parameters.entrySet()) {
httpRequestBase.setHeader(entry.getKey().toString(), entry.getValue().toString());
}
}
private SSLConnectionSocketFactory getSecurity(String storePath, String storePwd, String protocol)
throws KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException, CertificateException {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream clientInputStream = null;
try {
clientInputStream = new FileInputStream(storePath);
trustStore.load(clientInputStream, storePwd.toCharArray());
} finally {
if (clientInputStream != null) {
clientInputStream.close();
}
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).setProtocol(protocol).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
return sslsf;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.StringUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* INIFilter格式处理
* @author gechengyang
*
*/
public class INIFilter
extends AbsFilter
{
Map<String, Map<String, Object>> iniFile = new HashMap<String, Map<String, Object>>();
public void execute(Context context)
{
logger.info(LOG_FLAG + "INIFilter is begining to runnig." + LOG_FLAG);
context.setCurrentInstance(this);
String type = getFilterDef().getType();
try
{
iniFile = initINIFile((List<String>) context.getObject());
if (type.equals("out"))
{
super.execute(context);
context.setObject(write());
}
else
{
logger.info(LOG_FLAG + "INIFilterFilter解析" + LOG_FLAG);
super.execute(context);
}
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
logger.info(LOG_FLAG + "INIFilterFilter has finished running." + LOG_FLAG);
}
@Override
protected void packField(IFieldDef fieldDef, Object fieldValue)
{
String etag = (String) elParser.getExPression(context, fieldDef.getEtag(), null);
if (!StringUtil.isEmpty(etag))
{
String section = etag.split("\\.")[0];
String key = etag.split("\\.")[1];
setValue(section, key, fieldValue);
}
}
@Override
public Object getFieldValue(IFieldDef fieldDef)
{
String etag = (String) elParser.getExPression(context, fieldDef.getEtag(), null);
if (!StringUtil.isEmpty(etag))
{
String section = etag.split("\\.")[0];
String key = etag.split("\\.")[1];
return getValue(section, key);
}
return null;
}
public boolean delete(String section)
{
iniFile.remove(section);
return true;
}
public Map<String, Map<String, Object>> initINIFile(List<String> list)
throws IOException
{
Map<String, Map<String, Object>> iniFile = new HashMap<String, Map<String, Object>>();
String section = null;
for (String str : list)
{
if (StringUtil.isEmpty(str))
continue;
if (str.startsWith("["))
{
Map<String, Object> itemMap = new HashMap<String, Object>();
section = str.substring(1, str.length() - 1);
//System.out.println(section);
iniFile.put(section.trim(), itemMap);
}
else
{
Map<String, Object> itemMap = iniFile.get(section);
String key = str.substring(0, str.indexOf("="));
String value = str.substring(str.indexOf("=") + 1);
itemMap.put(key.trim(), value.trim());
// System.out.println(itemMap);
}
}
return iniFile;
}
public Map<String, Map<String, Object>> getAllNodes()
{
return iniFile;
}
public Object getValue(String section, String key)
{
Object obj = null;
Map<String, Object> item = iniFile.get(section);
if (item != null)
{
obj = item.get(key);
}
return obj;
}
public void setValue(String section, String key, Object value)
{
Map<String, Object> sectionMap = iniFile.get(section);
if (sectionMap == null)
{
sectionMap = new HashMap<String, Object>();
iniFile.put(section, sectionMap);
}
sectionMap.put(key, value);
}
public String write()
throws IOException
{
String lineSeparator = System.getProperty("line.separator", "\n");
StringBuilder sb = new StringBuilder("");
for (String section : iniFile.keySet())
{
sb.append("[").append(section).append("]").append(lineSeparator);
Map<String, Object> map = iniFile.get(section);
Set<String> keySet = map.keySet();
for (String key : keySet)
{
sb.append(key).append("=").append(map.get(key)).append(lineSeparator);
}
}
return sb.toString();
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.model.IModuleDef;
import com.brilliance.eibs.core.model.ISubfieldDef;
import com.brilliance.eibs.core.module.ISO8583Module;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.StringUtil;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 8583格式处理(支持万事达接口报文)
*
*/
public class ISO8583Filter extends AbsFilter {
private String direction;
private String iso8583str = "";
private List<String> bitmaplist = new ArrayList<String>();
String encoding = null;
ISO8583Module iso8583Module = null;
IModuleDef moduleDef = null;
public void execute(Context context) {
try {
encoding = getFilterDef().getEncoding();
String type = getFilterDef().getType();
// logger.info( LOG_FLAG +
// "ISO8583Filter is begining to runnig." + LOG_FLAG);
context.setCurrentInstance(this);
propertySaveToContext();
String id = (String) context.getVariable("moduleid");
moduleDef = context.getModulesMap().get(id);
if ("in".equals(getFilterDef().getType())) {
iso8583Module = new ISO8583Module(encoding, context.getObject(), moduleDef);
Map<String, Object> map = iso8583Module.unpackModule();
context.setObject(map);
// for(Map.Entry<String, Object> entry:map.entrySet()){
// saveToContext("transaction", entry.getKey(),
// entry.getValue());
// }
}
if (type.equals("out")) {
super.execute(context);
// logger.info( LOG_FLAG + "ISO8583Filter组装" +
// LOG_FLAG);
int bitmapsize = Integer.parseInt((String) context.getVariable("bitmapsize"));
byte[] bitmap = new byte[bitmapsize];
for (int i = 0; i < bitmapsize; i++) {
bitmap[i] = 0x00;
}
logger.debug( toBinaryString(bitmap));
if (bitmapsize == 16)
setBitmap(0, bitmap, true);
for (int index = 0; index < bitmaplist.size(); index++) {
String etag = bitmaplist.get(index);
int sequence = Integer.parseInt(etag);
setBitmap(sequence, bitmap, true);
}
byte[] bodybytes = new byte[bitmapsize + iso8583str.getBytes(encoding).length];
System.arraycopy(bitmap, 0, bodybytes, 0, bitmapsize);
System.arraycopy(iso8583str.getBytes(), 0, bodybytes, bitmapsize, iso8583str.getBytes(encoding).length);
logger.debug( toBinaryString(bodybytes));
context.setObject(bodybytes);
// saveToContext(getFilterDef().getScope(),
// getFilterDef().getTag(),
// context.getObject());
String aString = new String(bodybytes);
logger.debug( toBinaryString(bitmap));
logger.debug( aString);
} else {
// logger.info( LOG_FLAG + "ISO8583Filter解析" +
// LOG_FLAG);
}
// logger.info( LOG_FLAG +
// "ISO8583Filter has finished running." + LOG_FLAG);
} catch (Exception e) {
if (e instanceof InterfaceException)
throw (InterfaceException) e;
throw new InterfaceException("10000", e.getMessage(), e);
}
}
/**
* byte[]转化为十六进制字符串
*
* @param bytes
* @return
*/
public String toHexString(byte[] bytes) {
String str = "";
for (byte b : bytes) {
String hex = Integer.toHexString(b & 0xff);
if (hex.length() == 1) {
hex = '0' + hex;
}
str += hex;
}
return str;
}
/**
*
* @param bytes
* @return
*/
public String toBinaryString(byte[] bytes) {
String str = "";
for (byte b : bytes) {
String hex = Integer.toBinaryString(b & 0xff);
hex = String.format("%08d", Integer.parseInt(hex));
str += hex;
}
return str;
}
/**
* 设置bitmap的sequence对应位
*
* @param seq
* @param bitmap
* @param zero
*/
public void setBitmap(int seq, byte[] bitmap, boolean one) {
byte[] ones = new byte[] { (byte) 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
byte[] zeros = new byte[] { (byte) 0x7f, (byte) 0xbf, (byte) 0xd0, (byte) 0xef, (byte) 0xf7, (byte) 0xfb, (byte) 0xfd, (byte) 0xfe };
if (one)
bitmap[seq / 8] |= ones[seq % 8];
else
bitmap[seq / 8] &= zeros[seq % 8];
}
public void setDirection(String director) {
this.direction = director;
}
public String getDirection() {
return this.direction;
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
return null;
}
protected void packField(IFieldDef fieldDef, Object value) {
String str = (String) value;
String[] pars = str.split(":");
String tmpstr = "";
String etag = fieldDef.getEtag();
IFieldDef dstField = moduleDef.getMap().get(etag);
if (pars.length > 1) {
List<ISubfieldDef> subFieldDefs = dstField.getSubfields();
for (int i = 0; i < pars.length; i++) {
tmpstr += packFieldCore(subFieldDefs.get(i), pars[i]);
}
tmpstr = packFieldCore(dstField, tmpstr);
} else {
tmpstr = packFieldCore(dstField, value);
}
iso8583str += tmpstr;
bitmaplist.add(etag);
}
private String packFieldCore(IFieldDef fieldDef, Object value) {
String direct = "l";
String fillchar = " ";
String str = (String) value;
String type = fieldDef.getType();
if ("vrString".equals(type)) {
int size = 0;
String fieldSize = fieldDef.getSize();
String varSize = fieldDef.getVarSize();
if (StringUtil.isEmpty(fieldSize)) {
size = Integer.parseInt(StringUtil.repeat("9", Integer.parseInt(varSize)));
} else
size = Integer.parseInt(varSize);
if (str.length() > size) {
throw new InterfaceException("01003", "Length of 8583 string [" + str + "] is [" + str.length() + "],while size limit is [" + size
+ "]");
}
try {
str = String.format("%0" + varSize + "d", str.getBytes(encoding).length) + str;
} catch (UnsupportedEncodingException e) {
throw new InterfaceException("00403", "unsupported encoding:" + encoding, e);
}
} else {
int size = Integer.parseInt(fieldDef.getSize());
if (str.length() > size) {
throw new InterfaceException("01003", "Length of 8583 string [" + str + "] is [" + str.length() + "],while size limit is [" + size
+ "]");
}
if (str.length() < size) {
direct = !StringUtil.isEmpty(fieldDef.getDirect()) ? fieldDef.getDirect() : direct;
fillchar = !StringUtil.isEmpty(fieldDef.getFill()) ? fieldDef.getFill() : fillchar;
if (direct.equalsIgnoreCase("left") || direct.equalsIgnoreCase("l"))
str = StringUtil.repeat(fillchar, size - str.length()) + str;
else if (direct.equalsIgnoreCase("right") || direct.equalsIgnoreCase("r"))
str = str + StringUtil.repeat(fillchar, size - str.length());
}
}
return str;
}
/**
* 将正常的带小数点的数据转换为第一位表示小数位置的无小数点数据。例如将"9.972522"转换为"69972522"
*
* @param value
* @return
*/
public String decimalPositionRate(String value) {
if (value.lastIndexOf(".") == -1)
return "0" + value;
else {
return (value.length() - value.lastIndexOf(".") - 1) + value.replace(".", "");
}
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
public class InnerFilter
extends AbsFilter
{
@Override
public Object getFieldValue(IFieldDef fieldDef)
{
// TODO Auto-generated method stub
return null;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.javamail.MailSenderInfo;
import com.brilliance.eibs.javamail.SimpleMailSender;
import java.io.UnsupportedEncodingException;
/**
* 邮件功能
* @author gechengyang
* **/
public class JavaMailConnection
extends AbsConnection
{
public void execute(Context context)
{
logger.info(LOG_FLAG + "JavaMailConnection is Running." + LOG_FLAG);
String type = connectionDef.getType();
String encode = connectionDef.getEncoding();
boolean isSend = false;
//发送邮件
try
{
if (isSendMail(type))
{
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost(getPropertyValue("mailServerHost"));
logger.info("javamail serverHost:" + mailInfo.getMailServerHost());
mailInfo.setMailServerPort(getPropertyValue("mailServerPort"));
logger.info("javamail serverPort:" + mailInfo.getMailServerHost());
mailInfo.setFromAddress(getPropertyValue("fromAddress"));
logger.info("javamail fromAddress" + mailInfo.getFromAddress());
mailInfo.setToAddress(getPropertyValue("toAddress"));
logger.info("javamail toAddress" + mailInfo.getToAddress());
mailInfo.setUserName(getPropertyValue("userName"));
mailInfo.setPassword(getPropertyValue("password"));
mailInfo.setValidate(Boolean.parseBoolean((getPropertyValue("validate"))));
mailInfo.setSubject(getPropertyValue("subject"));
mailInfo.setCharset(encode);
mailInfo.setContent(getPropertyValue("content"));
String filename = getPropertyValue("fileName",true);
if (filename!=null && filename!="") {
mailInfo.setFilename(filename);
}
SimpleMailSender sms = new SimpleMailSender();
//发送文体格式
isSend = sms.sendTextMail(mailInfo);
logger.info("邮件发送状态为" + isSend);
}
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
throw new InterfaceException("00010", "JavaMailConnection exception occurs.", e);
}
context.setObject(isSend);
logger.info(LOG_FLAG + "JavaMailConnection has finished running." + LOG_FLAG);
}
private boolean isSendMail(String type)
{
return WRITE_FLG.equals(type);
}
private boolean isReciveMail(String type)
{
return READ_FLG.equals(type);
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IConnectionDef;
import com.brilliance.eibs.core.model.IPropertyDef;
import com.brilliance.eibs.core.model.impl.ConnectionDef;
import com.brilliance.eibs.core.service.Context;
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.JdbcExecutor;
import com.brilliance.eibs.util.LogUtil;
import com.brilliance.eibs.util.StringUtil;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 数据库连接类,创建数据库连接,并存入上下文
*
* @author xiaoyuanzhen
*/
public class JdbcConnection extends AbsConnection {
public static final String SQL_SESSION = "__sqlSession";
public final String CNT = "_cnt";
public void execute(Context context) {
// logger.debug( LOG_FLAG + "JdbcConnection is running." +
// LOG_FLAG);
context.setCurrentInstance(this);
super.execute(context);
ConnectionAdaptor connectionAdator = null;
Connection connection = null;
JdbcExecutor executor = null;
IConnectionDef connectionDefTmp = new ConnectionDef();
connectionDefTmp.combine(connectionDef);
String joinedId = connectionDefTmp.getJoinedid();
if (StringUtil.isEmpty(joinedId)) {
try {
IPropertyDef proDef = connectionDefTmp.getProperty("url");
String value = connectionDefTmp.getProperty("url").getValue();
value = (String) elParser.getExPression(context, value, null);
proDef.setValue(value);
connectionDefTmp.addProperty("url", proDef);
connectionAdator = createConnection(connectionDefTmp);
connection = connectionAdator.getConnection();
connection.setAutoCommit(false);
context.getResource().setConnection(connection);
boolean useCnt = Boolean.valueOf(getPropertyValue("use_table_cnt", true));
if (useCnt) {
connectionDefTmp.setId(connectionDefTmp.getId() + CNT);
ConnectionAdaptor cntConnectionAdator = createConnection(connectionDefTmp);
Connection cntConnection = cntConnectionAdator.getConnection();
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);
} else {
try {
context.setRollbackFlag(1);
connectionDefTmp.setId(connectionDefTmp.getId() + joinedId);
connection = createConnectionJoined(connectionDefTmp);
// connection.setAutoCommit(false);
context.getResource().setConnection(connection);
} 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.debug( LOG_FLAG +
// "JdbcConnection has finished runnig." + LOG_FLAG);
}
private ConnectionAdaptor createConnection(IConnectionDef connectionDefintion) throws SQLException, ClassNotFoundException {
String id = connectionDefintion.getId();
ConnectionAdaptor connectionAdaptor = context.getConnectionAdaptors().get(id);
if (null == connectionAdaptor || connectionAdaptor.isClosed()) {
connectionAdaptor = new ConnectionAdaptor(DBConnPool.getConnection(connectionDefintion, LogUtil.getLogger(context)));
context.getConnectionAdaptors().put(id, connectionAdaptor);
}
return connectionAdaptor;
}
private Connection createConnectionJoined(IConnectionDef connectionDefintion) throws Exception {
/*
* 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;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IConnectionDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.plugin.JSPool;
import com.brilliance.eibs.util.LogUtil;
import redis.clients.jedis.Jedis;
public class JedisConnection extends AbsConnection {
public void execute(Context context) {
// logger.info( LOG_FLAG + "JedisConnection is running." +
// LOG_FLAG);
context.setCurrentInstance(this);
super.execute(context);
Jedis jedis = null;
jedis = createConnection(connectionDef);
context.getResource().getJedisProxy().setJedis(jedis);
}
private Jedis createConnection(IConnectionDef connectionDefintion) {
String id = connectionDefintion.getId();
Jedis jedis = context.getJedisManager().getJediss().get(id);
if (null == jedis) {
jedis = JSPool.getConnection(connectionDefintion, LogUtil.getLogger(context));
context.getJedisManager().getJediss().put(id, jedis);
}
return jedis;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IPropertyDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.JsonUtil;
import com.brilliance.eibs.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.PropertyValue;
import org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter;
import org.springframework.jms.support.JmsUtils;
import javax.jms.*;
import java.util.Map;
/**
* 发送消息到mq的统一连接
*/
public class JmsConnection extends AbsConnection {
private static final String CONNECTION_FACTORY_SYMBOL = "connectionFactory";
private static final String USERNAME_SYMBOL = "username";
private static final String PASSWORD_SYMBOL = "xpassword";
private static final String CONNECTION_FACTORY_PROPERTY_PRE_SYMBOL = "connectionFactory.";
private static final String QUEUE_SYMBOL = "queue";
private static final String TIMEOUT_SYMBOL = "timeout";
private static ConnectionFactory connectionFactory;
public void execute(Context context) {
Connection connection = null;
Session session = null;
try {
String connectionFactoryClaz = getPropertyValue(CONNECTION_FACTORY_SYMBOL);
Class<?> connectionFactoryClazz = Class.forName(connectionFactoryClaz);
connectionFactory = (ConnectionFactory) BeanUtils.instantiate(connectionFactoryClazz);
String username = null;
String password = null;
Map<String, IPropertyDef> propertyMap = getPropertyMap();
if (propertyMap != null && !propertyMap.isEmpty()) {
// 连接工厂设置属性,动态设置
for (Map.Entry<String, IPropertyDef> entry : propertyMap.entrySet()) {
String propertyName = entry.getKey();
String value = entry.getValue().getValue();
if (propertyName.startsWith(CONNECTION_FACTORY_PROPERTY_PRE_SYMBOL)) {
propertyName = propertyName.substring(CONNECTION_FACTORY_PROPERTY_PRE_SYMBOL.length());
BeanWrapper bw = new BeanWrapperImpl(connectionFactory);
Object convertedValue = ((BeanWrapperImpl) bw).convertForProperty(value, propertyName);
PropertyValue pv = new PropertyValue(propertyName, convertedValue);
bw.setPropertyValue(pv);
} else if (USERNAME_SYMBOL.equals(propertyName)) {
username = value;
} else if (PASSWORD_SYMBOL.equals(propertyName)) {
password = value;
}
}
}
if (StringUtil.isNotEmpty(username)) {
UserCredentialsConnectionFactoryAdapter ucfa = new UserCredentialsConnectionFactoryAdapter();
ucfa.setTargetConnectionFactory(connectionFactory);
ucfa.setUsername(username);
ucfa.setPassword(password);
connectionFactory = ucfa;
}
// create connection
connection = connectionFactory.createConnection();
connection.start();
// create the session
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
String queue = getPropertyValue(QUEUE_SYMBOL);
Destination destination = session.createQueue(queue);
if ("out".equalsIgnoreCase(getType())) {
// create the producer
MessageProducer producer = session.createProducer(destination);
// create and send the message
Object messages = context.getObject();
if (messages instanceof String) {
String stringMessage = (String) messages;
Message message = session.createTextMessage(stringMessage);
producer.send(message);
} else if (messages instanceof byte[]) {
byte[] byteMessage = (byte[]) messages;
BytesMessage message = session.createBytesMessage();
message.writeBytes(byteMessage);
producer.send(message);
} else if (messages instanceof Map) {
Map<String, Object> mapMessage = (Map) messages;
MapMessage message = session.createMapMessage();
for (Map.Entry<String, Object> entry : mapMessage.entrySet()) {
message.setObject(entry.getKey(), entry.getValue());
}
producer.send(message);
producer.close();
}
logger.info("Send Message Completed:" + JsonUtil.toJson(messages));
} else if ("in".equalsIgnoreCase(getType())) {
String timeoutStr = getPropertyValue(TIMEOUT_SYMBOL, true);
long timeout = StringUtil.isEmpty(timeoutStr) ? 0L : Long.parseLong(timeoutStr);
MessageConsumer consumer = session.createConsumer(destination);
context.setObject(null);
// receive msg
Message msg = consumer.receive(timeout);
if (msg instanceof TextMessage) {
context.setObject(((TextMessage) msg).getText());
} else if (msg instanceof MapMessage) {
MapMessage message = (MapMessage) msg;
context.setObject(message);
} else if (msg instanceof BytesMessage) {
byte[] b = new byte[1024];
BytesMessage message = (BytesMessage) msg;
while ((message.readBytes(b)) != -1) {
}
context.setObject(b);
}
consumer.close();
super.execute(context);
logger.info("receive Message Completed:" + JsonUtil.toJson(context.getObject()));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
JmsUtils.closeSession(session);
JmsUtils.closeConnection(connection, true);
}
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import javax.jms.*;
public class JmsFilter extends AbsFilter {
private MessageProducer producer;
public void execute(final Context context) {
logger.info("Running JmsFilter.");
context.setCurrentInstance(this);
MessageConsumer comsumer = (MessageConsumer) context.getObject();
try {
comsumer.setMessageListener(new MessageListener() {
public void onMessage(Message m) {
try {
if (m instanceof TextMessage) { // 接收文本消息
TextMessage message = (TextMessage) m;
context.setObject(message.getText());
} else if (m instanceof MapMessage) { // 接收键值对消息
MapMessage message = (MapMessage) m;
context.setObject(message);
} else if (m instanceof StreamMessage) { // 接收流消息
StreamMessage message = (StreamMessage) m;
context.setObject(message);
} else if (m instanceof BytesMessage) { // 接收字节消息
byte[] b = new byte[1024];
int len = -1;
BytesMessage message = (BytesMessage) m;
while ((len = message.readBytes(b)) != -1) {
System.out.println(new String(b, 0, len));
}
context.setObject(b);
} else if (m instanceof ObjectMessage) { // 接收对象消息
ObjectMessage message = (ObjectMessage) m;
context.setObject(message.getObject());
}
handmessage();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Object getFieldValue(IFieldDef fieldDef) {
// TODO Auto-generated method stub
return null;
}
private boolean isSend(String type) {
return WRITE_FLG.equals(type);
}
public void handmessage() {
super.execute(context);
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.core.service.instance.plugin.ConnectionAdaptor;
import com.brilliance.eibs.core.service.instance.plugin.JdbcExecutor;
import com.brilliance.eibs.util.StringUtil;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
/**
* 数据库连接类,使用JNDI数据源获取数据库连接
*
* @author xiaoyuanzhen
*
*/
public class JndiDsConnection extends AbsConnection {
/**
* 数据源
*/
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);
Connection connection = null;
JdbcExecutor executor = null;
String id = connectionDef.getId();
try {
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);
}
/**
* 获取数据源
*
* @return
* @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>();
if (!StringUtil.isEmpty(providerUrl)) {
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
* @return
* @throws SQLException
*/
private Connection createConnection(String id) throws SQLException {
ConnectionAdaptor connAdaptor = context.getConnectionAdaptors().get(id);
if (connAdaptor == null || connAdaptor.isClosed()) {
Connection conn = dataSource.getConnection();
connAdaptor = new ConnectionAdaptor(conn);
context.getConnectionAdaptors().put(id, connAdaptor);
}
return connAdaptor.getConnection();
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.util.StringUtil;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.util.*;
public class LdapConnection
extends AbsConnection
{
private LdapContext ldapContext;
private String[] attrs;
private String searchDN;
private String searchfilter = "(objectClass=*)";
private int searchScope = SearchControls.ONELEVEL_SCOPE;
@Override
public void execute(com.brilliance.eibs.core.service.Context context)
{
logger.info(LOG_FLAG + "LdapConnection is Running." + LOG_FLAG);
context.setCurrentInstance(this);
String url = getPropertyValue("url");
logger.info("ldap url=" + url);
String dn = getPropertyValue("dn");
String password = getPropertyValue("password", true);
/* String xpassword = getPropertyValue("xpassword", true);
if (StringUtil.isEmpty(password) && !StringUtil.isEmpty(xpassword))
password = DESCoder.getMingWenByDes(xpassword);*/
searchDN = (String) elParser.getExPression(context, getPropertyValue("searchdn"), null);
String return_attrs = getPropertyValue("return_attrs", true);
String search_filter = getPropertyValue("searchfilter", true);
String search_scope = getPropertyValue("searchscope", true);
String connection_time = getPropertyValue("connected_timeout", true);
if (!StringUtil.isEmpty(search_scope))
searchScope = Integer.parseInt(search_scope);
if (!StringUtil.isEmpty(search_filter))
searchfilter = search_filter;
if (StringUtil.isEmpty(return_attrs) || return_attrs.equals("all"))
attrs = null;
else if (return_attrs.equals("null"))
attrs = new String[]{};
else
attrs = return_attrs.split(",");
connect(url, dn, password, connection_time);
List<Map<String, String>> results = getGroups();
logger.debug("ldap result size:" + results.size());
context.setObject(results);
close();
logger.info(LOG_FLAG + "LdapConnection has finished running." + LOG_FLAG);
// String outputString = "";
// for (Map<String, String> result : results)
// {
// outputString += result + System.getProperty("line.separator");
// }
// logger.debug("ldap result:" + outputString);
}
//搜索用户在哪些组中
public List<Map<String, String>> getGroups()
{
// 搜索控制,我们仅需要取得group的cn属性.
SearchControls searchControls = new SearchControls(searchScope, 0, 0, attrs, false, false);
// 搜索条件,类型为groupOfUniqueNames,包含成员userDn (注意uniqueMember为包含用户的dn,个别情况,可能不是完整dn,如:uid=000010,cn=users,
// 我们不考虑dn不完整的情况,不完整时当作错误数据处理即可)
List<Map<String, String>> results = new ArrayList<Map<String, String>>();
try
{
// 搜索
NamingEnumeration<SearchResult> enu = ldapContext.search(searchDN, searchfilter, searchControls);
while (enu.hasMore())
{
// 结果
SearchResult result = enu.next();
Attributes attributes = result.getAttributes();
NamingEnumeration<? extends Attribute> attrs = attributes.getAll();
Map<String, String> attrMap = new HashMap<String, String>();
while (attrs.hasMore())
{
Attribute attr = attrs.next();
Object obj = attr.get();
if (obj instanceof byte[])
{
attrMap.put(attr.getID(), new String((byte[]) obj));
}
else
attrMap.put(attr.getID(), (String) attr.get());
}
results.add(attrMap);
}
}
catch (NamingException e)
{
throw new InterfaceException("01602", e);
}
return results;
}
public void connect(String url, String dn, String password, String connection_time)
{
Hashtable<String, String> env = new Hashtable<String, String>();
// ldap上下文工厂
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put("com.sun.jndi.ldap.connect.timeout", connection_time);
if (StringUtil.isEmpty(password))
// ldap登录方式(none)
env.put(Context.SECURITY_AUTHENTICATION, "none");
else
{
// ldap登录方式(simple)
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_CREDENTIALS, password); // ldap访问密码
}
// ldap访问url
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_PRINCIPAL, dn); // ldap访问用户名,一般都会是dn的形式,如cn=admin
try
{
// 创建ldap上下文
ldapContext = new InitialLdapContext(env, null);
}
catch (NamingException e)
{
throw new InterfaceException("01601", e);
}
logger.debug("connect ldap success.");
}
private void close()
{
try
{
// 关闭ldap访问上下文
ldapContext.close();
}
catch (NamingException e)
{
throw new InterfaceException("01603", e);
}
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.monitor.nms.LogMenuParser;
import org.dom4j.DocumentException;
public class LogMonitorMenuFilter
extends AbsFilter {
@Override
public void execute(Context context) {
logger.info(LOG_FLAG + "LogMonitorMenuFilter is running" + LOG_FLAG);
context.setCurrentInstance(this);
super.execute(context);
LogMenuParser parser = new LogMenuParser();
try {
String content = (String) context.getObject();
context.setObject(parser.parseMenuXML(content));
} catch (DocumentException e) {
throw new InterfaceException("02801", e);
}
logger.info(LOG_FLAG + "LogMonitorMenuFilter has finished running" + LOG_FLAG);
}
@Override
public Object getFieldValue(IFieldDef fieldDef)
throws Exception {
return null;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.monitor.nms.LogFileSearcher;
import com.brilliance.eibs.util.StringUtil;
import javax.servlet.http.HttpServletRequest;
public class LogMonitorPageFilter
extends AbsFilter
{
@Override
public void execute(Context context)
{
logger.info(LOG_FLAG + "LogMonitorPageFilter is running" + LOG_FLAG);
context.setCurrentInstance(this);
super.execute(context);
HttpServletRequest request = (HttpServletRequest) context.getObject();
String files = request.getParameter("files");
String starttime = request.getParameter("starttime");
String endtime = request.getParameter("endtime");
int page = Integer.valueOf(request.getParameter("page"));
int records = Integer.valueOf(request.getParameter("rows"));
LogFileSearcher searcher = new LogFileSearcher(StringUtil.isEmpty(files) ? null : files.split(","));
searcher.setTime(starttime, endtime);
context.setObject(searcher.query(page, records));
logger.info(LOG_FLAG + "LogMonitorPageFilter has finished running" + LOG_FLAG);
}
@Override
public Object getFieldValue(IFieldDef fieldDef)
throws Exception
{
return null;
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.exception.InterfaceException;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.StringUtil;
import com.ibm.mq.MQException;
import com.ibm.mq.MQQueueManager;
import java.util.Hashtable;
/**
* mq连接器
*
* @author hujun
*
*/
public class MQConnection extends AbsConnection {
@Override
public void execute(Context context) {
logger.info( LOG_FLAG + "MQConnection is Running." + LOG_FLAG);
context.setCurrentInstance(this);
try {
// MQEnvironment.port = getPropertyValueInt(PORT_SYMBOL);
// logger.debug("mq port=" + MQEnvironment.port);
// MQEnvironment.hostname = getPropertyValue(IP_SYMBOL);
// logger.debug("mq ip=" + MQEnvironment.hostname);
// MQEnvironment.channel = getPropertyValue(MQ_CHANNEL_SYMBOL);
// MQEnvironment.CCSID = getPropertyValueInt(MQ_CCSID_SYMBOL);
// String userId= getPropertyValue("userID",true);
int port = getPropertyValueInt(PORT_SYMBOL);
logger.debug( "mq port=" + port);
String hostname = getPropertyValue(IP_SYMBOL);
logger.debug( "mq ip=" + hostname);
String channel = getPropertyValue(MQ_CHANNEL_SYMBOL);
int CCSID = getPropertyValueInt(MQ_CCSID_SYMBOL);
String userId = getPropertyValue("userID", true);
String password = getPropertyValue("password", true);
// if(StringUtil.isEmpty(userId))
// {
// MQEnvironment.userID =userId;
// }
logger.debug( "mq cssid=" + CCSID);
String managerName = getPropertyValue(MQ_QUEUE_MANAGER_SYMBOL);
// addProp2Context(MQ_QUEUE_SYMBOL);
addProp2Context("transaction", MQ_QUEUE_SYMBOL);
Object obj[] = new Object[3];
Hashtable<String, Object> options = new Hashtable<String, Object>();
options.put("hostname", hostname);
options.put("port", port);
options.put("channel", channel);
options.put("CCSID", CCSID);
if (!StringUtil.isEmpty(userId)) {
options.put("userID", userId);
}
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);
}
}
package com.brilliance.eibs.core.service.instance.impl;
import com.brilliance.eibs.core.model.IFieldDef;
import com.brilliance.eibs.core.model.IModuleDef;
import com.brilliance.eibs.core.module.ISO8583Module;
import com.brilliance.eibs.core.service.Context;
import com.brilliance.eibs.util.ByteUtil;
import com.brilliance.eibs.util.StringUtil;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* 8583格式处理
* @author xiaoyuanzhen
*
*/
public class Mac8583Filter
extends AbsFilter
{
private String direction;
private List<String> bitmaplist = new ArrayList<String>();
String encoding = null;
ISO8583Module iso8583Module = null;
IModuleDef moduleDef = null;
byte subbyts[] = null;
String controlInfo = "";
String varInfos = "";
public void execute(Context context)
{
try
{
encoding = getFilterDef().getEncoding();
String type = getFilterDef().getType();
logger.info(LOG_FLAG + "Mac8583Filter is begining to runnig." + LOG_FLAG);
context.setCurrentInstance(this);
propertySaveToContext();
String id = (String) context.getVariable("moduleid");
moduleDef = context.getModulesMap().get(id);
/* if ("in".equals(getFilterDef().getType()))
{
iso8583Module = new ISO8583Module(encoding, context.getObject(), moduleDef);
}*/
super.execute(context);
if (type.equals("out"))
{
logger.info(LOG_FLAG + "Mac8583Filter组装" + LOG_FLAG);
int bitmapsize = Integer.parseInt((String) context.getVariable("bitmapsize"));
byte[] bitmap = new byte[bitmapsize];
for (int i = 0; i < bitmapsize; i++)
{
bitmap[i] = 0x00;
}
/* logger.debug(toBinaryString(bitmap));
if (bitmapsize == 16)
setBitmap(0, bitmap, true);*/
for (int index = 0; index < bitmaplist.size(); index++)
{
String etag = bitmaplist.get(index);
int sequence = Integer.parseInt(etag);
setBitmap(sequence, bitmap, true);
}
//获取controlInfo长度
int controlLen = controlInfo.length();
int controlSize = controlLen % 8 == 0 ? controlLen / 8 : (controlLen / 8 + 1);
int lef = controlSize * 8 - controlLen;
String zero = StringUtil.repeat("0", lef);
//完整信息
String bitinfo = controlInfo + zero;
logger.info("bitinfo=" + bitinfo);
byte[] bittoBytebuffer = new byte[controlSize];
for (int i = 0; i < bittoBytebuffer.length; i++)
{
String temp = bitinfo.substring(i * 8, (i + 1) * 8);
bittoBytebuffer[i] = ByteUtil.bit2byte(temp);
}
byte[] bodybytes = null;
if (subbyts != null)
{
bodybytes = new byte[bitmapsize + subbyts.length + bittoBytebuffer.length + varInfos.getBytes(encoding).length];
System.arraycopy(bitmap, 0, bodybytes, 0, bitmapsize);
System.arraycopy(subbyts, 0, bodybytes, bitmapsize, subbyts.length);
System.arraycopy(bittoBytebuffer, 0, bodybytes, bitmapsize + subbyts.length, controlSize);
System.arraycopy(varInfos.getBytes(), 0, bodybytes, bitmapsize + subbyts.length + controlSize, varInfos.getBytes(encoding).length);
}
else
{
bodybytes = new byte[bitmapsize + bittoBytebuffer.length + varInfos.getBytes(encoding).length];
System.arraycopy(bitmap, 0, bodybytes, 0, bitmapsize);
System.arraycopy(bittoBytebuffer, 0, bodybytes, bitmapsize, controlSize);
System.arraycopy(varInfos.getBytes(), 0, bodybytes, bitmapsize + controlSize, varInfos.getBytes(encoding).length);
}
logger.debug("二进制代码为=" + toBinaryString(bodybytes));
context.setObject(bodybytes);
}
else
{
logger.info(LOG_FLAG + "Mac8583Filter解析" + LOG_FLAG);
}
logger.info(LOG_FLAG + "Mac8583Filter has finished running." + LOG_FLAG);
}
catch (Exception e)
{
// TODO: handle exception
}
}
/**
* byte[]转化为十六进制字符串
* @param bytes
* @return
*/
public String toHexString(byte[] bytes)
{
String str = "";
for (byte b : bytes)
{
String hex = Integer.toHexString(b & 0xff);
if (hex.length() == 1)
{
hex = '0' + hex;
}
str += hex;
}
return str;
}
/**
*
* @param bytes
* @return
*/
public String toBinaryString(byte[] bytes)
{
String str = "";
for (byte b : bytes)
{
String hex = Integer.toBinaryString(b & 0xff);
hex = String.format("%08d", Integer.parseInt(hex));
str += hex;
}
return str;
}
/**
* 设置bitmap的sequence对应位
* @param seq
* @param bitmap
* @param zero
*/
public void setBitmap(int seq, byte[] bitmap, boolean one)
{
byte[] ones = new byte[]{(byte) 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
byte[] zeros = new byte[]{(byte) 0x7f, (byte) 0xbf, (byte) 0xd0, (byte) 0xef, (byte) 0xf7, (byte) 0xfb, (byte) 0xfd, (byte) 0xfe};
if (one)
bitmap[seq / 8] |= ones[seq % 8];
else
bitmap[seq / 8] &= zeros[seq % 8];
}
public void setDirection(String director)
{
this.direction = director;
}
public String getDirection()
{
return this.direction;
}
@Override
public Object getFieldValue(IFieldDef fieldDef)
{
return null;
}
protected void packField(IFieldDef fieldDef, Object value)
{
// String str = (String) value;
String etag = fieldDef.getEtag();
IFieldDef dstField = moduleDef.getMap().get(etag);
fieldDef.setType(dstField.getType());
fieldDef.setSize(dstField.getSize());
int size = Integer.parseInt(fieldDef.getSize());
int val = 0;
if (etag.equals("0") && (value instanceof byte[]))
{
bitmaplist.add(etag);
subbyts = (byte[]) value;
String bit = Integer.toBinaryString(1);
int bitlen = bit.length();
String left = StringUtil.repeat("0", size - bitlen);
bit = left + bit;
controlInfo += bit;
return;
}
else if (etag.equals("0") && !(value instanceof byte[])&&StringUtil.isEmpty(dstField.getVarSize()))
{
return;
}
//变长
if (dstField.getType().equals("vrString") || dstField.getType().equals("fxString"))
{
String str = (String) value;
try
{
val = str.getBytes(encoding).length;
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (dstField.getType().equals("bit"))
{
val = Integer.parseInt(value.toString());
}
if (dstField.getType().equals("vrString") || dstField.getType().equals("bit"))
{
String bit = Integer.toBinaryString(val);
int bitlen = bit.length();
String left = StringUtil.repeat("0", size - bitlen);
bit = left + bit;
controlInfo += bit;
}
//变长
if (dstField.getType().equals("vrString") || dstField.getType().equals("fxString"))
{
varInfos += value;
}
/* if (etag.equals("0") && (value instanceof byte[]))
{
bitmaplist.add(etag);
subbyts = (byte[]) value;
}*/
bitmaplist.add(etag);
}
}
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