diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..1191ca8 --- /dev/null +++ b/.classpath @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.gitignore b/.gitignore index eb7d1de..5061420 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ /bin/ /.settings/ -/.project -/.classpath +/target/ + +/com/ +/.idea/ diff --git a/.project b/.project new file mode 100644 index 0000000..d012535 --- /dev/null +++ b/.project @@ -0,0 +1,36 @@ + + + JavaUtil + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + org.eclipse.wst.common.project.facet.core.nature + + diff --git a/JavaUtil.iml b/JavaUtil.iml new file mode 100644 index 0000000..5b24bb1 --- /dev/null +++ b/JavaUtil.iml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 46badb3..7dacfef 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,11 @@ -# JavaUtil -Java Util Tool +# Java Utilities +### JDK8 or later + +## 1.console function: print println log logArray. +## 2.directly compile java source code of strings. +## 3.using function to instantiate object or create array reference. +## 4.calc running time of codes. +## 5.dynamic cast. +## 6.Promise. + + diff --git a/lib/gson-2.8.5-sources.jar b/lib/gson-2.8.5-sources.jar new file mode 100644 index 0000000..a64f4e7 Binary files /dev/null and b/lib/gson-2.8.5-sources.jar differ diff --git a/lib/gson-2.8.5.jar b/lib/gson-2.8.5.jar new file mode 100644 index 0000000..0d5baf3 Binary files /dev/null and b/lib/gson-2.8.5.jar differ diff --git a/lib/x.jar b/lib/x.jar new file mode 100644 index 0000000..669ec4a Binary files /dev/null and b/lib/x.jar differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..de62004 --- /dev/null +++ b/pom.xml @@ -0,0 +1,133 @@ + + 4.0.0 + com.github.xiuyexye + xyjava + 0.0.20 + java lib for me + + + org.sonatype.oss + oss-parent + 7 + + + + + src + test + + + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9 + + + attach-javadocs + + jar + + + -Xdoclint:none + + + + + + + + + com.google.code.gson + gson + 2.8.6 + + + junit + junit + 4.12 + test + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + jdk8 + git@github.com:XiuyeXYE/JavaUtil.git + scm:git:git@github.com:XiuyeXYE/JavaUtil.git + scm:git:git@github.com:XiuyeXYE/JavaUtil.git + + + + xiuye + xiuye_engineer@outlook.com + ABCXIUYE + + + + \ No newline at end of file diff --git a/resourceURL.txt b/resourceURL.txt new file mode 100644 index 0000000..6563258 --- /dev/null +++ b/resourceURL.txt @@ -0,0 +1 @@ +https://blog.csdn.net/wangjingna/article/details/50488921 \ No newline at end of file diff --git a/resources/config.js b/resources/config.js new file mode 100644 index 0000000..324d1bd --- /dev/null +++ b/resources/config.js @@ -0,0 +1,231 @@ +/** + * echarts默认配置项 + * + * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 + * @author Kener (@Kener-林峰, kener.linfeng@gmail.com) + * + */ +define(function() { + // 请原谅我这样写,这显然可以直接返回个对象,但那样的话outline就显示不出来了~~ + var config = { + // 图表类型 + CHART_TYPE_LINE: 'line', + CHART_TYPE_BAR: 'bar', + CHART_TYPE_SCATTER: 'scatter', + CHART_TYPE_PIE: 'pie', + CHART_TYPE_RADAR: 'radar', + CHART_TYPE_VENN: 'venn', + CHART_TYPE_TREEMAP: 'treemap', + CHART_TYPE_TREE: 'tree', + CHART_TYPE_MAP: 'map', + CHART_TYPE_K: 'k', + CHART_TYPE_ISLAND: 'island', + CHART_TYPE_FORCE: 'force', + CHART_TYPE_CHORD: 'chord', + CHART_TYPE_GAUGE: 'gauge', + CHART_TYPE_FUNNEL: 'funnel', + CHART_TYPE_EVENTRIVER: 'eventRiver', + CHART_TYPE_WORDCLOUD: 'wordCloud', + + // 组件类型 + COMPONENT_TYPE_TITLE: 'title', + COMPONENT_TYPE_LEGEND: 'legend', + COMPONENT_TYPE_DATARANGE: 'dataRange', + COMPONENT_TYPE_DATAVIEW: 'dataView', + COMPONENT_TYPE_DATAZOOM: 'dataZoom', + COMPONENT_TYPE_TOOLBOX: 'toolbox', + COMPONENT_TYPE_TOOLTIP: 'tooltip', + COMPONENT_TYPE_GRID: 'grid', + COMPONENT_TYPE_AXIS: 'axis', + COMPONENT_TYPE_POLAR: 'polar', + COMPONENT_TYPE_X_AXIS: 'xAxis', + COMPONENT_TYPE_Y_AXIS: 'yAxis', + COMPONENT_TYPE_AXIS_CATEGORY: 'categoryAxis', + COMPONENT_TYPE_AXIS_VALUE: 'valueAxis', + COMPONENT_TYPE_TIMELINE: 'timeline', + COMPONENT_TYPE_ROAMCONTROLLER: 'roamController', + + // 全图默认背景 + backgroundColor: 'rgba(0,0,0,0)', + + // 默认色板 + color: ['#ff7f50','#87cefa','#da70d6','#32cd32','#6495ed', + '#ff69b4','#ba55d3','#cd5c5c','#ffa500','#40e0d0', + '#1e90ff','#ff6347','#7b68ee','#00fa9a','#ffd700', + '#6699FF','#ff6666','#3cb371','#b8860b','#30e0e0'], + + markPoint: { + clickable: true, + symbol: 'pin', // 标注类型 + symbolSize: 10, // 标注大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2 + // symbolRotate: null, // 标注旋转控制 + large: false, + effect: { + show: false, + loop: true, + period: 15, // 运动周期,无单位,值越大越慢 + type: 'scale', // 可用为 scale | bounce + scaleSize: 2, // 放大倍数,以markPoint点size为基准 + bounceDistance: 10 // 跳动距离,单位px + // color: 'gold', + // shadowColor: 'rgba(255,215,0,0.8)', + // shadowBlur: 0 // 炫光模糊 + }, + itemStyle: { + normal: { + // color: 各异, + // borderColor: 各异, // 标注边线颜色,优先于color + borderWidth: 2, // 标注边线线宽,单位px,默认为1 + label: { + show: true, + // 标签文本格式器,同Tooltip.formatter,不支持回调 + // formatter: null, + position: 'inside' // 可选为'left'|'right'|'top'|'bottom' + // textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE + } + }, + emphasis: { + // color: 各异 + label: { + show: true + // 标签文本格式器,同Tooltip.formatter,不支持回调 + // formatter: null, + // position: 'inside' // 'left'|'right'|'top'|'bottom' + // textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE + } + } + } + }, + + markLine: { + clickable: true, + // 标线起始和结束的symbol介绍类型,如果都一样,可以直接传string + symbol: ['circle', 'arrow'], + // 标线起始和结束的symbol大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2 + symbolSize: [2, 4], + // 标线起始和结束的symbol旋转控制 + //symbolRotate: null, + //smooth: false, + smoothness: 0.2, // 平滑度 + precision: 2, + effect: { + show: false, + loop: true, + period: 15, // 运动周期,无单位,值越大越慢 + scaleSize: 2 // 放大倍数,以markLine线lineWidth为基准 + // color: 'gold', + // shadowColor: 'rgba(255,215,0,0.8)', + // shadowBlur: lineWidth * 2 // 炫光模糊,默认等于scaleSize计算所得 + }, + // 边捆绑 + bundling: { + enable: false, + // [0, 90] + maxTurningAngle: 45 + }, + itemStyle: { + normal: { + // color: 各异, // 标线主色,线色,symbol主色 + // borderColor: 随color, // 标线symbol边框颜色,优先于color + borderWidth: 1.5, // 标线symbol边框线宽,单位px,默认为2 + label: { + show: true, + // 标签文本格式器,同Tooltip.formatter,不支持回调 + // formatter: null, + // 可选为 'start'|'end'|'left'|'right'|'top'|'bottom' + position: 'end' + // textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE + }, + lineStyle: { + // color: 随borderColor, // 主色,线色,优先级高于borderColor和color + // width: 随borderWidth, // 优先于borderWidth + type: 'dashed' + // shadowColor: 'rgba(0,0,0,0)', //默认透明 + // shadowBlur: 0, + // shadowOffsetX: 0, + // shadowOffsetY: 0 + } + }, + emphasis: { + // color: 各异 + label: { + show: false + // 标签文本格式器,同Tooltip.formatter,不支持回调 + // formatter: null, + // position: 'inside' // 'left'|'right'|'top'|'bottom' + // textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE + }, + lineStyle: {} + } + } + }, + + // 主题,主题 + textStyle: { + decoration: 'none', + fontFamily: 'Arial, Verdana, sans-serif', + fontFamily2: '微软雅黑', // IE8- 字体模糊并且,不支持不同字体混排,额外指定一份 + fontSize: 12, + fontStyle: 'normal', + fontWeight: 'normal' + }, + + EVENT: { + // -------全局通用 + REFRESH: 'refresh', + RESTORE: 'restore', + RESIZE: 'resize', + CLICK: 'click', + DBLCLICK: 'dblclick', + HOVER: 'hover', + MOUSEOUT: 'mouseout', + //MOUSEWHEEL: 'mousewheel', + // -------业务交互逻辑 + DATA_CHANGED: 'dataChanged', + DATA_ZOOM: 'dataZoom', + DATA_RANGE: 'dataRange', + DATA_RANGE_SELECTED: 'dataRangeSelected', + DATA_RANGE_HOVERLINK: 'dataRangeHoverLink', + LEGEND_SELECTED: 'legendSelected', + LEGEND_HOVERLINK: 'legendHoverLink', + MAP_SELECTED: 'mapSelected', + PIE_SELECTED: 'pieSelected', + MAGIC_TYPE_CHANGED: 'magicTypeChanged', + DATA_VIEW_CHANGED: 'dataViewChanged', + TIMELINE_CHANGED: 'timelineChanged', + MAP_ROAM: 'mapRoam', + FORCE_LAYOUT_END: 'forceLayoutEnd', + // -------内部通信 + TOOLTIP_HOVER: 'tooltipHover', + TOOLTIP_IN_GRID: 'tooltipInGrid', + TOOLTIP_OUT_GRID: 'tooltipOutGrid', + ROAMCONTROLLER: 'roamController' + }, + DRAG_ENABLE_TIME: 120, // 降低图表内元素拖拽敏感度,单位ms,不建议外部干预 + EFFECT_ZLEVEL : 10, // 特效动画zlevel + // 主题,默认标志图形类型列表 + symbolList: [ + 'circle', 'rectangle', 'triangle', 'diamond', + 'emptyCircle', 'emptyRectangle', 'emptyTriangle', 'emptyDiamond' + ], + loadingEffect: 'spin', + loadingText: '数据读取中...', + noDataEffect: 'bubble', + noDataText: '暂无数据', + // noDataLoadingOption: null, + // 可计算特性配置,孤岛,提示颜色 + calculable: false, // 默认关闭可计算特性 + calculableColor: 'rgba(255,165,0,0.6)', // 拖拽提示边框颜色 + calculableHolderColor: '#ccc', // 可计算占位提示颜色 + nameConnector: ' & ', + valueConnector: ': ', + animation: true, // 过渡动画是否开启 + addDataAnimation: true, // 动态数据接口是否开启动画效果 + animationThreshold: 2000, // 动画元素阀值,产生的图形原素超过2000不出动画 + animationDuration: 2000, // 过渡动画参数:进入 + animationDurationUpdate: 500, // 过渡动画参数:更新 + animationEasing: 'ExponentialOut' //BounceOut + }; + + return config; +}); \ No newline at end of file diff --git a/resources/echarts.js b/resources/echarts.js new file mode 100644 index 0000000..6bd230b --- /dev/null +++ b/resources/echarts.js @@ -0,0 +1,1759 @@ +/*! + * ECharts, a javascript interactive chart library. + * + * Copyright (c) 2015, Baidu Inc. + * All rights reserved. + * + * LICENSE + * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt + */ + +/** + * echarts + * + * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 + * @author Kener (@Kener-林峰, kener.linfeng@gmail.com) + * + */ +define(function (require) { + var ecConfig = require('./config'); + var zrUtil = require('zrender/tool/util'); + var zrEvent = require('zrender/tool/event'); + + var self = {}; + + var _canvasSupported = require('zrender/tool/env').canvasSupported; + var _idBase = new Date() - 0; + var _instances = {}; // ECharts实例map索引 + var DOM_ATTRIBUTE_KEY = '_echarts_instance_'; + + self.version = '2.2.4'; + self.dependencies = { + zrender: '2.0.9' + }; + /** + * 入口方法 + */ + self.init = function (dom, theme) { + var zrender = require('zrender'); + if ((zrender.version.replace('.', '') - 0) < (self.dependencies.zrender.replace('.', '') - 0)) { + console.error( + 'ZRender ' + zrender.version + + ' is too old for ECharts ' + self.version + + '. Current version need ZRender ' + + self.dependencies.zrender + '+' + ); + } + + dom = dom instanceof Array ? dom[0] : dom; + + // dom与echarts实例映射索引 + var key = dom.getAttribute(DOM_ATTRIBUTE_KEY); + if (!key) { + key = _idBase++; + dom.setAttribute(DOM_ATTRIBUTE_KEY, key); + } + + if (_instances[key]) { + // 同一个dom上多次init,自动释放已有实例 + _instances[key].dispose(); + } + _instances[key] = new Echarts(dom); + _instances[key].id = key; + _instances[key].canvasSupported = _canvasSupported; + _instances[key].setTheme(theme); + + return _instances[key]; + }; + + /** + * 通过id获得ECharts实例,id可在实例化后读取 + */ + self.getInstanceById = function (key) { + return _instances[key]; + }; + + /** + * 消息中心 + */ + function MessageCenter() { + zrEvent.Dispatcher.call(this); + } + zrUtil.merge(MessageCenter.prototype, zrEvent.Dispatcher.prototype, true); + + /** + * 基于zrender实现Echarts接口层 + * @param {HtmlElement} dom 必要 + */ + function Echarts(dom) { + // Fxxk IE11 for breaking initialization without a warrant; + // Just set something to let it be! + // by kener 2015-01-09 + dom.innerHTML = ''; + this._themeConfig = {}; // zrUtil.clone(ecConfig); + + this.dom = dom; + // this._zr; + // this._option; // curOption clone + // this._optionRestore; // for restore; + // this._island; + // this._toolbox; + // this._timeline; + // this._refreshInside; // 内部刷新标志位 + + this._connected = false; + this._status = { // 用于图表间通信 + dragIn: false, + dragOut: false, + needRefresh: false + }; + this._curEventType = false; // 破循环信号灯 + this._chartList = []; // 图表实例 + + this._messageCenter = new MessageCenter(); + + this._messageCenterOutSide = new MessageCenter(); // Echarts层的外部消息中心,做Echarts层的消息转发 + + // resize方法经常被绑定到window.resize上,闭包一个this + this.resize = this.resize(); + + // 初始化::构造函数 + this._init(); + } + + /** + * ZRender EVENT + * + * @inner + * @const + * @type {Object} + */ + var ZR_EVENT = require('zrender/config').EVENT; + + /** + * 要绑定监听的zrender事件列表 + * + * @const + * @inner + * @type {Array} + */ + var ZR_EVENT_LISTENS = [ + 'CLICK', 'DBLCLICK', 'MOUSEOVER', 'MOUSEOUT', + 'DRAGSTART', 'DRAGEND', 'DRAGENTER', 'DRAGOVER', 'DRAGLEAVE', 'DROP' + ]; + + /** + * 对echarts的实例中的chartList属性成员,逐个进行方法调用,遍历顺序为逆序 + * 由于在事件触发的默认行为处理中,多次用到相同逻辑,所以抽象了该方法 + * 由于所有的调用场景里,最多只有两个参数,基于性能和体积考虑,这里就不使用call或者apply了 + * + * @inner + * @param {ECharts} ecInstance ECharts实例 + * @param {string} methodName 要调用的方法名 + * @param {*} arg0 调用参数1 + * @param {*} arg1 调用参数2 + * @param {*} arg2 调用参数3 + */ + function callChartListMethodReverse(ecInstance, methodName, arg0, arg1, arg2) { + var chartList = ecInstance._chartList; + var len = chartList.length; + + while (len--) { + var chart = chartList[len]; + if (typeof chart[methodName] === 'function') { + chart[methodName](arg0, arg1, arg2); + } + } + } + + Echarts.prototype = { + /** + * 初始化::构造函数 + */ + _init: function () { + var self = this; + var _zr = require('zrender').init(this.dom); + this._zr = _zr; + + // wrap: n,e,d,t for name event data this + this._messageCenter.dispatch = function(type, event, eventPackage, that) { + eventPackage = eventPackage || {}; + eventPackage.type = type; + eventPackage.event = event; + + self._messageCenter.dispatchWithContext(type, eventPackage, that); + self._messageCenterOutSide.dispatchWithContext(type, eventPackage, that); + + // 如下注掉的代码,@see: https://github.com/ecomfe/echarts-discuss/issues/3 + // if (type != 'HOVER' && type != 'MOUSEOUT') { // 频繁事件直接抛出 + // setTimeout(function(){ + // self._messageCenterOutSide.dispatchWithContext( + // type, eventPackage, that + // ); + // },50); + // } + // else { + // self._messageCenterOutSide.dispatchWithContext( + // type, eventPackage, that + // ); + // } + }; + + this._onevent = function(param){ + return self.__onevent(param); + }; + for (var e in ecConfig.EVENT) { + if (e != 'CLICK' && e != 'DBLCLICK' + && e != 'HOVER' && e != 'MOUSEOUT' && e != 'MAP_ROAM' + ) { + this._messageCenter.bind(ecConfig.EVENT[e], this._onevent, this); + } + } + + + var eventBehaviors = {}; + this._onzrevent = function (param) { + return self[eventBehaviors[ param.type ]](param); + }; + + // 挂载关心的事件 + for (var i = 0, len = ZR_EVENT_LISTENS.length; i < len; i++) { + var eventName = ZR_EVENT_LISTENS[i]; + var eventValue = ZR_EVENT[eventName]; + eventBehaviors[eventValue] = '_on' + eventName.toLowerCase(); + _zr.on(eventValue, this._onzrevent); + } + + this.chart = {}; // 图表索引 + this.component = {}; // 组件索引 + + // 内置图表 + // 孤岛 + var Island = require('./chart/island'); + this._island = new Island(this._themeConfig, this._messageCenter, _zr, {}, this); + this.chart.island = this._island; + + // 内置通用组件 + // 工具箱 + var Toolbox = require('./component/toolbox'); + this._toolbox = new Toolbox(this._themeConfig, this._messageCenter, _zr, {}, this); + this.component.toolbox = this._toolbox; + + var componentLibrary = require('./component'); + componentLibrary.define('title', require('./component/title')); + componentLibrary.define('tooltip', require('./component/tooltip')); + componentLibrary.define('legend', require('./component/legend')); + + if (_zr.getWidth() === 0 || _zr.getHeight() === 0) { + console.error('Dom’s width & height should be ready before init.'); + } + }, + + /** + * ECharts事件处理中心 + */ + __onevent: function (param){ + param.__echartsId = param.__echartsId || this.id; + + // 来自其他联动图表的事件 + var fromMyself = (param.__echartsId === this.id); + + if (!this._curEventType) { + this._curEventType = param.type; + } + + switch (param.type) { + case ecConfig.EVENT.LEGEND_SELECTED : + this._onlegendSelected(param); + break; + case ecConfig.EVENT.DATA_ZOOM : + if (!fromMyself) { + var dz = this.component.dataZoom; + if (dz) { + dz.silence(true); + dz.absoluteZoom(param.zoom); + dz.silence(false); + } + } + this._ondataZoom(param); + break; + case ecConfig.EVENT.DATA_RANGE : + fromMyself && this._ondataRange(param); + break; + case ecConfig.EVENT.MAGIC_TYPE_CHANGED : + if (!fromMyself) { + var tb = this.component.toolbox; + if (tb) { + tb.silence(true); + tb.setMagicType(param.magicType); + tb.silence(false); + } + } + this._onmagicTypeChanged(param); + break; + case ecConfig.EVENT.DATA_VIEW_CHANGED : + fromMyself && this._ondataViewChanged(param); + break; + case ecConfig.EVENT.TOOLTIP_HOVER : + fromMyself && this._tooltipHover(param); + break; + case ecConfig.EVENT.RESTORE : + this._onrestore(); + break; + case ecConfig.EVENT.REFRESH : + fromMyself && this._onrefresh(param); + break; + // 鼠标同步 + case ecConfig.EVENT.TOOLTIP_IN_GRID : + case ecConfig.EVENT.TOOLTIP_OUT_GRID : + if (!fromMyself) { + // 只处理来自外部的鼠标同步 + var grid = this.component.grid; + if (grid) { + this._zr.trigger( + 'mousemove', + { + connectTrigger: true, + zrenderX: grid.getX() + param.x * grid.getWidth(), + zrenderY: grid.getY() + param.y * grid.getHeight() + } + ); + } + } + else if (this._connected) { + // 来自自己,并且存在多图联动,空间坐标映射修改参数分发 + var grid = this.component.grid; + if (grid) { + param.x = (param.event.zrenderX - grid.getX()) / grid.getWidth(); + param.y = (param.event.zrenderY - grid.getY()) / grid.getHeight(); + } + } + break; + /* + case ecConfig.EVENT.RESIZE : + case ecConfig.EVENT.DATA_CHANGED : + case ecConfig.EVENT.PIE_SELECTED : + case ecConfig.EVENT.MAP_SELECTED : + break; + */ + } + + // 多图联动,只做自己的一级事件分发,避免级联事件循环 + if (this._connected && fromMyself && this._curEventType === param.type) { + for (var c in this._connected) { + this._connected[c].connectedEventHandler(param); + } + // 分发完毕后复位 + this._curEventType = null; + } + + if (!fromMyself || (!this._connected && fromMyself)) { // 处理了完联动事件复位 + this._curEventType = null; + } + }, + + /** + * 点击事件,响应zrender事件,包装后分发到Echarts层 + */ + _onclick: function (param) { + callChartListMethodReverse(this, 'onclick', param); + + if (param.target) { + var ecData = this._eventPackage(param.target); + if (ecData && ecData.seriesIndex != null) { + this._messageCenter.dispatch( + ecConfig.EVENT.CLICK, + param.event, + ecData, + this + ); + } + } + }, + + /** + * 双击事件,响应zrender事件,包装后分发到Echarts层 + */ + _ondblclick: function (param) { + callChartListMethodReverse(this, 'ondblclick', param); + + if (param.target) { + var ecData = this._eventPackage(param.target); + if (ecData && ecData.seriesIndex != null) { + this._messageCenter.dispatch( + ecConfig.EVENT.DBLCLICK, + param.event, + ecData, + this + ); + } + } + }, + + /** + * 鼠标移入事件,响应zrender事件,包装后分发到Echarts层 + */ + _onmouseover: function (param) { + if (param.target) { + var ecData = this._eventPackage(param.target); + if (ecData && ecData.seriesIndex != null) { + this._messageCenter.dispatch( + ecConfig.EVENT.HOVER, + param.event, + ecData, + this + ); + } + } + }, + + /** + * 鼠标移出事件,响应zrender事件,包装后分发到Echarts层 + */ + _onmouseout: function (param) { + if (param.target) { + var ecData = this._eventPackage(param.target); + if (ecData && ecData.seriesIndex != null) { + this._messageCenter.dispatch( + ecConfig.EVENT.MOUSEOUT, + param.event, + ecData, + this + ); + } + } + }, + + /** + * dragstart回调,可计算特性实现 + */ + _ondragstart: function (param) { + // 复位用于图表间通信拖拽标识 + this._status = { + dragIn: false, + dragOut: false, + needRefresh: false + }; + + callChartListMethodReverse(this, 'ondragstart', param); + }, + + /** + * dragging回调,可计算特性实现 + */ + _ondragenter: function (param) { + callChartListMethodReverse(this, 'ondragenter', param); + }, + + /** + * dragstart回调,可计算特性实现 + */ + _ondragover: function (param) { + callChartListMethodReverse(this, 'ondragover', param); + }, + + /** + * dragstart回调,可计算特性实现 + */ + _ondragleave: function (param) { + callChartListMethodReverse(this, 'ondragleave', param); + }, + + /** + * dragstart回调,可计算特性实现 + */ + _ondrop: function (param) { + callChartListMethodReverse(this, 'ondrop', param, this._status); + this._island.ondrop(param, this._status); + }, + + /** + * dragdone回调 ,可计算特性实现 + */ + _ondragend: function (param) { + callChartListMethodReverse(this, 'ondragend', param, this._status); + + this._timeline && this._timeline.ondragend(param, this._status); + this._island.ondragend(param, this._status); + + // 发生过重计算 + if (this._status.needRefresh) { + this._syncBackupData(this._option); + + var messageCenter = this._messageCenter; + messageCenter.dispatch( + ecConfig.EVENT.DATA_CHANGED, + param.event, + this._eventPackage(param.target), + this + ); + messageCenter.dispatch(ecConfig.EVENT.REFRESH, null, null, this); + } + }, + + /** + * 图例选择响应 + */ + _onlegendSelected: function (param) { + // 用于图表间通信 + this._status.needRefresh = false; + callChartListMethodReverse(this, 'onlegendSelected', param, this._status); + + if (this._status.needRefresh) { + this._messageCenter.dispatch(ecConfig.EVENT.REFRESH, null, null, this); + } + }, + + /** + * 数据区域缩放响应 + */ + _ondataZoom: function (param) { + // 用于图表间通信 + this._status.needRefresh = false; + callChartListMethodReverse(this, 'ondataZoom', param, this._status); + + if (this._status.needRefresh) { + this._messageCenter.dispatch(ecConfig.EVENT.REFRESH, null, null, this); + } + }, + + /** + * 值域漫游响应 + */ + _ondataRange: function (param) { + this._clearEffect(); + // 用于图表间通信 + this._status.needRefresh = false; + callChartListMethodReverse(this, 'ondataRange', param, this._status); + + // 没有相互影响,直接刷新即可 + if (this._status.needRefresh) { + this._zr.refreshNextFrame(); + } + }, + + /** + * 动态类型切换响应 + */ + _onmagicTypeChanged: function () { + this._clearEffect(); + this._render(this._toolbox.getMagicOption()); + }, + + /** + * 数据视图修改响应 + */ + _ondataViewChanged: function (param) { + this._syncBackupData(param.option); + this._messageCenter.dispatch( + ecConfig.EVENT.DATA_CHANGED, + null, + param, + this + ); + this._messageCenter.dispatch(ecConfig.EVENT.REFRESH, null, null, this); + }, + + /** + * tooltip与图表间通信 + */ + _tooltipHover: function (param) { + var tipShape = []; + callChartListMethodReverse(this, 'ontooltipHover', param, tipShape); + }, + + /** + * 还原 + */ + _onrestore: function () { + this.restore(); + }, + + /** + * 刷新 + */ + _onrefresh: function (param) { + this._refreshInside = true; + this.refresh(param); + this._refreshInside = false; + }, + + /** + * 数据修改后的反向同步dataZoom持有的备份数据 + */ + _syncBackupData: function (curOption) { + this.component.dataZoom && this.component.dataZoom.syncBackupData(curOption); + }, + + /** + * 打包Echarts层的事件附件 + */ + _eventPackage: function (target) { + if (target) { + var ecData = require('./util/ecData'); + + var seriesIndex = ecData.get(target, 'seriesIndex'); + var dataIndex = ecData.get(target, 'dataIndex'); + + dataIndex = seriesIndex != -1 && this.component.dataZoom + ? this.component.dataZoom.getRealDataIndex( + seriesIndex, + dataIndex + ) + : dataIndex; + return { + seriesIndex: seriesIndex, + seriesName: (ecData.get(target, 'series') || {}).name, + dataIndex: dataIndex, + data: ecData.get(target, 'data'), + name: ecData.get(target, 'name'), + value: ecData.get(target, 'value'), + special: ecData.get(target, 'special') + }; + } + return; + }, + + _noDataCheck: function(magicOption) { + var series = magicOption.series; + + for (var i = 0, l = series.length; i < l; i++) { + if (series[i].type == ecConfig.CHART_TYPE_MAP + || (series[i].data && series[i].data.length > 0) + || (series[i].markPoint && series[i].markPoint.data && series[i].markPoint.data.length > 0) + || (series[i].markLine && series[i].markLine.data && series[i].markLine.data.length > 0) + || (series[i].nodes && series[i].nodes.length > 0) + || (series[i].links && series[i].links.length > 0) + || (series[i].matrix && series[i].matrix.length > 0) + || (series[i].eventList && series[i].eventList.length > 0) + ) { + return false; // 存在任意数据则为非空数据 + } + } + var loadOption = (this._option && this._option.noDataLoadingOption) + || this._themeConfig.noDataLoadingOption + || ecConfig.noDataLoadingOption + || { + text: (this._option && this._option.noDataText) + || this._themeConfig.noDataText + || ecConfig.noDataText, + effect: (this._option && this._option.noDataEffect) + || this._themeConfig.noDataEffect + || ecConfig.noDataEffect + }; + // 空数据 + this.clear(); + this.showLoading(loadOption); + return true; + }, + + /** + * 图表渲染 + */ + _render: function (magicOption) { + this._mergeGlobalConifg(magicOption); + + if (this._noDataCheck(magicOption)) { + return; + } + + var bgColor = magicOption.backgroundColor; + if (bgColor) { + if (!_canvasSupported + && bgColor.indexOf('rgba') != -1 + ) { + // IE6~8对RGBA的处理,filter会带来其他颜色的影响 + var cList = bgColor.split(','); + this.dom.style.filter = 'alpha(opacity=' + + cList[3].substring(0, cList[3].lastIndexOf(')')) * 100 + + ')'; + cList.length = 3; + cList[0] = cList[0].replace('a', ''); + this.dom.style.backgroundColor = cList.join(',') + ')'; + } + else { + this.dom.style.backgroundColor = bgColor; + } + } + + this._zr.clearAnimation(); + this._chartList = []; + + var chartLibrary = require('./chart'); + var componentLibrary = require('./component'); + + if (magicOption.xAxis || magicOption.yAxis) { + magicOption.grid = magicOption.grid || {}; + magicOption.dataZoom = magicOption.dataZoom || {}; + } + + var componentList = [ + 'title', 'legend', 'tooltip', 'dataRange', 'roamController', + 'grid', 'dataZoom', 'xAxis', 'yAxis', 'polar' + ]; + + var ComponentClass; + var componentType; + var component; + for (var i = 0, l = componentList.length; i < l; i++) { + componentType = componentList[i]; + component = this.component[componentType]; + + if (magicOption[componentType]) { + if (component) { + component.refresh && component.refresh(magicOption); + } + else { + ComponentClass = componentLibrary.get( + /^[xy]Axis$/.test(componentType) ? 'axis' : componentType + ); + component = new ComponentClass( + this._themeConfig, this._messageCenter, this._zr, + magicOption, this, componentType + ); + this.component[componentType] = component; + } + this._chartList.push(component); + } + else if (component) { + component.dispose(); + this.component[componentType] = null; + delete this.component[componentType]; + } + } + + var ChartClass; + var chartType; + var chart; + var chartMap = {}; // 记录已经初始化的图表 + for (var i = 0, l = magicOption.series.length; i < l; i++) { + chartType = magicOption.series[i].type; + if (!chartType) { + console.error('series[' + i + '] chart type has not been defined.'); + continue; + } + + if (!chartMap[chartType]) { + chartMap[chartType] = true; + ChartClass = chartLibrary.get(chartType); + if (ChartClass) { + if (this.chart[chartType]) { + chart = this.chart[chartType]; + chart.refresh(magicOption); + } + else { + chart = new ChartClass( + this._themeConfig, this._messageCenter, this._zr, + magicOption, this + ); + } + this._chartList.push(chart); + this.chart[chartType] = chart; + } + else { + console.error(chartType + ' has not been required.'); + } + } + } + + // 已有实例但新option不带这类图表的实例释放 + for (chartType in this.chart) { + if (chartType != ecConfig.CHART_TYPE_ISLAND && !chartMap[chartType]) { + this.chart[chartType].dispose(); + this.chart[chartType] = null; + delete this.chart[chartType]; + } + } + + this.component.grid && this.component.grid.refixAxisShape(this.component); + + this._island.refresh(magicOption); + this._toolbox.refresh(magicOption); + + magicOption.animation && !magicOption.renderAsImage + ? this._zr.refresh() + : this._zr.render(); + + var imgId = 'IMG' + this.id; + var img = document.getElementById(imgId); + if (magicOption.renderAsImage && _canvasSupported) { + // IE8- 不支持图片渲染形式 + if (img) { + // 已经渲染过则更新显示 + img.src = this.getDataURL(magicOption.renderAsImage); + } + else { + // 没有渲染过插入img dom + img = this.getImage(magicOption.renderAsImage); + img.id = imgId; + img.style.position = 'absolute'; + img.style.left = 0; + img.style.top = 0; + this.dom.firstChild.appendChild(img); + } + this.un(); + this._zr.un(); + this._disposeChartList(); + this._zr.clear(); + } + else if (img) { + // 删除可能存在的img + img.parentNode.removeChild(img); + } + img = null; + + this._option = magicOption; + }, + + /** + * 还原 + */ + restore: function () { + this._clearEffect(); + this._option = zrUtil.clone(this._optionRestore); + this._disposeChartList(); + this._island.clear(); + this._toolbox.reset(this._option, true); + this._render(this._option); + }, + + /** + * 刷新 + * @param {Object=} param,可选参数,用于附带option,内部同步用,外部不建议带入数据修改,无法同步 + */ + refresh: function (param) { + this._clearEffect(); + param = param || {}; + var magicOption = param.option; + + // 外部调用的refresh且有option带入 + if (!this._refreshInside && magicOption) { + // 做简单的差异合并去同步内部持有的数据克隆,不建议带入数据 + // 开启数据区域缩放、拖拽重计算、数据视图可编辑模式情况下,当用户产生了数据变化后无法同步 + // 如有带入option存在数据变化,请重新setOption + magicOption = this.getOption(); + zrUtil.merge(magicOption, param.option, true); + zrUtil.merge(this._optionRestore, param.option, true); + this._toolbox.reset(magicOption); + } + + this._island.refresh(magicOption); + this._toolbox.refresh(magicOption); + + // 停止动画 + this._zr.clearAnimation(); + // 先来后到,安顺序刷新各种图表,图表内部refresh优化检查magicOption,无需更新则不更新~ + for (var i = 0, l = this._chartList.length; i < l; i++) { + this._chartList[i].refresh && this._chartList[i].refresh(magicOption); + } + this.component.grid && this.component.grid.refixAxisShape(this.component); + this._zr.refresh(); + }, + + /** + * 释放图表实例 + */ + _disposeChartList: function () { + this._clearEffect(); + + // 停止动画 + this._zr.clearAnimation(); + + var len = this._chartList.length; + while (len--) { + var chart = this._chartList[len]; + + if (chart) { + var chartType = chart.type; + this.chart[chartType] && delete this.chart[chartType]; + this.component[chartType] && delete this.component[chartType]; + chart.dispose && chart.dispose(); + } + } + + this._chartList = []; + }, + + /** + * 非图表全局属性merge~~ + */ + _mergeGlobalConifg: function (magicOption) { + var mergeList = [ + // 背景颜色 + 'backgroundColor', + + // 拖拽重计算相关 + 'calculable', 'calculableColor', 'calculableHolderColor', + + // 孤岛显示连接符 + 'nameConnector', 'valueConnector', + + // 动画相关 + 'animation', 'animationThreshold', + 'animationDuration', 'animationDurationUpdate', + 'animationEasing', 'addDataAnimation', + + // 默认标志图形类型列表 + 'symbolList', + + // 降低图表内元素拖拽敏感度,单位ms,不建议外部干预 + 'DRAG_ENABLE_TIME' + ]; + + var len = mergeList.length; + while (len--) { + var mergeItem = mergeList[len]; + if (magicOption[mergeItem] == null) { + magicOption[mergeItem] = this._themeConfig[mergeItem] != null + ? this._themeConfig[mergeItem] + : ecConfig[mergeItem]; + } + } + + // 数值系列的颜色列表,不传则采用内置颜色,可配数组,借用zrender实例注入,会有冲突风险,先这样 + var themeColor = magicOption.color; + if (!(themeColor && themeColor.length)) { + themeColor = this._themeConfig.color || ecConfig.color; + } + + this._zr.getColor = function (idx) { + var zrColor = require('zrender/tool/color'); + return zrColor.getColor(idx, themeColor); + }; + + if (!_canvasSupported) { + // 不支持Canvas的强制关闭动画 + magicOption.animation = false; + magicOption.addDataAnimation = false; + } + }, + + /** + * 万能接口,配置图表实例任何可配置选项,多次调用时option选项做merge处理 + * @param {Object} option + * @param {boolean=} notMerge 多次调用时option选项是默认是合并(merge)的, + * 如果不需求,可以通过notMerger参数为true阻止与上次option的合并 + */ + setOption: function (option, notMerge) { + if (!option.timeline) { + return this._setOption(option, notMerge); + } + else { + return this._setTimelineOption(option); + } + }, + + /** + * 万能接口,配置图表实例任何可配置选项,多次调用时option选项做merge处理 + * @param {Object} option + * @param {boolean=} notMerge 多次调用时option选项是默认是合并(merge)的, + * 如果不需求,可以通过notMerger参数为true阻止与上次option的合并 + * @param {boolean=} 默认false。keepTimeLine 表示从timeline组件调用而来, + * 表示当前行为是timeline的数据切换,保持timeline, + * 反之销毁timeline。 详见Issue #1601 + */ + _setOption: function (option, notMerge, keepTimeLine) { + if (!notMerge && this._option) { + this._option = zrUtil.merge( + this.getOption(), + zrUtil.clone(option), + true + ); + } + else { + this._option = zrUtil.clone(option); + !keepTimeLine && this._timeline && this._timeline.dispose(); + } + + this._optionRestore = zrUtil.clone(this._option); + + if (!this._option.series || this._option.series.length === 0) { + this._zr.clear(); + return; + } + + if (this.component.dataZoom // 存在dataZoom控件 + && (this._option.dataZoom // 并且新option也存在 + || (this._option.toolbox + && this._option.toolbox.feature + && this._option.toolbox.feature.dataZoom + && this._option.toolbox.feature.dataZoom.show + ) + ) + ) { + // dataZoom同步数据 + this.component.dataZoom.syncOption(this._option); + } + this._toolbox.reset(this._option); + this._render(this._option); + return this; + }, + + /** + * 返回内部持有的当前显示option克隆 + */ + getOption: function () { + var magicOption = zrUtil.clone(this._option); + + var self = this; + function restoreOption(prop) { + var restoreSource = self._optionRestore[prop]; + + if (restoreSource) { + if (restoreSource instanceof Array) { + var len = restoreSource.length; + while (len--) { + magicOption[prop][len].data = zrUtil.clone( + restoreSource[len].data + ); + } + } + else { + magicOption[prop].data = zrUtil.clone(restoreSource.data); + } + } + } + + // 横轴数据还原 + restoreOption('xAxis'); + + // 纵轴数据还原 + restoreOption('yAxis'); + + // 系列数据还原 + restoreOption('series'); + + return magicOption; + }, + + /** + * 数据设置快捷接口 + * @param {Array} series + * @param {boolean=} notMerge 多次调用时option选项是默认是合并(merge)的, + * 如果不需求,可以通过notMerger参数为true阻止与上次option的合并。 + */ + setSeries: function (series, notMerge) { + if (!notMerge) { + this.setOption({series: series}); + } + else { + this._option.series = series; + this.setOption(this._option, notMerge); + } + return this; + }, + + /** + * 返回内部持有的当前显示series克隆 + */ + getSeries: function () { + return this.getOption().series; + }, + + /** + * timelineOption接口,配置图表实例任何可配置选项 + * @param {Object} option + */ + _setTimelineOption: function(option) { + this._timeline && this._timeline.dispose(); + var Timeline = require('./component/timeline'); + var timeline = new Timeline( + this._themeConfig, this._messageCenter, this._zr, option, this + ); + this._timeline = timeline; + this.component.timeline = this._timeline; + + return this; + }, + + /** + * 动态数据添加 + * 形参为单组数据参数,多组时为数据,内容同[seriesIdx, data, isShift, additionData] + * @param {number} seriesIdx 系列索引 + * @param {number | Object} data 增加数据 + * @param {boolean=} isHead 是否队头加入,默认,不指定或false时为队尾插入 + * @param {boolean=} dataGrow 是否增长数据队列长度,默认,不指定或false时移出目标数组对位数据 + * @param {string=} additionData 是否增加类目轴(饼图为图例)数据,附加操作同isHead和dataGrow + */ + addData: function (seriesIdx, data, isHead, dataGrow, additionData) { + var params = seriesIdx instanceof Array + ? seriesIdx + : [[seriesIdx, data, isHead, dataGrow, additionData]]; + + //this._optionRestore 和 magicOption 都要同步 + var magicOption = this.getOption(); + var optionRestore = this._optionRestore; + var self = this; + for (var i = 0, l = params.length; i < l; i++) { + seriesIdx = params[i][0]; + data = params[i][1]; + isHead = params[i][2]; + dataGrow = params[i][3]; + additionData = params[i][4]; + + var seriesItem = optionRestore.series[seriesIdx]; + var inMethod = isHead ? 'unshift' : 'push'; + var outMethod = isHead ? 'pop' : 'shift'; + if (seriesItem) { + var seriesItemData = seriesItem.data; + var mSeriesItemData = magicOption.series[seriesIdx].data; + + seriesItemData[inMethod](data); + mSeriesItemData[inMethod](data); + if (!dataGrow) { + seriesItemData[outMethod](); + data = mSeriesItemData[outMethod](); + } + + if (additionData != null) { + var legend; + var legendData; + + if (seriesItem.type === ecConfig.CHART_TYPE_PIE + && (legend = optionRestore.legend) + && (legendData = legend.data) + ) { + var mLegendData = magicOption.legend.data; + legendData[inMethod](additionData); + mLegendData[inMethod](additionData); + + if (!dataGrow) { + var legendDataIdx = zrUtil.indexOf(legendData, data.name); + legendDataIdx != -1 && legendData.splice(legendDataIdx, 1); + + legendDataIdx = zrUtil.indexOf(mLegendData, data.name); + legendDataIdx != -1 && mLegendData.splice(legendDataIdx, 1); + } + } + else if (optionRestore.xAxis != null && optionRestore.yAxis != null) { + // x轴类目 + var axisData; + var mAxisData; + var axisIdx = seriesItem.xAxisIndex || 0; + + if (optionRestore.xAxis[axisIdx].type == null + || optionRestore.xAxis[axisIdx].type === 'category' + ) { + axisData = optionRestore.xAxis[axisIdx].data; + mAxisData = magicOption.xAxis[axisIdx].data; + + axisData[inMethod](additionData); + mAxisData[inMethod](additionData); + if (!dataGrow) { + axisData[outMethod](); + mAxisData[outMethod](); + } + } + + // y轴类目 + axisIdx = seriesItem.yAxisIndex || 0; + if (optionRestore.yAxis[axisIdx].type === 'category') { + axisData = optionRestore.yAxis[axisIdx].data; + mAxisData = magicOption.yAxis[axisIdx].data; + + axisData[inMethod](additionData); + mAxisData[inMethod](additionData); + if (!dataGrow) { + axisData[outMethod](); + mAxisData[outMethod](); + } + } + } + } + + // 同步图表内状态,动画需要 + this._option.series[seriesIdx].data = magicOption.series[seriesIdx].data; + } + } + + this._zr.clearAnimation(); + var chartList = this._chartList; + var chartAnimationCount = 0; + var chartAnimationDone = function () { + chartAnimationCount--; + if (chartAnimationCount === 0) { + animationDone(); + } + }; + for (var i = 0, l = chartList.length; i < l; i++) { + if (magicOption.addDataAnimation && chartList[i].addDataAnimation) { + chartAnimationCount++; + chartList[i].addDataAnimation(params, chartAnimationDone); + } + } + + // dataZoom同步数据 + this.component.dataZoom && this.component.dataZoom.syncOption(magicOption); + + this._option = magicOption; + function animationDone() { + if (!self._zr) { + return; // 已经被释放 + } + self._zr.clearAnimation(); + for (var i = 0, l = chartList.length; i < l; i++) { + // 有addData动画就去掉过渡动画 + chartList[i].motionlessOnce = + magicOption.addDataAnimation && chartList[i].addDataAnimation; + } + self._messageCenter.dispatch( + ecConfig.EVENT.REFRESH, + null, + {option: magicOption}, + self + ); + } + + if (!magicOption.addDataAnimation) { + setTimeout(animationDone, 0); + } + return this; + }, + + /** + * 动态[标注 | 标线]添加 + * @param {number} seriesIdx 系列索引 + * @param {Object} markData [标注 | 标线]对象,支持多个 + */ + addMarkPoint: function (seriesIdx, markData) { + return this._addMark(seriesIdx, markData, 'markPoint'); + }, + + addMarkLine: function (seriesIdx, markData) { + return this._addMark(seriesIdx, markData, 'markLine'); + }, + + _addMark: function (seriesIdx, markData, markType) { + var series = this._option.series; + var seriesItem; + + if (series && (seriesItem = series[seriesIdx])) { + var seriesR = this._optionRestore.series; + var seriesRItem = seriesR[seriesIdx]; + var markOpt = seriesItem[markType]; + var markOptR = seriesRItem[markType]; + + markOpt = seriesItem[markType] = markOpt || {data: []}; + markOptR = seriesRItem[markType] = markOptR || {data: []}; + + for (var key in markData) { + if (key === 'data') { + // 数据concat + markOpt.data = markOpt.data.concat(markData.data); + markOptR.data = markOptR.data.concat(markData.data); + } + else if (typeof markData[key] != 'object' || markOpt[key] == null) { + // 简单类型或新值直接赋值 + markOpt[key] = markOptR[key] = markData[key]; + } + else { + // 非数据的复杂对象merge + zrUtil.merge(markOpt[key], markData[key], true); + zrUtil.merge(markOptR[key], markData[key], true); + } + } + + var chart = this.chart[seriesItem.type]; + chart && chart.addMark(seriesIdx, markData, markType); + } + + return this; + }, + + /** + * 动态[标注 | 标线]删除 + * @param {number} seriesIdx 系列索引 + * @param {string} markName [标注 | 标线]名称 + */ + delMarkPoint: function (seriesIdx, markName) { + return this._delMark(seriesIdx, markName, 'markPoint'); + }, + + delMarkLine: function (seriesIdx, markName) { + return this._delMark(seriesIdx, markName, 'markLine'); + }, + + _delMark: function (seriesIdx, markName, markType) { + var series = this._option.series; + var seriesItem; + var mark; + var dataArray; + + if (!( + series + && (seriesItem = series[seriesIdx]) + && (mark = seriesItem[markType]) + && (dataArray = mark.data) + ) + ) { + return this; + } + + markName = markName.split(' > '); + var targetIndex = -1; + + for (var i = 0, l = dataArray.length; i < l; i++) { + var dataItem = dataArray[i]; + if (dataItem instanceof Array) { + if (dataItem[0].name === markName[0] + && dataItem[1].name === markName[1] + ) { + targetIndex = i; + break; + } + } + else if (dataItem.name === markName[0]) { + targetIndex = i; + break; + } + } + + if (targetIndex > -1) { + dataArray.splice(targetIndex, 1); + this._optionRestore.series[seriesIdx][markType].data.splice(targetIndex, 1); + + var chart = this.chart[seriesItem.type]; + chart && chart.delMark(seriesIdx, markName.join(' > '), markType); + } + + return this; + }, + + /** + * 获取当前dom + */ + getDom: function () { + return this.dom; + }, + + /** + * 获取当前zrender实例,可用于添加额为的shape和深度控制 + */ + getZrender: function () { + return this._zr; + }, + + /** + * 获取Base64图片dataURL + * @param {string} imgType 图片类型,支持png|jpeg,默认为png + * @return imgDataURL + */ + getDataURL: function (imgType) { + if (!_canvasSupported) { + return ''; + } + + if (this._chartList.length === 0) { + // 渲染为图片 + var imgId = 'IMG' + this.id; + var img = document.getElementById(imgId); + if (img) { + return img.src; + } + } + + // 清除可能存在的tooltip元素 + var tooltip = this.component.tooltip; + tooltip && tooltip.hideTip(); + + switch (imgType) { + case 'jpeg': + break; + default: + imgType = 'png'; + } + + var bgColor = this._option.backgroundColor; + if (bgColor && bgColor.replace(' ','') === 'rgba(0,0,0,0)') { + bgColor = '#fff'; + } + + return this._zr.toDataURL('image/' + imgType, bgColor); + }, + + /** + * 获取img + * @param {string} imgType 图片类型,支持png|jpeg,默认为png + * @return img dom + */ + getImage: function (imgType) { + var title = this._optionRestore.title; + var imgDom = document.createElement('img'); + imgDom.src = this.getDataURL(imgType); + imgDom.title = (title && title.text) || 'ECharts'; + return imgDom; + }, + + /** + * 获取多图联动的Base64图片dataURL + * @param {string} imgType 图片类型,支持png|jpeg,默认为png + * @return imgDataURL + */ + getConnectedDataURL: function (imgType) { + if (!this.isConnected()) { + return this.getDataURL(imgType); + } + + var tempDom = this.dom; + var imgList = { + 'self': { + img: this.getDataURL(imgType), + left: tempDom.offsetLeft, + top: tempDom.offsetTop, + right: tempDom.offsetLeft + tempDom.offsetWidth, + bottom: tempDom.offsetTop + tempDom.offsetHeight + } + }; + + var minLeft = imgList.self.left; + var minTop = imgList.self.top; + var maxRight = imgList.self.right; + var maxBottom = imgList.self.bottom; + + for (var c in this._connected) { + tempDom = this._connected[c].getDom(); + imgList[c] = { + img: this._connected[c].getDataURL(imgType), + left: tempDom.offsetLeft, + top: tempDom.offsetTop, + right: tempDom.offsetLeft + tempDom.offsetWidth, + bottom: tempDom.offsetTop + tempDom.offsetHeight + }; + + minLeft = Math.min(minLeft, imgList[c].left); + minTop = Math.min(minTop, imgList[c].top); + maxRight = Math.max(maxRight, imgList[c].right); + maxBottom = Math.max(maxBottom, imgList[c].bottom); + } + + var zrDom = document.createElement('div'); + zrDom.style.position = 'absolute'; + zrDom.style.left = '-4000px'; + zrDom.style.width = (maxRight - minLeft) + 'px'; + zrDom.style.height = (maxBottom - minTop) + 'px'; + document.body.appendChild(zrDom); + + var zrImg = require('zrender').init(zrDom); + + var ImageShape = require('zrender/shape/Image'); + for (var c in imgList) { + zrImg.addShape(new ImageShape({ + style: { + x: imgList[c].left - minLeft, + y: imgList[c].top - minTop, + image: imgList[c].img + } + })); + } + + zrImg.render(); + var bgColor = this._option.backgroundColor; + if (bgColor && bgColor.replace(/ /g, '') === 'rgba(0,0,0,0)') { + bgColor = '#fff'; + } + + var image = zrImg.toDataURL('image/png', bgColor); + + setTimeout(function () { + zrImg.dispose(); + zrDom.parentNode.removeChild(zrDom); + zrDom = null; + }, 100); + + return image; + }, + + /** + * 获取多图联动的img + * @param {string} imgType 图片类型,支持png|jpeg,默认为png + * @return img dom + */ + getConnectedImage: function (imgType) { + var title = this._optionRestore.title; + var imgDom = document.createElement('img'); + imgDom.src = this.getConnectedDataURL(imgType); + imgDom.title = (title && title.text) || 'ECharts'; + return imgDom; + }, + + /** + * 外部接口绑定事件 + * @param {Object} eventName 事件名称 + * @param {Object} eventListener 事件响应函数 + */ + on: function (eventName, eventListener) { + this._messageCenterOutSide.bind(eventName, eventListener, this); + return this; + }, + + /** + * 外部接口解除事件绑定 + * @param {Object} eventName 事件名称 + * @param {Object} eventListener 事件响应函数 + */ + un: function (eventName, eventListener) { + this._messageCenterOutSide.unbind(eventName, eventListener); + return this; + }, + + /** + * 多图联动 + * @param connectTarget{ECharts | Array } connectTarget 联动目标 + */ + connect: function (connectTarget) { + if (!connectTarget) { + return this; + } + + if (!this._connected) { + this._connected = {}; + } + + if (connectTarget instanceof Array) { + for (var i = 0, l = connectTarget.length; i < l; i++) { + this._connected[connectTarget[i].id] = connectTarget[i]; + } + } + else { + this._connected[connectTarget.id] = connectTarget; + } + + return this; + }, + + /** + * 解除多图联动 + * @param connectTarget{ECharts | Array } connectTarget 解除联动目标 + */ + disConnect: function (connectTarget) { + if (!connectTarget || !this._connected) { + return this; + } + + if (connectTarget instanceof Array) { + for (var i = 0, l = connectTarget.length; i < l; i++) { + delete this._connected[connectTarget[i].id]; + } + } + else { + delete this._connected[connectTarget.id]; + } + + for (var k in this._connected) { + return k, this; // 非空 + } + + // 空,转为标志位 + this._connected = false; + return this; + }, + + /** + * 联动事件响应 + */ + connectedEventHandler: function (param) { + if (param.__echartsId != this.id) { + // 来自其他联动图表的事件 + this._onevent(param); + } + }, + + /** + * 是否存在多图联动 + */ + isConnected: function () { + return !!this._connected; + }, + + /** + * 显示loading过渡 + * @param {Object} loadingOption + */ + showLoading: function (loadingOption) { + var effectList = { + bar: require('zrender/loadingEffect/Bar'), + bubble: require('zrender/loadingEffect/Bubble'), + dynamicLine: require('zrender/loadingEffect/DynamicLine'), + ring: require('zrender/loadingEffect/Ring'), + spin: require('zrender/loadingEffect/Spin'), + whirling: require('zrender/loadingEffect/Whirling') + }; + this._toolbox.hideDataView(); + + loadingOption = loadingOption || {}; + + var textStyle = loadingOption.textStyle || {}; + loadingOption.textStyle = textStyle; + + var finalTextStyle = zrUtil.merge( + zrUtil.merge( + zrUtil.clone(textStyle), + this._themeConfig.textStyle + ), + ecConfig.textStyle + ); + + textStyle.textFont = finalTextStyle.fontStyle + ' ' + + finalTextStyle.fontWeight + ' ' + + finalTextStyle.fontSize + 'px ' + + finalTextStyle.fontFamily; + + textStyle.text = loadingOption.text + || (this._option && this._option.loadingText) + || this._themeConfig.loadingText + || ecConfig.loadingText; + + if (loadingOption.x != null) { + textStyle.x = loadingOption.x; + } + if (loadingOption.y != null) { + textStyle.y = loadingOption.y; + } + + loadingOption.effectOption = loadingOption.effectOption || {}; + loadingOption.effectOption.textStyle = textStyle; + + var Effect = loadingOption.effect; + if (typeof Effect === 'string' || Effect == null) { + Effect = effectList[ + loadingOption.effect + || (this._option && this._option.loadingEffect) + || this._themeConfig.loadingEffect + || ecConfig.loadingEffect + ] + || effectList.spin; + } + this._zr.showLoading(new Effect(loadingOption.effectOption)); + return this; + }, + + /** + * 隐藏loading过渡 + */ + hideLoading: function () { + this._zr.hideLoading(); + return this; + }, + + /** + * 主题设置 + */ + setTheme: function (theme) { + if (theme) { + if (typeof theme === 'string') { + // 默认主题 + switch (theme) { + case 'macarons': + theme = require('./theme/macarons'); + break; + case 'infographic': + theme = require('./theme/infographic'); + break; + default: + theme = {}; // require('./theme/default'); + } + } + else { + theme = theme || {}; + } + + // // 复位默认配置 + // // this._themeConfig会被别的对象引用持有 + // // 所以不能改成this._themeConfig = {}; + // for (var key in this._themeConfig) { + // delete this._themeConfig[key]; + // } + // for (var key in ecConfig) { + // this._themeConfig[key] = zrUtil.clone(ecConfig[key]); + // } + + // // 颜色数组随theme,不merge + // theme.color && (this._themeConfig.color = []); + + // // 默认标志图形类型列表,不merge + // theme.symbolList && (this._themeConfig.symbolList = []); + + // // 应用新主题 + // zrUtil.merge(this._themeConfig, zrUtil.clone(theme), true); + this._themeConfig = theme; + } + + if (!_canvasSupported) { // IE8- + var textStyle = this._themeConfig.textStyle; + textStyle && textStyle.fontFamily && textStyle.fontFamily2 + && (textStyle.fontFamily = textStyle.fontFamily2); + + textStyle = ecConfig.textStyle; + textStyle.fontFamily = textStyle.fontFamily2; + } + + this._timeline && this._timeline.setTheme(true); + this._optionRestore && this.restore(); + }, + + /** + * 视图区域大小变化更新,不默认绑定,供使用方按需调用 + */ + resize: function () { + var self = this; + return function(){ + self._clearEffect(); + self._zr.resize(); + if (self._option && self._option.renderAsImage && _canvasSupported) { + // 渲染为图片重走render模式 + self._render(self._option); + return self; + } + // 停止动画 + self._zr.clearAnimation(); + self._island.resize(); + self._toolbox.resize(); + self._timeline && self._timeline.resize(); + // 先来后到,不能仅刷新自己,也不能在上一个循环中刷新,如坐标系数据改变会影响其他图表的大小 + // 所以安顺序刷新各种图表,图表内部refresh优化无需更新则不更新~ + for (var i = 0, l = self._chartList.length; i < l; i++) { + self._chartList[i].resize && self._chartList[i].resize(); + } + self.component.grid && self.component.grid.refixAxisShape(self.component); + self._zr.refresh(); + self._messageCenter.dispatch(ecConfig.EVENT.RESIZE, null, null, self); + return self; + }; + }, + + _clearEffect: function() { + this._zr.modLayer(ecConfig.EFFECT_ZLEVEL, { motionBlur: false }); + this._zr.painter.clearLayer(ecConfig.EFFECT_ZLEVEL); + }, + + /** + * 清除已渲染内容 ,clear后echarts实例可用 + */ + clear: function () { + this._disposeChartList(); + this._zr.clear(); + this._option = {}; + this._optionRestore = {}; + this.dom.style.backgroundColor = null; + return this; + }, + + /** + * 释放,dispose后echarts实例不可用 + */ + dispose: function () { + var key = this.dom.getAttribute(DOM_ATTRIBUTE_KEY); + key && delete _instances[key]; + + this._island.dispose(); + this._toolbox.dispose(); + this._timeline && this._timeline.dispose(); + this._messageCenter.unbind(); + this.clear(); + this._zr.dispose(); + this._zr = null; + } + }; + + return self; +}); \ No newline at end of file diff --git a/resources/echarts.properties b/resources/echarts.properties new file mode 100644 index 0000000..13edba1 --- /dev/null +++ b/resources/echarts.properties @@ -0,0 +1,29 @@ +# +# The MIT License (MIT) +# +# Copyright (c) 2014-2015 abel533@gmail.com +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +# \uFFFD\u01F7\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0524\uFFFD\uFFFD +view = false + +# \uFFFD\uFFFD\uFFFD\uFFFDhtml\uFFFD\u013C\uFFFD\u013F\u00BC +exportpath = /tmp/echarts \ No newline at end of file diff --git a/resources/template b/resources/template new file mode 100644 index 0000000..b1965cc --- /dev/null +++ b/resources/template @@ -0,0 +1,38 @@ + + + + + ECharts - Generate By @isea533/abel533 + + + +
+
+

ECharts效果

+ +
+
+
+
+ + + + + + \ No newline at end of file diff --git a/src/META-INF/MANIFEST.MF b/src/META-INF/MANIFEST.MF new file mode 100644 index 0000000..e69de29 diff --git a/src/com/xiuye/sharp/Castor.java b/src/com/xiuye/sharp/Castor.java new file mode 100644 index 0000000..b9f85bc --- /dev/null +++ b/src/com/xiuye/sharp/Castor.java @@ -0,0 +1,15 @@ +package com.xiuye.sharp; + +import com.xiuye.util.cls.XType; + +public interface Castor { + + default T cast() { + return cast(this); + } + + default R cast(I in) { + return XType.cast(in); + } + +} diff --git a/src/com/xiuye/sharp/X.java b/src/com/xiuye/sharp/X.java new file mode 100644 index 0000000..0edfc7a --- /dev/null +++ b/src/com/xiuye/sharp/X.java @@ -0,0 +1,800 @@ +package com.xiuye.sharp; + +import java.io.IOException; +import java.net.DatagramSocket; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; + +import com.google.gson.Gson; +import com.xiuye.util.cls.XType; +import com.xiuye.util.json.JsonUtil; +import com.xiuye.util.log.XLog; + +public class X {// sharp tools + + // 一般是这步的计算结果,传递给下一步 + private RESULT result; + // 这步产生的错误 + private Throwable error; + + // 异常必须处理后才能进行下一步 + private static boolean ignoreException = true; + + public X() { + + } + + public X(RESULT result) { + this.result = result; + } + + public X(RESULT result, Throwable error) { + this.result = result; + this.error = error; + } + + public X(Throwable error) { + this.error = error; + } + + public Throwable getError() { + return error; + } + + public RESULT get() { + return result; + } + + private static void ifError(VoidCallbackWithParam callback, X x) { + if (!ignoreException && x.error != null) { + callback.vci(x.error); + } + } + + private static void ifError(X x) { + ifError((e) -> { + throw new RuntimeException("Some errors occur!" + "Please use \"except\" to handle error next step!", e); + }, x); + } + + //有异常都捕获 + private static R catchExec(ReturnCallbackNoParam callback, X x) { + ifError(x); + try { + return callback.rcv(); + } catch (Throwable e) { + x.error = e; + } + return null; + } + + private static T catchExec(VoidCallbackNoParam callback, X x) { + ifError(x); + try { + callback.vcv(); + } catch (Throwable e) { + x.error = e; + } + // error 的时候 ,result是不存在的!所有返回null是正确的! + return x.result; + } + + private static R errorHandler(VoidCallbackNoParam callback, X x) { + try { + callback.vcv(); + // 捕获异常后将上一步的异常 清理掉 + // 能到这一步,表示编译完美无误的处理异常! + // error 是 类中局部变量,好处是不会被 final 约束了 + x.error = null; + } catch (Throwable e) { + x.error = e; + } + // error 的时候 ,result是不存在的!所有返回null是正确的! + return null; + } + + // 必须自己实现与其他类库无关的接口,哪怕是SDK 标准库 + // 否则 将面临 传参 的 一些莫名其妙的错误! + + /** + * R call (I) + * + * @param + * @param + */ + public /* static default */ interface ReturnCallbackWithParam { + R rci(I in); + } + + /** + * void callback(I) + * + * @param + */ + public /* static default */ interface VoidCallbackWithParam { + void vci(I in); + } + + public /* static default */ interface VoidCallbackNoParam { + void vcv(); + } + + /** + * R call() + * + * @param + */ + public /* static default */ interface ReturnCallbackNoParam { + R rcv(); + } + + public static void ignoreException(boolean ignore) { + ignoreException = ignore; + } + + // static and non-static all can use it + private static boolean parseBoolean(I t) { + if (t == null) { + return false; + } else {// existence is true + boolean b = true; + if (t instanceof Boolean) { + b = XType.cast(t); + } + return b; + } + } + + public static X resolve() { + return new X<>(); + } + + public static X resolve(R r) { + return new X<>(r); + } + + private static X resolve(R r, E error) { + return new X<>(r, error); + } + + public static X reject(E e) { + return new X<>(e); + } + + public static X of() { + return resolve(); + } + + public static X of(R t) { + return resolve(t); + } + + public static X of(R r, E error) { + return resolve(r, error); + } + + public X THEN(ReturnCallbackNoParam callback) { + return of(catchExec(() -> callback.rcv(), this), this.error); + } + + public X THEN(ReturnCallbackWithParam callback) { + return of(catchExec(() -> callback.rci(result), this), error); + } + + public X THEN(VoidCallbackWithParam callback) { + return of(catchExec(() -> callback.vci(result), this), error); + } + + public X THEN(VoidCallbackNoParam callback) { + return of(catchExec(() -> callback.vcv(), this), error); + } + + public X FINALLY(ReturnCallbackNoParam callback) { + return THEN(callback); + } + + public X FINALLY(ReturnCallbackWithParam callback) { + return THEN(callback); + } + + public X FINALLY(VoidCallbackWithParam callback) { + return THEN(callback); + } + + public X FINALLY(VoidCallbackNoParam callback) { + return THEN(callback); + } + + // 传入都是空!所以随便返回什么类型 + + private boolean errorExist() { + return error != null; + } + + public X EX(ReturnCallbackNoParam callback) { + return resolve(errorExist() ? errorHandler(() -> callback.rcv(), this) : result, error); + } + + public X EX(ReturnCallbackWithParam callback) { + return resolve(errorExist() ? errorHandler(() -> callback.rci(error), this) : result, error); + } + + public X EX(VoidCallbackWithParam callback) { + return resolve(errorExist() ? errorHandler(() -> callback.vci(error), this) : result, error); + } + + public X EX(VoidCallbackNoParam callback) { + return resolve(errorExist() ? errorHandler(() -> callback.vcv(), this) : result, error); + } + + private boolean exist() { + return result != null; + } + + // exist + public X E() { + return of(exist(), error); + } + + public X E(ReturnCallbackNoParam callback) { + return exist() ? THEN(callback) : reject(error); + } + + public X E(ReturnCallbackWithParam callback) { + return exist() ? THEN(callback) : reject(error); + } + + public X E(VoidCallbackWithParam callback) { + return exist() ? THEN(callback) : reject(error); + } + + public X E(VoidCallbackNoParam callback) { + return exist() ? THEN(callback) : reject(error); + } + + public X1 begin() { + return new X1<>(result, error); + } + + public static X1 beginS() { + return new X1<>(); + } + + private boolean truely() { + return catchExec(() -> parseBoolean(result), this); + } + + // true + public X T() { + return of(truely(), error); + } + + public X T(ReturnCallbackNoParam callback) { + return truely() ? THEN(callback) : reject(error); + } + + public X T(ReturnCallbackWithParam callback) { + return truely() ? THEN(callback) : reject(error); + } + + public X T(VoidCallbackWithParam callback) { + return truely() ? THEN(callback) : reject(error); + } + + public X T(VoidCallbackNoParam callback) { + return truely() ? THEN(callback) : reject(error); + } + + public X F() { + return of(!truely(), error); + } + + public X F(ReturnCallbackNoParam callback) { + return !truely() ? THEN(callback) : reject(error); + } + + public X F(ReturnCallbackWithParam callback) { + return !truely() ? THEN(callback) : reject(error); + } + + public X F(VoidCallbackWithParam callback) { + return !truely() ? THEN(callback) : reject(error); + } + + public X F(VoidCallbackNoParam callback) { + return !truely() ? THEN(callback) : reject(error); + } + + public static abstract class AbstractPromiseTask extends Thread { + + protected FUNC func; + protected R result; + protected I input; + protected Throwable error; + + public AbstractPromiseTask(FUNC func) { + this.func = func; + } + + public AbstractPromiseTask(FUNC func, I input) { + this(func); + this.input = input; + } + + protected T catchExec(ReturnCallbackNoParam callback) { + try { + return callback.rcv(); + } catch (Throwable e) { + error = e; + } + return null; + } + + protected T catchExec(VoidCallbackNoParam callback) { + try { + callback.vcv(); + } catch (Throwable e) { + error = e; + } + return null; + } + + public R get() { + try { + this.join(); + } catch (InterruptedException e) { + error = e; + } + return result; + } + + public R get(long millis) throws InterruptedException { + try { + this.join(millis); + } catch (InterruptedException e) { + error = e; + } + return result; + } + +// public void set(R result) { +// this.result = result; +// } + + public Throwable getError() { + return error; + } + + public I getInput() { + return input; + } + + public void setInput(I input) { + this.input = input; + } + + } + + public static class PromiseTaskRCI extends AbstractPromiseTask, R, I> { + + public PromiseTaskRCI(ReturnCallbackWithParam func) { + super(func); + } + + public PromiseTaskRCI(ReturnCallbackWithParam func, I input) { + super(func, input); + } + + @Override + public void run() { + super.run(); + result = catchExec(() -> func.rci(input)); + } + + } + + public static class PromiseTaskRCV extends AbstractPromiseTask, R, I> { + + public PromiseTaskRCV(ReturnCallbackNoParam func) { + super(func); + } + + public PromiseTaskRCV(ReturnCallbackNoParam func, I input) { + super(func, input); + } + + @Override + public void run() { + super.run(); + result = catchExec(() -> func.rcv()); + } + + } + + public static class PromiseTaskVCI extends AbstractPromiseTask, R, I> { + + public PromiseTaskVCI(VoidCallbackWithParam func) { + super(func); + } + + public PromiseTaskVCI(VoidCallbackWithParam func, I input) { + super(func, input); + } + + @Override + public void run() { + super.run(); + result = catchExec(() -> func.vci(input)); + } + + } + + public static class PromiseTaskVCV extends AbstractPromiseTask { + + public PromiseTaskVCV(VoidCallbackNoParam func) { + super(func); + } + + public PromiseTaskVCV(VoidCallbackNoParam func, I input) { + super(func, input); + } + + @Override + public void run() { + super.run(); + result = catchExec(() -> func.vcv()); + } + + } + + public static X> taskS(VoidCallbackNoParam callback) { + AbstractPromiseTask taskObj = new PromiseTaskVCV<>(callback); + taskObj.start(); + return of(taskObj); + } + + public static X, R, I>> taskS( + VoidCallbackWithParam callback) { + AbstractPromiseTask, R, I> taskObj = new PromiseTaskVCI<>(callback); + taskObj.start(); + return of(taskObj); + } + + public static X, R, I>> taskS(VoidCallbackWithParam callback, + I input) { + AbstractPromiseTask, R, I> taskObj = new PromiseTaskVCI<>(callback, input); + taskObj.start(); + return of(taskObj); + } + + public static X, R, I>> taskS( + ReturnCallbackNoParam callback) { + AbstractPromiseTask, R, I> taskObj = new PromiseTaskRCV<>(callback); + taskObj.start(); + return of(taskObj); + } + + public static X, R, I>> taskS( + ReturnCallbackWithParam callback) { + AbstractPromiseTask, R, I> taskObj = new PromiseTaskRCI<>(callback); + taskObj.start(); + return of(taskObj); + } + + public static X, R, I>> taskS( + ReturnCallbackWithParam callback, I input) { + AbstractPromiseTask, R, I> taskObj = new PromiseTaskRCI<>(callback, input); + taskObj.start(); + return of(taskObj); + } + + public X> task(VoidCallbackNoParam callback) { + AbstractPromiseTask taskObj = new PromiseTaskVCV<>(callback, result); + taskObj.start(); + return of(taskObj, error); + } + + public X, R, RESULT>> task( + VoidCallbackWithParam callback) { + AbstractPromiseTask, R, RESULT> taskObj = new PromiseTaskVCI<>(callback, result); + taskObj.start(); + return of(taskObj, error); + } + + public X, R, I>> task(VoidCallbackWithParam callback, + I input) { + AbstractPromiseTask, R, I> taskObj = new PromiseTaskVCI<>(callback, input); + taskObj.start(); + return of(taskObj, error); + } + + public X, R, RESULT>> task(ReturnCallbackNoParam callback) { + AbstractPromiseTask, R, RESULT> taskObj = new PromiseTaskRCV<>(callback, result); + taskObj.start(); + return of(taskObj, error); + } + + public X, R, RESULT>> task( + ReturnCallbackWithParam callback) { + AbstractPromiseTask, R, RESULT> taskObj = new PromiseTaskRCI<>(callback, + result); + taskObj.start(); + return of(taskObj, error); + } + + public X, R, I>> task( + ReturnCallbackWithParam callback, I input) { + AbstractPromiseTask, R, I> taskObj = new PromiseTaskRCI<>(callback, input); + taskObj.start(); + return of(taskObj, error); + } + + @SafeVarargs + public static X logS(R... in) { + XLog.lg(in); + return of(in); + } + + @SafeVarargs + public static X lgS(R... in) { + return logS(in); + } + + @SafeVarargs + public static X lineS(R... in) { + X pro = of(in); + catchExec(() -> { + XLog.attach(3); + XLog.line(in); + XLog.dettach(3); + }, pro); + + return pro; + } + + @SafeVarargs + public static X lnS(R... in) { + X pro = of(in); + catchExec(() -> { + XLog.attach(3); + XLog.line(in); + XLog.dettach(3); + }, pro); + + return pro; + } + + public X log() { + XLog.lg(result); + return of(result, error); + } + + public X lg() { + return log(); + } + + public X line() { + catchExec(() -> { + XLog.attach(3); + XLog.line(result); + XLog.dettach(3); + }, this); + return of(result, error); + } + + public X ln() { + catchExec(() -> { + XLog.attach(3); + XLog.ln(result); + XLog.dettach(3); + }, this); + return of(result, error); + } + + public static X2 beanS(String name) { + return new X2<>(name); + } + + public static X2 beanS(String name, R object) { + return beanS(name, object, false); + } + + public static X2 beanS(String name, R object, boolean replace) { + return new X2<>(name, object, replace); + } + + public static X2 beanS(String name, Class clazz) { + return new X2<>(name, clazz); + } + + public static X2 beanS(String name, Class clazz, R r) { + return beanS(name, clazz, r, false); + } + + public static X2 beanS(String name, Class clazz, R r, boolean replace) { + return new X2<>(name, clazz, r, replace); + } + + public static X2 beanS( Class clazz,String name,R r) { + return beanS(clazz,name,r,false); + } + + public static X2 beanS( Class clazz,String name,R r, boolean replace) { + return new X2<>(name, clazz, r, replace); + } + + public static X2 beanS(Class clazz) { + return new X2<>(clazz); + } + + public static X2 beanS(Class clazz, R r) { + return beanS(clazz, r, false); + } + + public static X2 beanS(Class clazz, R r, boolean replace) { + return new X2<>(clazz, r, replace); + } + + public X2 bean(String name) { + return beanS(name); + } + + public X2 bean(String name, R object) { + return beanS(name, object); + } + + public X2 bean(String name, R object, boolean replace) { + return beanS(name, object, replace); + } + + public X2 bean(String name, Class clazz) { + return beanS(name, clazz); + } + + public X2 bean(String name, Class clazz, R r) { + return beanS(name, clazz, r); + } + + public X2 bean(String name, Class clazz, R r, boolean replace) { + return beanS(name, clazz, r, replace); + } + + public X2 bean(Class clazz) { + return beanS(clazz); + } + + public X2 bean(Class clazz, R r) { + return beanS(clazz, r); + } + + public X2 bean(Class clazz, R r, boolean replace) { + return beanS(clazz, r, replace); + } + + public X2 bean(){ + return beanS("X",result,true); + } + + public void set(RESULT r) { + this.result = r; + } + + public static X tcpS(int port) { + + X x = of(); + try { + x.set(new ServerSocket(port)); + } catch (IOException e) { + x.error = e; + } + return x; + } + + public X tcp(int port) { + return tcpS(port); + } + + public static X tcpS(String ip, int port) { + X x = of(); + try { +// return of(new Socket(ip, port)); + x.set(new Socket(ip, port)); + } catch (IOException e) { +// e.printStackTrace(); + x.error = e; + } + return x; + } + + public X tcp(String ip, int port) { + return tcp(ip, port); + } + + public static X udpS(int port) { + X x = of(); + try { +// return of(new DatagramSocket(port)); + x.set(new DatagramSocket(port)); + } catch (SocketException e) { + x.error = e; + } + return x; + } + + public X udp(int port) { + return udpS(port); + } + + public static X udpS() { + X x = of(); + try { + x.set(new DatagramSocket()); + } catch (SocketException e) { +// e.printStackTrace(); + x.error = e; + } + return x; + } + + public X udp() { + return udpS(); + } + + + public X toFormatJson() { + return of(catchExec(() -> JsonUtil.instance(JsonUtil.FORMAT_GSON).toJson(result),this), error); + } + + public X toJson() { + return of(catchExec(() -> JsonUtil.instance().toJson(result),this)); + } + + public X toObject(Class clazz) { + return of(catchExec(() -> JsonUtil.instance().fromJson(result != null ? result.toString() : null, clazz),this), + error); + } + + public static X formatterJsonKitS() { + + X gsonX = of(); + gsonX.set( + catchExec(()->JsonUtil.instance(JsonUtil.FORMAT_GSON), + gsonX)); + + return gsonX; + } + + public static X jsonKitS() { + X gsonX = of(); + gsonX.set( + catchExec(()->JsonUtil.instance(), + gsonX)); + return gsonX; + } + + public X formatterJsonKit() { + return of(catchExec(() -> JsonUtil.instance(JsonUtil.FORMAT_GSON),this), error); + } + + public X jsonKit() { + return of(catchExec(() -> JsonUtil.instance(),this), error); + } + + + public static X x() { + return resolve(); + } + + public static X x(R t) { + return resolve(t); + } + + public static X x(R r, E error) { + return resolve(r, error); + } + + + + +} diff --git a/src/com/xiuye/sharp/X1.java b/src/com/xiuye/sharp/X1.java new file mode 100644 index 0000000..ea752a5 --- /dev/null +++ b/src/com/xiuye/sharp/X1.java @@ -0,0 +1,545 @@ +package com.xiuye.sharp; + +import java.util.List; + +import com.xiuye.util.cls.XType; + +//for if else_if else;match as +//for program code +//x extension: x1 +public class X1 { + + // ================= programming ================ + + private static final String IF = "if"; + private static final String ELSE_IF = "else if"; + private static final String ELSE = "else"; + private static final String THEN = "then"; + private static final String MATCH = "match"; + private static final String AS = "as"; + private static final String DEFAULT = "default"; + + + private class TwoTuple{ + public String token; + public Object value; + + + private TwoTuple() { + + } + + private TwoTuple(String token, Object t) { + this.token = token; + this.value = t; + } + } + + private List tokens; + private TwoTuple result_token; + private Object inputValue; + + private int token_index = 0; + + + + //Promise的结果,在end后仍然传给 新的Promise + //error同 + private RESULT result; + private Throwable error; + + + protected X1() { + this.tokens = XType.list(); + } + + protected X1(RESULT r, Throwable error) { + this(); + this.result = r; + this.error = error; + + } + + +// private ProgramPromise programPromise(List tokens) { +// if (tokens == null) { +// throw new RuntimeException("please use begin() to start using promise in ef/eeseEf/else/thenDo !"); +// } +// return new ProgramPromise<>(tokens); +// } + + + /** + * syntax : + * S -> if .then .T + * T -> else if .then .T | else |ε + * . 分隔词组 + * + * @param t + * @param + * @return + */ + public X1 IF(I t) { + addToken(IF, t); +// return programPromise(tokens); + return this; + } + + public X1 ELIF(I t) { + addToken(ELSE_IF, t); +// return programPromise(tokens); + return this; + } + + /** + * S -> match . F + * F -> as . A . then . F | defaut | ε + * A -> as . A | ε + * + * @param + * @param in + * @return + */ + public X1 MATCH(I in) { + addToken(MATCH, in); + return this; + } + + public X1 AS(I in) { + addToken(AS, in); + return this; + } + + public X1 DEFAUT(VoidCallbackNoParam callback) { + addToken(DEFAULT, callback); + return this; + } + + public X1 DEFAUT(VoidCallbackWithParam callback) { + addToken(DEFAULT, callback); + return this; + } + + public X1 DEFAUT(ReturnCallbackWithParam callback) { + addToken(DEFAULT, callback); + return this; + } + public X1 DEFAUT(ReturnCallbackNoParam callback) { + addToken(DEFAULT, callback); + return this; + } + + + public X1 THEN(VoidCallbackNoParam callback) { + addToken(THEN, callback); +// return programPromise(tokens); + return this; + } + + public X1 THEN(VoidCallbackWithParam callback) { + addToken(THEN, callback); + return this; + } + + public X1 THEN(ReturnCallbackWithParam callback) { + addToken(THEN, callback); + return this; + } + public X1 THEN(ReturnCallbackNoParam callback) { + addToken(THEN, callback); + return this; + } + + + public X1 ELSE(VoidCallbackNoParam callback) { + addToken(ELSE, callback); +// return programPromise(tokens); + return this; + } + + + public X1 ELSE(VoidCallbackWithParam callback) { + addToken(ELSE, callback); + return this; + } + + public X1 ELSE(ReturnCallbackWithParam callback) { + addToken(ELSE, callback); + return this; + } + public X1 ELSE(ReturnCallbackNoParam callback) { + addToken(ELSE, callback); + return this; + } + + private void callTokenCallback() { + if (result_token != null) { + if (result_token.value instanceof VoidCallbackNoParam) { + VoidCallbackNoParam callback = XType.cast(result_token.value); + callback.vcv(); + } + else if(result_token.value instanceof VoidCallbackWithParam) { + VoidCallbackWithParam callback = XType.cast(result_token.value); + callback.vci(inputValue); + } + else if(result_token.value instanceof ReturnCallbackNoParam) { + ReturnCallbackNoParam callback = XType.cast(result_token.value); + callback.rcv(); + } + else if(result_token.value instanceof ReturnCallbackWithParam){ + ReturnCallbackWithParam callback = XType.cast(result_token.value); + result = callback.rci(inputValue); + } + + inputValue = null; + + //clear the previous executed token!!! + + result_token = null; + + } + + } + + private void nextTokenError(String token) { + throw new RuntimeException("The next token should be " + token); + } + + private String or(String... args) { + StringBuffer result = new StringBuffer(); + if (args.length > 0) { + for (int i = 0; i < args.length - 1; i++) { + result.append(args[i] + " or "); + } + result.append(args[args.length - 1]); + } + + return result.toString(); + } + + private boolean hasNextToken() { + return token_index < tokens.size(); + } + + private TwoTuple getNextToken() { + return getToken(token_index++); + } + + private void tokenIndexDecrement() { + token_index--; + } + + private void tokenIndexIncrement() { + token_index++; + } + + private TwoTuple currentToken() { + return getToken(token_index); + } + + private TwoTuple getToken(int index) { + return tokens.get(index); + } + + private void addToken(String token, Object value) { + tokens.add(new TwoTuple(token, value)); + } + + private boolean parseBoolean(I t) { + if (t == null) { + return false; + } else { + boolean b = true; + if (t instanceof Boolean) { + b = XType.cast(t); + } + return b; + } + } + + private void lookAheadSearchedWillRun(Runnable run, String... ts) { + if (hasNextToken()) { + TwoTuple next = currentToken(); + for (String t : ts) { + if (t.equals(next.token)) { + run.run(); + break; + } + } + } + } + + public interface VoidCallbackNoParam { + void vcv(); + } + + public interface VoidCallbackWithParam{ + void vci(I t); + } + + + public interface ReturnCallbackNoParam{ + R rcv(); + } + + public interface ReturnCallbackWithParam{ + R rci(I i); + } + + + //自顶向下分析 + //主要是选择分支结构的 + + /** + * S -> S | ε + *

+ *

+ * S -> if then T | ε + * T -> else if then T | else | ε + *

+ *

+ *

+ * S -> match . F | ε + * F -> as . A . then . B | default + * B -> F | ε + * A -> as . A | ε + *

+ * 为了实现错误检查 和 句型的完整性检查,在实现过程中 + * 对以上的产生式 ,微调了下, + * 实现仍是自上而下 的 + *

+ * 分支语句 每次只有 一个 执行! + *

+ * 现在这个实现的结构非常的复杂 + * 哎 ,我都看不懂了,嘿嘿 + *

+ * 先check 并且拿到 为true 的第一个执行的分支 + * check 结构没问题后,最后执行 这个 分支 得到结果! + * 这里面涉及到超前搜索,主要为了保证执行结构的完整性 + * ε <=> 直接执行结束,结束递归 等等! + */ + private void S_token() { + if (hasNextToken()) {//递归的终止条件! + //S -> if then T + TwoTuple start_token = getNextToken(); + /** + * S -> if then T | ε + * T -> else if then T | else | ε + * if then must be all in one + * + * 完整性 if then / if then else if then + * /if then else + */ + if (IF.equals(start_token.token)) { + TwoTuple then_token; + if (hasNextToken() + && THEN.equals((then_token = getNextToken()).token)) { + // 将要执行的token装入到 result_token中! + if (result_token == null && parseBoolean(start_token.value)) { + result_token = then_token; + inputValue = start_token.value; + } + // T -> else if then T | else | ε + T_token(); + } else { + nextTokenError(or(THEN)); + } + + } + /** + * 顺序性的要求 + * 完整性的要求 if then / if else / if else if else + * /match as then / match as then default / match default! + * 这里 ε 表示 没有下一个 token 符号 输入 ,直接 S_token结束 + * 非递归 终结符单词 才能 继续调用下一个 分支 语句? + * 需要 first集合? + * 或者 follow 集合? + * select? + * S -> match . F | ε + * F -> as . A . then . B | default + * B -> F | ε // match as then or match default !!! + * A -> as . A | ε + */ + else if (MATCH.equals(start_token.token)) {/* syntax check */ + + F_token(start_token.value); + + } else { + nextTokenError(or(IF, MATCH)); + } + + callTokenCallback(); + + //check and execute next program fragment! + S_token(); + + } + } + + /** + * F handler + * after match it should be as or default!!! + * F -> as . A . then . B | default + * B -> F | ε //保证了 match as then 或 match default 的完整性! + * A -> as . A | ε + * + * @param matchValue + */ + private void F_token(Object matchValue) { + + if (hasNextToken()) { + + TwoTuple f_token = getNextToken(); + + if (AS.equals(f_token.token)) { + boolean asOK = matchValue != null + && + matchValue.equals(f_token.value) + | + A_token(matchValue);// left + TwoTuple then_token; + if (hasNextToken() && THEN.equals((then_token = getNextToken()).token)/* syntax check */) { + // 正式 匹配的有 then 然后执行! + if (result_token == null && asOK) { + result_token = then_token; + inputValue = matchValue; + } + + //递归条件,也是超前搜索 + //为了 match as then的完整性 + lookAheadSearchedWillRun(() -> { + B_token(matchValue); + }, AS, DEFAULT);//开始 中间 结尾 的单词要分清楚 +// B_token(matchValue); + } else { + nextTokenError(or(THEN)); + } + } else if (DEFAULT.equals(f_token.token)) { + if (result_token == null) { + result_token = f_token; + inputValue = matchValue; + } + } else { + nextTokenError(or(AS, DEFAULT)); + } + + } else { + nextTokenError(or(AS, DEFAULT)); + } + + } + + /** + * match as then 必须是一个整体! + * B -> F | ε + * A -> as . A | ε + * + * @param matchValue + */ + private void B_token(Object matchValue) { + if (hasNextToken()) { + F_token(matchValue); + } + //ε <=> 没有代码可执行,没有下一步可执行! + } + + //右递归 + + /** + * as handler + * A -> as . A | ε + * + * @param matchValue + * @return + */ + private boolean A_token(Object matchValue) { + boolean matched = false; + if (hasNextToken()) { + TwoTuple as_token = getNextToken(); + if (AS.equals(as_token.token)) { + if (result_token == null //说明还没有匹配的有! + && !matched //本次 as 的匹配 已经匹配过的话 matched = true! + //,可以加快速度(小优化) + && matchValue != null +// && as_token.value != null + //只要 matchValue 存在就可以 调用equals 了 + //并且 都为 null 的时候 ,直接返回false (暗含) + && matchValue.equals(as_token.value) + ) { + matched = true; + } + matched = matched || A_token(matchValue); + } else { + //多取一次未处理的话,应该回溯一个 + //也是递归终止条件 + tokenIndexDecrement(); + } + + } + + return matched; + } + + /** + * T -> else if then 【加入超前搜索!保证完整性】 T | else | ε + */ + private void T_token() { + + // 需要超前遍历 才能 可以随意 的调用任何 完整结构 的语句! + lookAheadSearchedWillRun(() -> { + TwoTuple t_token = getNextToken(); + if (ELSE_IF.equals(t_token.token)) { + TwoTuple then_token; + if (hasNextToken() && THEN.equals((then_token = getNextToken()).token)) { + + if (result_token == null && parseBoolean(t_token.value)) { + result_token = then_token; + inputValue = t_token.value; + } + // T -> else if then T | else | E + // recursion + + T_token(); + } else { + nextTokenError(or(THEN)); + } + } else if (ELSE.equals(t_token.token)) { + if (result_token == null) { + result_token = t_token; + inputValue = null; + } + + } + //if then 检验是完整的,为了match as then 或者 下一 if then + //不需要这一句,去check : if then else if then/ + // if then else 因为 if then在S_token中实现是完整的 +// else { +// nextTokenError(or(ELSE_IF, ELSE)); +// } + + }, ELSE_IF, ELSE); + + } + + + //不支持 if else 嵌套! + private void analyzeTokensAndExec() { + //分析语法结构 + //然后执行! + + S_token(); + + + } + + + public X end() { + + analyzeTokensAndExec(); +// clear tokens! + tokens = null; + return X.of(result, error); + } + + +} diff --git a/src/com/xiuye/sharp/X2.java b/src/com/xiuye/sharp/X2.java new file mode 100644 index 0000000..2302b9a --- /dev/null +++ b/src/com/xiuye/sharp/X2.java @@ -0,0 +1,293 @@ +package com.xiuye.sharp; + +import java.util.Map; +import java.util.Objects; + +import com.xiuye.util.cls.XType; + +//singleton beans manager +public class X2 { + + // name -> bean + // 多元信息保存 + private static final Map nameMappingBeans; + // singleton + // class -> bean + private static final Map, Object> classMappingBeans; + static { + nameMappingBeans = XType.sync(XType.map()); + classMappingBeans = XType.sync(XType.map()); + } + + // 一元信息 + + private R result; + // 定义接口做决策! + private BeanOps beanOps; + + /** + * for get bean + * + * @param name + * @param clazz + */ + public X2(String name, Class clazz) { + this.beanOps = new NameAndClassBeanPoolPromise(name, clazz); + } + + /** + * for get bean + * + * @param name + */ + public X2(String name) { + this.beanOps = new NameBeanPoolPromise(name); + } + + /** + * for get bean + * + * @param clazz + */ + public X2(Class clazz) { + this.beanOps = new ClassBeanPoolPromise(clazz); + } + + /** + * for register + * + * @param name + * @param clazz + * @param r + */ + public X2(String name, Class clazz, R r) { + this(name, clazz, r, false); + } + + public X2(String name, Class clazz, R r, boolean replace) { + this.beanOps = new NameAndClassBeanPoolPromise(name, clazz, r, replace); + } + + /** + * for register + * + * @param clazz + * @param r + */ + public X2(Class clazz, R r) { + this(clazz, r, false); + } + + public X2(Class clazz, R r, boolean replace) { + this.beanOps = new ClassBeanPoolPromise(clazz, r, replace); + } + + /** + * for register + * + * @param name + * @param r + */ + public X2(String name, R r) { + this(name, r, false); + } + + public X2(String name, R r, boolean replace) { + this.beanOps = new NameBeanPoolPromise(name, r, replace); + } + + /** + * 定义接口 做决策 执行那一实现类 操作 + * + * @author engineer + * + * @param + */ + private interface BeanOps { + public T getBean(); + + public void register(); + + /** + * register bean by class + * + * @param clazz + * @param in + * @return + */ + default void register(Class clazz, T in, boolean replace) { + synchronized (BeanOps.class) { + if (replace) { + classMappingBeans.put(clazz, in); + } else { + if (Objects.nonNull(classMappingBeans.putIfAbsent(clazz, in))) { + throw new RuntimeException("Bean:the class: " + clazz + " already exists!"); + } + } + } + } + + /** + * register bean by name + * + * @param name + * @param in + * @return + */ + default void register(String name, T in, boolean replace) { + synchronized (BeanOps.class) { + if (replace) { + nameMappingBeans.put(name, in); + } else { + if (Objects.nonNull(nameMappingBeans.putIfAbsent(name, in))) { + throw new RuntimeException("The bean name: " + name + " already exists!"); + } + } + } + } + } + + /** + * register bean or get bean by name + * + * @author engineer + * + */ + class NameBeanPoolPromise implements BeanOps { + + private String name; + private boolean replace; + + public NameBeanPoolPromise(String name) { + this.name = name; + } + + public NameBeanPoolPromise(String name, R r, boolean replace) { + this(name); + this.replace = replace; + result = r; + } + + public NameBeanPoolPromise(String name, R r) { + this(name, r, false); + } + + @Override + public R getBean() { + return XType.cast(nameMappingBeans.get(name)); + } + + @Override + public void register() { + register(name, result, replace); + } + + } + + /** + * register bean or get bean by class + * + * @author engineer + * + */ + class ClassBeanPoolPromise implements BeanOps { + + private Class clazz; + private boolean replace; + + public ClassBeanPoolPromise(Class clazz) { + this.clazz = clazz; + } + + public ClassBeanPoolPromise(Class clazz, R r, boolean replace) { + this(clazz); + this.replace = replace; + result = r; + } + + public ClassBeanPoolPromise(Class clazz, R r) { + this(clazz, r, false); + } + + @Override + public R getBean() { + return clazz.cast(classMappingBeans.get(clazz)); + } + + @Override + public void register() { + register(clazz, result, replace); + } + + } + + /** + * register bean or get bean by both name and class + * + * @author engineer + * + */ + class NameAndClassBeanPoolPromise implements BeanOps { + + private String name; + private Class clazz; + private boolean replace; + + public NameAndClassBeanPoolPromise(String name, Class clazz) { + this.name = name; + this.clazz = clazz; + } + + public NameAndClassBeanPoolPromise(String name, Class clazz, R r, boolean replace) { + this(name, clazz); + this.replace = replace; + result = r; + } + + public NameAndClassBeanPoolPromise(String name, Class clazz, R r) { + this(name, clazz, r, false); + } + + @Override + public R getBean() { + // check + R r1 = clazz.cast(nameMappingBeans.get(name)); + R r2 = clazz.cast(classMappingBeans.get(clazz)); + + if (r1 == null && r1 == null) { + return null; + } else if (Objects.nonNull(r1) && Objects.nonNull(r2) && r1.equals(r2)) { + return r1; + } else { + throw new RuntimeException("Did you register bean by name and(&&) class?!"); + } + } + + @Override + public void register() { + register(name, result, replace); + register(clazz, result, replace); + } + + } + + public X2 getBean() { + result = this.beanOps.getBean(); + return this; + } + + public X2 register() { + this.beanOps.register(); + return this; + } + + /** + * return back to promise + * + * @return + */ + public X end() { + return X.of(result); + } + +} diff --git a/src/com/xiuye/util/annotation/XBean.java b/src/com/xiuye/util/annotation/XBean.java new file mode 100644 index 0000000..cbd26eb --- /dev/null +++ b/src/com/xiuye/util/annotation/XBean.java @@ -0,0 +1,12 @@ +package com.xiuye.util.annotation; + +import java.lang.annotation.*; + +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface XBean { + + String value() default ""; + +} diff --git a/src/com/xiuye/util/annotation/XInject.java b/src/com/xiuye/util/annotation/XInject.java new file mode 100644 index 0000000..1efe58c --- /dev/null +++ b/src/com/xiuye/util/annotation/XInject.java @@ -0,0 +1,10 @@ +package com.xiuye.util.annotation; + + +import java.lang.annotation.*; + +@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface XInject { +} diff --git a/src/com/xiuye/util/annotation/XScope.java b/src/com/xiuye/util/annotation/XScope.java new file mode 100644 index 0000000..ced5571 --- /dev/null +++ b/src/com/xiuye/util/annotation/XScope.java @@ -0,0 +1,11 @@ +package com.xiuye.util.annotation; + + +import java.lang.annotation.*; + +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface XScope { + String value() default "singleton"; +} diff --git a/src/com/xiuye/util/cls/MetaUtil.java b/src/com/xiuye/util/cls/MetaUtil.java deleted file mode 100644 index 05216c2..0000000 --- a/src/com/xiuye/util/cls/MetaUtil.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.xiuye.util.cls; - - -public class MetaUtil { - public static Caller caller(int functionLayer) { - StackTraceElement[] ss = Thread.currentThread().getStackTrace(); - Caller c = null; - if(ss.length > functionLayer) { - c = new Caller(); - c.setClassLoaderName(ss[functionLayer].getClassLoaderName()); - c.setClassName(ss[functionLayer].getClassName()); - c.setModuleName(ss[functionLayer].getModuleName()); - c.setFileName(ss[functionLayer].getFileName()); - c.setLineNumber(ss[functionLayer].getLineNumber()); - c.setMethodName(ss[functionLayer].getMethodName()); - c.setModuleVersion(ss[functionLayer].getModuleVersion()); - } - return c; - } - public static class Caller{ - private String className; - private String methodName; - private String fileName; - private int lineNumber; - private String classLoaderName; - private String moduleName; - private String moduleVersion; - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - public String getMethodName() { - return methodName; - } - public void setMethodName(String methodName) { - this.methodName = methodName; - } - public String getFileName() { - return fileName; - } - public void setFileName(String fileName) { - this.fileName = fileName; - } - public int getLineNumber() { - return lineNumber; - } - public void setLineNumber(int lineNumber) { - this.lineNumber = lineNumber; - } - public String getClassLoaderName() { - return classLoaderName; - } - public void setClassLoaderName(String classLoaderName) { - this.classLoaderName = classLoaderName; - } - public String getModuleName() { - return moduleName; - } - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } - public String getModuleVersion() { - return moduleVersion; - } - public void setModuleVersion(String moduleVersion) { - this.moduleVersion = moduleVersion; - } - @Override - public String toString() { - return "Caller [className=" + className + ", methodName=" + methodName + ", fileName=" + fileName - + ", lineNumber=" + lineNumber + ", classLoaderName=" + classLoaderName + ", moduleName=" - + moduleName + ", moduleVersion=" + moduleVersion + "]"; - } - - } -} diff --git a/src/com/xiuye/util/cls/XClassLoader.java b/src/com/xiuye/util/cls/XClassLoader.java new file mode 100644 index 0000000..a58c5a0 --- /dev/null +++ b/src/com/xiuye/util/cls/XClassLoader.java @@ -0,0 +1,34 @@ +package com.xiuye.util.cls; + +import java.net.URL; +import java.net.URLClassLoader; + +/** + * self defined ClassLoader for load class file + * + * @author xiuye + */ +public class XClassLoader extends URLClassLoader { + + /** + * ClassLoader constructor + * + * @param urls + */ + public XClassLoader(URL[] urls) { + super(urls); + } + + /** + * load a class by class name + * + * @param + * @param name + * @return + * @throws ClassNotFoundException + */ + public Class load(String name) throws ClassNotFoundException { + return XType.cast(this.loadClass(name)); + } + +} diff --git a/src/com/xiuye/util/cls/XMeta.java b/src/com/xiuye/util/cls/XMeta.java new file mode 100644 index 0000000..cf1021e --- /dev/null +++ b/src/com/xiuye/util/cls/XMeta.java @@ -0,0 +1,143 @@ +package com.xiuye.util.cls; + +import java.util.Arrays; + +/** + * class meta info operator + * + * @author xiuye + */ +public class XMeta { + + + public static Caller caller() { + return caller(4); + } + + /** + * get caller function info + * + * @param functionLayer + * @return + */ + public static Caller caller(int functionLayer) { + return caller(Thread.currentThread(), functionLayer); + } + + public static Caller caller(Thread parent, int functionLayer) { + StackTraceElement[] ss = parent.getStackTrace(); + Caller c = null; + if (ss.length > functionLayer) { + c = new Caller(); + c.setLevel(functionLayer); + c.setTrace(ss); + c.setClassName(ss[functionLayer].getClassName()); + c.setFileName(ss[functionLayer].getFileName()); + c.setLineNumber(ss[functionLayer].getLineNumber()); + c.setMethodName(ss[functionLayer].getMethodName()); + } + return c; + } + + /** + * caller info bean + * + * @author xiuye + */ + public static class Caller { + private String className; + private String methodName; + private String fileName; + private int lineNumber; + private String classLoaderName; + private String moduleName; + private String moduleVersion; + + private StackTraceElement[] trace; + + private int level; + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public int getLineNumber() { + return lineNumber; + } + + public void setLineNumber(int lineNumber) { + this.lineNumber = lineNumber; + } + + public String getClassLoaderName() { + return classLoaderName; + } + + public void setClassLoaderName(String classLoaderName) { + this.classLoaderName = classLoaderName; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public String getModuleVersion() { + return moduleVersion; + } + + public void setModuleVersion(String moduleVersion) { + this.moduleVersion = moduleVersion; + } + + public StackTraceElement[] getTrace() { + return trace; + } + + public void setTrace(StackTraceElement[] trace) { + this.trace = trace; + } + + + public int getLevel() { + return level; + } + + public void setLevel(int level) { + this.level = level; + } + + @Override + public String toString() { + return "Caller [className=" + className + ", methodName=" + methodName + ", fileName=" + fileName + + ", lineNumber=" + lineNumber + ", classLoaderName=" + classLoaderName + ", moduleName=" + + moduleName + ", moduleVersion=" + moduleVersion + ", level=" + level + ", trace=" + + Arrays.toString(trace) + "]"; + } + + + } +} diff --git a/src/com/xiuye/util/cls/XType.java b/src/com/xiuye/util/cls/XType.java new file mode 100644 index 0000000..75a4b3d --- /dev/null +++ b/src/com/xiuye/util/cls/XType.java @@ -0,0 +1,711 @@ +package com.xiuye.util.cls; + +import com.xiuye.util.cls.XClassLoader; + +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; + +/** + * Type operator + * + * @author xiuye + */ +public class XType { + + // 适合引用类型 ,不适合 基本类型 + + /** + * cast T to R In general,T is ancestor class , R is subclass + * + * @param + * @param + * @param e instantiated object + * @return reference of subclass + */ + @SuppressWarnings("unchecked") + public static R cast(T e) { + return (R) e; + } + + // boolean byte char short int long float double + + /** + * for default constructor + * + * @param + * @author xiuye + */ + public interface DefaultConstructor { + R construct(); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithParam { + R construct(T t); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithTwoParams { + R construct(T1 t1, T2 t2); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithThreeParams { + R construct(T1 t1, T2 t2, T3 t3); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithFourParams { + R construct(T1 t1, T2 t2, T3 t3, T4 t4); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithFiveParams { + R construct(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithSixParams { + R construct(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithSevenParams { + R construct(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithEightParams { + R construct(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithNineParams { + R construct(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithTenParams { + R construct(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10); + } + + /** + * for parameters-ed constructor + * + * @param + * @param + * @author xiuye + */ + public interface ConstructorWithParams { + @SuppressWarnings("unchecked") + R construct(T... t); + } + + /** + * instantiate object by default constructor + * + * @param + * @param c + * @return + */ + public static R newInstance(DefaultConstructor c) { + return c.construct(); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param c + * @param t + * @return + */ + public static R newInstance(ConstructorWithParam c, T t) { + return c.construct(t); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param + * @param c + * @param t1 + * @param t2 + * @return + */ + public static R newInstance(ConstructorWithTwoParams c, T1 t1, T2 t2) { + return c.construct(t1, t2); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param c + * @param t1 + * @param t2 + * @param t3 + * @return + */ + public static R newInstance(ConstructorWithThreeParams c, T1 t1, T2 t2, T3 t3) { + return c.construct(t1, t2, t3); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param c + * @param t1 + * @param t2 + * @param t3 + * @param t4 + * @return + */ + public static R newInstance(ConstructorWithFourParams c, T1 t1, T2 t2, T3 t3, + T4 t4) { + return c.construct(t1, t2, t3, t4); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param c + * @param t1 + * @param t2 + * @param t3 + * @param t4 + * @param t5 + * @return + */ + public static R newInstance(ConstructorWithFiveParams c, T1 t1, + T2 t2, T3 t3, T4 t4, T5 t5) { + return c.construct(t1, t2, t3, t4, t5); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param c + * @param t1 + * @param t2 + * @param t3 + * @param t4 + * @param t5 + * @param t6 + * @return + */ + public static R newInstance(ConstructorWithSixParams c, + T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) { + return c.construct(t1, t2, t3, t4, t5, t6); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param c + * @param t1 + * @param t2 + * @param t3 + * @param t4 + * @param t5 + * @param t6 + * @param t7 + * @return + */ + public static R newInstance( + ConstructorWithSevenParams c, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, + T7 t7) { + return c.construct(t1, t2, t3, t4, t5, t6, t7); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param c + * @param t1 + * @param t2 + * @param t3 + * @param t4 + * @param t5 + * @param t6 + * @param t7 + * @param t8 + * @return + */ + public static R newInstance( + ConstructorWithEightParams c, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, + T7 t7, T8 t8) { + return c.construct(t1, t2, t3, t4, t5, t6, t7, t8); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param c + * @param t1 + * @param t2 + * @param t3 + * @param t4 + * @param t5 + * @param t6 + * @param t7 + * @param t8 + * @param t9 + * @return + */ + public static R newInstance( + ConstructorWithNineParams c, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, + T6 t6, T7 t7, T8 t8, T9 t9) { + return c.construct(t1, t2, t3, t4, t5, t6, t7, t8, t9); + } + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param + * @param c + * @param t1 + * @param t2 + * @param t3 + * @param t4 + * @param t5 + * @param t6 + * @param t7 + * @param t8 + * @param t9 + * @param t10 + * @return + */ + public static R newInstance( + ConstructorWithTenParams c, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, + T6 t6, T7 t7, T8 t8, T9 t9, T10 t10) { + return c.construct(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); + } + + // Now , T[] <=> T...t + + /** + * instantiate object by parameters-ed constructor + * + * @param + * @param + * @param c + * @param t + * @return + */ + @SafeVarargs + public static R newInstance(ConstructorWithParams c, T... t) { + return c.construct(t); + } + +// public static R newInstance(ConstructorWithParams c,Object...t) { +// return c.construct(t); +// } + + /** + * HashMap + * + * @param + * @param + * @return + */ + public static Map map() { + return newInstance(HashMap::new); + } + + /** + * ArrayList + * + * @param + * @return + */ + public static List list() { + return newInstance(ArrayList::new); + } + + /** + * HashSet + * + * @param + * @return + */ + public static Set set() { + return newInstance(HashSet::new); + } + + /** + * to ArrayList + * + * @param + * @param a + * @return + */ + public static List toList(T[] a) { + List L = list(); + for (T e : a) { + L.add(e); + } + return L; + } + + /** + * to ArrayList + * + * @param a + * @return + */ + public static List toList(int[] a) { + List L = list(); + for (int e : a) { + L.add(e); + } + return L; + } + + /** + * handle new ArrayList + * + * @param + * @param + * @param func + * @return + */ + public static List toList(Function, List> func) { + return func.apply(list()); + } + + public static Set toSet(Function, Set> func) { + return func.apply(set()); + } + + /** + * create ClassLoader with paths + * + * @param urls + * @return + */ + public static XClassLoader createClassLoader(URL[] urls) { + return new XClassLoader(urls); + } + + /** + * current class path: . + * + * @return + * @throws MalformedURLException + */ + public static XClassLoader createClassLoader() throws MalformedURLException { + return createClassLoader("."); + } + + /** + * create ClassLoader with paths + * + * @param paths + * @return + * @throws MalformedURLException + */ + public static XClassLoader createClassLoader(String... paths) throws MalformedURLException { + List urlsList = list(); + for (String p : paths) { + URL u = Paths.get(p).toUri().toURL(); + urlsList.add(u); + } + URL[] urls = urlsList.toArray(new URL[urlsList.size()]); +// LogUtil.logarray(urls); + return createClassLoader(urls); + } + + /** + * create ClassLoader with paths + * + * @param paths + * @return + * @throws MalformedURLException + */ + public static XClassLoader createClassLoader(List paths) throws MalformedURLException { + + URL[] urls = new URL[paths.size()]; + + for (int i = 0; i < urls.length; i++) { + urls[i] = Paths.get(paths.get(i)).toUri().toURL(); + } + + return createClassLoader(urls); + + } + + /** + * if first-value is null, + * return second value else return first value + * + * @param s1 + * @param s2 + * @return + */ + public static String nvl(String s1, String s2) { + if (Objects.isNull(s1)) + return s2; + return s1; + + } + +// public static Class loadClass(ClassLoader cl, String name) throws ClassNotFoundException { +// return cl.loadClass(name); +// } + + /** + * synchronizedMap + * synchronizedSet + * synchronizedList + * + * @param + * @param t + * @return + */ + public static T sync(T t) { + if (t instanceof Map) { + return cast(Collections.synchronizedMap(cast(t))); + } + if (t instanceof List) { + return cast(Collections.synchronizedList(cast(t))); + } + if (t instanceof Set) { + return cast(Collections.synchronizedSet(cast(t))); + } + return t; + } + + /** + * handle new HashMap + * + * @param + * @param + * @param func + * @return + */ + public static Map toMap(Function, Map> func) { + return func.apply(map()); + } + + + /** + * the following code does not come true! + */ +// public static R alloc() { +// return newInstance(R::new); +// } + + public static String firstUpperCase(String str) { + String ret = null; + if(Objects.nonNull(str)) { + char[] strArr = str.toCharArray(); + if(strArr.length>0) { +// strArr[0] -='a'; +// strArr[0] += 'A'; +// + if(!Character.isUpperCase(strArr[0])) { + strArr[0] = Character.toUpperCase(strArr[0]); + } + ret = String.valueOf(strArr); + } + } + return ret; + } + + public static String firstLowerCase(String str) { + String ret = null; + if(Objects.nonNull(str)) { + char[] strArr = str.toCharArray(); + if(strArr.length>0) { +// strArr[0] -='a'; +// strArr[0] += 'A'; +// + if(!Character.isLowerCase(strArr[0])) { + strArr[0] = Character.toLowerCase(strArr[0]); + } + ret = String.valueOf(strArr); + } + } + return ret; + } + + + +} diff --git a/src/com/xiuye/util/code/JavaSourceCode.java b/src/com/xiuye/util/code/JavaSourceCode.java new file mode 100644 index 0000000..0184ec3 --- /dev/null +++ b/src/com/xiuye/util/code/JavaSourceCode.java @@ -0,0 +1,32 @@ +package com.xiuye.util.code; + +import java.net.URI; + +import javax.tools.SimpleJavaFileObject; + +/** + * A file object used to represent source coming from a string. + */ +public class JavaSourceCode extends SimpleJavaFileObject { + /** + * The source code of this "file". + */ + final String code; + + /** + * Constructs a new JavaSourceFromString. + * + * @param name the name of the compilation unit represented by this file object + * @param code the source code for the compilation unit represented by this file + * object + */ + public JavaSourceCode(String name, String code) { + super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE); + this.code = code; + } + + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return code; + } +} \ No newline at end of file diff --git a/src/com/xiuye/util/code/XCode.java b/src/com/xiuye/util/code/XCode.java new file mode 100644 index 0000000..cb401bd --- /dev/null +++ b/src/com/xiuye/util/code/XCode.java @@ -0,0 +1,247 @@ +package com.xiuye.util.code; + +import com.xiuye.util.log.XLog; +import com.xiuye.util.time.XTime; +import com.xiuye.util.time.XTime.Callback; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Objects; + +/** + * Run code time + * + * @author xiuye + */ +public class XCode { + + private static int level = 5; + + public static int attach(int delta) { + int old = level; + level += delta; + return old; + } + + public static int dettach(int delta) { + int old = level; + level -= delta; + return old; + } + + /** + * run code and return time of code running + * + * @param runnable + * @return run nanoseconds + */ + public static synchronized long run(Runnable runnable) { + return run(level, runnable); + } + + /** + * run code and return nanoseconds + * + * @param runnable + * @param cs + */ + public static synchronized long runNS(Runnable runnable, Callback... cs) { + return runNS(level, runnable); + } + + /** + * run code and return milliseconds + * + * @param runnable + * @param cs + */ + public static synchronized long runMS(Runnable runnable, Callback... cs) { + return runMS(level, runnable); + } + + /** + * run code and return seconds + * + * @param runnable + * @param cs + */ + public static synchronized long runS(Runnable runnable, Callback... cs) { + return runS(5, runnable); + } + + /** + * run code and return time of code running + * + * @param runnable + * @return run nanoseconds + */ + public static synchronized long run(int level, Runnable runnable) { + if (Objects.nonNull(runnable)) { + XTime xtime = new XTime(level); + xtime.start(); + runnable.run(); + return xtime.cost(); + + } + return -1; + } + + /** + * run code and return nanoseconds + * + * @param runnable + * @param cs + */ + public static synchronized long runNS(int level, Runnable runnable, Callback... cs) { + if (Objects.nonNull(runnable)) { + XTime xtime = new XTime(level); + xtime.start(); + runnable.run(); + return xtime.outByNS(cs); + } + return -1; + } + + /** + * run code and return milliseconds + * + * @param runnable + * @param cs + */ + public static synchronized long runMS(int level, Runnable runnable, Callback... cs) { + if (Objects.nonNull(runnable)) { + XTime xtime = new XTime(level); + xtime.start(); + runnable.run(); + return xtime.outByMS(cs); + } + return -1; + } + + /** + * run code and return seconds + * + * @param runnable + * @param cs + */ + public static synchronized long runS(int level, Runnable runnable, Callback... cs) { + if (Objects.nonNull(runnable)) { + XTime xtime = new XTime(level); + xtime.start(); + runnable.run(); + return xtime.outByS(cs); + } + return -1; + } + + // private static ExecutorService pool ; +// static { +// pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2); +// } + public static Thread runAsync(Runnable runnable) { + Thread t = new Thread(runnable); + t.start(); + return t; +// pool.execute(runnable); + } + + + /** + * covert java source code to unicode code + * + * @param outputFilePath + * @throws IOException + */ + public static void java2Unicode(String fileName, String outputFilePath) throws IOException { + File f = new File(fileName); + if (!f.exists()) { + XLog.log("文件:" + fileName + "不存在!"); + return; + } + BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); + BufferedWriter bw = new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(outputFilePath + File.pathSeparator + fileName))); + int i = -1; + String str = ""; + String unicodeOriginal = ""; + String unicodeTemp = ""; + while ((i = br.read()) != -1) { + unicodeOriginal = Integer.toHexString(i); + int length = unicodeOriginal.length(); + if (length == 1) { + unicodeTemp = "000" + unicodeOriginal; + } else if (length == 2) { + unicodeTemp = "00" + unicodeOriginal; + } else if (length == 3) { + unicodeTemp = "0" + unicodeOriginal; + } else { + unicodeTemp = unicodeOriginal; + } + str = "\\u" + unicodeTemp; + bw.write(str, 0, str.length()); + bw.flush(); +// System.out.print("\\u" + unicodeTemp); + XLog.print("\\u" + unicodeTemp); + } + XLog.println(); + br.close(); + bw.close(); + + } + + /** + * covert unicode code to java source code + * + * @param outputFilePath + * @throws IOException + */ + public static void unicode2Java(String fileName, String outputFilePath) throws IOException { + File f = new File(fileName); + if (!f.exists()) { + XLog.log("文件:" + fileName + "不存在!"); + return; + } + Path outPath = Paths.get(outputFilePath); + if (!Files.exists(outPath)) { + Files.createDirectory(outPath); + } + BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); + BufferedWriter bw = new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(outputFilePath + File.separator + fileName))); + int ch = -1; + while ((ch = br.read()) != -1) { + if (ch == '\\') { + ch = br.read(); + if (ch == 'u') { + String s = ""; + for (int i = 0; i < 4; i++) { + ch = br.read(); + s += (char) ch; + } + bw.write(Integer.parseInt(s, 16)); + XLog.print(s); + } else { + bw.write(ch); + XLog.print(ch); + } + } else { + bw.write(ch); + XLog.print(ch); + } + } + XLog.println(); + br.close(); + bw.close(); + + } + +} diff --git a/src/com/xiuye/util/code/XCompiler.java b/src/com/xiuye/util/code/XCompiler.java new file mode 100644 index 0000000..b7a37e5 --- /dev/null +++ b/src/com/xiuye/util/code/XCompiler.java @@ -0,0 +1,132 @@ +package com.xiuye.util.code; + +import com.xiuye.util.cls.XType; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; + +/** + * java code compiler + * + * @author xiuye + */ +public class XCompiler { + + /** + * compile java source code on current path . output class file to current path + * + * @param files + * @return + */ + public static boolean compileFile(List files) { + return compileFile(".", files); + } + + /** + * compile java source code assign output path + * + * @param binPath + * @param files + * @return + */ + public static boolean compileFile(String binPath, List files) { + List options = XType.list(); + options.add("-d"); + options.add(binPath); + return compileFile(options, files); + } + + /** + * compile java source code + * + * @param options compile arguments + * @param filenames + * @return + */ + public static boolean compileFile(List options, List filenames) { + + JavaCompiler jc = ToolProvider.getSystemJavaCompiler(); +// DiagnosticCollector diagnostics = new DiagnosticCollector(); + try (StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null)) { + Iterable compilationUnits = sjfm.getJavaFileObjectsFromStrings(filenames); + + boolean b = jc.getTask(null, sjfm, null, options, null, compilationUnits).call(); +// for (Diagnostic diagnostic : diagnostics.getDiagnostics()) +// LogUtil.err("Error on line", diagnostic.getLineNumber(), "in", diagnostic.getSource().toUri()); + return b; + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + /** + * compile java source code for java file + * + * @param arguments + * @return + */ + public static boolean compileFile(String... arguments) { + JavaCompiler jc = ToolProvider.getSystemJavaCompiler(); + return jc.run(null, null, null, arguments) == 0; + } + + /** + * compile source code for string java code + * + * @param codes + * @return + */ + public static boolean compileCode(Map codes) { + return compileCode(".", codes); + } + + /** + * compile java source string code + * + * @param binPath + * @param codes + * @return + */ + public static boolean compileCode(String binPath, Map codes) { + List options = XType.list(); + options.add("-d"); + options.add(binPath); + return compileCode(options, codes); + } + + /** + * compile java source code codes[Map structure] : package(String) => + * code(string) + * + * @param options compile arguments + * @param codes + * @return + */ + public static boolean compileCode(List options, Map codes) { + JavaCompiler jc = ToolProvider.getSystemJavaCompiler(); +// DiagnosticCollector diagnostics = new DiagnosticCollector(); + try (StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null)) { + + List compilationUnits = XType.list(); + for (Entry code : codes.entrySet()) { + compilationUnits.add(new JavaSourceCode(code.getKey(), code.getValue())); + } + boolean b = jc.getTask(null, sjfm, null, options, null, compilationUnits).call(); +// for (Diagnostic diagnostic : diagnostics.getDiagnostics()) +// LogUtil.err("Error on line", diagnostic.getLineNumber(), "in", diagnostic.getSource().toUri()); + return b; + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + +} diff --git a/src/com/xiuye/util/code/XProxy.java b/src/com/xiuye/util/code/XProxy.java new file mode 100644 index 0000000..8e2579a --- /dev/null +++ b/src/com/xiuye/util/code/XProxy.java @@ -0,0 +1,9 @@ +package com.xiuye.util.code; + +public class XProxy { + + public static void main(String[] args) { + + } + +} diff --git a/src/com/xiuye/util/code/gen/ClassInfo.java b/src/com/xiuye/util/code/gen/ClassInfo.java new file mode 100644 index 0000000..ae50289 --- /dev/null +++ b/src/com/xiuye/util/code/gen/ClassInfo.java @@ -0,0 +1,300 @@ +package com.xiuye.util.code.gen; + +import com.xiuye.util.cls.XType; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +public class ClassInfo implements GenImportPackages, GenModifier, GenField, GenFcuntion, GenCoder { + + public static final String ACCESS_PRIVATE = "private"; + public static final String ACCESS_DEFAULT = ""; + public static final String ACCESS_PROTECTED = "protected"; + public static final String ACCESS_PUBLIC = "public"; + + public static final String STATIC_MODIFIER = "static"; + public static final String FINAL_MODIFIER = "final"; + public static final String TYPE_INTERFACE = "interface"; + public static final String TYPE_CLASS = "class"; + + private String packageName; + private List importPackages; + private String access; + private List modifiers; + private String type; + private String name; + // private String fullClassName; + private List fields; + private List functions; + + private String superClasses; + private List interfaces; + + { + importPackages = XType.list(); + modifiers = XType.list(); + fields = XType.list(); + functions = XType.list(); + } + public ClassInfo() { + + } + + public ClassInfo(String simpleClassName) { + this(null,simpleClassName); + } + + public ClassInfo(String packageName, String simpleClassName) { + this.setPackageName(packageName); + this.setAccess(ClassInfo.ACCESS_PUBLIC); +// this.addModifier(ClassInfo.FINAL_MODIFIER); + this.setType(ClassInfo.TYPE_CLASS); + this.setName(simpleClassName); + } + + public String getFullName() { + if(Objects.nonNull(packageName)&&!packageName.isEmpty()) { + return packageName + "." + name; + } + else { + return name; + } + + } + + public FieldInfo addField(String type, String name) { + FieldInfo fi = new FieldInfo(); + fi.setAccess(FieldInfo.ACCESS_PRIVATE); +// fi.addModifier(FieldInfo.STATIC_MODIFIER); +// fi.addModifier(FieldInfo.FINAL_MODIFIER); + fi.setType(type); + fi.setName(name); + this.addField(fi); + return fi; + } + + //default private + public FieldInfo addField(String type, String name, String value) { + FieldInfo fi = new FieldInfo(); + fi.setAccess(FieldInfo.ACCESS_PRIVATE); +// fi.addModifier(FieldInfo.STATIC_MODIFIER); +// fi.addModifier(FieldInfo.FINAL_MODIFIER); + fi.setType(type); + fi.setName(name); + fi.setValue(value); + this.addField(fi); + String bName = XType.firstUpperCase(name); + addMethod("void", "set" + bName, "this." + name + "=" + name + ";", type, name); + addMethod(type, "get" + bName, "return this." + name + ";"); + return fi; + } + + public FunctionInfo addConstructor(String methodBody, String... params) { + return addMethod(null, name, methodBody, params); + } + + public void ext(String... superClasses) { + if (superClasses.length > 0) { + if (TYPE_CLASS.equalsIgnoreCase(this.type)) { + this.superClasses = superClasses[0]; + } else if (TYPE_INTERFACE.equalsIgnoreCase(this.type)) { + this.interfaces = Arrays.asList(superClasses); + } + } + + } + + public void impl(String... interfaces) { + this.interfaces = Arrays.asList(interfaces); + } + + public FunctionInfo addMethod(String returnType, String name, String methodBody, String... params) { + + if (params.length % 2 != 0) { + throw new RuntimeException("Input params's number must be even!"); + } + FunctionInfo fi = new FunctionInfo(); + fi.setAccess(FunctionInfo.ACCESS_PUBLIC); +// fi.addModifier(FunctionInfo.STATIC_MODIFIER); +// fi.addModifier(FunctionInfo.FINAL_MODIFIER); + fi.setType(returnType); + fi.setName(name); + for (int i = 0; i < params.length; i += 2) { + fi.addParameter(params[i], params[i + 1]); + } + + fi.setFunctionBody(methodBody); + this.addFunction(fi); + return fi; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public List getImportPackages() { + return importPackages; + } + + public String getAccess() { + return access; + } + + public void setAccess(String access) { + this.access = access; + } + + public List getModifiers() { + return modifiers; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getFields() { + return fields; + } + + public boolean addField(FieldInfo field) { + return this.fields.add(field); + } + + public List getFunctions() { + return functions; + } + + public boolean addFunction(FunctionInfo func) { + return this.functions.add(func); + } + + @Override + public String toString() { + return codeLine(); + } + + @Override + public String code() { + return "package " + packageName + ";\n" + combinePackages() + "\n" + XType.nvl(access, ACCESS_DEFAULT) + " " + + combineModifiers() + type + " " + name + combineExtends() + "\n" + codeBlockBegin() + "\n" + + combineFields() + "\n" + combineFunctions() + "\n" + codeBlockEnd(); + } + + @Override + public String codeLine() { + return code() + "\n"; + } + + public String combineExtends() { + StringBuffer si = new StringBuffer(); + if (TYPE_CLASS.equalsIgnoreCase(this.type)) { + if (Objects.nonNull(superClasses) && !superClasses.isEmpty()) { + si.append(" extends "); + si.append(superClasses); + } + if (Objects.nonNull(this.interfaces) && !interfaces.isEmpty()) { + si.append(" implements "); + for (int i = 0; i < interfaces.size() - 1; i++) { + si.append(interfaces.get(i) + ","); + } + si.append(interfaces.get(interfaces.size() - 1)); + } + } else if (TYPE_INTERFACE.equalsIgnoreCase(this.type)) { + if (Objects.nonNull(this.interfaces) && !interfaces.isEmpty()) { + si.append(" extends "); + for (int i = 0; i < interfaces.size() - 1; i++) { + si.append(interfaces.get(i) + ","); + } + si.append(interfaces.get(interfaces.size() - 1)); + } + } + + return si.toString(); + + } + + @Override + public String combineFunctions() { + if (functions.isEmpty()) + return ""; + StringBuffer fc = new StringBuffer(); + functions.forEach(d -> { + fc.append("\t" + d.codeLine()); + }); + return fc.toString(); + } + + @Override + public String combineFields() { + if (fields.isEmpty()) + return ""; + StringBuffer fc = new StringBuffer(); + fields.forEach(d -> { + fc.append("\t" + d.codeLine()); + }); + return fc.toString(); + } + + @Override + public boolean addModifier(String modifier) { + return modifiers.add(modifier); + } + + @Override + public String combineModifiers() { + if (modifiers.isEmpty()) + return " "; + StringBuffer mc = new StringBuffer(); + modifiers.forEach(d -> { + mc.append(d + " "); + }); + return mc.toString(); + } + + @Override + public String combinePackages() { + if (importPackages.isEmpty()) + return ""; + StringBuffer pc = new StringBuffer(); + importPackages.forEach(d -> { + pc.append("import " + d + ";\n"); + }); + return pc.toString(); + } + + @Override + public boolean addImportPackage(String packageName) { + return importPackages.add(packageName); + } + + @Override + public boolean importPackage(String... packageName) { + + boolean ret = false; + + for (String pack : packageName) { + ret = addImportPackage(pack); + } + + return ret; + + } + +} diff --git a/src/com/xiuye/util/code/gen/FieldInfo.java b/src/com/xiuye/util/code/gen/FieldInfo.java new file mode 100644 index 0000000..528fad8 --- /dev/null +++ b/src/com/xiuye/util/code/gen/FieldInfo.java @@ -0,0 +1,97 @@ +package com.xiuye.util.code.gen; + +import com.xiuye.util.cls.XType; + +import java.util.List; +import java.util.Objects; + +public class FieldInfo implements GenModifier, GenCoder { + + public static final String ACCESS_PRIVATE = "private"; + public static final String ACCESS_DEFAULT = ""; + public static final String ACCESS_PROTECTED = "protected"; + public static final String ACCESS_PUBLIC = "public"; + + public static final String STATIC_MODIFIER = "static"; + public static final String FINAL_MODIFIER = "final"; + + private String access; + private List modifiers; + private String type; + private String name; + private String value; + + public FieldInfo() { + modifiers = XType.list(); + } + + public String getAccess() { + return access; + } + + public void setAccess(String access) { + this.access = access; + } + + public List getModifiers() { + return modifiers; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public String toString() { + return codeLine(); + } + + @Override + public boolean addModifier(String modifier) { + return modifiers.add(modifier); + } + + public String combineModifiers() { + if (modifiers.isEmpty()) + return " "; + StringBuffer mc = new StringBuffer(); + modifiers.forEach(d -> { + mc.append(d + " "); + }); + return mc.toString(); + } + + public String code() { + String tmp = XType.nvl(access, ACCESS_DEFAULT) + " " + combineModifiers() + type + " " + name; + if (Objects.nonNull(value) && !value.isEmpty()) { + tmp += " = " + value; + } + + return tmp + ";"; + } + + public String codeLine() { + return code() + "\n"; + } + +} diff --git a/src/com/xiuye/util/code/gen/FunctionInfo.java b/src/com/xiuye/util/code/gen/FunctionInfo.java new file mode 100644 index 0000000..8094f9e --- /dev/null +++ b/src/com/xiuye/util/code/gen/FunctionInfo.java @@ -0,0 +1,165 @@ +package com.xiuye.util.code.gen; + +import com.xiuye.util.cls.XType; + +import java.util.List; +import java.util.Objects; + +public class FunctionInfo implements GenModifier, GenParameter, GenCoder { + + public static class Parameter { + + private String type; + private String name; + + public Parameter() { + } + + public Parameter(String type, String name) { + this.type = type; + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return type + " " + name; + } + + } + + public static final String ACCESS_PRIVATE = "private"; + public static final String ACCESS_DEFAULT = ""; + public static final String ACCESS_PROTECTED = "protected"; + public static final String ACCESS_PUBLIC = "public"; + + public static final String STATIC_MODIFIER = "static"; + public static final String FINAL_MODIFIER = "final"; + + private String access; + private List modifiers; + private String type; + private String name; + private List parameters; + private String functionBody; + + public FunctionInfo() { + modifiers = XType.list(); + parameters = XType.list(); + } + + public String getAccess() { + return access; + } + + public void setAccess(String access) { + this.access = access; + } + + public List getModifiers() { + return modifiers; + } + + public void setModifiers(List modifiers) { + this.modifiers = modifiers; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getParameters() { + return parameters; + } + + public String getFunctionBody() { + return functionBody; + } + + public void setFunctionBody(String functionBody) { + this.functionBody = functionBody; + } + + @Override + public String toString() { + return codeLine(); + } + + @Override + public boolean addModifier(String modifier) { + return modifiers.add(modifier); + } + + @Override + public String combineModifiers() { + if (modifiers.isEmpty()) + return " "; + StringBuffer mc = new StringBuffer(); + modifiers.forEach(d -> { + mc.append(d + " "); + }); + return mc.toString(); + } + + @Override + public boolean addParameter(String type, String name) { + return parameters.add(new Parameter(type, name)); + } + + @Override + public String combineParameters() { + + List pc = XType.list(); + parameters.forEach(d -> { + pc.add(d.toString()); + }); + + return String.join(",", pc); + } + + @Override + public String code() { + String tmp = XType.nvl(access, ACCESS_DEFAULT) + " " + combineModifiers() + XType.nvl(type, "") + " " + name + + "(" + combineParameters() + ")"; + if (Objects.nonNull(functionBody) && !functionBody.isEmpty()) { + tmp += codeBlockBegin() + functionBody + codeBlockEnd(); + }else { + tmp += ";"; + } + + return tmp; + } + + @Override + public String codeLine() { + return code() + "\n"; + } + +} diff --git a/src/com/xiuye/util/code/gen/GenCoder.java b/src/com/xiuye/util/code/gen/GenCoder.java new file mode 100644 index 0000000..301955a --- /dev/null +++ b/src/com/xiuye/util/code/gen/GenCoder.java @@ -0,0 +1,16 @@ +package com.xiuye.util.code.gen; + +public interface GenCoder { + + String code(); + + String codeLine(); + + default String codeBlockBegin() { + return "{"; + } + + default String codeBlockEnd() { + return "}"; + } +} diff --git a/src/com/xiuye/util/code/gen/GenFcuntion.java b/src/com/xiuye/util/code/gen/GenFcuntion.java new file mode 100644 index 0000000..2c6d1ce --- /dev/null +++ b/src/com/xiuye/util/code/gen/GenFcuntion.java @@ -0,0 +1,5 @@ +package com.xiuye.util.code.gen; + +public interface GenFcuntion { + String combineFunctions(); +} diff --git a/src/com/xiuye/util/code/gen/GenField.java b/src/com/xiuye/util/code/gen/GenField.java new file mode 100644 index 0000000..1498cb0 --- /dev/null +++ b/src/com/xiuye/util/code/gen/GenField.java @@ -0,0 +1,5 @@ +package com.xiuye.util.code.gen; + +public interface GenField { + String combineFields(); +} diff --git a/src/com/xiuye/util/code/gen/GenImportPackages.java b/src/com/xiuye/util/code/gen/GenImportPackages.java new file mode 100644 index 0000000..a20bfea --- /dev/null +++ b/src/com/xiuye/util/code/gen/GenImportPackages.java @@ -0,0 +1,11 @@ +package com.xiuye.util.code.gen; + +public interface GenImportPackages { + + String combinePackages(); + + boolean addImportPackage(String packageName); + + boolean importPackage(String... packageName); + +} diff --git a/src/com/xiuye/util/code/gen/GenModifier.java b/src/com/xiuye/util/code/gen/GenModifier.java new file mode 100644 index 0000000..e0251df --- /dev/null +++ b/src/com/xiuye/util/code/gen/GenModifier.java @@ -0,0 +1,7 @@ +package com.xiuye.util.code.gen; + +public interface GenModifier { + boolean addModifier(String modifier); + + String combineModifiers(); +} diff --git a/src/com/xiuye/util/code/gen/GenParameter.java b/src/com/xiuye/util/code/gen/GenParameter.java new file mode 100644 index 0000000..f6f057e --- /dev/null +++ b/src/com/xiuye/util/code/gen/GenParameter.java @@ -0,0 +1,9 @@ +package com.xiuye.util.code.gen; + +public interface GenParameter { + + String combineParameters(); + + boolean addParameter(String type, String name); + +} diff --git a/src/com/xiuye/util/graph/AcyclicSP.java b/src/com/xiuye/util/graph/AcyclicSP.java new file mode 100644 index 0000000..7e7a76d --- /dev/null +++ b/src/com/xiuye/util/graph/AcyclicSP.java @@ -0,0 +1,34 @@ +package com.xiuye.util.graph; + +public class AcyclicSP { + + private DirectedEdge[] edgeTo; + private double []distTo; + + public AcyclicSP(EdgeWeightedDigraph g,int s) { + edgeTo = new DirectedEdge[g.V()]; + distTo = new double[g.V()]; + for(int v=0;vdistTo[v]+e.getWeight()) { + distTo[w] = distTo[v] + e.getWeight(); + edgeTo[w] = e; + + } + } + } + +} diff --git a/src/com/xiuye/util/graph/Bag.java b/src/com/xiuye/util/graph/Bag.java new file mode 100644 index 0000000..9549d64 --- /dev/null +++ b/src/com/xiuye/util/graph/Bag.java @@ -0,0 +1,45 @@ +package com.xiuye.util.graph; + +import java.util.Iterator; + +public class Bag implements Iterable{ + + private Node first; + private class Node{ + T item; + Node next; + } + + public void add(T t) { + Node oldFirst = first; + first = new Node(); + first.item = t; + first.next = oldFirst; + } + + public Iterator iterator(){ + return new ListIterator(); + } + + private class ListIterator implements Iterator{ + + private Node current = first; + + + @Override + public boolean hasNext() { + return current != null; + } + + @Override + public T next() { + T t = current.item; + current = current.next; + return t; + } + + } + + + +} diff --git a/src/com/xiuye/util/graph/BellmanFordSP.java b/src/com/xiuye/util/graph/BellmanFordSP.java new file mode 100644 index 0000000..45b90c9 --- /dev/null +++ b/src/com/xiuye/util/graph/BellmanFordSP.java @@ -0,0 +1,60 @@ +package com.xiuye.util.graph; + +import javax.swing.plaf.IconUIResource; +import java.util.LinkedList; +import java.util.Queue; + +public class BellmanFordSP { + private double distTo[]; + private DirectedEdge[] edgeTo; + private boolean []onQ; + private Queue queue; + + private int cost; + private Iterable cycle; + + public BellmanFordSP(EdgeWeightedDigraph g,int s){ + distTo = new double[g.V()]; + edgeTo = new DirectedEdge[g.V()]; + onQ = new boolean[g.V()]; + queue = new LinkedList<>(); + for(int v=0;v distTo[v]+e.getWeight()){ + distTo[w] = distTo[v] + e.getWeight(); + edgeTo[w] = e; + if(!onQ[w]){ + queue.add(w); + onQ[w] = true; + } + } + if(cost++%g.V() == 0){ + findNegativeCycle(); + } + } + } + + private void findNegativeCycle() { + } + + private boolean hashNegativeCycle() { + return false; + } + +} diff --git a/src/com/xiuye/util/graph/DijkstraAllPairsSP.java b/src/com/xiuye/util/graph/DijkstraAllPairsSP.java new file mode 100644 index 0000000..295b2ed --- /dev/null +++ b/src/com/xiuye/util/graph/DijkstraAllPairsSP.java @@ -0,0 +1,23 @@ +package com.xiuye.util.graph; + + + +public class DijkstraAllPairsSP { + + private DijkstraSP[] all; + public DijkstraAllPairsSP(EdgeWeightedDigraph g) { + all = new DijkstraSP[g.V()]; + for(int v=0;v path(int s,int t){ + return all[s].pathTo(t); + } + double dist(int s,int t) { + return all[s].distTo(t); + } + + +} diff --git a/src/com/xiuye/util/graph/DijkstraSP.java b/src/com/xiuye/util/graph/DijkstraSP.java new file mode 100644 index 0000000..a457337 --- /dev/null +++ b/src/com/xiuye/util/graph/DijkstraSP.java @@ -0,0 +1,61 @@ +package com.xiuye.util.graph; + +import java.util.Stack; + +public class DijkstraSP { + + private DirectedEdge[] edgeTo; + private double []distTo; + private IndexMinPQ pq; + public DijkstraSP(EdgeWeightedDigraph g,int s) { + edgeTo = new DirectedEdge[g.V()]; + distTo = new double[g.V()]; + pq = new IndexMinPQ<>(g.V()); + + //initialize distTo + for(int i=0;idistTo[v]+e.getWeight()) { + distTo[w] = distTo[v] + e.getWeight(); + edgeTo[w] = e; + if(pq.contains(w)) { + pq.change(w, distTo[w]); + } + else { + pq.insert(w, distTo[w]); + } + } + } + } + public Iterable pathTo(int t) { + if(!hasPathTo(t))return null; + Stack path = new Stack(); + for(DirectedEdge e=edgeTo[t];e!=null;e=edgeTo[e.from()]) { + path.push(e); + } + return path; + } + + public boolean hasPathTo(int v) { + return distTo[v] < Double.POSITIVE_INFINITY; + } + + public double distTo(int t) { + return distTo[t]; + } + +} diff --git a/src/com/xiuye/util/graph/DirectedEdge.java b/src/com/xiuye/util/graph/DirectedEdge.java new file mode 100644 index 0000000..9007375 --- /dev/null +++ b/src/com/xiuye/util/graph/DirectedEdge.java @@ -0,0 +1,32 @@ +package com.xiuye.util.graph; + +public class DirectedEdge { + + private final int v; + private final int w; + private final double weight; + + public DirectedEdge(int v, int w, int weight) { + this.v = v; + this.w = w; + this.weight = weight; + + } + + public double getWeight() { + return weight; + } + + public int from() { + return v; + } + + public int to() { + return w; + } + + @Override + public String toString() { + return String.format("%d->%d %.2f", v,w,weight); + } +} diff --git a/src/com/xiuye/util/graph/Edge.java b/src/com/xiuye/util/graph/Edge.java new file mode 100644 index 0000000..d7b738b --- /dev/null +++ b/src/com/xiuye/util/graph/Edge.java @@ -0,0 +1,46 @@ +package com.xiuye.util.graph; + + +public class Edge implements Comparable { + + private final int v; + private final int w; + private final double weight; + + public Edge(int v,int w,int weight) { + this.v = v; + this.w = w; + this.weight = weight; + + } + + public double getWeight() { + return weight; + } + + public int either() { + return v; + } + + public int other(int vertex) { + if(vertex == v) { + return w; + } + else if(vertex == w) { + return v; + } + else throw new RuntimeException("Inconsostent edge"); + } + + + + @Override + public int compareTo(Edge that) { + + if(this.weight < that.weight)return -1; + else if(this.weight > that.weight)return +1; + else return 0; + + } + +} diff --git a/src/com/xiuye/util/graph/EdgeWeightedDigraph.java b/src/com/xiuye/util/graph/EdgeWeightedDigraph.java new file mode 100644 index 0000000..1a525e1 --- /dev/null +++ b/src/com/xiuye/util/graph/EdgeWeightedDigraph.java @@ -0,0 +1,49 @@ +package com.xiuye.util.graph; + +public class EdgeWeightedDigraph { + + private final int V; + private int E; + private Bag []adj; + + public EdgeWeightedDigraph(int V) { + this.V = V; + this.E = 0; + adj = new Bag[V]; + + for(int v=0;v < V;v++) { + adj[v] = new Bag<>(); + } + + } + + public int V() { + return V; + } + + public int E() { + return E; + } + + + public void addEdge(DirectedEdge e) { + adj[e.from()].add(e); + E++; + } + + public Iterable edges(){ + Bag b = new Bag<>(); + for(int v=0;v adj(int v) { + return adj[v]; + } + +} + diff --git a/src/com/xiuye/util/graph/EdgeWeightedGraph.java b/src/com/xiuye/util/graph/EdgeWeightedGraph.java new file mode 100644 index 0000000..ca8eb1d --- /dev/null +++ b/src/com/xiuye/util/graph/EdgeWeightedGraph.java @@ -0,0 +1,53 @@ +package com.xiuye.util.graph; + +public class EdgeWeightedGraph { + + private final int V; + private int E; + private Bag []adj; + + public EdgeWeightedGraph(int V) { + this.V = V; + this.E = 0; + adj = new Bag[V]; + + for(int v=0;v < V;v++) { + adj[v] = new Bag<>(); + } + + } + + public int V() { + return V; + } + + public int E() { + return E; + } + + + public void addEdge(Edge e) { + int v = e.either(); + int w = e.other(v); + adj[v].add(e); + adj[w].add(e); + E++; + } + + public Iterable edges(){ + Bag b = new Bag<>(); + for(int v=0;v v)// v-w: w>v,then add ????? what's up? + b.add(e); + } + } + return b; + } + + public Bag adj(int v) { + return adj[v]; + } + +} + diff --git a/src/com/xiuye/util/graph/GCD.java b/src/com/xiuye/util/graph/GCD.java new file mode 100644 index 0000000..b2c8140 --- /dev/null +++ b/src/com/xiuye/util/graph/GCD.java @@ -0,0 +1,71 @@ +package com.xiuye.util.graph; + +import java.math.BigInteger; + +import com.xiuye.sharp.X; + +public class GCD { + + public static int gcd(int a,int b) { + + if(a { + + public IndexMinPQ(int v) { + } + + public void insert(int i, double d) { + // TODO Auto-generated method stub + + } + + public boolean isEmpty() { + // TODO Auto-generated method stub + return false; + } + + public int delMin() { + // TODO Auto-generated method stub + return 0; + } + + public boolean contains(int w) { + // TODO Auto-generated method stub + return false; + } + + public void change(int w, double d) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/com/xiuye/util/graph/KruskalMST.java b/src/com/xiuye/util/graph/KruskalMST.java new file mode 100644 index 0000000..8d671ea --- /dev/null +++ b/src/com/xiuye/util/graph/KruskalMST.java @@ -0,0 +1,41 @@ +package com.xiuye.util.graph; + +import java.util.LinkedList; +import java.util.Queue; + +public class KruskalMST { + + private Queue mst; + + public KruskalMST(EdgeWeightedGraph g) { + + mst = new LinkedList(); + + MinPQ pq = new MinPQ<>(); + for(Edge e:g.edges()) + pq.insert(e); + + UF uf = new UF(g.V()); + + while(!pq.isEmpty()&&mst.size() edges(){ + return mst; + } + +} diff --git a/src/com/xiuye/util/graph/LazyPrimMST.java b/src/com/xiuye/util/graph/LazyPrimMST.java new file mode 100644 index 0000000..a1b63e1 --- /dev/null +++ b/src/com/xiuye/util/graph/LazyPrimMST.java @@ -0,0 +1,47 @@ +package com.xiuye.util.graph; + +import java.util.LinkedList; +import java.util.Queue; + + +public class LazyPrimMST { + + + private boolean []marked; + private Queue mst; + private MinPQ pq; + + public LazyPrimMST(EdgeWeightedGraph g) { + pq = new MinPQ(); + marked = new boolean[g.V()]; + mst = new LinkedList<>(); + visit(g,0); + while(!pq.isEmpty()) { + Edge e = pq.delMin(); + int v = e.either(); + int w = e.other(v); + if(marked[v]&&marked[w]) { + continue; + } + mst.add(e); + if(!marked[v]) + visit(g,v); + if(!marked[w]) + visit(g,v); + } + + } + + private void visit(EdgeWeightedGraph g, int v) { + marked[v] = true; + for(Edge e:g.adj(v)) { + if(!marked[e.other(v)]) { + pq.insert(e); + } + } + } + + public Iterable edges(){ + return mst; + } +} diff --git a/src/com/xiuye/util/graph/MinPQ.java b/src/com/xiuye/util/graph/MinPQ.java new file mode 100644 index 0000000..db87d5f --- /dev/null +++ b/src/com/xiuye/util/graph/MinPQ.java @@ -0,0 +1,19 @@ +package com.xiuye.util.graph; + +public class MinPQ { + + public boolean isEmpty() { + // TODO Auto-generated method stub + return false; + } + + public Edge delMin() { + // TODO Auto-generated method stub + return null; + } + + public void insert(Edge e) { + + } + +} diff --git a/src/com/xiuye/util/graph/PrimMST.java b/src/com/xiuye/util/graph/PrimMST.java new file mode 100644 index 0000000..f4fc64d --- /dev/null +++ b/src/com/xiuye/util/graph/PrimMST.java @@ -0,0 +1,53 @@ +package com.xiuye.util.graph; + +public class PrimMST { + private Edge[] edgeTo; + private double []distTo; + private boolean []marked; + private IndexMinPQ pq; + + + + public PrimMST(EdgeWeightedGraph g) { + edgeTo = new Edge[g.V()]; + distTo = new double[g.V()]; + marked = new boolean[g.V()]; + for(int v=0;v(g.V()); + + distTo[0]= 0.0; + pq.insert(0,0.0); + while(!pq.isEmpty()) { + visit(g,pq.delMin()); + } + + + } + + + + private void visit(EdgeWeightedGraph g, int v) { + + marked[v] = true; + for(Edge e:g.adj(v)) { + int w = e.other(v); + if(marked[w] ) continue; + if(e.getWeight() order() { + return null; + } + +} diff --git a/src/com/xiuye/util/graph/UF.java b/src/com/xiuye/util/graph/UF.java new file mode 100644 index 0000000..f698296 --- /dev/null +++ b/src/com/xiuye/util/graph/UF.java @@ -0,0 +1,18 @@ +package com.xiuye.util.graph; + +public class UF { + + public UF(int v) { + } + + public boolean connected(int v, int w) { + // TODO Auto-generated method stub + return false; + } + + public void union(int v, int w) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/com/xiuye/util/json/JsonUtil.java b/src/com/xiuye/util/json/JsonUtil.java new file mode 100644 index 0000000..827c494 --- /dev/null +++ b/src/com/xiuye/util/json/JsonUtil.java @@ -0,0 +1,32 @@ +package com.xiuye.util.json; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class JsonUtil { + + public static final int FORMAT_GSON = 1; + public static final int GENERAL_GSON = 2; + + private static Gson formatterGson; + private static Gson generalGson; + + static { + formatterGson = new GsonBuilder().setPrettyPrinting().create(); + generalGson = new Gson(); + } + + public static Gson instance() { + return generalGson; + } + + public static Gson instance(int type) { + + if (FORMAT_GSON == type) { + return formatterGson; + } + return generalGson; + + } + +} diff --git a/src/com/xiuye/util/log/LogUtil.java b/src/com/xiuye/util/log/LogUtil.java deleted file mode 100644 index 4a76046..0000000 --- a/src/com/xiuye/util/log/LogUtil.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.xiuye.util.log; - -public class LogUtil { - - public static void log(T... t) { - - for (T s : t) { - System.out.print(s + " "); - } - System.out.println(); - } - - - -} diff --git a/src/com/xiuye/util/log/XLog.java b/src/com/xiuye/util/log/XLog.java new file mode 100644 index 0000000..9a8e912 --- /dev/null +++ b/src/com/xiuye/util/log/XLog.java @@ -0,0 +1,537 @@ +package com.xiuye.util.log; + +import com.xiuye.util.cls.XMeta; +import com.xiuye.util.cls.XMeta.Caller; + +import java.io.PrintStream; +import java.util.Objects; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * System.out extension + * + * @author xiuye + */ +public class XLog { + + private static int level = 4; + + public static int setLineLevel(int lvl) { + int old = level; + level = lvl; + return old; + } + + public static int getLineLevel() { + return level; + } + + + private static final Lock mutex = new ReentrantLock(); + + public static int attach(int delta) { + mutex.lock(); + int old = level; + level += delta; + return old; + } + + public static int dettach(int delta) { + int old = level; + level -= delta; + mutex.unlock(); + return old; + } + + @SafeVarargs + public static void ln(T... t) { +// int old = level; +// level = old + 1; + attach(1); + line(t); + dettach(1); +// level = old; + + } + + @SafeVarargs + public static void line(T... t) { + Caller caller = XMeta.caller(level); + String fileline = "\t[ line:" + caller.getLineNumber() + " | " + caller.getClassName() + " | " + + caller.getFileName() + " ]"; + Object[] os = new Object[t.length + 1]; + for (int i = 0; i < t.length; i++) { + os[i] = t[i]; + } + os[t.length] = fileline; + log(os); + } + + /** + * output many params + * + * @param + * @param t any many params for output + */ + @SafeVarargs + public static void println(T... t) { + log(t); + } + + /** + * output many params + * + * @param + * @param t + * @see log + */ + @SafeVarargs + public static void lg(T... t) { + log(t); + } + + /** + * output level 1 array! + * + * @param + * @param arr + */ + public static void logArray(T[] arr) { + + for (T t : arr) { + print(t); + } + println(); + } + + /** + * output level 1 array with separator + * + * @param + * @param arr + * @param separator + */ + public static void logArray(T[] arr, String separator) { + + if (Objects.nonNull(arr)) { + if (arr.length == 0) { + print(); + } else { + for (int i = 0; i < arr.length - 1; i++) { + print(arr[i] + separator); + } + print(arr[arr.length - 1]); + } + + } + println(); + } + + /** + * output level 1 array with separator + * + * @param arr + * @param separator + */ + public static void logArray(double[] arr, String separator) { + + if (Objects.nonNull(arr)) { + if (arr.length == 0) { + print(); + } else { + for (int i = 0; i < arr.length - 1; i++) { + print(arr[i] + separator); + } + print(arr[arr.length - 1]); + } + + } + println(); + } + + /** + * output level 1 array with separator + * + * @param arr + */ + public static void logArray(double[] arr) { + + for (double t : arr) { + print(t); + } + println(); + } + + /** + * output level 1 array with separator + * + * @param arr + * @param separator + */ + public static void logArray(int[] arr, String separator) { + + if (Objects.nonNull(arr)) { + if (arr.length == 0) { + print(); + } else { + for (int i = 0; i < arr.length - 1; i++) { + print(arr[i] + separator); + } + print(arr[arr.length - 1]); + } + + } + println(); + } + + /** + * output level 1 array + * + * @param arr + */ + public static void logArray(int[] arr) { + + for (int t : arr) { + print(t); + } + println(); + } + + /** + * output level 1 array with separator + * + * @param arr + * @param separator + */ + public static void logArray(long[] arr, String separator) { + + if (Objects.nonNull(arr)) { + if (arr.length == 0) { + print(); + } else { + for (int i = 0; i < arr.length - 1; i++) { + print(arr[i] + separator); + } + print(arr[arr.length - 1]); + } + + } + println(); + } + + /** + * output level 1 array + * + * @param arr + */ + public static void logArray(long[] arr) { + + for (long t : arr) { + print(t); + } + println(); + } + + /** + * output level 1 array with separator + * + * @param arr + * @param separator + */ + public static void logArray(short[] arr, String separator) { + + if (Objects.nonNull(arr)) { + if (arr.length == 0) { + print(); + } else { + for (int i = 0; i < arr.length - 1; i++) { + print(arr[i] + separator); + } + print(arr[arr.length - 1]); + } + + } + println(); + } + + /** + * output level 1 array + * + * @param arr + */ + public static void logArray(short[] arr) { + + for (short t : arr) { + print(t); + } + println(); + } + + /** + * output level 1 array + * + * @param arr + * @param separator + */ + public static void logArray(char[] arr, String separator) { + + if (Objects.nonNull(arr)) { + if (arr.length == 0) { + print(); + } else { + for (int i = 0; i < arr.length - 1; i++) { + print(arr[i] + separator); + } + print(arr[arr.length - 1]); + } + + } + println(); + } + + /** + * output level 1 array + * + * @param arr + */ + public static void logArray(char[] arr) { + + for (char t : arr) { + print(t); + } + println(); + } + + /** + * output level 1 array with separator + * + * @param arr + * @param separator + */ + public static void logArray(byte[] arr, String separator) { + + if (Objects.nonNull(arr)) { + if (arr.length == 0) { + print(); + } else { + for (int i = 0; i < arr.length - 1; i++) { + print(arr[i] + separator); + } + print(arr[arr.length - 1]); + } + + } + println(); + } + + /** + * output level 1 array + * + * @param arr + */ + public static void logArray(byte[] arr) { + + for (byte t : arr) { + print(t); + } + println(); + } + + /** + * output level 1 array with separator + * + * @param arr + * @param separator + */ + public static void logArray(boolean[] arr, String separator) { + + if (Objects.nonNull(arr)) { + if (arr.length == 0) { + print(); + } else { + for (int i = 0; i < arr.length - 1; i++) { + print(arr[i] + separator); + } + print(arr[arr.length - 1]); + } + + } + println(); + } + + /** + * output level 1 array + * + * @param arr + */ + public static void logArray(boolean[] arr) { + + for (boolean t : arr) { + print(t); + } + println(); + } + + /** + * output level 1 array with separator + * + * @param arr + * @param separator + */ + public static void logArray(float[] arr, String separator) { + + if (Objects.nonNull(arr)) { + if (arr.length == 0) { + print(); + } else { + for (int i = 0; i < arr.length - 1; i++) { + print(arr[i] + separator); + } + print(arr[arr.length - 1]); + } + + } + println(); + } + + /** + * output level 1 array + * + * @param arr + */ + public static void logArray(float[] arr) { + + for (float t : arr) { + print(t); + } + println(); + } + + private static boolean OUTPUT = true; + + /** + * set output true/false + * + * @param output + * @return old output value + */ + public static boolean setOutput(boolean output) { + boolean oldOutput = OUTPUT; + OUTPUT = output; + return oldOutput; + } + + /** + * get output value + * + * @return true/false + */ + public static boolean isOutput() { + return OUTPUT; + } + + /** + * set output stream + * + * @param out + * @return + */ + public static PrintStream setOut(PrintStream out) { + PrintStream oldOut = System.out; + System.setOut(out); + return oldOut; + } + + /** + * set err output stream! + * + * @param err + * @return + */ + public static PrintStream setErr(PrintStream err) { + PrintStream oldErr = System.err; + System.setErr(err); + return oldErr; + } + + /** + * get output stream + * + * @return + */ + public static PrintStream getOut() { + return System.out; + } + + /** + * get err output stream + * + * @return + */ + public static PrintStream getErr() { + return System.err; + } + + /** + * output many params + * + * @param + * @param t + */ + @SafeVarargs + public static void log(T... t) { + if (!OUTPUT) + return; + if (t.length == 0) + System.out.println(); + else { + for (int i = 0; i < t.length - 1; i++) { + System.out.print(t[i] + " "); + } + System.out.println(t[t.length - 1]); + } + + } + + /** + * output many params + * + * @param + * @param t + */ + @SafeVarargs + public static void err(T... t) { + if (!OUTPUT) + return; + if (t.length == 0) + System.err.println(); + else { + for (int i = 0; i < t.length - 1; i++) { + System.err.print(t[i] + " "); + } + System.err.println(t[t.length - 1]); + } + + } + + /** + * output many params + * + * @param + * @param ts + */ + @SafeVarargs + public static void print(T... ts) { + if (!OUTPUT) + return; + if (ts.length > 0) { + for (int i = 0; i < ts.length - 1; i++) { + System.out.print(ts[i] + " "); + } + System.out.print(ts[ts.length - 1]); + } + + } + +} diff --git a/src/com/xiuye/util/math/XMath.java b/src/com/xiuye/util/math/XMath.java new file mode 100644 index 0000000..5c9679b --- /dev/null +++ b/src/com/xiuye/util/math/XMath.java @@ -0,0 +1,230 @@ +package com.xiuye.util.math; + +/** + * math operator + * + * @author xiuye + */ +public interface XMath { + + public static final double E = 2.7182818284590452354; + public static final double PI = 3.14159265358979323846; + + /** + * Euclidean algorithm for gcd + * + * @param a + * @param b + * @return + */ + public static int gcd(int a, int b) { + if (b == 0) + return a; + int r = a % b; + return gcd(b, r); + } + + /** + * max value + * + * @param a + * @param b + * @return + */ + public static int max(int a, int b) { + return a >= b ? a : b; + } + + /** + * max value + * + * @param a + * @param b + * @return + */ + public static double max(double a, double b) { + return a >= b ? a : b; + } + + /** + * max value + * + * @param a + * @return + */ + public static int max(int[] a) { + if (a.length <= 0) + throw new RuntimeException("blank array"); + int max = a[0]; + for (int i = 1; i < a.length; i++) { +// if(a[i]>max)max=a[i]; + max = max(max, a[i]); + } + return max; + + } + + /** + * max value + * + * @param a + * @return + */ + public static double max(double[] a) { + if (a.length <= 0) + throw new RuntimeException("blank array"); + double max = a[0]; + for (int i = 1; i < a.length; i++) { +// if(a[i]>max)max=a[i]; + max = max(max, a[i]); + } + return max; + + } + + /** + * average value + * + * @param a + * @return + */ + public static double average(double[] a) { + double sum = 0.0; + + for (double i : a) { + sum += i; + } + return sum / a.length; + } + + /** + * average value + * + * @param a + * @return + */ + public static double average(int[] a) { + double sum = 0.0; + + for (double i : a) { + sum += i; + } + return sum / a.length; + } + + /** + * reverse array + * + * @param a + */ + public static void reverse(int[] a) { + for (int i = 0; i < a.length / 2; i++) { + int temp = a[i]; + a[i] = a[a.length - i - 1]; + a[a.length - i - 1] = temp; + } + } + + /** + * reverse array + * + * @param a + */ + public static void reverse(double[] a) { + for (int i = 0; i < a.length / 2; i++) { + double temp = a[i]; + a[i] = a[a.length - i - 1]; + a[a.length - i - 1] = temp; + } + } + + /** + * abs value + * + * @param x + * @return + */ + public static int abs(int x) { + if (x < 0) + return -x; + return x; + } + + /** + * abs value + * + * @param x + * @return + */ + public static double abs(double x) { + if (x < 0.0) + return -x; + return x; + } + + // mark! + + /** + * judge prime + * + * @param x + * @return + */ + public static boolean isPrime(int x) { + if (x < 2) + return false; + // i <= sqrt(x) <=> i*i <= x + for (int i = 2; i * i <= x; i++) { + if (x % i == 0) + return false; + } + return true; + } + + // sqrt 牛顿迭代法: d*d = n => f(Xn) = Xn*Xn-n;Xn+1 = Xn - f(Xn)/f`(Xn) + // 设f(Xn)=0,迭代求出Xn + + /** + * sqrt value + * + * @param x + * @return + */ + public static double sqrt(double x) { + if (x < 0.0) + return Double.NaN; + double err = 1e-15; + double t = x; +// while(abs(t*t-x)>err) { +// t = (t+x/t)/2.0; +// } + // Xn*Xn-n = 0 <=> Xn-n/Xn = 0 <=> Xn-n/Xn = 0*Xn + while (abs(t - x / t) > err * t) { + t = (t + x / t) / 2.0; + } + return t; + } + + /** + * TriangleHypotenuse + * + * @param a + * @param b + * @return + */ + public static double rightTriangleHypotenuse(double a, double b) { + return sqrt(a * a + b * b); + } + +// public static double sqrtQ(double x) { +// if(x == 0) return 0; +// double result = x; +// double xhalf = 0.5f*result; +// int i = *(int*)&result; +// i = 0x5f375a86- (i>>1); // what the fuck? +// result = *(double*)&i; +// result = result*(1.5f-xhalf*result*result); // Newton step, repeating increases accuracy +// result = result*(1.5f-xhalf*result*result); +// return 1.0f/result; +// } +} diff --git a/src/com/xiuye/util/proxy/XProxy.java b/src/com/xiuye/util/proxy/XProxy.java new file mode 100644 index 0000000..e89e115 --- /dev/null +++ b/src/com/xiuye/util/proxy/XProxy.java @@ -0,0 +1,7 @@ +package com.xiuye.util.proxy; + +public class XProxy { + +// proxy() + +} diff --git a/src/com/xiuye/util/security/RSA.java b/src/com/xiuye/util/security/RSA.java new file mode 100644 index 0000000..18c1879 --- /dev/null +++ b/src/com/xiuye/util/security/RSA.java @@ -0,0 +1,286 @@ +package com.xiuye.util.security; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Random; + +import com.xiuye.sharp.X; +import com.xiuye.util.cls.XType; + + + +/** + * 第一步,随机选择两个不相等的质数p和q。 + * 第二步,计算p和q的乘积n。 + * 第三步,计算n的欧拉函数φ(n)。 + * 第四步,随机选择一个整数e,条件是1< e < φ(n),且e与φ(n) 互质。 + * 第五步,计算e对于φ(n)的模反元素d。 + * + * @author Administrator + * + */ +public class RSA { + + private BigInteger p,q; + private BigInteger n; + private BigInteger Euler_n; + + private BigInteger pubKey; + private BigInteger priKey; + + private publicKey pubK; + private privateKey priK; + + { + + X.lnS("Primes number:",primes.size()); + + p = primes.get(rand.nextInt(primes.size()));//随机大素数p + X.lnS("p:",p); + q = primes.get(rand.nextInt(primes.size()));//随机大素数q + X.lnS("q:",q); + n = p.multiply(q);//n=p*q + X.lnS("n:",n); + BigInteger pt = p.subtract(BigInteger.ONE);//p-1 + X.lnS("p-1:",pt); + BigInteger qt = q.subtract(BigInteger.ONE);//q-1 + X.lnS("q-1:",qt); + Euler_n = pt.multiply(qt);// (p-1)*(q-1) //欧拉函数 + X.lgS("Euler function value:",Euler_n); + + +// 根据互质数的bai定义,可总结出一些规du律,利用这些规律能迅速判断一组数是否互质。 +// (1)两个不相同的质数一定是互质数。如:7和11、17和31是互质数。 +// (2)两个连续的自然数一定是互质数。如:4和5、13和14是互质数。 +// (3)相邻的两个奇数一定是互质数。如:5和7、75和77是互质数。 +// (4)1和其他所有的自然数一定是互质数。如:1和4、1和13是互质数。 +// (5)两个数中的较大一个是质数,这两个数一定是互质数。如:3和19、16和97是互质数。 +// (6)两个数中的较小一个是质数,而较大数是合数且不是较小数的倍数,这两个数一定是互质数。如:2和15、7和54是互质数。 +// (7)较大数比较小数的2倍多1或少1,这两个数一定是互质数。如:13和27、13和25是互质数。 + + //选择公钥 中的 e +//  ed ≡ 1 (mod φ(n)) + // 不要使用 Euler(x) -1 的 质数 ,否则得出 后面x,y结果是 -1 和 1 + //非常的不好! +// pubKey = Euler_n.subtract(BigInteger.ONE);//according to (2) + + //=65537 + pubKey = crtBigInt("65537"); + X.lnS("public key:",pubKey); + + //计算模反元素 d + //e => pubKey + //d => priKey + //d => x +//  ed ≡ 1 (mod φ(n)) +// <=> ed - 1 = kφ(n) +// <=> ex + φ(n)y = 1 + XY xy = new XY(); + extendEuclidGCD(pubKey,Euler_n, xy); + +// X.lnS(xy.x,xy.y); + + + priKey = xy.x; + + X.lnS("private key:",priKey); + + pubK = new publicKey(); + + priK = new privateKey(); + + pubK.N = n; + pubK.pubKey = pubKey; + + priK.N = n; + priK.priKey = priKey; + + } + + private class publicKey{ + private BigInteger pubKey; + private BigInteger N; + } + private class privateKey{ + private BigInteger priKey; + private BigInteger N; + } + + //for function output! + private class XY{ + private BigInteger x = BigInteger.ZERO; + private BigInteger y = BigInteger.ZERO; + } + +// 贝祖定理(一般形式) +// 对于不全为 0 的自然数 a,ba,b,则必然存在整数 x,yx,y (不唯一)满足等式 +// ax+by=gcd(a,b) + //if a和b 互质 ,then gcd(a,b) == 1 + //即 ax + by = 1; +// 若整数 a,ba,b 互质,则存在整数解 x,yx,y 满足 ax+by=1 + //扩展欧几里得算法 + private BigInteger extendEuclidGCD(BigInteger a,BigInteger b,XY xy) { + + //b == 0 + if(BigInteger.ZERO.equals(b)) { + xy.x = BigInteger.ONE;//x = 1 + xy.y = BigInteger.ZERO;//y = 0 + return a; + } +// X.lnS(a,b); + BigInteger r = extendEuclidGCD(b, a.mod(b), xy); + + //t = x + BigInteger t = xy.x; +// x = y + xy.x = xy.y; + //y = t - a/b*y; + xy.y = t.subtract(a.divide(b).multiply(xy.y)); + + X.lnS(a,b,xy.x,xy.y); + + return r; + } + + + private static BigInteger maxBigNum = crtBigInt("70000"); + + private static BigInteger startBigNum = crtBigInt("5000"); + + private static List primes; + private static Random rand; + + static { + + primes = XType.list(); + + BigInteger numMax = maxBigNum; + + for(BigInteger i = startBigNum;i.compareTo(numMax)<0;i=i.add(BigInteger.ONE)) { +// X.lnS(i,isPrime(i)); + if(isPrime(i)) { + primes.add(i); + } + } + rand = new Random(System.currentTimeMillis()); + + } + + + private static boolean isPrime(BigInteger i) { + BigInteger n = i.divide(BigInteger.valueOf(2)).add(BigInteger.ONE); +// X.lnS(i,n,BigInteger.ZERO.compareTo(n),i.mod(n)); + for(BigInteger j=BigInteger.valueOf(2);j.compareTo(n)<0;j=j.add(BigInteger.ONE)) { +// X.lnS(i,j); +// X.lnS(i.mod(j)); + if(BigInteger.ZERO.equals(i.mod(j))) { + return false; + } + } + return true; + } + + private static BigInteger crtBigInt(String val) { + return new BigInteger(val); + } + + private static BigInteger crtBigInt(byte[] val) { + return new BigInteger(val); + } + + public RSA() { + } + + private static BigInteger pow(BigInteger num,BigInteger n) { + BigInteger sum = BigInteger.ONE; + for(BigInteger i=BigInteger.ZERO;i.compareTo(n)<0;i=i.add(BigInteger.ONE)) { + sum = sum.multiply(num); + } + return sum; + } + + //encrypt by public key + public byte[] encryptByPubKey(byte []data) { + List ret = XType.list(); + //N 存储的 byte的大小确定存储单元的长度 + int byteMemNum = pubK.N.toByteArray().length; + //每一个数据都是 byteMemNum 个 byte 为单元存储的! + if(Objects.nonNull(data)) { + for(int i=0;i0) { + for(int j=0;j ret = XType.list(); + //N 存储的 byte的大小确定存储单元的长度 + int byteMemNum = priK.N.toByteArray().length; + if(Objects.nonNull(data)) { + //以存储的单元大小来处理数据 + for(int i=0;i data) { + byte[] ret = new byte[data.size()]; + for(int i=0;i{ +// X.lnS(d); +// }); + +// RSA rsa = new RSA(); +// byte [] data = rsa.encryptByPubKey("123456".getBytes()); +// X.lnS(new String(rsa.decryptByPriKey(data))); +// 65537 574744487 54 +// -136072447 574744487 1 +// 302847963 +// X.lnS(pow(crtBigInt("54"),crtBigInt("65537")).mod(crtBigInt("574744487"))); +// X.lnS(pow(crtBigInt("302847963"),crtBigInt("1121606477")).mod(crtBigInt("574744487"))); + } + +} diff --git a/src/com/xiuye/util/string/Insertion.java b/src/com/xiuye/util/string/Insertion.java new file mode 100644 index 0000000..2b46dbe --- /dev/null +++ b/src/com/xiuye/util/string/Insertion.java @@ -0,0 +1,6 @@ +package com.xiuye.util.string; + +public class Insertion { + public static void sort(String[] a, int lo, int hi, int d) { + } +} diff --git a/src/com/xiuye/util/string/LSD.java b/src/com/xiuye/util/string/LSD.java new file mode 100644 index 0000000..e1e16b2 --- /dev/null +++ b/src/com/xiuye/util/string/LSD.java @@ -0,0 +1,75 @@ +package com.xiuye.util.string; + +import com.xiuye.sharp.X; +import com.xiuye.util.log.XLog; + +import java.util.Arrays; + +public class LSD { + + public static void sort(String []a,int W){ + int N = a.length; + int R = 256; + String []aux = new String[N]; + for(int d=W-1;d>=0;d--){ + int []count = new int[R+1]; + for(int i=0;iv){ + exch(a,i,gt--); + } + else{ + i++; + } + } + sort(a,lo,lt-1,d); + if(v>=0){ + sort(a,lt,gt,d+1); + } + sort(a,gt+1,hi,d); + } + + private static void exch(String[] a, int i, int i1) { + } + +} diff --git a/src/com/xiuye/util/string/TrieST.java b/src/com/xiuye/util/string/TrieST.java new file mode 100644 index 0000000..335c271 --- /dev/null +++ b/src/com/xiuye/util/string/TrieST.java @@ -0,0 +1,177 @@ +package com.xiuye.util.string; + +import com.xiuye.util.cls.XType; +import com.xiuye.util.log.XLog; + +import java.util.LinkedList; +import java.util.Queue; + +public class TrieST { + private static int R = 256; + private Node root; + + private static class Node { + private Object val; + private Node[] next = new Node[R]; + } + + public V get(String key) { + Node x = get(root, key, 0); + if (x == null) return null; + return (V) x.val; + } + + //core + private Node get(Node x, String key, int d) { + //return back x as root + if (x == null) { + return null; + } + if (d == key.length()) { + return x; + } + char c = key.charAt(d); + return get(x.next[c], key, d + 1); + } + +// private char charAt(int d) { +// return 0; +// } + + public void put(String key, V val) { + root = put(root, key, val, 0); + } + + //core + private Node put(Node x, String key, V val, int i) { + if (x == null) {//no node,alloc node! + x = XType.newInstance(Node::new); + } + if (i == key.length()) { + x.val = val; + return x; + } + char c = key.charAt(i); + x.next[c] = put(x.next[c], key, val, i + 1); + return x; + } + + public int size() { + return size(root); + } + + private int size(Node x) { + if (x == null) { + return 0; + } + int cnt = 0; + if (x.val != null) { + cnt++; + } + for (char c = 0; c < R; c++) {//travel all letters! + cnt += size(x.next[c]); + } + return cnt; + + } + + + public Iterable keys() { + return keysWithPrefix(""); + } + + private Iterable keysWithPrefix(String pre) { + Queue q = XType.newInstance(LinkedList::new); + collect(get(root, pre, 0), pre, q); + return q; + } + + private void collect(Node x, String pre, Queue q) { + if (x == null) return; + if (x.val != null) { + q.add(pre); + } + + + for (char c = 0; c < R; c++) {//travel all characters! + //pre+c == key!!! + collect(x.next[c], pre + c, q); + } + + + } + + public Iterable keysThatMatch(String pat) { + Queue q = XType.newInstance(LinkedList::new); + collect(root, "", pat, q); + return q; + } + + private void collect(Node x, String pre, String pat, Queue q) { + int d = pre.length(); + if (x == null) { + return; + } + if (d == pat.length() && x.val != null) { + q.add(pre); + } + if (d == pat.length()) { + return; + } + + char next = pat.charAt(d); + for (char c = 0; c < R; c++) { + if (next == '.' || next == c) { + collect(x.next[c], pre + c, pat, q); + } + } + } + + public String longestPreffixOf(String s) { + int length = search(root,s,0,0); + return s.substring(0,length); + } + + private int search(Node x, String s, int d, int length) { + if(x == null)return length; + if(x.val != null)length=d; + if(d == s.length())return length; + char c = s.charAt(d); + return search(x.next[c],s,d+1,length); + } + + public void delete(String key){ + root = delete(root,key,0); + } + + private Node delete(Node x, String key, int d) { + if(x == null)return null; + if(d == key.length()){ + x.val = null; + } + else{ + char c = key.charAt(d); + x.next[c] = delete(x.next[c],key,d+1); + } + if(x.val != null) + { + return x; + } + for(char c=0;c root = new TreeNode<>();// 树的根节点 + root.setValue("A"); + root.setStatus("open"); + List> nodes = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + TreeNode node = new TreeNode<>(); + node.setValue("B" + i); + node.setStatus("close"); + List> l = new ArrayList<>(); + for (int j = 0; j < 3; j++) { + TreeNode nodej = new TreeNode<>(); + nodej.setValue("C" + j); + nodej.setStatus("close"); + l.add(nodej); + } + node.setNodes(l); + nodes.add(node); + } + root.setNodes(nodes); + XLog.log(root); + XLog.log(gson.toJson(root)); + + XLog.log("遍历(应该是先序):"); + XTime xtime = new XTime(); + xtime.start(); + travel(root); + xtime.outByMS(); + + // 查询节点 + XLog.log(); + XLog.log("仅仅查出含有msg的节点,如果有上层节点就包含上层节点,但不包含其节点的子节点:"); + TreeNode out = new TreeNode<>(); + getSearchNode("9", root, out); + xtime.outByMS(); + XLog.log(gson.toJson(out)); + + // 查询节点 2 + XLog.log(); + XLog.log("保留下一级所有子节点,但子节点不open:"); + out = new TreeNode<>(); + getSearchNodeIncludeChildren("9", root, out); + xtime.outByMS(); + XLog.log(gson.toJson(out)); + } + + // 遍历 + public static void travel(TreeNode root) { + + XLog.print(root.getValue()); + List> nodes = root.getNodes(); + if (nodes != null) + for (int i = 0; i < nodes.size(); i++) { + travel(nodes.get(i)); + } + + } + + // 仅仅查出含有msg的节点,如果有上层节点就包含上层节点,但不包含其节点的子节点 + public static void getSearchNode(String msg, TreeNode root, TreeNode out) { + + if (Objects.isNull(msg)) { + throw new NullPointerException("Searching msg is not blank!"); + } + + boolean isSetFatherNodeValue = false; + // 节点包含 msg中的信息,就赋值 + String v = root.getValue(); + if (!v.isEmpty() && v.toLowerCase().indexOf(msg.toLowerCase()) > -1) { +// LogUtil.log("Campared"); + out.setValue(v); + out.setStatus(root.getStatus()); + isSetFatherNodeValue = true; + } + + // 遍历子节点 + List> nodes = root.getNodes(); + if (nodes != null && nodes.size() > 0) { + List> ns = new ArrayList<>(); + for (int i = 0; i < nodes.size(); i++) { + TreeNode node = new TreeNode<>(); + getSearchNode(msg, nodes.get(i), node); + // 只有当node有值时候,加入数组 + if (!Objects.isNull(node.getValue()) && !node.getValue().isEmpty()) { + ns.add(node);// 子节点有了,父节点即使开始没有(没有赋值成功),那现在也有了 + if (!isSetFatherNodeValue) { + out.setValue(root.getValue()); + out.setStatus(root.getStatus()); + } + + } + + } + // 如果ns中有节点再加入到根节点上 + if (ns.size() > 0) { + out.setNodes(ns); + } + } + + } + + // 保留下一级所有子节点,但子节点不open + public static void getSearchNodeIncludeChildren(String msg, TreeNode root, TreeNode out) { + + if (Objects.isNull(msg)) { + throw new NullPointerException("Searching msg is not blank!"); + } + + boolean isSetFatherNodeValue = false; + // 节点包含 msg中的信息,就赋值 + String v = root.getValue(); + if (!v.isEmpty() && v.toLowerCase().indexOf(msg.toLowerCase()) > -1) { +// LogUtil.log("Campared"); + out.setValue(v); + out.setStatus("open"); + isSetFatherNodeValue = true; + } + + // 遍历子节点 + List> nodes = root.getNodes(); + if (nodes != null && nodes.size() > 0) { + List> ns = new ArrayList<>(); + + for (int i = 0; i < nodes.size(); i++) { + TreeNode node = new TreeNode<>(); + getSearchNodeIncludeChildren(msg, nodes.get(i), node); + // 只有当node有值时候,加入数组 + if (!Objects.isNull(node.getValue()) && !node.getValue().isEmpty()) { + ns.add(node);// 子节点有了,父节点即使开始没有(没有赋值成功),那现在也有了 + if (!isSetFatherNodeValue) { + out.setValue(root.getValue()); + out.setStatus("open"); + } + + // 判断nodes[i]是否有根节点,并且判断node节点是否没有子节点 + // nodes[i]与node的节点是同一等级的节点,既然node没有子节点了, + // 而nodes[i]有子节点,说明,node此时已经是out的叶节点,所以,node + // 加上nodes[i]的子节点,使其子节点都不展开,这样就是查询出包含有子节点的节点, + // 而与其他查询出的root的叶子节点(没有子节点),共同构成了,查询出的结果. + // 总结:子节点有时,父节点必须有,而子节点的子节点可以有但不展开 + if ((node.getNodes() == null || node.getNodes().isEmpty())/* 说明是叶节点 */ + && !Objects.isNull(nodes.get(i).getNodes()) + && !nodes.get(i).getNodes().isEmpty()/* 说明同级的nodes[i]有子节点 */ + ) { + copyNodeAndSetClose(nodes.get(i), node); + } + + } + + } + if (ns.size() > 0) { + out.setNodes(ns); + } + } + + } + + // 只需要一级关闭就行了,但是是深度复制啊 + private static void copyNodeAndSetClose(TreeNode source, TreeNode target) { + List> children = source.getNodes(); + List> targetChildren = new ArrayList<>(); + for (TreeNode child : children) { + TreeNode node = new TreeNode<>(); + node.setValue(child.getValue()); + node.setStatus("close"); + targetChildren.add(node); + if (!Objects.isNull(child.getNodes()) && !child.getNodes().isEmpty()) { + copyNodeAndSetClose(child, node); + } + } + target.setNodes(targetChildren); + } +} diff --git a/src/com/xiuye/util/tree/TreeNode.java b/src/com/xiuye/util/tree/TreeNode.java new file mode 100644 index 0000000..1c05403 --- /dev/null +++ b/src/com/xiuye/util/tree/TreeNode.java @@ -0,0 +1,41 @@ +package com.xiuye.util.tree; + +import java.util.List; + +public class TreeNode { + + private T value; + private T status; + + public T getStatus() { + return status; + } + + public void setStatus(T status) { + this.status = status; + } + + private List> nodes; + + public T getValue() { + return value; + } + + public void setValue(T value) { + this.value = value; + } + + public List> getNodes() { + return nodes; + } + + public void setNodes(List> nodes) { + this.nodes = nodes; + } + + @Override + public String toString() { + return "TreeNode [value=" + value + ", status=" + status + ", nodes=" + nodes + "]"; + } + +} diff --git a/src/module-info.java b/src/module-info.java deleted file mode 100644 index 7a3c3f5..0000000 --- a/src/module-info.java +++ /dev/null @@ -1,13 +0,0 @@ -/** - * - */ -/** - * @author Administrator - * - */ -module Util { - exports com.xiuye.util.time/* to Java10*/; - exports com.xiuye.util.log; - requires junit; - opens com.xiuye.util.test.time to junit; -} \ No newline at end of file diff --git a/test/com/github/abel533/echarts/Generator.java b/test/com/github/abel533/echarts/Generator.java new file mode 100644 index 0000000..4ac23fc --- /dev/null +++ b/test/com/github/abel533/echarts/Generator.java @@ -0,0 +1,84 @@ +package com.github.abel533.echarts; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author liuzh_3nofxnp + * @since 2016-02-28 09:58 + */ +public class Generator { + public static void main(String[] args) { + String _lines = "private TextStyle textStyle;"; + String _type = "DataZoom"; +// simple(_type, _lines); + simpleNew(_type, _lines); + } + + /** + * 最简单的形式 + * + * @param _type + * @param _lines + */ + public static void simple(String _type, String _lines) { + String _this = "\treturn this;"; + if (_type.equals("T")) { + _this = "\treturn (T) this;"; + } + String[] lines = lines(_lines); + for (String line : lines) { + String[] ls = line.split(" "); + System.out.println("public " + ls[1] + " " + ls[2] + "(){"); + System.out.println("\treturn this." + ls[2] + ";"); + System.out.println("}\n"); + System.out.println("public " + _type + " " + ls[2] + "(" + ls[1] + " " + ls[2] + "){"); + System.out.println("\tthis." + ls[2] + " = " + ls[2] + ";"); + System.out.println(_this); + System.out.println("}\n"); + } + } + + /** + * 最简单的形式 + * + * @param _type + * @param _lines + */ + public static void simpleNew(String _type, String _lines) { + String _this = "\treturn this;"; + if (_type.equals("T")) { + _this = "\treturn (T) this;"; + } + String[] lines = lines(_lines); + for (String line : lines) { + String[] ls = line.split(" "); + System.out.println("public " + ls[1] + " " + ls[2] + "(){"); + System.out.println("\tif(this." + ls[2] + " == null){"); + System.out.println("\t\tthis." + ls[2] + "= new " + ls[1] + "();"); + System.out.println("\t}"); + System.out.println("\treturn this." + ls[2] + ";"); + System.out.println("}\n"); + System.out.println("public " + _type + " " + ls[2] + "(" + ls[1] + " " + ls[2] + "){"); + System.out.println("\tthis." + ls[2] + " = " + ls[2] + ";"); + System.out.println(_this); + System.out.println("}\n"); + } + } + + public static String[] lines(String _lines) { + List lineList = new ArrayList(); + String[] lines = _lines.split("\n"); + for (String line : lines) { + line = line.trim(); + if (line.length() == 0) { + continue; + } + if (line.endsWith(";")) { + line = line.substring(0, line.length() - 1); + } + lineList.add(line); + } + return lineList.toArray(new String[]{}); + } +} diff --git a/test/com/github/abel533/echarts/TestConfig.java b/test/com/github/abel533/echarts/TestConfig.java new file mode 100644 index 0000000..0932d36 --- /dev/null +++ b/test/com/github/abel533/echarts/TestConfig.java @@ -0,0 +1,40 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2015 abel533@gmail.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.github.abel533.echarts; + +/** + * @author liuzh + */ +public interface TestConfig { + /** + * 测试文件生成的目录 + */ + String EXPORT_PATH = "/tmp/echarts/"; + + /** + * 通过view控制所有测试是否打开浏览器 + */ + Boolean VIEW = true; +} diff --git a/test/com/github/abel533/echarts/util/ChainUtil.java b/test/com/github/abel533/echarts/util/ChainUtil.java new file mode 100644 index 0000000..27abd51 --- /dev/null +++ b/test/com/github/abel533/echarts/util/ChainUtil.java @@ -0,0 +1,146 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2015 abel533@gmail.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.github.abel533.echarts.util; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +/** + * 自动生成链式调用方法 - 仅针对本项目之前的代码 + * + * @author liuzh + */ +public class ChainUtil { + public static void main(String[] args) { + //输出全部类 +// String srcPath = getSrcPath(); +// File srcFoler = new File(srcPath); +// List all = allFiles(srcFoler); +// for (File file : all) { +// chainFile(file); +// } + chainFile(new File("G:\\Git\\OpenSource\\ECharts\\src\\main\\java\\com\\github\\abel533\\echarts\\RoamController.java")); + } + + public static void chainFile(File file) { + BufferedReader reader = null; + StringBuffer sb = new StringBuffer(); + try { + reader = new BufferedReader(new FileReader(file)); + String line = null; + String className = file.getName(); + className = className.substring(0, className.lastIndexOf(".")); + while ((line = reader.readLine()) != null) { + String tempLline = line.trim(); + if (tempLline.startsWith("public") && tempLline.endsWith(";")) { + //去分号 + tempLline = tempLline.substring(0, tempLline.length() - 1); + String[] strs = tempLline.split(" "); + if (strs.length != 3) { + sb.append(line).append("\n"); + continue; + } + //链式 + sb.append("\tprivate " + strs[1] + " " + strs[2] + ";\n\n"); + sb.append("\tpublic " + strs[1] + " " + strs[2] + "(){\n"); + sb.append("\t\treturn this." + strs[2] + ";\n\t}\n\n"); + sb.append("\tpublic " + className + " " + strs[2] + "(" + strs[1] + " " + strs[2] + "){\n"); + sb.append("\t\tthis." + strs[2] + " = " + strs[2] + ";\n"); + sb.append("\t\treturn this;\n\t}\n"); + } else { + sb.append(line).append("\n"); + } + } + //System.out.println(sb.toString()); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + BufferedWriter writer = null; + try { + writer = new BufferedWriter(new FileWriter(file)); + writer.write(sb.toString()); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + public static List allFiles(File file) { + List result = new ArrayList(); + if (file.isFile()) { + result.add(file); + } else if (file.isDirectory()) { + File[] files = file.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + if (dir.isDirectory()) { + return true; + } else if (name.toUpperCase().endsWith(".JAVA")) { + return true; + } + return false; + } + }); + for (File f : files) { + result.addAll(allFiles(f)); + } + } + return result; + } + + public static String getSrcPath() { + String basePath = getBasePath(); + return basePath + "src/main/java"; + } + + public static String getBasePath() { + String path = ChainUtil.class.getResource("/").getPath(); + if (path.startsWith("/")) { + path = path.substring(1); + } + if (path.indexOf("target1") > 0) { + path = path.substring(0, path.indexOf("target")); + } else if (path.indexOf("ECharts") > 0) { + path = path.substring(0, path.indexOf("ECharts")) + "Echarts/"; + } + return path; + } +} diff --git a/test/com/github/abel533/echarts/util/CommentsUtil.java b/test/com/github/abel533/echarts/util/CommentsUtil.java new file mode 100644 index 0000000..7f3bf44 --- /dev/null +++ b/test/com/github/abel533/echarts/util/CommentsUtil.java @@ -0,0 +1,170 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2015 abel533@gmail.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.github.abel533.echarts.util; + +import java.io.*; + +/** + * 自动生成链式调用方法 - 仅针对本项目之前的代码 + * + * @author liuzh + */ +public class CommentsUtil { + public static final String[] EMPTY = new String[0]; + + public static void main(String[] args) { + //输出全部类 +// String srcPath = ChainUtil.getSrcPath(); +// File srcFoler = new File(srcPath); +// List files = ChainUtil.allFiles(srcFoler); +// for (File file : files) { +// commentsFile(file); +// } + commentsFile(new File("E:\\Git\\OpenSource\\ECharts\\src\\main\\java\\com\\github\\abel533\\echarts\\series\\EventRiver.java")); + commentsFile(new File("E:\\Git\\OpenSource\\ECharts\\src\\main\\java\\com\\github\\abel533\\echarts\\series\\event\\Detail.java")); + commentsFile(new File("E:\\Git\\OpenSource\\ECharts\\src\\main\\java\\com\\github\\abel533\\echarts\\series\\event\\Event.java")); + commentsFile(new File("E:\\Git\\OpenSource\\ECharts\\src\\main\\java\\com\\github\\abel533\\echarts\\series\\event\\Evolution.java")); + } + + public static void commentsFile(File file) { + BufferedReader reader = null; + StringBuffer sb = new StringBuffer(); + try { + reader = new BufferedReader(new FileReader(file)); + String line = null; + String className = file.getName(); + className = className.substring(0, className.lastIndexOf(".")); + String prevLine = null; + while ((line = reader.readLine()) != null) { + String tempLline = line; + if (tempLline.contains("private") || tempLline.contains("public") || tempLline.contains("protected")) { + if (prevLine == null || !prevLine.contains("*")) { + if (tempLline.contains("(") && tempLline.contains(")")) { + //分解参数 + tempLline = tempLline.trim(); + String[] ps = getParameter(tempLline); + if (ps == EMPTY) { + if (isConstructor(tempLline)) { + sb.append("\t/**\n\t * 构造函数 \n"); + } else { + sb.append("\t/**\n\t * 获取" + getMethodFieldName(tempLline) + "值 \n"); + } + } else { + String v = ""; + for (String p : ps) { + if (!v.equals("")) { + v += ","; + } + v += p; + } + if (isConstructor(tempLline)) { + sb.append("\t/**\n\t * 构造函数,参数:" + v + " \n\t * \n"); + } else { + sb.append("\t/**\n\t * 设置" + v + "值 \n\t * \n"); + } + for (String s : ps) { + + sb.append("\t * @param " + s + "\n"); + } + } + sb.append("\t */\n"); + tempLline = "\t" + tempLline; + } + } + } + sb.append(tempLline + "\n"); + prevLine = tempLline; + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + BufferedWriter writer = null; + try { + writer = new BufferedWriter(new FileWriter(file)); + writer.write(sb.toString()); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + public static boolean isConstructor(String line){ + line = line.substring(0,line.indexOf("(")).trim(); + if (line.split(" ").length == 2) { + return true; + } + return false; + } + + public static String getMethodFieldName(String line) { + int end = line.lastIndexOf("("); + int start = line.lastIndexOf(" ", end); + String name = line.substring(start + 1, end); + if (name.startsWith("get")) { + name = name.substring(3); + name = name.substring(0, 1).toLowerCase() + name.substring(1); + } + return name; + } + + public static String[] getParameter(String line) { + if (line.contains("(") && line.contains(")")) { + //分解参数 + String all = line.substring(line.indexOf("(") + 1, line.lastIndexOf(")")); + if (all.equals("")) { + return EMPTY; + } + while (all.contains("<")) { + int start = all.indexOf("<"); + int end = all.indexOf(">", start); + all = all.substring(0, start) + all.substring(end + 1); + } + String[] alls = all.split(","); + String[] parameters = new String[alls.length]; + System.out.println("All:" + all); + for (int i = 0; i < alls.length; i++) { + System.out.println("\t" + alls[i]); + parameters[i] = alls[i].trim().split(" ")[1].trim(); + } + return parameters; + } + return EMPTY; + } +} diff --git a/test/com/xiuye/test/TestClass.java b/test/com/xiuye/test/TestClass.java new file mode 100644 index 0000000..3c6cfd2 --- /dev/null +++ b/test/com/xiuye/test/TestClass.java @@ -0,0 +1,7 @@ +package com.xiuye.test; + +public abstract class TestClass { + + public abstract void testClass(); + +} diff --git a/test/com/xiuye/test/TestCompiler.java b/test/com/xiuye/test/TestCompiler.java new file mode 100644 index 0000000..0e07258 --- /dev/null +++ b/test/com/xiuye/test/TestCompiler.java @@ -0,0 +1,118 @@ +package com.xiuye.test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.util.Map; + +import org.junit.Test; + +import com.xiuye.util.cls.XClassLoader; +import com.xiuye.util.cls.XType; +import com.xiuye.util.code.XCompiler; +import com.xiuye.util.code.gen.ClassInfo; +import com.xiuye.util.log.XLog; + +public class TestCompiler { + + @Test + public void testGenerateClass() throws MalformedURLException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { + ClassInfo dc = new ClassInfo("com.xy.app", "ABC"); + dc.addImportPackage("com.xiuye.test.TestCompiler"); + dc.addConstructor("System.out.println(\"Hello World!Constructor!\");" + + "System.out.println(a);" + + "System.out.println(b);" + + "","int","a","int","b"); + dc.addField("int", "lang"); + dc.addField("int", "lang2", "100"); + dc.addMethod("int", "f1", "return a>b?a:b;", "int", "a", "int", "b"); +// dc.addMethod("int", "f2", null, "int", "a", "int", "b"); + dc.addMethod("int", "f3", "TestCompiler test = new TestCompiler();" + + "try{" + + "test.testGenerateClass();" + + "}catch(Exception e1){" + + "e1.printStackTrace();" + + "}" + + "return 100;", "int", "a", "int", "b"); + XLog.ln(dc); + XLog.ln(XType.firstUpperCase("abcdefg")); + XLog.ln(XType.firstLowerCase("ABCDEFG")); + + XLog.ln(dc.getFullName()); + + Map code = XType.map(); + code.put(dc.getFullName(),dc.toString()); + XCompiler.compileCode(code); + XClassLoader cl = XType.createClassLoader(); + + Class clazz = cl.load(dc.getFullName()); + XLog.ln(clazz); + Method m = clazz.getMethod("getLang2"); + Constructor con = clazz.getConstructor(int.class,int.class); + Object obj = con.newInstance(7,88); + int a = (int) m.invoke(obj); + XLog.ln(a); + Method f1 = clazz.getMethod("f1", int.class,int.class); + XLog.ln(f1.invoke(obj, 5,8)); + + //下面的调用会无限的循环,无限的套娃!!! + //好好看看 f3 和 外部类的 调用关系!!! +// Method f3 = clazz.getMethod("f3", int.class,int.class); +// XLog.ln(f3.invoke(obj, 98,88)); + + + + + } + + @Test + public void testProxy() throws MalformedURLException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException, SecurityException { + + ClassInfo dc = new ClassInfo("com.xy.app", "Tdd"); +// dc.addImportPackage("com.xiuye.test.TestClass"); + dc.importPackage("com.xiuye.util.log.XLog", + "com.xiuye.test.TestInterface", + "com.xiuye.test.TestClass"); + dc.ext("TestClass"); + dc.impl("TestInterface"); + dc.addConstructor("System.out.println(\"Hello World!Constructor!\");" + + "System.out.println(a);" + + "System.out.println(b);" + + "","int","a","int","b"); + dc.addField("int", "lang"); + dc.addField("int", "lang2", "100"); + dc.addMethod("int", "f1", "return a>b?a:b;", "int", "a", "int", "b"); + dc.addMethod("void", "testClass", "XLog.ln(\"testClass\");"); + dc.addMethod("void", "testInterface", "XLog.ln(\"testInterface\");"); + + XLog.ln(dc); + + + Map code = XType.map(); + code.put(dc.getFullName(),dc.toString()); + XCompiler.compileCode(code); + XClassLoader cl = XType.createClassLoader(); + + + + Class clazz1 = cl.load(dc.getFullName()); + Constructor con1 = clazz1.getConstructor(int.class,int.class); + TestClass obj1 = con1.newInstance(7,88); + obj1.testClass(); + + Class clazz2 = cl.load(dc.getFullName()); + Constructor con2 = clazz2.getConstructor(int.class,int.class); + TestInterface obj2 = con2.newInstance(99,108); + obj2.testInterface(); + + XLog.ln(clazz1.getClassLoader()); + XLog.ln(clazz2.getClassLoader()); + XLog.ln(cl); + } + + public static void main(String[] args) { + + } + +} diff --git a/test/com/xiuye/test/TestDirectefWeightGraph.java b/test/com/xiuye/test/TestDirectefWeightGraph.java new file mode 100644 index 0000000..5717830 --- /dev/null +++ b/test/com/xiuye/test/TestDirectefWeightGraph.java @@ -0,0 +1,81 @@ +package com.xiuye.test; + +import java.util.Iterator; +import java.util.List; +import java.util.Stack; + +import com.xiuye.test.TestDirectefWeightGraph.DirectefWeightGraph; + +public class TestDirectefWeightGraph { + + public class DirectefWeightGraph { + List [] adj; + } + + //distTo[v] == s->v 的路径权重之和 + //edgeTo[v] == s->v 的到数第一条边,也就是最后一条边 + private double []distTo;//s->v 的距离 ,distTo[s]=0! + private DirectedWeightEdge []edgeTo;//s->v 的边,最短路径 + + class DirectedWeightEdge{ + int v; + int w; + double weight; + int from() { + return v; + } + int to() { + return w; + } + } + //边的松弛函数 + //distTo[0(s)] = 0;distTo[(!s)1..] = infinite + private void relax(DirectedWeightEdge e) { + int v = e.from(); + int w = e.to(); + //s->v v->w 的中的 权重比较 + //这是一个递推公式 : key,crucial!!! + if(distTo[w] > distTo[v]+e.weight) { + distTo[w] = distTo[v] +e.weight; + edgeTo[w] = e; + } + } + + //顶点的松弛: + //遍历顶点 + 边的松弛 + private void relax(DirectefWeightGraph g,int v/*start vertex*/) { + for(DirectedWeightEdge e:g.adj[v]) { + //v->w : weight ,smallest + int w = e.to(); + if(distTo[w] > distTo[v]+e.weight) { + distTo[w] = distTo[v] + e.weight; + edgeTo[w] = e; + } + } + } + + public double distTo(int v) { + return distTo[v]; + } + + //s -> v + public boolean hasPathTo(int v) { + return distTo[v] < Double.POSITIVE_INFINITY; + } + //s->v + //all routes + public Stack pathTo(int v) { + if(!hasPathTo(v))return null; + Stack path = new Stack<>(); + for(DirectedWeightEdge e = edgeTo[v];e!= null;e=edgeTo[e.from()]) { + path.push(e); + } + return path; + } + + public static void main(String[] args) { + + + } + +} diff --git a/test/com/xiuye/test/TestInterface.java b/test/com/xiuye/test/TestInterface.java new file mode 100644 index 0000000..b4202b3 --- /dev/null +++ b/test/com/xiuye/test/TestInterface.java @@ -0,0 +1,7 @@ +package com.xiuye.test; + +public interface TestInterface { + + void testInterface(); + +} diff --git a/test/com/xiuye/test/TestX.java b/test/com/xiuye/test/TestX.java new file mode 100644 index 0000000..2a11f6b --- /dev/null +++ b/test/com/xiuye/test/TestX.java @@ -0,0 +1,98 @@ +package com.xiuye.test; + +import org.junit.Test; + +import com.xiuye.sharp.X; +import com.xiuye.util.log.XLog; + +public class TestX { + + + @Test + public void testBasicFunctions() { + X.of(123).THEN(d->{ + XLog.ln(d); + }).FINALLY(d->{ + XLog.ln(d); + }).EX(d->{ + XLog.ln(d); + }).THEN(d->{ + XLog.ln("skip exception hander"); + }).E().THEN(d->{ + XLog.ln(d); + }).T().THEN(d->{ + XLog.lg(d); + }).T(d->{ + XLog.ln(d); + }); + } + + @Test + public void testX1BasicFunctions() { + X.beginS().IF(false).THEN(()->{ + XLog.lg("if"); + }).ELSE(()->{ + XLog.lg("else"); + })/*.ELIF(false)*/.end(); + X.beginS().MATCH("ABC").AS(1).AS(2).THEN(()->{ + XLog.ln("MATCH OK!"); + }).end().ln(); + + X.beginS().MATCH(123).AS("ABC").THEN(d->{ + XLog.ln(d); + }).DEFAUT(d->{ + XLog.ln("default",d); + }).end().ln(); + + X.beginS().MATCH(888).AS(888).THEN(d->{ + XLog.ln(d); + return "ABC"; + }).end().ln().THEN(d->{ + XLog.ln(d); + }); + X.beginS().MATCH(99).DEFAUT(d->{ + XLog.ln(d); + return "JKL"; + }).end().ln(); + } + @Test + public void testXTask() { + X.taskS(()->{ + for(int i=0;i<100;i++) { + XLog.ln(i); + } + }).THEN(t->{ + XLog.ln(t.get()); + }).task(d->{ + XLog.lg(d); + }).THEN(d->{ + XLog.ln(d); + }); + } + + @Test + public void testOutput() { + X.lgS(123,5677).lg().ln(); + X.lineS().ln(); + X.lnS("A","C",123).line(); + } + + @Test + public void testBean() { + X.beanS(String.class).getBean().end().ln(); + X.beanS(String.class,"ABC").register().getBean().end().ln(); + X.beanS(String.class,"C++",true).register().getBean().end().ln(); + X.beanS(String.class).getBean().end().ln(); + X.beanS("KEY",String.class,"ABC",true).register().getBean().end().ln(); + X x = X.beanS(String.class,"ABC","BBB",true).register().getBean().end().ln() + .bean().register().getBean().end().ln(); + ; + X.lnS(x.get()); + X.beanS("X").getBean().end().ln(); + } + + public static void main(String[] args) { + + } + +} diff --git a/test/com/xiuye/test/cls/ClassLoaderTest.java b/test/com/xiuye/test/cls/ClassLoaderTest.java new file mode 100644 index 0000000..58e5b73 --- /dev/null +++ b/test/com/xiuye/test/cls/ClassLoaderTest.java @@ -0,0 +1,21 @@ +package com.xiuye.test.cls; + +import java.net.MalformedURLException; + +import org.junit.Test; + +public class ClassLoaderTest { + + @Test + public void testLoadClass() + throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException { +// ClassLoader cl = XType.createClassLoader(".","E:\\code\\Utils"); +// Class cls = cl.loadClass("A"); +// XLog.log(cls); +// XLog.log(cls.newInstance()); +// cls = cl.loadClass("demo.Demo1"); +// XLog.log(cls); +// XLog.log(cls.newInstance()); + } + +} diff --git a/test/com/xiuye/test/cls/CompilerTest.java b/test/com/xiuye/test/cls/CompilerTest.java new file mode 100644 index 0000000..a546279 --- /dev/null +++ b/test/com/xiuye/test/cls/CompilerTest.java @@ -0,0 +1,38 @@ +package com.xiuye.test.cls; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Map; + +import org.junit.Test; + +import com.xiuye.util.cls.XType; +import com.xiuye.util.code.XCompiler; +import com.xiuye.util.log.XLog; + +public class CompilerTest { + + @Test + public void testCompileFile() { +// List files = Arrays.asList("C:\\Users\\admin\\Desktop\\java\\Demo1.java"); +// XLog.err(XYCompiler.compileFile(files)); +// XLog.err(XYCompiler.compileFile("C:\\Users\\admin\\Desktop\\java\\Demo1.java")); + } + + @Test + public void testComileCode() + throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { + Map codes = XType.map(); + codes.put("com.xiuye.A", "package com.xiuye;" + "import com.xiuye.util.log.XLog;" + "public class A{" + + "public A(){" + "XLog.log(\"OK,A created!\");" + "}" + "}"); + XLog.log(XCompiler.compileCode(codes)); + XLog.log(XCompiler.compileCode(Arrays.asList("-d",".","-verbose"),codes)); +// LogUtil.log(Paths.get(".").toRealPath()); + // 使用类加载器加载 + ClassLoader cl = XType.createClassLoader(); + Class cls = cl.loadClass("com.xiuye.A"); + XLog.log(cls); + XLog.log(cls.newInstance()); + } + +} diff --git a/test/com/xiuye/test/cls/XMetaTest.java b/test/com/xiuye/test/cls/XMetaTest.java new file mode 100644 index 0000000..882c2ed --- /dev/null +++ b/test/com/xiuye/test/cls/XMetaTest.java @@ -0,0 +1,19 @@ +package com.xiuye.test.cls; + +import org.junit.Test; + +import com.xiuye.util.cls.XMeta; +import com.xiuye.util.log.XLog; + +public class XMetaTest { + + @Test + public void testCaller() { + XLog.ln(XMeta.caller()); + XLog.ln(XMeta.caller().getTrace().length); + for(StackTraceElement trace : XMeta.caller().getTrace()) { + XLog.ln(trace); + } + } + +} diff --git a/test/com/xiuye/util/test/cls/TestMain.java b/test/com/xiuye/util/test/cls/TestMain.java new file mode 100644 index 0000000..0a7c093 --- /dev/null +++ b/test/com/xiuye/util/test/cls/TestMain.java @@ -0,0 +1,22 @@ +package com.xiuye.util.test.cls; + +public class TestMain { + + + + public static void main(String[] args) { + new A().new B().g(); + } + +} + +class A{ + public void f() { + System.out.println("A::f"); + } + class B{ + public void g() { + f(); + } + } +} \ No newline at end of file diff --git a/test/com/xiuye/util/test/cls/TypeUtilTest.java b/test/com/xiuye/util/test/cls/TypeUtilTest.java new file mode 100644 index 0000000..cb80ec4 --- /dev/null +++ b/test/com/xiuye/util/test/cls/TypeUtilTest.java @@ -0,0 +1,193 @@ +package com.xiuye.util.test.cls; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Test; + +import com.xiuye.util.cls.XType; +import com.xiuye.util.log.XLog; + +public class TypeUtilTest { + + private static class C { + static { + XLog.log("static"); + } + + private C() { + XLog.log("C::construct"); + } + } + + @Test + public void testNew() { + XType.newInstance(C::new); + XType.newInstance(C::new); + } + + public static void main(String[] args) { + XType.newInstance(A::new); + XType.newInstance(A::new, "ABC"); + XType.newInstance(A::new, 1); + XType.newInstance(A::new, 1, 1, 2, 3, 4, 5, 6); + // Now , T[] <=> T...t +// TypeUtil.newInstance(A::new, new Integer[]{1,2}); + XType.newInstance(A::new, new int[] { 1, 2 }); + XType.newInstance(A::new, new Integer[] { 1, 2 }, new Integer[] { 1, 2 }); + XType.newInstance(A::new, 1, "abc", 1L); + XType.newInstance(A::new, "GGGGGG", "abc"); + Object o = "ABC"; + String s = XType.cast(o); + s = XType.cast("JJJJJJJJJJJJJJJJJJJ"); + XLog.log(s); +// LogUtil.log(TypeUtil.dynamic_cast(o));//error + o = XType.cast(s); + XLog.log(o); + XLog.log(XType.cast(o)); + XLog.log("ABC", 1, 2, 3, 4, 5, 6, "GGGG", 7L); + XType.newInstance(B::new, 1, "abc", 1L); + XLog.log(XType.map()); + XLog.log(XType.list()); + XLog.log(XType.set()); + Map m = XType.map(); + m.put("A", "A"); + List l = XType.list(); + l.add("123"); + l.add("123"); + Set se = XType.set(); + se.add("OK"); + se.add("OK"); + XLog.log(m, l, se); + } + + static class B { + B(Integer i, String s, Long l) { + XLog.log("A(int i,String s,Long l)"); + } + } + + static class A { + A() { + XLog.log("A()"); + } + + A(int i) { + XLog.log("A(int i)"); + } + + A(String s) { + XLog.log("A(String s)"); + } + + A(String s1, String s2) { + XLog.log("A(String s1,String s2)"); + } + +// A(Integer []s){ +// LogUtil.log("A(Integer []s)"); +// } + A(Integer... s) { + XLog.log("A(Integer ...s)"); + } + + A(String... s) { + XLog.log("A(String ... s)"); + } + +// A(int...i){ +// LogUtil.log("A(int ... i)"); +// } + A(int[] i) { + XLog.log("A(int ... i)"); + } + + A(int i, String s, Long l) { + XLog.log("A(int i,String s,Long l)"); + } + +// A(T...t){ +// LogUtil.log("A(T...t)"); +// } + A(Object... t) { + XLog.log("A(T...t)"); + } + } + + @Test + public void testNewArray() { + // new 一维数组 + int[] i = XType.newInstance(int[]::new, 10); + XLog.log(i.length); + XLog.logArray(i); + // new 一维数组 + String[] ss = XType.newInstance(String[]::new, 10); + XLog.log(ss.length); + XLog.logArray(ss, ":"); + // new 二维数组 => new String[10][]; + // new String[][](10/*第一个参数*/) + String[][] s1 = XType.newInstance(String[][]::new, 10); + // new 一维数组 => new String[8] + s1[0] = XType.newInstance(String[]::new, 8); + XLog.log(s1); + XLog.logArray(s1); + XLog.print(s1); + XLog.println(); + XLog.println(); + // <=> the above + String[][] s2 = new String[10][]; + XLog.log(s2); + XLog.logArray(s2, ","); +// String[]s =new String[0]; + XLog.print(1, 2, 3); + XLog.print(1); + XLog.print(2); + XLog.print(3); + } + + @Test + public void testInstantiate() { + class A { + A(String... a) { + XLog.logArray(a, " "); + } + } +// XType.newInstance(A::new, +// "123","987","998" +// ,"123","987","998" +// ,"123","987","998" +// ,"123","987","998" +// ,"123","987","998" +// ); + } + + public static R cast(T t) { + return (R) t; + } + + @Test + public void testCast() { + int i = 100; + long j = i; + XLog.log(j); +// int k = cast(j);//error +// XLog.log(i); + } + +// public static R newi() { +// return XType.newInstance(R::new); +// } + @Test + public void newCases() { + + } + + @Test + public void testSyncCollections() { + XLog.lg(XType.sync(XType.set())); + XLog.lg(XType.sync(XType.list())); + XLog.lg(XType.sync(XType.map())); + } + +} diff --git a/test/com/xiuye/util/test/code/ABC.java b/test/com/xiuye/util/test/code/ABC.java new file mode 100644 index 0000000..a71b5b9 --- /dev/null +++ b/test/com/xiuye/util/test/code/ABC.java @@ -0,0 +1,8 @@ +package com.xiuye.util.test.code; + +public interface ABC { + + void f(int i); + void g(); + +} diff --git a/test/com/xiuye/util/test/code/EncryptJavaCode.java b/test/com/xiuye/util/test/code/EncryptJavaCode.java new file mode 100644 index 0000000..a89a8d1 --- /dev/null +++ b/test/com/xiuye/util/test/code/EncryptJavaCode.java @@ -0,0 +1,31 @@ +package com.xiuye.util.test.code; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import com.xiuye.util.code.XCode; +import com.xiuye.util.log.XLog; + +/** + * covert java source code to unicode code + * + * @author xiuye + * + */ +public class EncryptJavaCode { + + public static void main(String args[]) throws IOException { +// Scanner in = new Scanner(System.in); +// XLog.log("请输入已存在的文件名:"); +// String fileName = in.nextLine(); +// XCode.java2Unicode(fileName,".."); +// +// in.close(); + + XLog.lg(Files.isDirectory(Paths.get("out"))); + + XCode.unicode2Java("EncryptJava2Unicode.java", "out"); + } + +} diff --git a/test/com/xiuye/util/test/code/PromiseTest.java b/test/com/xiuye/util/test/code/PromiseTest.java new file mode 100644 index 0000000..5b43a8f --- /dev/null +++ b/test/com/xiuye/util/test/code/PromiseTest.java @@ -0,0 +1,748 @@ +//package com.xiuye.util.test.code; +// +//import java.io.IOException; +//import java.util.Map; +//import java.util.concurrent.CountDownLatch; +//import java.util.concurrent.ExecutionException; +//import java.util.concurrent.TimeoutException; +// +//import org.apache.zookeeper.CreateMode; +//import org.apache.zookeeper.KeeperException; +//import org.apache.zookeeper.ZooKeeper; +//import org.apache.zookeeper.Watcher.Event.EventType; +//import org.apache.zookeeper.Watcher.Event.KeeperState; +//import org.apache.zookeeper.ZooDefs; +//import org.apache.zookeeper.data.Stat; +//import org.junit.Test; +// +//import com.xiuye.sharp.Promise; +//import com.xiuye.util.code.XCode; +//import com.xiuye.util.log.XLog; +// +//public class PromiseTest { +// +//// @Test +//// public void test() { +//// // default true +////// Promise.implyErrorHandler(false); +//// new Promise<>(99999).THEN(d -> { +//// XLog.lg(d); +//// XLog.lg("void call(I in)"); +//// +//// }).THEN(d -> { +//// XLog.lg(d); +//// XLog.lg("R call(I in)"); +//// +//// return 999; +//// }).THEN(() -> { +//// XLog.lg("R call()"); +//// return "ABC"; +//// }).THEN(() -> { +//// XLog.lg("void call()"); +//// }).THEN(() -> { +//// XLog.lg("End"); +//// }).THEN(() -> { +//// throw new RuntimeException("My Exception intentional"); +//// }).EXCEPT(e -> { +//// XLog.lg(e); +//// return e; +//// }).EXCEPT(e -> { +//// XLog.lg(e); +//// }).EXCEPT(e -> { +//// XLog.lg(e); +//// }).EXCEPT(() -> { +//// throw new RuntimeException("Nothing"); +//// })./* then(()->{}). */EXCEPT(e -> { +//// XLog.lg(e); +//// return 100; +//// }).EXCEPT(d -> { +//// XLog.log(d); +//// }).EXCEPT(() -> { +//// +////<<<<<<< HEAD +//// }).EXCEPT(() -> { +//// +//// }); +//// } +//// +//// @Test +//// public void testIfElse() { +//// +//// +//// Promise.resolve().begin().ef(false).then(() -> { +//// XLog.lg("123"); +//// }).eeseEf(true).then(() -> { +//// XLog.lg("then"); +//// }).eeseEf(true).then(() -> { +//// XLog.lg("then2"); +//// }).eese(() -> { +//// XLog.lg("ABC"); +//// }).ef(true).then(() -> { +//// XLog.lg("2 then"); +//// }).eese(() -> { +//// XLog.lg("EESE"); +//// }).end().then(d -> { +//// +//// XLog.lg(d); +//// }); +//// +//// XLog.lg(trueflag() | falseflag()); +//// XLog.lg(trueflag() || falseflag()); +//// +//// } +//// +//// private boolean trueflag() { +//// XLog.lg("trueflag run"); +//// return true; +//// } +//// +//// private boolean falseflag() { +//// XLog.lg("falseflag run"); +//// return false; +//// } +//// +//// @Test +//// public void testMatchAs() { +//// Promise.OF().BEGIN().MATCH(123).AS(99).THEN(()->{ +//// XLog.lg("matched 1"); +//// }).AS(100).AS(123).THEN(()->{ +//// XLog.lg("matched 2"); +//// }).DEFAUT(()->{ +//// XLog.lg("default"); +//// }).END(); +//// +//// Promise.OF().BEGIN().MATCH(11).AS(56789).AS(11).THEN(()->{ +//// XLog.lg("56789"); +//// }).DEFAUT(()->{ +//// XLog.lg("default"); +//// }).THEN(()->{}).END().THEN(()->{ +//// Promise.of().begin().match(123).as(99).then(() -> { +//// XLog.lg("matched 1"); +//// }).as(100).as(123).then(() -> { +//// XLog.lg("matched 2"); +//// }).defaut(() -> { +//// XLog.lg("default"); +//// }).end(); +//// +//// Promise.of().begin().match(11).as(56789).as(11).then(() -> { +//// XLog.lg("56789"); +//// }).defaut(() -> { +//// XLog.lg("default"); +//// }).then(() -> { +//// }).end().then(() -> { +//// XLog.lg("then"); +//// }); +//// XLog.lg(null instanceof String); +//// String s = null; +//// XLog.lg(s instanceof String); +//// +//// } +//// +//// @Test +//// public void testAllSwitchStatement() { +//// +//// Promise.BEGINS().IF(false).THEN(()->{ +//// XLog.lg(false); +//// }).ELIF(true).THEN(()->{ +//// XLog.lg(127,true); +//// }).ELSE(()->{ +//// XLog.lg("else"); +//// }).IF(true).THEN(()->{ +//// XLog.lg(131,true); +//// }).ELSE(()->{ +//// XLog.lg("eese"); +//// }).MATCH(5).AS(7).THEN(()->{ +//// XLog.lg(7); +//// }) +//// .AS(5).THEN(()->{ +//// XLog.lg(137,5); +//// }) +//// .DEFAUT(()->{ +//// XLog.lg(999); +//// }) +//// .IF(true).THEN(()->{ +//// XLog.lg(139,true); +//// }) +//// .END(); +//// +//// Promise.BEGINS().MATCH(123).AS(123).AS(99).THEN(()->{ +//// XLog.lg(149,123); +//// }).END(); +//// +//// Promise.BEGINS().MATCH(99) +//// .AS(123).THEN(()->{ +//// XLog.lg(153,123); +//// }) +//// .AS(99).AS(100).THEN(()->{ +//// XLog.lg(157,123); +//// }) +//// .IF(true).THEN(()->{XLog.lg(159,true);}) +//// .IF(true).THEN(()->{XLog.lg(160,true);}) +//// .MATCH(true).DEFAUT(()->{XLog.lg(161,true);}) +//// .MATCH("ABC").AS("ABC").THEN(()->{ +//// XLog.lg("ABC"); +//// }) +//// .MATCH(1).AS(1).AS(2) +//// .THEN(()->{ +//// XLog.lg(1); +//// }) +//// .IF(false) +//// .THEN(()->{ +//// XLog.lg(false); +//// }) +//// .ELIF(true) +//// .THEN(()->{ +//// XLog.lg(true); +//// }) +//// .IF(false) +//// .THEN(()->{ +//// XLog.lg(false); +//// }) +//// .ELSE(()->{ +//// XLog.lg("else"); +//// }) +//// .IF(false) +//// .THEN(()->{ +//// XLog.lg("doing"); +//// }) +////// .ef(false) +//// .MATCH(11) +//// .AS(88) +//// .AS(11) +//// .THEN(()->{ +//// XLog.lg(193); +//// }) +//// .AS(11) +//// .THEN(()->{ +//// XLog.lg(197); +//// }) +//// .DEFAUT(()->{ +//// XLog.lg("default"); +//// }) +//// .IF(true) +//// .THEN(()->{ +//// XLog.line(true); +//// }) +//// .IF(true) +//// .THEN(()->{ +//// XLog.ln(true); +//// }) +//// .END(); +//// +//// Promise.beginS().ef(false).then(() -> { +//// XLog.lg(false); +//// }).eeseEf(true).then(() -> { +//// XLog.lg(127, true); +//// }).eese(() -> { +//// XLog.lg("else"); +//// }).ef(true).then(() -> { +//// XLog.lg(131, true); +//// }).eese(() -> { +//// XLog.lg("eese"); +//// }).match(5).as(7).then(() -> { +//// XLog.lg(7); +//// }).as(5).then(() -> { +//// XLog.lg(137, 5); +//// }).defaut(() -> { +//// XLog.lg(999); +//// }).ef(true).then(() -> { +//// XLog.lg(139, true); +//// }).end(); +//// +//// Promise.beginS().match(123).as(123).as(99).then(() -> { +//// XLog.lg(149, 123); +//// }).end(); +//// +//// Promise.beginS().match(99).as(123).then(() -> { +//// XLog.lg(153, 123); +//// }).as(99).as(100).then(() -> { +//// XLog.lg(157, 123); +//// }).ef(true).then(() -> { +//// XLog.lg(159, true); +//// }).ef(true).then(() -> { +//// XLog.lg(160, true); +//// }).match(true).defaut(() -> { +//// XLog.lg(161, true); +//// }).match("ABC").as("ABC").then(() -> { +//// XLog.lg("ABC"); +//// }).match(1).as(1).as(2).then(() -> { +//// XLog.lg(1); +//// }).ef(false).then(() -> { +//// XLog.lg(false); +//// }).eeseEf(true).then(() -> { +//// XLog.lg(true); +//// }).ef(false).then(() -> { +//// XLog.lg(false); +//// }).eese(() -> { +//// XLog.lg("else"); +//// }).ef(false).then(() -> { +//// XLog.lg("doing"); +//// }) +////// .ef(false) +//// .match(11).as(88).as(11).then(() -> { +//// XLog.lg(193); +//// }).as(11).then(() -> { +//// XLog.lg(197); +//// }).defaut(() -> { +//// XLog.lg("default"); +//// }).ef(true).then(() -> { +//// XLog.line(true); +//// }).ef(true).then(() -> { +//// XLog.ln(true); +//// }).end(); +//// } +//// +//// @Test +//// public void testThread() throws InterruptedException { +//// Promise.threadS(()->{ +//// XLog.ln("thread S"); +//// }).THEN(t->{ +//// t.start(); +//// }).thread(d->{ +//// XLog.ln(d); +//// }).THEN(d->{ +//// d.start(); +//// }); +////======= +////// Promise.threadS(()->{ +////// XLog.ln("thread S"); +////// }).then(t->{ +////// t.start(); +////// }).thread(d->{ +////// XLog.ln(d); +////// }).then(d->{ +////// d.start(); +////// }); +//// +//// Promise.of().task(() -> { +//// XLog.ln(123); +//// }).task(d -> { +//// XLog.ln(d); +//// }).task(d -> { +//// XLog.ln(d); +//// return 100; +//// }).task(d -> { +//// XLog.ln(d, d.get(), d.getError()); +//// }).task(() -> 88888).line().ln(); +//// Promise.lineS("ABC", 123); +//// Promise.lnS("ABC", 123); +//// Thread.sleep(3000); +////// Thread.class.wait(); +//// +//// Promise.taskS(() -> { +//// throw new RuntimeException("OKOKOKOKOKOKOK"); +//// }).except(e -> { +//// XLog.ln(e); +//// e.printStackTrace(); +//// }).then(d -> { +//// XLog.ln(d, d.get(), d.getError()); +//// }); +//// Promise.lnS(Promise.taskS(() -> { +//// return "KKKKKKKKKKKK"; +//// }).get().get()); +//// +//// } +//// +//// @Test +//// public void testLogOut() throws InterruptedException, ExecutionException, TimeoutException { +//// Promise.logS(123,666,"ABC"); +//// Promise.lgS(123,666,"ABC"); +//// Promise.lnS(123,666,"ABC"); +//// Promise.lineS(123,666,"ABC").line().log().toJson().line().toFormatterJson().line().log(); +//// XLog.ln(123,"ABC"); +//// XLog.line(123,"ABC"); +//// String []ss = { +//// "A","B","C" +//// }; +//// Promise.OF(ss).line(); +//// Promise.OF(ss).toJson().line().toJson().line(); +//// Promise.OF(ss).toFormatterJson().line().toFormatterJson().line(); +//// Promise.formatterJsonKitS().THEN(d->{ +//// return d.fromJson((String)null, Object.class); +//// }).line(); +//// Promise.OF(ss).toJson().line().toObject(String[].class).THEN(d->{ +//// for(String s : d) { +//// XLog.ln(s); +// +// Promise.reject(new RuntimeException("ABC")).except(e -> { +// XLog.ln(e); +// return e; +// }).line(); +// +// new Promise<>(123); +// new Promise<>(new RuntimeException("ABC")).except(() -> { +// }); +// +// } +// +// @Test +// public void testBeansPool() { +// Promise.beanS("abc", String.class).getBean().end().ln(); +// Promise.beanS("abc", "ABC").register().getBean().end().ln(); +// Promise.beanS("abc").getBean().end().ln(); +// Promise.beanS("def", String.class, "DEF").register().getBean().end().ln(); +// Promise.beanS("def", String.class).getBean().end().ln(); +// Promise.beanS("abc").end().ln().bean("abc").getBean().end().ln(); +// +// Promise.beanS(String.class).getBean().end().ln(); +// Promise.beanS(String.class, "CCCCC", true).register().getBean().end().ln(); +// } +// +// @Test +// public void testBeansPool2() { +// Promise.beanS(String.class).getBean().end().ln(); +// Promise.beanS("a", "ABC").register().getBean().end().ln().then(d -> { +// XLog.ln(d.toCharArray()); +// return d.toCharArray(); +// }).bean(String.class, "DEF").register().getBean().end().ln().bean(String.class).getBean().end().ln().bean("a") +// .getBean().end().ln(); +//// XCode.runS(()->{ +//// for(int i=0;i<10000;i++) { +//// Promise.beanS(String.class,"abc"+i,true) +//// .register() +//// .getBean() +//// .end() +//// .ln(); +//// Promise.beanS("abc"+i,"abc"+i) +//// .register() +//// .getBean() +//// .end() +//// .ln(); +//// } +//// }); +// +// XCode.runS(() -> { +// for (int i = 0; i < 10000; i++) { +// int j = i; +// +// Promise.taskS(() -> { +// Promise.beanS(String.class, "abc" + j, true).register().getBean().end().ln(); +// }); +// Promise.taskS(() -> { +// Promise.beanS("abc" + j, "abc" + j).register().getBean().end().ln(); +// }); +// +// } +// }); +// +// Promise.beanS(String.class).getBean().end().ln(); +// } +// +// @Test +// public void testNetworkServer() { +//// Promise.udpS(8888).then(d->{ +//// byte []data = new byte[1024]; +//// DatagramPacket dp = new DatagramPacket(data, data.length); +//// try { +//// d.receive(dp); +//// XLog.lg(dp,new String(data)); +//// } catch (IOException e) { +//// e.printStackTrace(); +//// } +//// +//// }); +// +//// Promise.tcpS(8888).then(d->{ +//// try { +//// return d.accept(); +//// } catch (IOException e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//>>>>>>> branch 'jdk8' of git@github.com:XiuyeXYE/JavaUtil.git +//// } +//// return null; +//// }).toObject(String[].class).line().AND(true).OR(true).line().ln(); +//// +//// Promise.OF(new A("ABC","DEF")).toFormatterJson().line().toObject(Map.class).line() +//// .toFormatterJson().line().toObject(A.class).line() +//// .toObject(Map.class).EXCEPT(e->{ +//// e.printStackTrace(); +//// }).line(); +//// +////======= +//// Promise.logS(123, 666, "ABC"); +//// Promise.lgS(123, 666, "ABC"); +//// Promise.lnS(123, 666, "ABC"); +//// Promise.lineS(123, 666, "ABC").line().log().toJson().line().toFormatterJson().line().log(); +//// XLog.ln(123, "ABC"); +//// XLog.line(123, "ABC"); +//// String[] ss = { "A", "B", "C" }; +//// Promise.of(ss).line(); +//// Promise.of(ss).toJson().line().toJson().line(); +//// Promise.of(ss).toFormatterJson().line().toFormatterJson().line(); +//// Promise.formatterJsonKitS().then(d -> { +//// return d.fromJson((String) null, Object.class); +//// }).line(); +//// Promise.of(ss).toJson().line().toObject(String[].class).then(d -> { +//// for (String s : d) { +//// XLog.ln(s); +//// } +//// return null; +//// }).toObject(String[].class).line().and(true).or(true).line().ln(); +//// +//// Promise.of(new A("ABC", "DEF")).toFormatterJson().line().toObject(Map.class).line().toFormatterJson().line() +//// .toObject(A.class).line().toObject(Map.class).except(e -> { +//// e.printStackTrace(); +//// }).line(); +//// +////>>>>>>> 129ac581f0ae333784ad502729c1b2e1a9c35b62 +////// FutureTask futureTask = new FutureTask<>(()->{ +////// return "ABC"; +////// }); +////// XLog.ln(futureTask.get(1, TimeUnit.SECONDS)); +////// Thread.sleep(3000); +//// } +//// +//// private static class A { +//// String a; +//// String b; +//// +//// public A(String a, String b) { +//// super(); +//// this.a = a; +//// this.b = b; +//// } +//// +//// public String getA() { +//// return a; +//// } +//// +//// public void setA(String a) { +//// this.a = a; +//// } +//// +//// public String getB() { +//// return b; +//// } +//// +//// public void setB(String b) { +//// this.b = b; +//// } +//// +//// @Override +//// public String toString() { +//// return "A [a=" + a + ", b=" + b + "]"; +//// } +//// +//// } +//// +//// @Test +//// public void testReject() { +////// Promise.reject(new RuntimeException("ABC")).then(d->{ +////// XLog.ln(d); +////// return d; +////// }).line(); +//// +//// Promise.reject(new RuntimeException("ABC")).except(e -> { +//// XLog.ln(e); +//// return e; +//// }).line(); +//// +//// new Promise<>(123); +//// new Promise<>(new RuntimeException("ABC")).except(() -> { +//// }); +//<<<<<<< HEAD +//// +//// } +//// +//// @Test +//// public void testBeansPool() { +//// Promise.beanS("abc",String.class).getBean().end().ln(); +//// Promise.beanS("abc", "ABC").register().getBean().end().ln(); +//// Promise.beanS("abc").getBean().end().ln(); +//// Promise.beanS("def",String.class,"DEF").register().getBean().end().ln(); +//// Promise.beanS("def",String.class).getBean().end().ln(); +//// Promise.beanS("abc").end().ln().bean("abc").getBean() +//// .end().ln(); +//// +//// Promise.beanS(String.class).getBean().end().ln(); +//// Promise.beanS(String.class,"CCCCC",true).register().getBean().end().ln(); +//// } +//// +//// @Test +//// public void testBeansPool2() { +//// Promise.beanS(String.class).getBean().end().ln(); +//// Promise.beanS("a","ABC").register().getBean().end().ln() +//// .then(d->{ +//// XLog.ln(d.toCharArray()); +//// return d.toCharArray(); +//// }) +//// .bean(String.class, "DEF").register().getBean().end().ln() +//// .bean(String.class).getBean().end().ln() +//// .bean("a").getBean().end().ln() +//// ; +////// XCode.runS(()->{ +////// for(int i=0;i<10000;i++) { +////// Promise.beanS(String.class,"abc"+i,true) +////// .register() +////// .getBean() +////// .end() +////// .ln(); +////// Promise.beanS("abc"+i,"abc"+i) +////// .register() +////// .getBean() +////// .end() +////// .ln(); +////// } +////// }); +//// +//// XCode.runS(()->{ +//// for(int i=0;i<10000;i++) { +//// int j = i; +//// +//// Promise.taskS(()->{ +//// Promise.beanS(String.class,"abc"+j,true) +//// .register() +//// .getBean() +//// .end() +//// .ln(); +//// }); +//// Promise.taskS(()->{ +//// Promise.beanS("abc"+j,"abc"+j) +//// .register() +//// .getBean() +//// .end() +//// .ln(); +//// }); +//// +// +// } +// +// @Test +// public void testNetworkClient() { +// +//// Promise.tcpS("localhost",8888).then(d->{ +//// OutputStream os; +//// try { +//// os = d.getOutputStream(); +//// os.write("汉字".getBytes()); +//// d.close(); +//// } catch (IOException e1) { +//// e1.printStackTrace(); +//// } +//// }); +//// +//// Promise.beanS(String.class).getBean().end().ln(); +//// } +//// +//// @Test +//// public void testNetworkServer() { +////// Promise.udpS(8888).then(d->{ +////// byte []data = new byte[1024]; +////// DatagramPacket dp = new DatagramPacket(data, data.length); +////// try { +////// d.receive(dp); +////// XLog.lg(dp,new String(data)); +////// } catch (IOException e) { +////// e.printStackTrace(); +////// } +////// +////// }); +//// +////// Promise.tcpS(8888).then(d->{ +////// try { +////// return d.accept(); +////// } catch (IOException e) { +////// // TODO Auto-generated catch block +////// e.printStackTrace(); +////// } +////// return null; +////// }).exist(d->{ +////// try { +////// InputStream is = d.getInputStream(); +//////// int i=-1; +//////// while((i=is.read())!=-1) { +//////// XLog.print(i); +//////// } +////// byte []data = new byte[1024]; +////// is.read(data); +////// XLog.lg(new String(data)); +////// d.close(); +////// } catch (IOException e) { +////// e.printStackTrace(); +////// } +////// +////// }); +//// +//// } +//// +//// @Test +//// public void testNetworkClient() { +//// +////// Promise.tcpS("localhost",8888).then(d->{ +////// OutputStream os; +////// try { +////// os = d.getOutputStream(); +////// os.write("汉字".getBytes()); +////// d.close(); +////// } catch (IOException e1) { +////// e1.printStackTrace(); +////// } +////// }); +//// +////// Promise.udpS().then(d->{ +////// String s = "汉字,这是汉字!嘿嘿!"; +////// try { +////// DatagramPacket dp = new DatagramPacket( +////// s.getBytes(), +////// s.getBytes().length, +////// InetAddress.getByName("localhost"), +////// 8888 +////// ); +////// d.send(dp); +////// XLog.lg("sent!"); +////// } catch (IOException e) { +////// e.printStackTrace(); +////// } +////// +////// }); +//// } +// +//// Promise.udpS().then(d->{ +//// String s = "汉字,这是汉字!嘿嘿!"; +//// try { +//// DatagramPacket dp = new DatagramPacket( +//// s.getBytes(), +//// s.getBytes().length, +//// InetAddress.getByName("localhost"), +//// 8888 +//// ); +//// d.send(dp); +//// XLog.lg("sent!"); +//// } catch (IOException e) { +//// e.printStackTrace(); +//// } +//// +//// }); +// } +// +// private ZooKeeper zk = null; +// +//// @Test +// public void testZooKeeper() throws IOException, InterruptedException, KeeperException { +// CountDownLatch connectedSemaphore = new CountDownLatch(1); +// Stat stat = new Stat(); +// String path = "/demo_five"; +// zk = new ZooKeeper("127.0.0.1:2181", 5000, e -> { +// if (KeeperState.SyncConnected == e.getState()) { +// if (EventType.None == e.getType() && null == e.getPath()) { +// connectedSemaphore.countDown(); +// } else if (e.getType() == EventType.NodeDataChanged) { +// try { +// XLog.ln(zk); +// XLog.ln("配置已修改,新值为:" + new String(zk.getData(e.getPath(), true, stat))); +// } catch (KeeperException | InterruptedException e1) { +// e1.printStackTrace(); +// } +// } +// } +// }); +//// zk.create(path, "终于".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); +// connectedSemaphore.await(); +// XLog.ln(new String(zk.getData(path, true, stat))); +// zk.setData(path, "第三方科技按还款法还是开发开放了".getBytes(), -1); +// +// Thread.sleep(10000); +// +// } +//} diff --git a/test/com/xiuye/util/test/code/PromiseTest.java.orig b/test/com/xiuye/util/test/code/PromiseTest.java.orig new file mode 100644 index 0000000..44d2984 --- /dev/null +++ b/test/com/xiuye/util/test/code/PromiseTest.java.orig @@ -0,0 +1,630 @@ +package com.xiuye.util.test.code; + +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; + +import org.junit.Test; + +import com.xiuye.sharp.Promise; +import com.xiuye.util.code.XCode; +import com.xiuye.util.log.XLog; + +public class PromiseTest { + + @Test + public void test() { + // default true +// Promise.implyErrorHandler(false); + new Promise<>(99999).THEN(d -> { + XLog.lg(d); + XLog.lg("void call(I in)"); + + }).THEN(d -> { + XLog.lg(d); + XLog.lg("R call(I in)"); + + return 999; + }).THEN(() -> { + XLog.lg("R call()"); + return "ABC"; + }).THEN(() -> { + XLog.lg("void call()"); + }).THEN(() -> { + XLog.lg("End"); + }).THEN(() -> { + throw new RuntimeException("My Exception intentional"); + }).EXCEPT(e -> { + XLog.lg(e); + return e; + }).EXCEPT(e -> { + XLog.lg(e); + }).EXCEPT(e -> { + XLog.lg(e); + }).EXCEPT(() -> { + throw new RuntimeException("Nothing"); + })./* then(()->{}). */EXCEPT(e -> { + XLog.lg(e); + return 100; + }).EXCEPT(d -> { + XLog.log(d); + }).EXCEPT(() -> { + +<<<<<<< HEAD + }).EXCEPT(() -> { + +======= + }).except(() -> { + +>>>>>>> 129ac581f0ae333784ad502729c1b2e1a9c35b62 + }); + } + + @Test + public void testIfElse() { +<<<<<<< HEAD + + Promise.RESOLVE() + .BEGIN() + .IF(false) + .THEN(()->{ + XLog.lg("123"); + }) + .ELIF(true) + .THEN(()->{ + XLog.lg("then"); + }) + .ELIF(true) + .THEN(()->{ + XLog.lg("then2"); + }) + .ELSE(()->{ + XLog.lg("ABC"); + }) + .IF(true) + .THEN(()->{ + XLog.lg("2 then"); + }) + .ELSE(()->{ + XLog.lg("EESE"); + }) + .END().THEN(d->{ +======= + + Promise.resolve().begin().ef(false).then(() -> { + XLog.lg("123"); + }).eeseEf(true).then(() -> { + XLog.lg("then"); + }).eeseEf(true).then(() -> { + XLog.lg("then2"); + }).eese(() -> { + XLog.lg("ABC"); + }).ef(true).then(() -> { + XLog.lg("2 then"); + }).eese(() -> { + XLog.lg("EESE"); + }).end().then(d -> { +>>>>>>> 129ac581f0ae333784ad502729c1b2e1a9c35b62 + XLog.lg(d); + }); + + XLog.lg(trueflag() | falseflag()); + XLog.lg(trueflag() || falseflag()); + + } + + private boolean trueflag() { + XLog.lg("trueflag run"); + return true; + } + + private boolean falseflag() { + XLog.lg("falseflag run"); + return false; + } + + @Test + public void testMatchAs() { +<<<<<<< HEAD + Promise.OF().BEGIN().MATCH(123).AS(99).THEN(()->{ + XLog.lg("matched 1"); + }).AS(100).AS(123).THEN(()->{ + XLog.lg("matched 2"); + }).DEFAUT(()->{ + XLog.lg("default"); + }).END(); + + Promise.OF().BEGIN().MATCH(11).AS(56789).AS(11).THEN(()->{ + XLog.lg("56789"); + }).DEFAUT(()->{ + XLog.lg("default"); + }).THEN(()->{}).END().THEN(()->{ +======= + Promise.of().begin().match(123).as(99).then(() -> { + XLog.lg("matched 1"); + }).as(100).as(123).then(() -> { + XLog.lg("matched 2"); + }).defaut(() -> { + XLog.lg("default"); + }).end(); + + Promise.of().begin().match(11).as(56789).as(11).then(() -> { + XLog.lg("56789"); + }).defaut(() -> { + XLog.lg("default"); + }).then(() -> { + }).end().then(() -> { +>>>>>>> 129ac581f0ae333784ad502729c1b2e1a9c35b62 + XLog.lg("then"); + }); + XLog.lg(null instanceof String); + String s = null; + XLog.lg(s instanceof String); + + } + + @Test + public void testAllSwitchStatement() { +<<<<<<< HEAD + + Promise.BEGINS().IF(false).THEN(()->{ + XLog.lg(false); + }).ELIF(true).THEN(()->{ + XLog.lg(127,true); + }).ELSE(()->{ + XLog.lg("else"); + }).IF(true).THEN(()->{ + XLog.lg(131,true); + }).ELSE(()->{ + XLog.lg("eese"); + }).MATCH(5).AS(7).THEN(()->{ + XLog.lg(7); + }) + .AS(5).THEN(()->{ + XLog.lg(137,5); + }) + .DEFAUT(()->{ + XLog.lg(999); + }) + .IF(true).THEN(()->{ + XLog.lg(139,true); + }) + .END(); + + Promise.BEGINS().MATCH(123).AS(123).AS(99).THEN(()->{ + XLog.lg(149,123); + }).END(); + + Promise.BEGINS().MATCH(99) + .AS(123).THEN(()->{ + XLog.lg(153,123); + }) + .AS(99).AS(100).THEN(()->{ + XLog.lg(157,123); + }) + .IF(true).THEN(()->{XLog.lg(159,true);}) + .IF(true).THEN(()->{XLog.lg(160,true);}) + .MATCH(true).DEFAUT(()->{XLog.lg(161,true);}) + .MATCH("ABC").AS("ABC").THEN(()->{ + XLog.lg("ABC"); + }) + .MATCH(1).AS(1).AS(2) + .THEN(()->{ + XLog.lg(1); + }) + .IF(false) + .THEN(()->{ + XLog.lg(false); + }) + .ELIF(true) + .THEN(()->{ + XLog.lg(true); + }) + .IF(false) + .THEN(()->{ + XLog.lg(false); + }) + .ELSE(()->{ + XLog.lg("else"); + }) + .IF(false) + .THEN(()->{ + XLog.lg("doing"); + }) +// .ef(false) + .MATCH(11) + .AS(88) + .AS(11) + .THEN(()->{ + XLog.lg(193); + }) + .AS(11) + .THEN(()->{ + XLog.lg(197); + }) + .DEFAUT(()->{ + XLog.lg("default"); + }) + .IF(true) + .THEN(()->{ + XLog.line(true); + }) + .IF(true) + .THEN(()->{ + XLog.ln(true); + }) + .END(); +======= + + Promise.beginS().ef(false).then(() -> { + XLog.lg(false); + }).eeseEf(true).then(() -> { + XLog.lg(127, true); + }).eese(() -> { + XLog.lg("else"); + }).ef(true).then(() -> { + XLog.lg(131, true); + }).eese(() -> { + XLog.lg("eese"); + }).match(5).as(7).then(() -> { + XLog.lg(7); + }).as(5).then(() -> { + XLog.lg(137, 5); + }).defaut(() -> { + XLog.lg(999); + }).ef(true).then(() -> { + XLog.lg(139, true); + }).end(); + + Promise.beginS().match(123).as(123).as(99).then(() -> { + XLog.lg(149, 123); + }).end(); + + Promise.beginS().match(99).as(123).then(() -> { + XLog.lg(153, 123); + }).as(99).as(100).then(() -> { + XLog.lg(157, 123); + }).ef(true).then(() -> { + XLog.lg(159, true); + }).ef(true).then(() -> { + XLog.lg(160, true); + }).match(true).defaut(() -> { + XLog.lg(161, true); + }).match("ABC").as("ABC").then(() -> { + XLog.lg("ABC"); + }).match(1).as(1).as(2).then(() -> { + XLog.lg(1); + }).ef(false).then(() -> { + XLog.lg(false); + }).eeseEf(true).then(() -> { + XLog.lg(true); + }).ef(false).then(() -> { + XLog.lg(false); + }).eese(() -> { + XLog.lg("else"); + }).ef(false).then(() -> { + XLog.lg("doing"); + }) +// .ef(false) + .match(11).as(88).as(11).then(() -> { + XLog.lg(193); + }).as(11).then(() -> { + XLog.lg(197); + }).defaut(() -> { + XLog.lg("default"); + }).ef(true).then(() -> { + XLog.line(true); + }).ef(true).then(() -> { + XLog.ln(true); + }).end(); +>>>>>>> 129ac581f0ae333784ad502729c1b2e1a9c35b62 + } + + @Test + public void testThread() throws InterruptedException { +<<<<<<< HEAD + Promise.threadS(()->{ + XLog.ln("thread S"); + }).THEN(t->{ + t.start(); + }).thread(d->{ + XLog.ln(d); + }).THEN(d->{ + d.start(); + }); +======= +// Promise.threadS(()->{ +// XLog.ln("thread S"); +// }).then(t->{ +// t.start(); +// }).thread(d->{ +// XLog.ln(d); +// }).then(d->{ +// d.start(); +// }); + + Promise.of().task(() -> { + XLog.ln(123); + }).task(d -> { + XLog.ln(d); + }).task(d -> { + XLog.ln(d); + return 100; + }).task(d -> { + XLog.ln(d, d.get(), d.getError()); + }).task(() -> 88888).line().ln(); + Promise.lineS("ABC", 123); + Promise.lnS("ABC", 123); +>>>>>>> 129ac581f0ae333784ad502729c1b2e1a9c35b62 + Thread.sleep(3000); +// Thread.class.wait(); + + Promise.taskS(() -> { + throw new RuntimeException("OKOKOKOKOKOKOK"); + }).except(e -> { + XLog.ln(e); + e.printStackTrace(); + }).then(d -> { + XLog.ln(d, d.get(), d.getError()); + }); + Promise.lnS(Promise.taskS(() -> { + return "KKKKKKKKKKKK"; + }).get().get()); + + } + + @Test + public void testLogOut() throws InterruptedException, ExecutionException, TimeoutException { +<<<<<<< HEAD + Promise.logS(123,666,"ABC"); + Promise.lgS(123,666,"ABC"); + Promise.lnS(123,666,"ABC"); + Promise.lineS(123,666,"ABC").line().log().toJson().line().toFormatterJson().line().log(); + XLog.ln(123,"ABC"); + XLog.line(123,"ABC"); + String []ss = { + "A","B","C" + }; + Promise.OF(ss).line(); + Promise.OF(ss).toJson().line().toJson().line(); + Promise.OF(ss).toFormatterJson().line().toFormatterJson().line(); + Promise.formatterJsonKitS().THEN(d->{ + return d.fromJson((String)null, Object.class); + }).line(); + Promise.OF(ss).toJson().line().toObject(String[].class).THEN(d->{ + for(String s : d) { + XLog.ln(s); + } + return null; + }).toObject(String[].class).line().AND(true).OR(true).line().ln(); + + Promise.OF(new A("ABC","DEF")).toFormatterJson().line().toObject(Map.class).line() + .toFormatterJson().line().toObject(A.class).line() + .toObject(Map.class).EXCEPT(e->{ + e.printStackTrace(); + }).line(); + +======= + Promise.logS(123, 666, "ABC"); + Promise.lgS(123, 666, "ABC"); + Promise.lnS(123, 666, "ABC"); + Promise.lineS(123, 666, "ABC").line().log().toJson().line().toFormatterJson().line().log(); + XLog.ln(123, "ABC"); + XLog.line(123, "ABC"); + String[] ss = { "A", "B", "C" }; + Promise.of(ss).line(); + Promise.of(ss).toJson().line().toJson().line(); + Promise.of(ss).toFormatterJson().line().toFormatterJson().line(); + Promise.formatterJsonKitS().then(d -> { + return d.fromJson((String) null, Object.class); + }).line(); + Promise.of(ss).toJson().line().toObject(String[].class).then(d -> { + for (String s : d) { + XLog.ln(s); + } + return null; + }).toObject(String[].class).line().and(true).or(true).line().ln(); + + Promise.of(new A("ABC", "DEF")).toFormatterJson().line().toObject(Map.class).line().toFormatterJson().line() + .toObject(A.class).line().toObject(Map.class).except(e -> { + e.printStackTrace(); + }).line(); + +>>>>>>> 129ac581f0ae333784ad502729c1b2e1a9c35b62 +// FutureTask futureTask = new FutureTask<>(()->{ +// return "ABC"; +// }); +// XLog.ln(futureTask.get(1, TimeUnit.SECONDS)); +// Thread.sleep(3000); + } + + private static class A { + String a; + String b; + + public A(String a, String b) { + super(); + this.a = a; + this.b = b; + } + + public String getA() { + return a; + } + + public void setA(String a) { + this.a = a; + } + + public String getB() { + return b; + } + + public void setB(String b) { + this.b = b; + } + + @Override + public String toString() { + return "A [a=" + a + ", b=" + b + "]"; + } + + } + + @Test + public void testReject() { +// Promise.reject(new RuntimeException("ABC")).then(d->{ +// XLog.ln(d); +// return d; +// }).line(); + + Promise.reject(new RuntimeException("ABC")).except(e -> { + XLog.ln(e); + return e; + }).line(); + + new Promise<>(123); + new Promise<>(new RuntimeException("ABC")).except(() -> { + }); + + } + + @Test + public void testBeansPool() { + Promise.beanS("abc",String.class).getBean().end().ln(); + Promise.beanS("abc", "ABC").register().getBean().end().ln(); + Promise.beanS("abc").getBean().end().ln(); + Promise.beanS("def",String.class,"DEF").register().getBean().end().ln(); + Promise.beanS("def",String.class).getBean().end().ln(); + Promise.beanS("abc").end().ln().bean("abc").getBean() + .end().ln(); + + Promise.beanS(String.class).getBean().end().ln(); + Promise.beanS(String.class,"CCCCC",true).register().getBean().end().ln(); + } + + @Test + public void testBeansPool2() { + Promise.beanS(String.class).getBean().end().ln(); + Promise.beanS("a","ABC").register().getBean().end().ln() + .then(d->{ + XLog.ln(d.toCharArray()); + return d.toCharArray(); + }) + .bean(String.class, "DEF").register().getBean().end().ln() + .bean(String.class).getBean().end().ln() + .bean("a").getBean().end().ln() + ; +// XCode.runS(()->{ +// for(int i=0;i<10000;i++) { +// Promise.beanS(String.class,"abc"+i,true) +// .register() +// .getBean() +// .end() +// .ln(); +// Promise.beanS("abc"+i,"abc"+i) +// .register() +// .getBean() +// .end() +// .ln(); +// } +// }); + + XCode.runS(()->{ + for(int i=0;i<10000;i++) { + int j = i; + + Promise.taskS(()->{ + Promise.beanS(String.class,"abc"+j,true) + .register() + .getBean() + .end() + .ln(); + }); + Promise.taskS(()->{ + Promise.beanS("abc"+j,"abc"+j) + .register() + .getBean() + .end() + .ln(); + }); + + } + }); + + Promise.beanS(String.class).getBean().end().ln(); + } + + @Test + public void testNetworkServer() { +// Promise.udpS(8888).then(d->{ +// byte []data = new byte[1024]; +// DatagramPacket dp = new DatagramPacket(data, data.length); +// try { +// d.receive(dp); +// XLog.lg(dp,new String(data)); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// +// }); + +// Promise.tcpS(8888).then(d->{ +// try { +// return d.accept(); +// } catch (IOException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +// return null; +// }).exist(d->{ +// try { +// InputStream is = d.getInputStream(); +//// int i=-1; +//// while((i=is.read())!=-1) { +//// XLog.print(i); +//// } +// byte []data = new byte[1024]; +// is.read(data); +// XLog.lg(new String(data)); +// d.close(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// +// }); + + } + + @Test + public void testNetworkClient() { + +// Promise.tcpS("localhost",8888).then(d->{ +// OutputStream os; +// try { +// os = d.getOutputStream(); +// os.write("汉字".getBytes()); +// d.close(); +// } catch (IOException e1) { +// e1.printStackTrace(); +// } +// }); + +// Promise.udpS().then(d->{ +// String s = "汉字,这是汉字!嘿嘿!"; +// try { +// DatagramPacket dp = new DatagramPacket( +// s.getBytes(), +// s.getBytes().length, +// InetAddress.getByName("localhost"), +// 8888 +// ); +// d.send(dp); +// XLog.lg("sent!"); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// +// }); + } +} diff --git a/test/com/xiuye/util/test/code/XCodeTest.java b/test/com/xiuye/util/test/code/XCodeTest.java new file mode 100644 index 0000000..37c0f8a --- /dev/null +++ b/test/com/xiuye/util/test/code/XCodeTest.java @@ -0,0 +1,205 @@ +package com.xiuye.util.test.code; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.util.Map; +import java.util.UUID; + +import org.junit.Test; + +import com.xiuye.util.cls.XType; +import com.xiuye.util.cls.XClassLoader; +import com.xiuye.util.code.XCode; +import com.xiuye.util.code.XCompiler; +import com.xiuye.util.code.gen.ClassInfo; +import com.xiuye.util.code.gen.FieldInfo; +import com.xiuye.util.code.gen.FunctionInfo; +import com.xiuye.util.log.XLog; + +public class XCodeTest { + + @Test + public void test() throws InterruptedException { + XCode.runS(()->{ + XLog.ln("ABC"); + XLog.ln("ABC"); + XLog.ln("ABC"); + XLog.ln("ABC"); + XLog.ln("ABC"); + }); + XCode.runMS(()->{ + XLog.ln("ABC"); + XLog.line("ABC"); + XLog.ln("ABC"); + XLog.line("ABC"); + XLog.ln("ABC"); + }); + XCode.runNS(()->{ + XLog.ln("ABC"); + XLog.line("ABC"); + XLog.ln("ABC"); + XLog.line("ABC"); + XLog.ln("ABC"); + }); + XCode.run(()->{ + XLog.ln("ABC"); + XLog.line("ABC"); + XLog.ln("ABC"); + XLog.line("ABC"); + XLog.ln("ABC"); + }); + XLog.line("DEF"); + XLog.ln("DEF"); + } + + @Test + public void testCompileCode() + throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException { + Map code = XType.map(); + code.put("com.xiuye.util.test.code.AI", + "package com.xiuye.util.test.code;" + "import com.xiuye.util.log.XLog;" + + " public interface AI extends Runnable{" + " public void f();" + + "default void g(){XLog.lg(\"AI::g()\");}}"); + code.put("com.xiuye.util.test.code.AIImpl", + "package com.xiuye.util.test.code;" + "import com.xiuye.util.log.XLog;" + + " public class AIImpl implements AI{" + " public void f(){XLog.lg(\"AI::f()\");} " + "" + + "public void run(){XLog.lg(\"AIImpl::run()\");}" + "}"); + XLog.lg(XCompiler.compileCode(code) ? "successful" : "failure"); + XClassLoader cl = XType.createClassLoader(); +// XLog.lg(cl.loadClass("com.xiuye.util.test.code.AI")); + Class clazz = cl.load("com.xiuye.util.test.code.AIImpl"); + clazz = cl.load("com.xiuye.util.test.code.AIImpl"); + XLog.lg(clazz); + XLog.lg(clazz.newInstance()); + Runnable run = XType.cast(clazz.newInstance()); + run.run(); + + XLog.log(run.getClass().getClassLoader()); + XLog.lg(run.getClass().getClassLoader().getParent()); + XLog.lg(run.getClass().getClassLoader().getParent().getParent()); + XLog.lg(run.getClass().getClassLoader().getParent().getParent().getParent()); + XLog.lg(Class.forName("java.lang.Runnable").getClassLoader()); + Map codes2 = XType.map(); + codes2.put("com.xiuye.BIImpl", + "package com.xiuye;" + "import com.xiuye.util.test.code.XCodeTest.BI;" + + "import com.xiuye.util.log.XLog;" + " public class BIImpl implements BI{" + "public void b(){" + + "XLog.lg(\"BIImpl::b()\");" + "}" + "}"); + codes2.put("com.xiuye.util.test.code.CIImpl", + "package com.xiuye.util.test.code;" + "import com.xiuye.util.test.code.XCodeTest.CI;" + + "import com.xiuye.util.log.XLog;" + " public class CIImpl implements CI{" + "public void c(){" + + "XLog.lg(\"CIImpl::c()\");" + "}" + "}"); + XLog.lg(XCompiler.compileCode(codes2)); + XLog.lg(cl.load("com.xiuye.BIImpl")); + XLog.lg(cl.load("com.xiuye.BIImpl").newInstance()); + BI b = XType.cast(cl.load("com.xiuye.BIImpl").newInstance()); + b.b(); + CI c = XType.cast(cl.load("com.xiuye.util.test.code.CIImpl").newInstance()); + c.c(); + + } + + public interface BI { + void b(); + } + + public interface CI { + void c(); + } + + @Test + public void testGenJavaCode() throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { + ClassInfo info = new ClassInfo(); + info.setPackageName("com.xiuye.util.test.code"); + info.addImportPackage("com.xiuye.util.log.XLog"); + info.setAccess(ClassInfo.ACCESS_PUBLIC); + info.addModifier(ClassInfo.FINAL_MODIFIER); + info.setType(ClassInfo.TYPE_CLASS); + info.setName("Demo1"); + + for (int i = 0; i < 10; i++) { + FieldInfo fi = new FieldInfo(); + fi.setAccess(FieldInfo.ACCESS_PRIVATE); +// fi.addModifier(FieldInfo.STATIC_MODIFIER); + fi.addModifier(FieldInfo.FINAL_MODIFIER); + fi.setType("int"); + fi.setName("inNumber" + i); + info.addField(fi); + } + for (int i = 0; i < 10; i++) { + FunctionInfo fi = new FunctionInfo(); + fi.setAccess(FunctionInfo.ACCESS_PUBLIC); + fi.addModifier(FunctionInfo.STATIC_MODIFIER); + fi.addModifier(FunctionInfo.FINAL_MODIFIER); + fi.setType("void"); + fi.setName("function" + i); + fi.addParameter("int", "a"); + fi.addParameter("int", "b"); + fi.addParameter("long", "c"); + fi.setFunctionBody("XLog.lg(a,b,c);"); + info.addFunction(fi); + } + + FunctionInfo fi = new FunctionInfo(); + fi.setAccess(FunctionInfo.ACCESS_PUBLIC); +// fi.setType(""); + fi.setName("Demo1"); + String conBody = ""; + for(int i=0;i<10;i++) { + conBody += "inNumber" + i+" = "+ i +";"; + } + + fi.setFunctionBody(conBody); + info.addFunction(fi); + + XLog.lg(info); + Map codes = XType.map(); + codes.put("com.xiuye.util.test.code.Demo1",info.code()); +// codes.put(info.getPackageName(),info.code()); + XCompiler.compileCode(codes); + XClassLoader cl = XType.createClassLoader(); + XLog.lg(cl.load("com.xiuye.util.test.code.Demo1")); + Class clazz = cl.load("com.xiuye.util.test.code.Demo1"); + + Object o = clazz.newInstance(); + Method m = clazz.getDeclaredMethod("function9", int.class,int.class,long.class); + + m.invoke(o, 1,2,3); + } + + @Test + public void testProxyInterface() throws ClassNotFoundException { + Class clazz = XType.cast(Class.forName("com.xiuye.util.test.code.ABC")); + Method [] ms = clazz.getDeclaredMethods(); + for(Method m : ms) { + XLog.lg(m); + XLog.lg(m.getModifiers()); + XLog.lg(m.getReturnType()); + XLog.lg(m.getGenericReturnType()); + XLog.lg(m.getName()); + XLog.lg(m.getParameters()); + XLog.lg(m.getParameterTypes()); + XLog.lg(m.getGenericParameterTypes()); + XLog.lg(m.getParameterCount()); + } + + + } + @Test + public void testHowManyThreadsOK() throws InterruptedException { + for(int i=0;i<10000;i++) { + int j = i; + XCode.runAsync(()->{ + XLog.ln(UUID.randomUUID().toString(),j); +// for(;;); + }); + + } + +// while(true); + + Thread.sleep(3000); + + + } +} diff --git a/test/com/xiuye/util/test/math/MathUtillTest.java b/test/com/xiuye/util/test/math/MathUtillTest.java new file mode 100644 index 0000000..b43eeb5 --- /dev/null +++ b/test/com/xiuye/util/test/math/MathUtillTest.java @@ -0,0 +1,36 @@ +package com.xiuye.util.test.math; + +import com.xiuye.util.log.XLog; +import com.xiuye.util.math.XMath; + +public class MathUtillTest { + public static void main(String[] args) { + XLog.log(XMath.gcd(5, 5)); + XLog.log(XMath.gcd(5, 4)); + XLog.log(XMath.gcd(8, 10)); + int[] a1 = { 6, 12, 55, 99, 1, 22, 76 }; + XLog.log(XMath.max(a1)); + double[] a2 = { 6, 12, 55, 99, 1, 22, 76, 987 }; + XLog.log(XMath.max(a2)); + XLog.log(XMath.average(a1)); + XLog.log(XMath.average(a2)); + XMath.reverse(a1); + XLog.logArray(a1); + XMath.reverse(a2); + XLog.logArray(a2); + XLog.log(XMath.abs(-1)); + XLog.log(XMath.abs(-1.1)); + XLog.log(XMath.isPrime(9)); + XLog.log(XMath.isPrime(5)); + XLog.log(XMath.isPrime(95)); + XLog.log(XMath.sqrt(2)); + XLog.log(XMath.sqrt(3)); + XLog.log(XMath.sqrt(4)); + XLog.log(XMath.sqrt(5)); + XLog.log(XMath.sqrt(9)); + XLog.log(XMath.sqrt(100)); + XLog.log(XMath.sqrt(101)); + XLog.log(XMath.rightTriangleHypotenuse(3, 4)); + + } +} diff --git a/test/com/xiuye/util/test/time/TestTimeUtil.java b/test/com/xiuye/util/test/time/TestTimeUtil.java deleted file mode 100644 index 8e1bd18..0000000 --- a/test/com/xiuye/util/test/time/TestTimeUtil.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.xiuye.util.test.time; - -import org.junit.Test; - -import com.xiuye.util.log.LogUtil; -import com.xiuye.util.time.TimeUtil; - -public class TestTimeUtil { - - @Test - public void testCostTime() { - TimeUtil.start(); - long counter = 0; - for (var i = 0; i < 1000000000; i++) { - counter++; - - } - LogUtil.log(counter); - TimeUtil.outCostOnConsoleNs(); - TimeUtil.start(); - counter = 0; - for (var i = 0; i < 1000000000; i++) { - counter++; - - } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - LogUtil.log(counter); - TimeUtil.outCostOnConsoleMs(); - TimeUtil.start(); - counter = 0; - for (var i = 0; i < 1000000000; i++) { - counter++; - - } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - LogUtil.log(counter); - TimeUtil.outCostOnConsoleS(() -> { - LogUtil.log("Call in the end or start?"); - }); - - } - - @Test - public void testStackTrace() { - StackTraceElement[] stes = Thread.currentThread().getStackTrace(); - var counter = 0; - for (StackTraceElement ste : stes) { - - LogUtil.log(counter + "." + "StackTraceElement : " + ste); - LogUtil.log(counter + "." + "FileName : " + ste.getFileName()); - LogUtil.log(counter + "." + "LineNumber : " + ste.getLineNumber()); - LogUtil.log(counter + "." + "ClassName : " + ste.getClassName()); - LogUtil.log(counter + "." + "MethodName : " + ste.getMethodName()); - LogUtil.log(counter + "." + "ClassLoaderName : " + ste.getClassLoaderName()); - LogUtil.log(counter + "." + "ModuleName : " + ste.getModuleName()); - LogUtil.log(counter + "." + "ModuleVersion : " + ste.getModuleVersion()); - counter++; - } - } - - @Test - public void testTimeUtilCallerIsOK() { - TimeUtil.start(); - TimeUtil.outCostOnConsoleNs(() -> { - LogUtil.log("OK", "YES"); - }, () -> { - LogUtil.log("End", "Last", 1, 23); - }); - TimeUtil.outCostOnConsoleMs(() -> { - LogUtil.log("OK", "YES"); - }, () -> { - LogUtil.log("End", "Last", 1, 23); - }); - TimeUtil.outCostOnConsoleS(() -> { - LogUtil.log("OK", "YES"); - }, () -> { - LogUtil.log("End", "Last", 1, 23); - }); - } - -} diff --git a/xyjava.iml b/xyjava.iml new file mode 100644 index 0000000..fcef099 --- /dev/null +++ b/xyjava.iml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file