FormulaUtils.java 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. package com.mixsmart.utils;
  2. import cn.hutool.log.StaticLog;
  3. import com.jfireel.expression.Expression;
  4. import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
  5. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  6. import org.apache.poi.ss.usermodel.*;
  7. import java.awt.Color;
  8. import org.jfree.chart.ChartFactory;
  9. import org.jfree.chart.ChartPanel;
  10. import org.jfree.chart.ChartUtils;
  11. import org.jfree.chart.JFreeChart;
  12. import org.jfree.chart.axis.NumberAxis;
  13. import org.jfree.chart.axis.NumberTickUnit;
  14. import org.jfree.chart.plot.PlotOrientation;
  15. import org.jfree.chart.plot.ValueMarker;
  16. import org.jfree.chart.plot.XYPlot;
  17. import org.jfree.chart.renderer.xy.XYSplineRenderer;
  18. import org.jfree.chart.title.TextTitle;
  19. import org.jfree.data.xy.XYSeries;
  20. import org.jfree.data.xy.XYSeriesCollection;
  21. import org.jsoup.Jsoup;
  22. import org.jsoup.nodes.Document;
  23. import org.springblade.common.utils.BaseUtils;
  24. import org.springblade.core.tool.utils.CollectionUtil;
  25. import org.springblade.core.tool.utils.Func;
  26. import org.springblade.core.tool.utils.IoUtil;
  27. import org.springblade.core.tool.utils.StringPool;
  28. import org.springblade.manager.dto.Coords;
  29. import org.springblade.manager.dto.ElementData;
  30. import org.springblade.manager.dto.FormData;
  31. import org.springblade.manager.dto.LocalVariable;
  32. import org.springblade.manager.entity.Formula;
  33. import org.springblade.manager.utils.FileUtils;
  34. import java.awt.*;
  35. import java.awt.Font;
  36. import java.awt.Shape;
  37. import java.awt.geom.Ellipse2D;
  38. import java.io.*;
  39. import java.nio.charset.StandardCharsets;
  40. import java.security.MessageDigest;
  41. import java.security.NoSuchAlgorithmException;
  42. import java.util.*;
  43. import java.util.List;
  44. import java.util.concurrent.atomic.AtomicInteger;
  45. import java.util.regex.Matcher;
  46. import java.util.regex.Pattern;
  47. import java.util.stream.Collectors;
  48. import java.util.stream.IntStream;
  49. import java.util.stream.Stream;
  50. import static java.util.regex.Pattern.*;
  51. /**
  52. * @author yangyj
  53. * @Date 2022/7/14 15:55
  54. * @description TODO
  55. */
  56. public class FormulaUtils {
  57. public static Map<String,Object> triangleSquare(Object ranges){
  58. Map<String,Object> map =new HashMap<>();
  59. if(StringUtils.isEmpty(ranges)){
  60. //z的默认取值范围
  61. ranges="(0,15)";
  62. }
  63. Matcher m = RegexUtils.matcher("(\\-?\\d+)(\\D)(\\+?\\d+)",ranges.toString());
  64. if(m.find()) {
  65. System.out.println();
  66. int min = StringUtils.handObj2Integer(m.group(1));
  67. int max = StringUtils.handObj2Integer(m.group(3));
  68. Integer[] r = pythagorean(min, max);
  69. map.put("X", String.valueOf(r[0]));
  70. map.put("Y", String.valueOf(r[1]));
  71. map.put("Z", String.valueOf(r[2]));
  72. }
  73. return map;
  74. }
  75. /**
  76. * @Description 字符串相似度
  77. * @Param [s1, s2]
  78. * @return double
  79. * @Author yangyj
  80. * @Date 2023.04.12 18:01
  81. **/
  82. public static double getJaccardSimilarity(String s1, String s2) {
  83. Set<Character> set1 = new HashSet<>();
  84. Set<Character> set2 = new HashSet<>();
  85. for (char c : s1.toCharArray()) {
  86. set1.add(c);
  87. }
  88. for (char c : s2.toCharArray()) {
  89. set2.add(c);
  90. }
  91. Set<Character> intersection = new HashSet<>(set1);
  92. intersection.retainAll(set2);
  93. Set<Character> union = new HashSet<>(set1);
  94. union.addAll(set2);
  95. return (double) intersection.size() / union.size();
  96. }
  97. public static Double similarity(String s1,String s2){
  98. return getJaccardSimilarity(parseItemName(s1),parseItemName(s2));
  99. }
  100. /**
  101. * result[0]^2+result[1]^2=result[2]^2 result[] 元素均为正整数
  102. */
  103. public static Integer[] pythagorean(Integer min,Integer max){
  104. Integer[] result = null;
  105. List<Integer[]> list = new ArrayList<>();
  106. for(int i=1;i<=max;i++){
  107. for(int j=1;j<=max;j++){
  108. double tmp = Math.sqrt(Math.pow(i,2)+Math.pow(j,2));
  109. int z= (int) Math.round(tmp);
  110. if(min<z&&z<=max){
  111. Integer[] arr = new Integer[]{ i,j,z};
  112. list.add(arr);
  113. }
  114. }
  115. }
  116. if(ListUtils.isNotEmpty(list)){
  117. Random rm = new Random();
  118. result = list.get(rm.nextInt(list.size()));
  119. }
  120. return result;
  121. }
  122. /*public static void main(String[] args) {
  123. FormData fd = new FormData();
  124. fd.setEName("1111");
  125. List<ElementData> list = new ArrayList<>();
  126. list.add(new ElementData(1,1,1));
  127. test(fd);
  128. System.out.println(fd.getEName());
  129. }*/
  130. public static void write(FormData fd, Object data,Boolean nullOrBlank ){
  131. if(Func.isEmpty(fd.getValues())){
  132. /*无定位信息不写入*/
  133. return;
  134. }
  135. try {
  136. /*一个单元格且存在多张,全部设置为自动拓展 20230816*/
  137. if(fd.getCoordsList().size()==1&&fd.getValues().size()>1&&fd.getFormula()!=null){
  138. fd.getFormula().setOutm(Formula.FULL);
  139. }
  140. /*写入前清空内容*/
  141. fd.getValues().forEach(t->t.setValue(null));
  142. if(data instanceof List){
  143. List<Object> values = (List<Object>) data;
  144. if(!nullOrBlank){
  145. values=values.stream().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
  146. }
  147. if(values.size()>fd.getValues().size()){
  148. /*当生成的数据超过实际容量的时候,会自动追加页数*/
  149. if(fd.getCoordsList().size()==1){
  150. if(values.stream().filter(CustomFunction::containsZH).anyMatch(e->e.toString().contains("\n"))){
  151. fd.getValues().get(0).setValue(values.stream().filter(Objects::nonNull).map(Object::toString).collect(Collectors.joining()));
  152. }else{
  153. /*日期类型的元素只获取最后一个非空*/
  154. if(StringUtils.isEquals(4,fd.getEType())){
  155. fd.getValues().get(0).setValue(values.stream().filter(StringUtils::isNotEmpty).reduce((first, second) -> second).orElse(null));
  156. }else{
  157. fd.getValues().get(0).setValue(values.stream().map(StringUtils::handleNull).collect(Collectors.joining("、")));
  158. }
  159. }
  160. }else{
  161. // copy(fd,values);
  162. for(int n=0;n<fd.getValues().size();n++){
  163. fd.getValues().get(n).setValue(values.get(n));
  164. }
  165. List<Object> overList=values.stream().skip(fd.getValues().size()).collect(Collectors.toList());
  166. List<Coords> coordsList = fd.getCoordsList();
  167. int addPage=(int)Math.ceil((double)overList.size()/(double)coordsList.size());
  168. fd.setAddPages(addPage);
  169. ElementData last =fd.getValues().get(fd.getValues().size()-1);
  170. int indexBase=last.getIndex()+1;
  171. List<ElementData> addList= new ArrayList<>();
  172. for(int i=0;i<addPage;i++){
  173. for(int j=0;j<coordsList.size();j++){
  174. /*超页就尽管写进去,格式化阶段再加表*/
  175. Coords coords = coordsList.get(j);
  176. Object v=null;
  177. int st=i*coordsList.size()+j;
  178. if(st<overList.size()){
  179. v= overList.get(st);
  180. }
  181. addList.add(new ElementData(indexBase+i,last.getGroupId(),v,coords.getX(),coords.getY()));
  182. }
  183. }
  184. fd.getValues().addAll(addList);
  185. }
  186. }else{
  187. for(int n=0;n<values.size();n++){
  188. fd.getValues().get(n).setValue(values.get(n));
  189. }
  190. }
  191. }else{
  192. if(Formula.FULL.equals(fd.getFormula().getOutm())){
  193. /*填充策略*/
  194. fd.getValues().forEach(e->e.setValue(data));
  195. }else{
  196. fd.getValues().get(0).setValue(data);
  197. }
  198. }
  199. fd.setUpdate(1);
  200. }catch (Exception e){
  201. e.printStackTrace();
  202. }
  203. }
  204. /**从元素名称中解析项目名称,细化项目匹配用*/
  205. public static String parseItemName(String eName){
  206. if (StringUtils.isEmpty(eName)) {
  207. return eName;
  208. }
  209. String str = eName.replaceAll("\\s", "");
  210. Pattern pattern = compile("[((_]");
  211. String[] candidate = pattern.split(str);
  212. String regex = "[^\\u4e00-\\u9fa5]+";
  213. Pattern p = compile(regex);
  214. return Arrays.stream(candidate)
  215. .filter(s -> !isContainKeywords(s))
  216. .map(s -> filterString(s, p))
  217. .collect(Collectors.joining());
  218. }
  219. /*A15检查内容专用*/
  220. public static String checkItemName(String eName){
  221. if (StringUtils.isEmpty(eName)) {
  222. return eName;
  223. }
  224. /*分割字符串,选取第一个匹配的子串*/
  225. String str = eName.replaceAll("\\s", "");
  226. Pattern pattern = compile("[((_]");
  227. String[] candidate = pattern.split(str);
  228. String regex = "[^\\u4e00-\\u9fa5]+";
  229. return Arrays.stream(candidate).map(s->s.replaceAll(regex,"")).distinct().filter(StringUtils::isNotEmpty).filter(s->!isContainKeywords2(s)).findFirst().orElse("");
  230. }
  231. private static String filterString(String s, Pattern p) {
  232. s=s.replaceAll("【[^【】]+】","");
  233. Matcher matcher = p.matcher(s);
  234. return matcher.replaceAll("").replaceAll(getRegex(), "").replaceAll("(设计|合格).*","");
  235. }
  236. private static String getRegex() {
  237. return "(在合格标准内|满足设计要求|质量评定|评定|判定|项目|总数|抽测|实测|偏差|尺量)";
  238. }
  239. private static boolean isContainKeywords(String s) {
  240. List<String> keywords = Arrays.asList( ":", "个","附录","抽查","测","求","小于","大于","检查","仪","按","不","各","记录","且","规定","值或实");
  241. return keywords.stream().anyMatch(s::contains);
  242. }
  243. private static boolean isContainKeywords2(String s) {
  244. List<String> keywords = Arrays.asList( "实测项目");
  245. return keywords.stream().anyMatch(s::contains);
  246. }
  247. /*回归·测试变量*/
  248. public static List<String> itemNames =Arrays.asList(
  249. ""
  250. ,"压 实 度 (%)下路床 特重、极重交通荷载等级 设计值"
  251. ,"1△_压 实 度 (%)_下路床_轻、中及重交通 荷载等级_0.3m~0.8m_≧96_≧95_≧94_实测值或实测偏差值"
  252. ,"1△_压 实 度 (%)_下路提_轻、中及重交通 荷载等级_&gt;1.5m_≧93_≧92_≧90_实测值或实测偏差值"
  253. ,"1△_压 实 度 (%)_上路提_轻、中及重交通 荷载等级_0.8m~1.5m_≧94_≧94_≧93_实测值或实测偏差值"
  254. ,"压 实 度 (%)下路提 轻、中及重交通荷载等级 设计值"
  255. ,"压 实 度 (%)下路床 特重、极重交通荷载等级 合格率"
  256. ,"压 实 度 (%)下路提 轻、中及重交通荷载等级\t合格率"
  257. ,"5△_保护层 厚度 (mm)_基础、锚碇、墩台身、墩柱_±10_实测值或实测偏差值"
  258. ,"钢筋骨架尺寸宽、高或直径 (mm)_尺量:按骨架总数30%抽测_±5_实测值或实测偏差值"
  259. ,"钢筋骨架尺寸长 (mm)_±10_尺量:按骨架总数30%抽测_实测值或实测偏差值"
  260. , "受力钢筋间距 (mm)同排 梁、板、拱肋及拱上建筑 设计值"
  261. ,"受力钢筋间距 (mm)同排 梁、板、拱肋及拱上建筑 合格率"
  262. ," 箍筋、构造钢筋、螺旋筋间距(mm) 设计值"
  263. ,"箍筋、构造钢筋、螺旋筋间距(mm) 合格率"
  264. ,"实测项目_桩位 (mm)_群桩_≤100_质量评定_合格判定"
  265. ,"实测项目_桩位 (mm)_群桩_≤100_实测值或实测偏差值"
  266. ,"实测项目_桩位 (mm)_排架桩_实测值或实测偏差值"
  267. ,"实测项目_桩位 (mm)_排架桩_质量评定_合格判定"
  268. ,"实测项目_桩位 (mm)_群桩_≤100_质量评定_合格率(%)"
  269. ,"实测项目_桩位 (mm)_排架桩_质量评定_合格率(%)"
  270. ,"3△_支座高程(mm)_满足设计要求;设 计未要求时±5_水准仪:测每支座中心线_实测值或实测偏差值"
  271. ,"基底承载力(KPa)_不小于设计_直观或动力触探试验_实测值或实测偏差值"
  272. ,"实 测 项 目_花卉数量_满足设计要求_实测值或实测偏差值"
  273. ,"实 测 项 目_2△_草坪、草本地被覆盖率(%)_取弃土场绿 地_≥90_实测值或实测偏差值"
  274. ,"轴线偏位(mm)_全站仪:20m检查3点_实测值或实测偏差值"
  275. ,"1△_基材混合物喷射厚度(mm)_设计厚度±10_实测值或实测偏差值"
  276. ,"1△_混凝土强度 (MPA)_在合格标准内_按附录D检查_实测值或实测偏差值"
  277. ,"边坡坡度_不陡于设计值_水准仪:每200m测2点,且不少于5点_实测值或实测偏差值"
  278. ,"几何尺寸(mm)_±50_尺量:长、宽、高、壁厚各2点_实测值或实测偏差值"
  279. ,"4△_桩长(mm)_不小于设计_查施工记录_实测值或偏差值"
  280. ,"单桩每延米喷粉 (浆)量_不小于设计_查施工记录_实测值或偏差值"
  281. ,"搭接宽度(mm)_≥150【纵向】_尺量:抽查2%_实测值或实测偏差值",
  282. "搭接宽度(mm)_≥50(横向)_尺量:抽查2%_实测值或实测偏差值"
  283. ,"竖直度(mm)_挖孔桩_0.5%桩长,且≤200_铅锤线:每桩检测_实测值或实测偏差值"
  284. , "2△_压浆压力值 (Mpa)_满足施工技术 规范规定_查油压表读书;每管道检查_实测值或实测偏差值"
  285. , "基底承载力(KPa)_不小于设计_实测值或实测偏差值"
  286. ,"1△_受力钢筋间距 (mm)_两排以上间距_±5_实测值或实测偏差值"
  287. );
  288. /* public static void main(String[] args) {
  289. // itemNames.stream().map(FormulaUtils::parseItemName).forEach(System.out::println);
  290. itemNames.stream().map(FormulaUtils::checkItemName).forEach(System.out::println);
  291. }*/
  292. public static Object getValue(Cell cell) {
  293. if (cell != null) {
  294. switch (cell.getCellTypeEnum()) {
  295. case STRING:
  296. return cell.getStringCellValue() == null ? null : cell.getStringCellValue().trim();
  297. case NUMERIC:
  298. HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
  299. return dataFormatter.formatCellValue(cell);
  300. case BOOLEAN:
  301. return cell.getBooleanCellValue();
  302. case ERROR:
  303. return cell.getErrorCellValue();
  304. case FORMULA:
  305. try {
  306. return cell.getStringCellValue();
  307. } catch (IllegalStateException e) {
  308. return cell.getNumericCellValue();
  309. }
  310. default:
  311. cell.setCellType(CellType.STRING);
  312. return cell.getStringCellValue() == null ? null : cell.getStringCellValue().trim();
  313. }
  314. }
  315. return null;
  316. }
  317. public static List<ElementData> getElementDataList(String coords,String values){
  318. if(StringUtils.isNotEmpty(coords,values)){
  319. List<Coords> coordsList = Stream.of(coords).flatMap(s -> Arrays.stream(s.split(";"))).map(s -> {
  320. String[] xy = s.split("_");
  321. return new Coords(xy[1], xy[0]);
  322. }).collect(Collectors.toList());
  323. return str2ElementData(values,coordsList,null,null);
  324. }
  325. return Collections.emptyList();
  326. }
  327. public static List<ElementData> str2ElementData(String pg, List<Coords> coordsList ,String code,Integer index){
  328. List<ElementData> eds = new ArrayList<>();
  329. if(StringUtils.isNotEmpty(pg)&&ListUtils.isNotEmpty(coordsList)) {
  330. if(code==null){
  331. code="code";
  332. }
  333. if(index==null){
  334. index=1;
  335. }
  336. String[] val = pg.split("☆");
  337. Map<String, Object> tmpMap = new LinkedHashMap<>();
  338. for (String s : val) {
  339. String[] t = s.split("_\\^_");
  340. String[] c = t[1].split("_");
  341. tmpMap.put(StringUtils.join(code, 0, index, Func.toInt(c[1]), Func.toInt(c[0]), StringPool.AT), t[0]);
  342. }
  343. for (Coords c : coordsList) {
  344. Object data = null;
  345. String key = StringUtils.join(code, 0, index, c.getX(), c.getY(), StringPool.AT);
  346. if (tmpMap.containsKey(key)) {
  347. data = tmpMap.get(key);
  348. }
  349. eds.add(new ElementData(index, 0, data, c.getX(), c.getY()));
  350. }
  351. }
  352. return eds;
  353. }
  354. /**
  355. * @Description Poi 动态执行公式 测试
  356. * @Param [url]
  357. * @Author yangyj
  358. * @Date 2023.05.05 14:28
  359. **/
  360. public static void evaluateFormulaCell(String url) {
  361. try {
  362. url="C:/Users/yangyj/Desktop/test.xlsx";
  363. Workbook workbook = WorkbookFactory.create(new File(url));
  364. Sheet sheet = workbook.getSheetAt(0);
  365. Cell cell = sheet.getRow(0).getCell(0);
  366. FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  367. CellType cellType = evaluator.evaluateFormulaCellEnum(cell);
  368. if (cellType == CellType.NUMERIC) {
  369. double value = cell.getNumericCellValue();
  370. System.out.println("公式计算结果:" + value);
  371. } else if (cellType == CellType.STRING) {
  372. String value = cell.getStringCellValue();
  373. System.out.println("公式计算结果:" + value);
  374. }
  375. cell.setCellFormula("B1+C1+D1");
  376. evaluator.clearAllCachedResultValues();
  377. cellType = evaluator.evaluateFormulaCellEnum(cell);
  378. if (cellType == CellType.NUMERIC) {
  379. double value = cell.getNumericCellValue();
  380. System.out.println("公式计算结果:" + value);
  381. } else if (cellType == CellType.STRING) {
  382. String value = cell.getStringCellValue();
  383. System.out.println("公式计算结果:" + value);
  384. }
  385. }catch (IOException | InvalidFormatException e){
  386. e.printStackTrace();
  387. }
  388. }
  389. public static Map<String, String> getElementCell(String uri){
  390. return getElementCell(uri,null);
  391. }
  392. public static Map<String, String> getElementCell(String uri,String key) {
  393. try {
  394. InputStream inputStreamByUrl = FileUtils.getInputStreamByUrl(uri);
  395. String filter=" [keyname]";
  396. if(Func.isNotBlank(key)){
  397. filter="[keyname^="+key+"__]";
  398. }
  399. Document document=Jsoup.parse(IoUtil.readToString(inputStreamByUrl));
  400. Map<String,String> result= document
  401. .select("table").first()
  402. .select(filter).stream()
  403. .map(d -> d.attr("keyname")).filter(StringUtils::isNotEmpty).map(e -> e.split("__"))
  404. .collect(
  405. Collectors.toMap(
  406. b -> b[0],
  407. b -> b[1],
  408. (v1, v2) -> v1 + ";" + v2
  409. )
  410. );
  411. if(result.size()>0){
  412. for(Map.Entry<String,String> entry:result.entrySet()){
  413. entry.setValue(FormulaUtils.coordsSorted(entry.getValue()));
  414. }
  415. }
  416. return result;
  417. }catch (Exception e){
  418. e.printStackTrace();
  419. return new HashMap<>();
  420. }
  421. }
  422. public static List<ElementData> setScale(Integer scale, List<ElementData> data){
  423. if(scale==null){
  424. scale=StringUtils.getScale(data.stream().map(ElementData::getValue).filter(StringUtils::isDouble).collect(Collectors.toList()));
  425. }
  426. Integer finalScale = scale;
  427. return data.stream().peek(e->{if(StringUtils.isDouble(e.getValue())){e.setValue(StringUtils.number2StringZero(e.getValue(),finalScale));}}).collect(Collectors.toList());
  428. }
  429. /* public static void main(String[] args) {
  430. Map<String,String> map=getElementCell("/www/wwwroot/Users/hongchuangyanfa/Desktop/privateUrl/1694630551069130752.html","key_22");
  431. System.out.println(map);
  432. }*/
  433. /**
  434. * @Description 定位信息排序
  435. * @Param [coords]
  436. * @return java.lang.String
  437. * @Author yangyj
  438. * @Date 2023.07.11 15:39
  439. **/
  440. public static String coordsSorted(String coords){
  441. if(StringUtils.isNotEmpty(coords)){
  442. List<String> dataList=Arrays.asList(coords.split(";"));
  443. if(dataList.size()>2){
  444. LinkedList<Integer> list=dataList.stream().map(e->e.split("_")[1]).distinct().map(Integer::parseInt).sorted(Comparator.comparingInt(e->e)).collect(Collectors.toCollection(LinkedList::new));
  445. if(list.getLast()-list.getFirst()>list.size()-1){
  446. coords=dataList.stream()
  447. .sorted(Comparator.comparingInt((String str) -> Integer.parseInt(str.split("_")[1]))
  448. .thenComparingInt(str -> Integer.parseInt(str.split("_")[0])))
  449. .collect(Collectors.joining(";"));
  450. }
  451. }
  452. }
  453. return coords;
  454. }
  455. public static String coordsSorted2(String coords){
  456. if(StringUtils.isNotEmpty(coords)){
  457. List<String> dataList=Arrays.asList(coords.split(";"));
  458. if(dataList.size()>2){
  459. /*判断分区:根据行列长度*/
  460. List<Integer> row =dataList.stream().map(e->e.split("_")[0]).distinct().map(Integer::parseInt).collect(Collectors.toList());
  461. List<Integer> column=dataList.stream().map(e->e.split("_")[1]).distinct().map(Integer::parseInt).collect(Collectors.toList());
  462. if(row.size()>=column.size()){
  463. /*纵向*/
  464. if(column.size()>1){
  465. List<List<Integer>> consecutiveGroups = IntStream.range(0, column.size())
  466. .boxed()
  467. .collect(Collectors.collectingAndThen(
  468. Collectors.groupingBy(
  469. i -> i - column.get(i),
  470. LinkedHashMap::new,
  471. Collectors.mapping(column::get, Collectors.toList())
  472. ),
  473. map -> new ArrayList<>(map.values())
  474. ));
  475. }
  476. }
  477. /* 确定区内方向:*/
  478. }
  479. }
  480. return coords;
  481. }
  482. /* public static void main(String[] args) {
  483. List<Integer> column = Arrays.asList(1, 2, 3, 5, 6, 7, 9, 11, 17);
  484. List<List<Integer>> consecutiveGroups = IntStream.range(0, column.size())
  485. .boxed()
  486. .collect(Collectors.collectingAndThen(
  487. Collectors.groupingBy(
  488. i -> i - column.get(i),
  489. LinkedHashMap::new,
  490. Collectors.mapping(column::get, Collectors.toList())
  491. ),
  492. map -> new ArrayList<>(map.values())
  493. ));
  494. AtomicInteger i = new AtomicInteger(column.get(0));
  495. List<List<Integer>> consecutiveGroups2= new ArrayList<>(column.stream().collect(Collectors.groupingBy(e -> e - i.getAndSet(e) > 1, LinkedHashMap::new, Collectors.toList())).values());
  496. System.out.println();
  497. }*/
  498. public static List<Object> slice(List<LocalVariable> local, String formula){
  499. int min =0;
  500. List<Object> result = new ArrayList<>();
  501. try {
  502. pretreatment(local,formula);
  503. List<Object> r= local.stream().map(e-> {
  504. /*所有依赖元素的内容必须非空才进行计算,否则返回空值*/
  505. return e.hasEmptyElementValue()?"": Expression.parse(e.getFormula()).calculate(e.getCurrentMap()).toString();
  506. }).collect(Collectors.toList());
  507. if(CollectionUtil.isNotEmpty(r)&&r.stream().anyMatch(StringUtils::isNotEmpty)){
  508. result.addAll(r);
  509. }
  510. }catch (Exception e){
  511. StaticLog.error("公式:{},执行出错",formula);
  512. }
  513. return result;
  514. }
  515. public static void pretreatment(List<LocalVariable> local,String formula){
  516. formula=StringUtils.removeMultiSpace(formula);
  517. if(formula.contains("LIST")){
  518. Matcher m=RegexUtils.matcher("\\(([^)]*)\\)/LIST",formula);
  519. while (m.find()){
  520. List<String> codes=getCodeList(m.group(1).replaceAll("[+-]",","));
  521. local=local.stream().peek(e->{
  522. @SuppressWarnings("unckecked")
  523. Map<String,Object> map = (Map<String, Object>) e.getCurrentMap().getOrDefault("E",new HashMap<>());
  524. int listSize=(int)codes.stream().filter(c->StringUtils.isNotEmpty(map.get(c))).count();
  525. if(listSize<=0||listSize>codes.size()){
  526. listSize=codes.size();
  527. }
  528. map.put("LIST",listSize);
  529. }).collect(Collectors.toList());
  530. }
  531. }
  532. }
  533. /**从方法参数中获取全部code*/
  534. public static List<String> getCodeList(String param){
  535. List<String> list = new ArrayList<>();
  536. if(StringUtils.isNotEmpty(param)){
  537. Arrays.stream(param.split(",")).forEach(s->{
  538. list.add(s.replaceAll("[E\\[\\]']",""));
  539. });
  540. }
  541. return list;
  542. }
  543. /**从时间段中获取最后一个日期*/
  544. static final String RANGE_DATE_REG="^\\[(\\d{4}[年.\\-]\\d{2}[月.\\-]\\d{2}[日]?),\\s+(\\d{4}[年.\\-]\\d{2}[月.\\-]\\d{2}[日]?)]$";
  545. public static String range2end(String t){
  546. if(t!=null&&Pattern.matches(RANGE_DATE_REG,t)){
  547. t=t.replaceAll("^\\[|]$","").split(",")[1].trim();
  548. }
  549. return t;
  550. }
  551. public static FormData createFormDataFast(String name,String code,String values,String coords){
  552. if(StringUtils.isNotEmpty(code,name)){
  553. if(StringUtils.isNotEmpty(coords)) {
  554. /*定位信息存在才合法*/
  555. List<Coords> coordsList = Stream.of(coords).flatMap(s -> Arrays.stream(s.split(";"))).map(s -> {
  556. String[] xy = s.split("_");
  557. return new Coords(xy[1], xy[0]);
  558. }).collect(Collectors.toList());
  559. List<ElementData> eds = new ArrayList<>();
  560. if (StringUtils.isNotEmpty(values)) {
  561. String[] pages = values.split(";;");
  562. for (int index = 0; index < pages.length; index++) {
  563. String pg = pages[index];
  564. if (Func.isNotBlank(pg)) {
  565. String[] val = pg.split("☆");
  566. Map<String, Object> tmpMap = new LinkedHashMap<>();
  567. for (String s : val) {
  568. String[] t = s.split("_\\^_");
  569. String[] c = t[1].split("_");
  570. tmpMap.put(StringUtils.join(code, 0, index, Func.toInt(c[1]), Func.toInt(c[0]), StringPool.AT), t[0]);
  571. }
  572. for (Coords c : coordsList) {
  573. Object data = null;
  574. String key = StringUtils.join(code, 0, index, c.getX(), c.getY(), StringPool.AT);
  575. if (tmpMap.containsKey(key)) {
  576. data = tmpMap.get(key);
  577. }
  578. eds.add(new ElementData(index, 0, data, c.getX(), c.getY()));
  579. }
  580. }
  581. }
  582. } else {
  583. eds = coordsList.stream().map(c -> new ElementData(0, 0, null, c.getX(), c.getY())).collect(Collectors.toList());
  584. }
  585. FormData one = new FormData(code, eds, null, coords);
  586. one.setEName(name);
  587. /*备份原始数据,用于更新比较*/
  588. one.init();
  589. return one;
  590. }
  591. }
  592. return null;
  593. }
  594. public static void mainT(String[] args) throws IOException {
  595. XYSeries series = new XYSeries("Data Series");
  596. series.add(10.2, 1.82);
  597. series.add(11.9, 1.86);
  598. series.add(15.9, 1.87);
  599. series.add(19.3, 1.85);
  600. series.add(20.3, 1.80);
  601. XYSeriesCollection dataset = new XYSeriesCollection();
  602. dataset.addSeries(series);
  603. JFreeChart chart = ChartFactory.createXYLineChart(
  604. "测试散点图", // 标题
  605. "X", // 横轴标题
  606. "Y", // 纵轴标题
  607. dataset, // 数据集
  608. PlotOrientation.VERTICAL, // 图表方向
  609. true, // 是否显示图例
  610. false, // 是否生成工具提示
  611. false // 是否生成URL链接
  612. );
  613. // 设置字体
  614. Font titleFont = new Font("SimSun", Font.PLAIN, 18); // 指定使用宋体字体
  615. Font axisFont = new Font("SimSun", Font.PLAIN, 12); // 指定使用宋体字体
  616. // 设置标题字体
  617. TextTitle title = chart.getTitle();
  618. title.setFont(titleFont);
  619. XYPlot plot = (XYPlot) chart.getPlot();
  620. XYSplineRenderer renderer = new XYSplineRenderer();
  621. plot.setRenderer(renderer);
  622. plot.setBackgroundPaint(Color.WHITE);
  623. // Set the line stroke and shape for the renderer
  624. renderer.setSeriesStroke(0, new BasicStroke(2.0f));
  625. Shape circle = new Ellipse2D.Double(-3, -3, 6, 6);
  626. renderer.setSeriesShape(0, circle);
  627. renderer.setSeriesPaint(0, Color.BLUE);
  628. // 自定义 X 轴刻度
  629. NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
  630. domainAxis.setTickUnit(new NumberTickUnit(5)); // 设置刻度间隔
  631. domainAxis.setRange(0.0, 25); // 设置轴的范围
  632. // 自定义 Y 轴刻度
  633. NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
  634. rangeAxis.setTickUnit(new NumberTickUnit(0.01)); // 设置刻度间隔
  635. rangeAxis.setRange(1.79, 1.90); // 设置轴的范围
  636. // 添加横杠
  637. for(int i=175;i<190;i++){
  638. ValueMarker marker = new ValueMarker((double) i /100);
  639. marker.setPaint(Color.BLUE); // 横杠的颜色
  640. plot.addRangeMarker(marker);
  641. }
  642. ChartPanel chartPanel = new ChartPanel(chart);
  643. chartPanel.setPreferredSize(new Dimension(500, 400));
  644. // 保存图表为图片
  645. int width = 800;
  646. int height = 600;
  647. ChartUtils.saveChartAsPNG(new File("C:/Users/yangyj/Desktop/Swap_space/poi_statistics.png"), chart, width, height);
  648. }
  649. /**字符串sha256映射*/
  650. public static String sha256(String input) {
  651. try {
  652. MessageDigest digest = MessageDigest.getInstance("SHA-256");
  653. byte[] encodedHash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
  654. StringBuilder hexString = new StringBuilder();
  655. for (byte b : encodedHash) {
  656. String hex = Integer.toHexString(0xff & b);
  657. if (hex.length() == 1) {
  658. hexString.append('0');
  659. }
  660. hexString.append(hex);
  661. }
  662. return hexString.toString();
  663. } catch (NoSuchAlgorithmException e) {
  664. e.printStackTrace();
  665. }
  666. return "";
  667. }
  668. /**根据步长获取字符*/
  669. public static String getEveryNthChar(String input, int step) {
  670. StringBuilder result = new StringBuilder();
  671. for (int i = 0; i < input.length(); i += step) {
  672. result.append(input.charAt(i));
  673. }
  674. return result.toString();
  675. }
  676. }