Commit 9578bb05 authored by shulidong's avatar shulidong

报告生成基础代码及获取hbase最后一条数据

parent 493d231f
......@@ -231,6 +231,7 @@
<artifactId>jcommon</artifactId>
<version>1.0.24</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
......
......@@ -59,6 +59,11 @@ public class DataPower implements Serializable {
*/
private List<String> value = new ArrayList<>();
private List<String> singleType = new ArrayList<>();
/**
* 量程
*/
private Float measuer;
}
}
package cn.wise.sc.energy.power.plant.business.constant;
/**
* @author neo.shu
* @since 2020/10/6 09:43
*/
public class Constance {
/**
* 摄氏度符号
*/
public static final String CELSIUS = new String(new int[]{0x2103}, 0, 1);
/**
* 目前仅在tableUtil里面插入表格内容时处理了。表示换行
*/
public static final String RETURN = "\n";
public static final String SPLIT = ":";
}
package cn.wise.sc.energy.power.plant.business.controller;
import cn.wise.sc.energy.power.plant.business.domain.vo.AlertInfoVo;
import cn.wise.sc.energy.power.plant.business.utils.poi.DocxService;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
/**
* @description: 阈值更新记录
......@@ -17,8 +21,19 @@ import java.util.List;
@RequestMapping("alertinfo/")
public class AlertInfoController {
@GetMapping
@Autowired
DocxService docxService;
@GetMapping("/test")
public BaseResponse<List<AlertInfoVo>> list(){
try {
docxService.fillDocx();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package cn.wise.sc.energy.power.plant.business.controller;
import lombok.extern.slf4j.Slf4j;
import cn.wise.sc.energy.power.plant.business.domain.AbstractEntity;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.service.IBaseService;
import cn.wise.sc.energy.power.plant.common.core.bean.EntityQuery;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import cn.wise.sc.energy.power.plant.common.core.bean.EntityQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
......
......@@ -9,9 +9,12 @@ import cn.wise.sc.energy.power.plant.business.jna.C2TreeAnalysis;
import cn.wise.sc.energy.power.plant.business.repository.BtreeInfoConfigRepository;
import cn.wise.sc.energy.power.plant.business.utils.BeanUtilsExt;
import cn.wise.sc.energy.power.plant.business.utils.Utils;
import cn.wise.sc.energy.power.plant.business.utils.dfs.FastDFSUtils;
import cn.wise.sc.energy.power.plant.business.utils.poi.DocxService;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
......@@ -24,6 +27,9 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
......@@ -37,6 +43,7 @@ import java.util.concurrent.TimeUnit;
@CrossOrigin
@RestController
@RequestMapping("btreeinspec/")
@Slf4j
public class BtreeInspectionController {
@Autowired
......@@ -161,4 +168,30 @@ public class BtreeInspectionController {
}
@Autowired
protected HttpServletResponse response;
@Autowired
protected HttpServletRequest request;
@Autowired
DocxService docxService;
@PostMapping("/reportDownload")
public BaseResponse fileDownload() {
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment;filename=" + "demo1" + ".docx");
response.setContentType("application/force-download");
out = response.getOutputStream();
byte[] by = docxService.fillDocx();
out.write(by);
out.close();
return BaseResponse.okMsg("成功");
} catch (Exception e) {
log.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
}
package cn.wise.sc.energy.power.plant.business.controller;
import cn.wise.sc.energy.power.plant.business.bean.DataPower;
import cn.wise.sc.energy.power.plant.business.domain.BtreeInfoConfig;
import cn.wise.sc.energy.power.plant.business.domain.CharacterParamInfo;
import cn.wise.sc.energy.power.plant.business.domain.TendencyQuery;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.repository.CharacterParamRepository;
import cn.wise.sc.energy.power.plant.business.service.ICharacterParamService;
import cn.wise.sc.energy.power.plant.business.utils.BeanUtilsExt;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import com.spring4all.spring.boot.starter.hbase.api.HbaseTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -22,10 +27,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.constraints.NotEmpty;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -44,6 +46,9 @@ public class CharacterParamController {
final
ICharacterParamService iCharacterParamService;
@Autowired
CharacterParamRepository characterParamRepository;
final
HbaseTemplate hbaseTemplate;
......@@ -93,4 +98,24 @@ public class CharacterParamController {
return BaseResponse.okData(iCharacterParamService.getFrequencyByUpload(file));
}
@ApiOperation("更新阈值")
@PostMapping("/configUpdate")
public BaseResponse<Boolean> interaction(@RequestBody CharacterParamInfo info) {
CharacterParamInfo config;
if (info.getKksCode() == null) {
config = characterParamRepository.save(info);
} else {
config = characterParamRepository.getOne(info.getKksCode());
BeanUtils.copyProperties(info, config, BeanUtilsExt.getNullPropertyNames(info));
config = characterParamRepository.save(config);
}
if (config.getKksCode() != null) {
return BaseResponse.okData(true);
} else {
return BaseResponse.okData(false);
}
}
}
......@@ -9,6 +9,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotEmpty;
import java.util.List;
......
package cn.wise.sc.energy.power.plant.business.controller;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.energy.power.plant.business.domain.CaseAnalysisInfo;
import cn.wise.sc.energy.power.plant.business.domain.CharacterParamInfo;
import cn.wise.sc.energy.power.plant.business.domain.EventInfo;
import cn.wise.sc.energy.power.plant.business.domain.PageQuery;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.repository.EventInfoRepository;
import cn.wise.sc.energy.power.plant.business.service.IEventInfoService;
import cn.wise.sc.energy.power.plant.business.utils.BeanUtilsExt;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
......@@ -18,12 +30,15 @@ import java.util.List;
**/
@CrossOrigin
@RestController
@RequestMapping("event/info/")
@RequestMapping("eventinfo/")
public class EventInfoController {
final
IEventInfoService iEventInfoService;
@Autowired
EventInfoRepository repository;
public EventInfoController(IEventInfoService iEventInfoService) {
this.iEventInfoService = iEventInfoService;
}
......@@ -38,4 +53,30 @@ public class EventInfoController {
}
}
@PostMapping("/page")
public BaseResponse<Page<EventInfo>> page(@RequestBody PageQuery page) {
return iEventInfoService.page(page);
}
@ApiOperation("更新事件状态")
@PostMapping("/configUpdate")
public BaseResponse<Boolean> interaction(@RequestBody EventInfo info) {
EventInfo config;
if (info.getId() == null) {
config = repository.save(info);
} else {
config = repository.getOne(info.getId());
BeanUtils.copyProperties(info, config, BeanUtilsExt.getNullPropertyNames(info));
config = repository.save(config);
}
if (config.getId() != null) {
return BaseResponse.okData(true);
} else {
return BaseResponse.okData(false);
}
}
}
......@@ -8,6 +8,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotEmpty;
import java.util.List;
......
package cn.wise.sc.energy.power.plant.business.dataware;
import lombok.Builder;
import lombok.Data;
/**
* @author neo.shu
* @since 2020/9/29 22:39
*/
@Data
@Builder
public class PointDataFromHbase {
private String tag;
private long timeStamp;
private String value;
}
package cn.wise.sc.energy.power.plant.business.dataware;
import com.spring4all.spring.boot.starter.hbase.api.RowMapper;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.client.Result;
/**
* @author: neo.shu
* @create: 2020-09-29 22:38
**/
public class PointRowKeyMapper implements RowMapper<PointDataFromHbase> {
@Override
public PointDataFromHbase mapRow(Result result, int rowNum) {
Cell cell = (result.rawCells())[0];
//System.out.println("查询到hbase时间戳==============="+cell.getTimestamp());
return PointDataFromHbase.builder().timeStamp(cell.getTimestamp())
.build();
}
}
package cn.wise.sc.energy.power.plant.business.domain;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
import java.time.LocalTime;
/**
* @author neo.shu
* @since 2020/9/28 14:33
*/
@Data
@Entity
@Table(name = "autoInspection")
public class AutoInspection {
private String id;
@Id
private Integer recordid;
private LocalDateTime btreetime;
private Integer grade;
private String plantid;
private String deviceid;
private String typed;
private String unitname;
private String btreename;
private Integer result;
private String diagnosis;
public static void main(String[] args) {
String a = "{\"name\": \"励端\", \"RunoutX\": {\"1X\": 1.47635805606842, \"2X\": 0.04492176324129105, \"3X\": 1.47635805606842}, \"RunoutY\": {\"1X\": 1.47635805606842, \"2X\": 0.04492176324129105, \"3X\": 1.47635805606842}, \"VibrateX\": {\"1X\": 1.47635805606842, \"2X\": 0.04492176324129105, \"3X\": 1.47635805606842}, \"VibrateY\": {\"1X\": 1.47635805606842, \"2X\": 0.04492176324129105, \"3X\": 1.47635805606842}, \"diagnosis\": \"机械不存在故障\"}";
JSONObject jsonObject = JSON.parseObject(a);
jsonObject.get("");
}
}
......@@ -149,6 +149,14 @@ public class CharacterParamInfo extends AbstractEntity<String> implements Serial
@Column(name = "hasderiveparam")
private Integer hasDeriveParam;
private Integer measuringrangerulevalid;
private Float measuringrangeruleminvalue;
private Float measuringrangerulemaxvalue;
private Integer measuringrangeruleexclude;
@Override
public String getId() {
return getKksCode();
......
......@@ -10,6 +10,7 @@ import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
/**
* @description: 事件记录
......@@ -35,7 +36,7 @@ public class EventInfo extends AbstractEntity<Long> {
* 记录时间
*/
@Column(name = "valuetime")
private long valueTime;
private LocalDateTime valueTime;
/**
* 监测特征所属电站的标识
......@@ -110,4 +111,9 @@ public class EventInfo extends AbstractEntity<Long> {
@Column(name = "eventinfo")
private Integer eventInfo;
/**
* 联表查询测点名称
*/
private String cpname;
}
......@@ -24,7 +24,8 @@ public class PageQuery implements Serializable {
private String plantId;
private String startTime;
private String endTime;
private String unitcodeid;
private Integer alertstat;
private String order;
}
......@@ -73,7 +73,8 @@ public class RowKeyMapper implements RowMapper<Oscillogram> {
try {
oscillogram.setStart(Long.parseLong(startTime));
} catch (NumberFormatException ex) {
throw new RuntimeException("HBase这个波形图开始时间不为0");
oscillogram.setStart(System.currentTimeMillis());
//throw new RuntimeException("HBase这个波形图开始时间不为0");
}
return oscillogram;
}
......
......@@ -109,9 +109,18 @@ public class CharacterParamInfoVo extends EntityVo{
private Integer hasDeriveParam;
private List<CharacterParamInfoVo> child;
/**
* 图形
*/
private String function;
private Integer measuringrangerulevalid;
private Float measuringrangeruleminvalue;
private Float measuringrangerulemaxvalue;
private Integer measuringrangeruleexclude;
}
package cn.wise.sc.energy.power.plant.business.opentsdb;
import cn.wise.sc.energy.power.plant.business.config.MyApplicationContextAware;
import cn.wise.sc.energy.power.plant.business.dataware.PointDataFromHbase;
import cn.wise.sc.energy.power.plant.business.dataware.PointRowKeyMapper;
import cn.wise.sc.energy.power.plant.business.domain.CharacterParamInfo;
import cn.wise.sc.energy.power.plant.business.domain.Oscillogram;
import cn.wise.sc.energy.power.plant.business.domain.RowKeyMapper;
import cn.wise.sc.energy.power.plant.business.domain.vo.CharacterParamInfoVo;
import cn.wise.sc.energy.power.plant.business.opentsdb.bean.PutRequestExt;
import cn.wise.sc.energy.power.plant.business.opentsdb.bean.QueryRequestExt;
import cn.wise.sc.energy.power.plant.business.utils.OkHttpClientUtil;
import com.alibaba.fastjson.JSON;
import com.spring4all.spring.boot.starter.hbase.api.HbaseTemplate;
import net.opentsdb.client.api.Endpoint;
import net.opentsdb.client.api.annotation.request.CreateAnnotationRequest;
import net.opentsdb.client.api.annotation.request.DeleteAnnotationRequest;
......@@ -33,6 +39,7 @@ import net.opentsdb.client.bean.LastDataPointQuery;
import net.opentsdb.client.bean.QueryResult;
import net.opentsdb.client.util.JsonUtil;
import okhttp3.Response;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
......@@ -211,14 +218,53 @@ public class OpentsdbOkHttpClient {
.build();
}
public static Long queryLast(List<CharacterParamInfoVo> characterParamInfoVos) {
QueryLastRequest queryLastRequest = new QueryLastRequest();
/* QueryLastRequest queryLastRequest = new QueryLastRequest();
List<LastDataPointQuery> list = new ArrayList<>();
characterParamInfoVos.stream().forEach(info -> {
list.add(LastDataPointQuery.builder().metric(info.getKksCode()).build());
});
queryLastRequest.setQueries(list);
QueryLastResponse queryLastResponse;
try {
queryLastResponse = OpentsdbOkHttpClient.queryLast(queryLastRequest);
List<LastDataPoint> results = queryLastResponse.getResults();
final Long[] latestTime = {0L};
if (!CollectionUtils.isEmpty(results)) {
results.stream().forEach(result -> {
if (latestTime[0] < result.getTimestamp()) {
latestTime[0] = result.getTimestamp();
}
});
return latestTime[0];
} else {
return System.currentTimeMillis();
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}*/
HbaseTemplate hbaseTemplate = (HbaseTemplate) MyApplicationContextAware.getApplicationContext().getBean("hbaseTemplate");
try {
PointDataFromHbase pointDataFromHbase = hbaseTemplate.get("thermalpower-plant-point-data", characterParamInfoVos.get(0).getKksCode(), new PointRowKeyMapper());
return pointDataFromHbase.getTimeStamp();
} catch (Exception e) {
return System.currentTimeMillis();
}
}
public static Long queryLastBykks(List<String> kkscodes) {
/*QueryLastRequest queryLastRequest = new QueryLastRequest();
List<LastDataPointQuery> list = new ArrayList<>();
kkscodes.stream().forEach(value -> {
list.add(LastDataPointQuery.builder().metric(value).build());
});
queryLastRequest.setQueries(list);
QueryLastResponse queryLastResponse;
try {
queryLastResponse = OpentsdbOkHttpClient.queryLast(queryLastRequest);
List<LastDataPoint> results = queryLastResponse.getResults();
......@@ -239,7 +285,16 @@ public class OpentsdbOkHttpClient {
} catch (URISyntaxException e) {
e.printStackTrace();
}
return 0L;
return 0L;*/
HbaseTemplate hbaseTemplate = (HbaseTemplate) MyApplicationContextAware.getApplicationContext().getBean("hbaseTemplate");
try {
PointDataFromHbase pointDataFromHbase = hbaseTemplate.get("thermalpower-plant-point-data", kkscodes.get(0), new PointRowKeyMapper());
return pointDataFromHbase.getTimeStamp();
} catch (Exception e) {
return System.currentTimeMillis();
}
}
/**
......
package cn.wise.sc.energy.power.plant.business.poi;
import java.util.ArrayList;
import java.util.HashMap;
import cn.afterturn.easypoi.entity.ImageEntity;
/**
* @author 何昌杰
*/
public class WordDemo1 {
public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>(4);
long startTime = System.currentTimeMillis();
//模拟饼状图数据
HashMap<String, Integer> datas = new HashMap<>(3);
datas.put("一号",10);
datas.put("二号",20);
datas.put("三号",40);
ImageEntity imageEntity = JfreeUtil.pieChart("测试",datas, 500, 300);
map.put("picture", imageEntity);
//模拟其它普通数据
map.put("username", "张三");
map.put("date", "2019-10-10");
map.put("desc", "测试");
map.put("boo", true);
//模拟表格数据
ArrayList<HashMap<String, String>> list = new ArrayList<>(2);
HashMap<String, String> temp = new HashMap<>(3);
temp.put("sn","1");
temp.put("name","第一个人");
temp.put("age","23");
list.add(temp);
for (int i = 0; i < 100; i++) {
temp = new HashMap<>(3);
temp.put("sn","2");
temp.put("name","第二个人");
temp.put("age","24");
list.add(temp);
}
map.put("personlist",list);
//word模板相对路径、word生成路径、word生成的文件名称、数据源
WordUtil.exportWord("C:\\Users\\admin\\Desktop\\template\\demo1.docx", "D:/", "生成文件.docx", map);
System.out.println(System.currentTimeMillis()-startTime);
}
}
\ No newline at end of file
package cn.wise.sc.energy.power.plant.business.repository;
import cn.wise.sc.energy.power.plant.business.domain.AlertInfo;
import cn.wise.sc.energy.power.plant.business.domain.AutoInspection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @description: 阈值更新记录仓储
* @author: neo.shu
* @create: 2020-10-06 14:41
**/
@Repository
public interface AutoInspectionRepository extends
JpaRepository<AutoInspection, Integer>,
JpaSpecificationExecutor<AutoInspection> {
List<AutoInspection> findAutoInspectionsById(String id);
}
......@@ -25,6 +25,6 @@ public interface EventInfoRepository extends
* @return list
*/
@Query(value = "SELECT COUNT(e.alertStat) as count, e.alertStat, e.deviceId FROM EventInfo as e" +
" where e.alertStat > 1 and e.alertStat < 5 GROUP BY e.alertStat,e.deviceId")
" where e.alertStat > 1 and e.alertStat < 6 GROUP BY e.alertStat,e.deviceId")
List<Object[]> countAlert();
}
......@@ -48,10 +48,10 @@ public class JWTFilter extends BasicAuthenticationFilter {
final String token = this.getToken(request);
//设置websocket 子协议头
response.setHeader("Sec-WebSocket-Protocol",request.getHeader("Sec-WebSocket-Protocol"));
/*if(true){
if(true){
filterChain.doFilter(request, response);
return;
}*/
}
if(request.getServletPath().contains("/login")||request.getServletPath().contains("/plantInfo/allPlantInfo")){
filterChain.doFilter(request, response);
return;
......
package cn.wise.sc.energy.power.plant.business.service;
import cn.wise.sc.energy.power.plant.business.domain.EventInfo;
import cn.wise.sc.energy.power.plant.business.domain.PageQuery;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.service.impl.EventInfoServiceImpl;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import org.springframework.data.domain.Page;
import java.util.List;
/**
......@@ -31,4 +35,6 @@ public interface IEventInfoService extends IBaseService<Long, EventInfo> {
* @return 报警记录
*/
List<EventInfo> getList(List<String> kKSCodes);
BaseResponse<Page<EventInfo>> page(PageQuery page);
}
......@@ -30,6 +30,7 @@ import lombok.extern.slf4j.Slf4j;
import net.opentsdb.client.api.query.response.QueryResponse;
import net.opentsdb.client.bean.Aggregator;
import net.opentsdb.client.bean.QueryResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
......@@ -362,10 +363,11 @@ public class CharacterParamServiceImpl extends BaseServiceImpl<String, Character
}
return in;
});
//如果时间传0 默认取最后一条数据向前推1h
//如果时间传0 查最后一条 往前推30min
if (timeModelQuery.getStart() == 0 || timeModelQuery.getEnd() == 0) {
timeModelQuery.setStart(1597456800000L);
timeModelQuery.setEnd(1597460400000L);
long lastTime = OpentsdbOkHttpClient.queryLastBykks(keys);
timeModelQuery.setStart(lastTime-1*3600*1000);
timeModelQuery.setEnd(lastTime);
// QueryLastRequest queryLastRequest = new QueryLastRequest();
// LastDataPointQuery lastDataPointQuery = new LastDataPointQuery();
......@@ -455,8 +457,9 @@ public class CharacterParamServiceImpl extends BaseServiceImpl<String, Character
System.out.println("============rowKey=============");
for (String kKSCode : kksCodes) {
System.out.println(getRowKey(kKSCode));
Oscillogram oscillogram = hbaseTemplate.get(tableName, getRowKey(kKSCode),
Oscillogram oscillogram = hbaseTemplate.get(tableName, kKSCode.toLowerCase(),
new RowKeyMapper());
if (oscillogram != null) {
oscillogramList.add(oscillogram);
}
......@@ -671,8 +674,14 @@ public class CharacterParamServiceImpl extends BaseServiceImpl<String, Character
String str = "时间\t1F定子上下线棒层间温度1A\t1F定子上下线棒层间温度2A";
String[] split = str.split("\t");
System.out.println(split[1]);
}
double a = 23;
double b = Double.parseDouble(a + "" + "02");
String substring = "C0A00101MKA12CY614R".substring("C0A00101MKA12CY614R".length() - 1);
System.out.println( StrUtil.swapCase(substring + "C0A00101MKA12CY614R"));
System.out.println("C0A00101MKA12CY614R".toLowerCase());
System.out.println(b);
}
private DataPower buildDataPower(List<QueryResult> results,
List<CharacterParamInfo> characterParamInfos) {
......@@ -721,6 +730,8 @@ public class CharacterParamServiceImpl extends BaseServiceImpl<String, Character
return StrUtil.swapCase(substring + kKSCode);
}
/**
* 拼装报警点
*
......
package cn.wise.sc.energy.power.plant.business.service.impl;
import cn.wise.sc.energy.power.plant.business.domain.CaseAnalysisInfo;
import cn.wise.sc.energy.power.plant.business.domain.DeviceInfo;
import cn.wise.sc.energy.power.plant.business.domain.EventInfo;
import cn.wise.sc.energy.power.plant.business.domain.PageQuery;
import cn.wise.sc.energy.power.plant.business.domain.vo.EntityVo;
import cn.wise.sc.energy.power.plant.business.repository.DeviceInfoRepository;
import cn.wise.sc.energy.power.plant.business.repository.EventInfoRepository;
import cn.wise.sc.energy.power.plant.business.service.IEventInfoService;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
......@@ -43,17 +55,17 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
List<Object[]> objects = eventInfoRepository.countAlert();
List<AlertCount> rts = new ArrayList<>();
Map<String,AlertCount> tendencyAlertMap =new HashMap<>();
for (Object[] objs : objects) {
//countAlert()查询2个字段 count()、alertState
if (objs.length != 2) {
/* if (objs.length != 2) {
continue;
}
}*/
Long count = (long) objs[0];
Integer state = (int) objs[1];
String deviceId = (String) objs[2];
Optional<DeviceInfo> byId = deviceInfoRepository.findById(deviceId);
if (byId.isPresent()) {
if (!byId.isPresent()) {
continue;
}
String deviceName = byId.get().getDeviceName();
......@@ -62,12 +74,17 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
alertCount = new AlertCount("preAlert", deviceName, count);
} else if (state == 3) {
alertCount = new AlertCount("tallAlert", deviceName, count);
} else {
} else if(state==4){
alertCount = new AlertCount("tooTallAlert", deviceName, count);
}else{
//趋势报警 5,6加和
alertCount = tendencyAlertMap.getOrDefault(deviceName, new AlertCount("tendencyAlert"));
alertCount.setCount(alertCount.getCount() + count);
alertCount.setDeviceName(deviceName);
tendencyAlertMap.put(deviceName, alertCount);
}
rts.add(alertCount);
}
return rts;
}
......@@ -106,7 +123,34 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
});
}
@Override
public BaseResponse<Page<EventInfo>> page(PageQuery page) {
Sort sort = Sort.by(Sort.Direction.DESC, "valueTime");
if (page.getOrder() != null && !page.getOrder().trim().equals("")) {
sort = Sort.by(Sort.Direction.DESC, page.getOrder());
}
Pageable pages = PageRequest.of(page.getPageNo(), page.getPageSize(), sort);
Page<EventInfo> infoPage;
Specification<EventInfo> specification = (root, query, cb) -> {
List<Predicate> list = new ArrayList<Predicate>();
//搜索
if (!StringUtils.isEmpty(page.getUnitcodeid())) {
list.add(cb.equal(root.get("unitCodeId").as(String.class), page.getUnitcodeid()));
}
//搜索
if (page.getAlertstat()!=null) {
list.add(cb.equal(root.get("alertStat").as(Integer.class), page.getAlertstat()));
}
return cb.and(list.toArray(new Predicate[list.size()]));
};
infoPage = eventInfoRepository.findAll(specification, pages);
return BaseResponse.okData(infoPage);
}
@Data
@NoArgsConstructor
public static class AlertCount {
public AlertCount(String alertLevel, String deviceName, Long count) {
this.alertLevel = alertLevel;
......@@ -114,6 +158,9 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
this.count = count;
}
public AlertCount(String alertLevel) {
this.alertLevel = alertLevel;
}
/**
* 报警级别
*/
......@@ -127,6 +174,6 @@ public class EventInfoServiceImpl extends BaseServiceImpl<Long, EventInfo> imple
/**
* 对应报警次数
*/
private Long count;
private Long count=0L;
}
}
......@@ -57,7 +57,7 @@ public class HydrogeSystem1Task extends ScheduleTask {
//向每个webSocket推送系统实时数据
for (String deviceId : groupMap.keySet()) {
List<CharacterParamInfoVo> characterParamInfoVos = taskCacheDataService.cacheHydrogeCha(deviceId);
Map<String, String> KKsCodes = characterParamInfoVos.stream().filter(item -> IS_CONTAINS(item.getCpName(), new String[]{"汽端发电机冷氢温度"})).collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpName));
Map<String, String> KKsCodes = characterParamInfoVos.stream().filter(item -> IS_CONTAINS(item.getCpName(), new String[]{"汽端冷氢温度"})).collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpName));
Long lastTime = OpentsdbOkHttpClient.queryLast(characterParamInfoVos);
QueryResponse response = iCharacterParamService
......@@ -75,7 +75,7 @@ public class HydrogeSystem1Task extends ScheduleTask {
finalList.add(item.toString());
});
powerPoints.setValue(finalList);
if (KKsCodes.get(queryResult.getMetric()).contains("汽端发电机冷氢温度")) {
if (KKsCodes.get(queryResult.getMetric()).contains("汽端冷氢温度")) {
DataPower dataPower = map.getOrDefault("rightBottom", new DataPower());
dataPower.setXAxis(xAxis);
dataPower.getDataList().add(powerPoints);
......
......@@ -51,7 +51,7 @@ public class HydrogeSystem3Task extends ScheduleTask {
}
//给每个deviceid分组,然后统一查询,进行推送
Map<String, List<Map.Entry<String, String>>> groupMap = deviceMap.entrySet().stream().collect(Collectors.groupingBy(c -> c.getValue()));
String[] measure_points = new String[]{"发电机机内氢压", "机内氢气湿度", "漏氢含量"};
String[] measure_points = new String[]{"机内氢压", "机内氢气湿度", "在线漏氢"};
//向每个webSocket推送系统实时数据
for (String deviceId : groupMap.keySet()) {
List<CharacterParamInfoVo> characterParamInfoVos = taskCacheDataService.cacheHydrogeCha(deviceId);
......@@ -78,7 +78,7 @@ public class HydrogeSystem3Task extends ScheduleTask {
finalList.add(item.toString());
});
powerPoints.setValue(finalList);
if (KKsCodes.get(queryResult.getMetric()).contains("发电机机内氢压")) {
if (KKsCodes.get(queryResult.getMetric()).contains("机内氢压")) {
//左上图
DataPower dataPower = map.getOrDefault("leftTop",new DataPower());
dataPower.setXAxis(xAxis);
......@@ -91,7 +91,7 @@ public class HydrogeSystem3Task extends ScheduleTask {
dataPower.getDataList().add(powerPoints);
map.putIfAbsent("leftBottom", dataPower);
}
if (KKsCodes.get(queryResult.getMetric()).contains("漏氢含量")) {
if (KKsCodes.get(queryResult.getMetric()).contains("在线漏氢")) {
DataPower dataPower = map.getOrDefault("rightTop",new DataPower());
dataPower.setXAxis(xAxis);
dataPower.getDataList().add(powerPoints);
......
......@@ -3,10 +3,12 @@ package cn.wise.sc.energy.power.plant.business.task;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.wise.sc.energy.power.plant.business.bean.DataPower;
import cn.wise.sc.energy.power.plant.business.domain.CharacterParamInfo;
import cn.wise.sc.energy.power.plant.business.domain.vo.CharacterParamInfoVo;
import cn.wise.sc.energy.power.plant.business.opentsdb.OpentsdbOkHttpClient;
import cn.wise.sc.energy.power.plant.business.service.ICharacterParamService;
import cn.wise.sc.energy.power.plant.business.service.IEventInfoService;
import cn.wise.sc.energy.power.plant.business.service.impl.EventInfoServiceImpl;
import cn.wise.sc.energy.power.plant.business.task.schedule.ScheduleTask;
import com.alibaba.fastjson.JSON;
import net.opentsdb.client.api.query.response.QueryResponse;
......@@ -17,8 +19,11 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
......@@ -79,6 +84,7 @@ public class IndexRealTimeTask extends ScheduleTask {
//获取kkscode
List<CharacterParamInfoVo> characterParamInfoVos ;
//全场
Map<String, List<CharacterParamInfo>> groupByDeviceId = new HashMap<>();
if ("total".equals(deviceId)) {
characterParamInfoVos = characterParamInfoList;
}else{
......@@ -112,6 +118,8 @@ public class IndexRealTimeTask extends ScheduleTask {
"定子负序电流",
})) {
//右上图
//添加量程
powerPoints.setMeasuer(characterParamInfoVos.stream().filter(item->item.getKksCode().equals(queryResult.getMetric())).findFirst().get().getMeasuringrangerulemaxvalue());
DataPower dataPower = map.getOrDefault("rightTop", new DataPower());
dataPower.setXAxis(xAxis);
dataPower.getDataList().add(powerPoints);
......@@ -194,6 +202,49 @@ public class IndexRealTimeTask extends ScheduleTask {
}
}
if("total".equals(deviceId)){
//添加报警点
DataPower dataPower4 = new DataPower();
List<EventInfoServiceImpl.AlertCount> alertCounts = iEventInfoService.countAlert();
DataPower.PowerPoints powerPoints = new DataPower.PowerPoints();
powerPoints.setName("预报警");
DataPower.PowerPoints powerPoints1 = new DataPower.PowerPoints();
powerPoints1.setName("高报警");
DataPower.PowerPoints powerPoints2 = new DataPower.PowerPoints();
powerPoints2.setName("高高报警");
DataPower.PowerPoints powerPoints3= new DataPower.PowerPoints();
powerPoints3.setName("趋势报警");
dataPower4.getDataList().add(powerPoints);
dataPower4.getDataList().add(powerPoints1);
dataPower4.getDataList().add(powerPoints2);
dataPower4.getDataList().add(powerPoints3);
//获取设备长度
Set<String> deviceNames = new TreeSet<>();
alertCounts.forEach(arg -> deviceNames.add(arg.getDeviceName()));
int idx = 0;
for (String deviceName : deviceNames) {
dataPower4.getXAxis().add(deviceName);
int finalIdx = idx;
alertCounts.forEach(arg -> {
//处理名字报警
if ("preAlert".equals(arg.getAlertLevel())) {
//预报警
dataPower4.getDataList().get(0).getValue().add( arg.getCount() + "");
} else if ("tallAlert".equals(arg.getAlertLevel())) {
//高报
dataPower4.getDataList().get(1).getValue().add( arg.getCount() + "");
} else if ("tooTallAlert".equals(arg.getAlertLevel())){
//高高报
dataPower4.getDataList().get(2).getValue().add( arg.getCount() + "");
}else{
dataPower4.getDataList().get(3).getValue().add( arg.getCount() + "");
}
});
idx++;
}
map.put("alert", dataPower4);
}
try {
List<Map.Entry<String, String>> deviceGroupMap = groupMap.get(deviceId);
//根据deviceid统一发送
......
......@@ -23,10 +23,10 @@ public class TaskCacheDataService {
@Cacheable(value = "hydroge-character", key = "#deviceId")
public List<CharacterParamInfoVo> cacheHydrogeCha(String deviceId) {
List<String> characterNames = new ArrayList<>();
characterNames.add("发电机机内氢压");
characterNames.add("机内氢压");
characterNames.add("机内氢气湿度");
characterNames.add("漏氢含量");
characterNames.add("汽端发电机冷氢温度");
characterNames.add("在线漏氢");
characterNames.add("汽端冷氢温度");
List<CharacterParamInfoVo> characterParamInfoVos =
iCharacterParamService.getCharacterByName(characterNames, "", deviceId);
return characterParamInfoVos;
......
......@@ -44,7 +44,7 @@ public class TendencyTask extends ScheduleTask {
public void run() {
ConcurrentHashMap<String, TendencyWebSocket> webSocketMap =
TendencyWebSocket.webSocketMap;
ConcurrentHashMap<String, String> deviceMap = HydrogenSystemWebSocket.deviceMap;
ConcurrentHashMap<String, String> deviceMap = TendencyWebSocket.deviceMap;
if (webSocketMap.size() == 0 || deviceMap.size() == 0) {
return;
}
......@@ -52,13 +52,13 @@ public class TendencyTask extends ScheduleTask {
Map<String, List<Map.Entry<String, String>>> groupMap = deviceMap.entrySet().stream().collect(Collectors.groupingBy(c -> c.getValue()));
//向每个webSocket推送系统实时数据
for (String deviceId : groupMap.keySet()) {
List<CharacterParamInfoVo> characterParamInfoVos = taskCacheDataService.cacheHydrogeCha(deviceId);
Map<String, String> KKsCodes = characterParamInfoVos.stream().filter(item -> IS_CONTAINS(item.getCpName(), new String[]{"汽端发电机冷氢温度"})).collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpName));
Long lastTime = OpentsdbOkHttpClient.queryLast(characterParamInfoVos);
for (String kkscode : groupMap.keySet()) {
List<String> kksCodeList = new ArrayList<>();
kksCodeList.add(kkscode);
Long lastTime = OpentsdbOkHttpClient.queryLastBykks(kksCodeList);
QueryResponse response = iCharacterParamService
.getRealTimeDataByKksCode(new ArrayList<>(KKsCodes.keySet()), (lastTime - 1) + "", lastTime + "", "");
.getRealTimeDataByKksCode(kksCodeList, (lastTime - 1) + "", lastTime + "", "");
//组装数据结构
List<Object> xAxis = response.getResults().get(0).getDps().keySet().stream().map(item -> item.toString()).collect(Collectors.toList());
......@@ -66,22 +66,19 @@ public class TendencyTask extends ScheduleTask {
for (QueryResult queryResult : response.getResults()) {
DataPower.PowerPoints powerPoints = new DataPower.PowerPoints();
powerPoints.setKksCode(queryResult.getMetric());
powerPoints.setName(KKsCodes.get(queryResult.getMetric()));
List<String> finalList = new ArrayList<>();
queryResult.getDps().values().stream().forEach(item -> {
finalList.add(item.toString());
});
powerPoints.setValue(finalList);
if (KKsCodes.get(queryResult.getMetric()).contains("汽端发电机冷氢温度")) {
DataPower dataPower = map.getOrDefault("rightBottom", new DataPower());
DataPower dataPower = map.getOrDefault("data", new DataPower());
dataPower.setXAxis(xAxis);
dataPower.getDataList().add(powerPoints);
map.putIfAbsent("rightBottom", dataPower);
map.putIfAbsent("data", dataPower);
}
//左上图
}
try {
List<Map.Entry<String, String>> deviceGroupMap = groupMap.get(deviceId);
List<Map.Entry<String, String>> deviceGroupMap = groupMap.get(kkscode);
//根据deviceid统一发送
for (Map.Entry<String, String> entry : deviceGroupMap) {
final SendWebSocket webSocket = webSocketMap.get(entry.getKey());
......
......@@ -25,7 +25,7 @@ import java.util.concurrent.ConcurrentHashMap;
**/
@Slf4j
@Component
@ServerEndpoint("/tendency/{deviceId}")
@ServerEndpoint("/tendency/{kkscode}")
@DependsOn("myApplicationContextAware")
public class TendencyWebSocket implements SendWebSocket{
......@@ -44,29 +44,26 @@ public class TendencyWebSocket implements SendWebSocket{
private Session session;
private String uuid;
private HydrogeSystem1Task hydrogeSystem1Task = (HydrogeSystem1Task) MyApplicationContextAware.getApplicationContext().getBean("hydrogeSystem1Task");
private HydrogeSystem3Task hydrogeSystem3Task = (HydrogeSystem3Task) MyApplicationContextAware.getApplicationContext().getBean("hydrogeSystem3Task");
private TendencyTask tendencyTask = (TendencyTask) MyApplicationContextAware.getApplicationContext().getBean("tendencyTask");
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("deviceId") String deviceId) {
public void onOpen(Session session, @PathParam("kkscode") String kkscode) {
this.session = session;
uuid = UUID.randomUUID().toString();
deviceMap.put(uuid, deviceId);
deviceMap.put(uuid, kkscode);
webSocketMap.put(uuid, this);
//加入set中
addOnlineCount();
//启动任务
ScheduleUtil.start(hydrogeSystem1Task,1000);
ScheduleUtil.start(hydrogeSystem3Task,1000*3600);
ScheduleUtil.start(tendencyTask,1000);
//已有用户的情况,主动推送一次
if (webSocketMap.size() > 1) {
hydrogeSystem1Task.run();
hydrogeSystem3Task.run();
tendencyTask.run();
}
log.info("用户连接:" + deviceId + ",当前在线人数为:" + getOnlineCount());
log.info("用户连接:" + kkscode + ",当前在线人数为:" + getOnlineCount());
}
/**
......@@ -81,8 +78,7 @@ public class TendencyWebSocket implements SendWebSocket{
subOnlineCount();
}
if (webSocketMap.size() == 0) {
ScheduleUtil.cancel(hydrogeSystem1Task);
ScheduleUtil.cancel(hydrogeSystem3Task);
ScheduleUtil.cancel(tendencyTask);
}
log.info("用户退出:" + uuid + ",当前在线人数为:" + getOnlineCount());
}
......
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.wise.sc.energy.power.plant.business.domain.AutoInspection;
import cn.wise.sc.energy.power.plant.business.repository.AutoInspectionRepository;
import cn.wise.sc.energy.power.plant.common.core.exception.ResponseEnum;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
/**
* @author shulidong
* @since 2020/9/21 14:04
*/
@Service
public class DocxService {
@Autowired
AutoInspectionRepository autoInspectionRepository;
private static final Logger LOGGER = LoggerFactory.getLogger(DocxService.class);
public byte[] fillDocx() throws Exception {
List<AutoInspection> list = autoInspectionRepository.findAutoInspectionsById("C0A001 - 1 - 1600756452620");
if (CollectionUtil.isEmpty(list)) {
ResponseEnum.BUSINESS_ERROR.newException("未找到相应的报告项");
}
final InputStream inputStream = new ClassPathResource("templates/" + "demo1.docx").getStream();
XWPFDocument document = new XWPFDocument(inputStream);
//添加页眉 需要固定的文字(中文标点)在模板上->{{:text:date:date:}}
List<XWPFHeader> pageHeaders = document.getHeaderList();
JSONObject original = new JSONObject();
JSONObject date = new JSONObject();
date.put("date",LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
original.put("date", date);
for (int i = 0; i < pageHeaders.size(); i++) {
XWPFHeader pageHeader = pageHeaders.get(i);
List<XWPFParagraph> headerPara = pageHeader.getParagraphs();
XWPFParagraph headerParagraph = headerPara.get(0);
if (headerParagraph.getRuns().size() > 1) {
PoiiUtiil.parseThisParagraph(headerParagraph,original);
}
}
//获取所有的段落
List<XWPFParagraph> paragraphs = document.getParagraphs();
//把文档groupby
List<XWPFParagraph> texts = new ArrayList<>();
List<XWPFTable> tables = new ArrayList<>();
for (XWPFParagraph paragraph : paragraphs) {
String text = paragraph.getText();
//只有这三种标签能够混用
if (text.contains("{{:text") || text.contains("{{:for") || text.contains("{{:desc")) {
texts.add(paragraph);
}
}
for (XWPFTable table : document.getTables()) {
if (table == null) {
LOGGER.error("table is null, please stop!");
}
if (table.getText().contains("{{:table") || table.getText().contains("{{:text")) {
tables.add(table);
}
}
JSONObject allin = new JSONObject();
JSONObject fuzhu = new JSONObject();
fuzhu.put("MKW05CP001", 12.578);
allin.put("fuzhu", fuzhu);
JSONObject reportInfo = new JSONObject();
reportInfo.put("username", "张三");
reportInfo.put("a", "张三");
reportInfo.put("date", LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE).toString());
allin.put("reportInfo", reportInfo);
try {
PoiiUtiil.paragraph(texts, allin);
PoiiUtiil.table(tables, allin);
//要求word在打开时提示更新域
document.enforceUpdateFields();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
FileOutputStream fos = new FileOutputStream("D:/"+ "生成文件.docx");
document.write(fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package cn.wise.sc.energy.power.plant.business.poi;
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.afterturn.easypoi.entity.ImageEntity;
import lombok.extern.slf4j.Slf4j;
......
package cn.wise.sc.energy.power.plant.business.utils.poi;
/**
* @author qilei
* @since 2018-05-15 16:50
*/
public interface POIConstance {
/**
* A4纸的宽度。
*/
Integer A4_TABLE_EARLY_AND_REVIEW_WIDTH = 8494;
Integer A4_TABLE_TENDER_WIDTH = 8290;
/**
* 4个空格
*/
Integer FOUR_SPACE = 420;
}
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.POIColor;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGrid;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGridCol;
import java.math.BigInteger;
public class StyleUtil {
/**
* @Description: 设置表格列宽
*/
private static void setTableGridCol(XWPFTable table, int colLength, int tableWidth) {
CTTbl ttbl = table.getCTTbl();
CTTblGrid tblGrid = ttbl.getTblGrid() != null ? ttbl.getTblGrid() : ttbl.addNewTblGrid();
for (int j = 0; j < colLength; j++) {
CTTblGridCol gridCol = tblGrid.addNewGridCol();
gridCol.setW(new BigInteger(String.valueOf(tableWidth / colLength)));
}
}
/**
* 简单的设置字体和字号,为run设置
*
* @param run
* @param fontSizeMutiply2 字号*2 比如要设置10.5号字,就传入21
* @param englishFont Nullable
* @param chineseFont Nullable
*/
public static void setFontAndSize(XWPFRun run, int fontSizeMutiply2, String englishFont, String chineseFont) {
run.setColor(POIColor.BLACK.toString());
//给字体赋值,避免设置字体时出现null
run.setFontFamily(chineseFont == null ? "宋体" : chineseFont);
//给字号赋值,避免设置字号时出现null
run.setFontSize(9);
//这地方 因为fontSize不存在小数点,所以很蛋疼,这里的BigInteger是fontSize*2,看源码即可知道。
run.getCTR().getRPr().getSz().setVal(new BigInteger(fontSizeMutiply2 + ""));
//设置英文字体
run.getCTR().getRPr().getRFonts().setAscii(englishFont == null ? "Times New Roman" : englishFont);
//设置中文字体
run.getCTR().getRPr().getRFonts().setEastAsia(chineseFont == null ? "宋体" : chineseFont);
}
}
package cn.wise.sc.energy.power.plant.business.utils.poi;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import cn.afterturn.easypoi.entity.ImageEntity;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.data.category.DefaultCategoryDataset;
/**
* @author 何昌杰
*/
public class WordDemo1 {
public static void main(String[] args) throws IOException {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
String group1 = "huawei ";
dataset.addValue(5, group1, "w1");
dataset.addValue(6, group1, "w2");
dataset.addValue(4, group1, "w3");
dataset.addValue(2, group1, "w4");
dataset.addValue(5, group1, "w5");
dataset.addValue(5, group1, "w6");
dataset.addValue(5, group1, "w7");
dataset.addValue(8, group1, "w8");
group1 = "apple ";
dataset.addValue(2, group1, "w1");
dataset.addValue(4, group1, "w2");
dataset.addValue(4, group1, "w3");
dataset.addValue(5, group1, "w4");
dataset.addValue(5, group1, "w5");
dataset.addValue(8, group1, "w6");
dataset.addValue(9, group1, "w7");
dataset.addValue(8, group1, "w8");
SpiderWebPlot spiderwebplot = new SpiderWebPlot(dataset);
JFreeChart jfreechart = new JFreeChart("Test", TextTitle.DEFAULT_FONT, spiderwebplot, false);
LegendTitle legendtitle = new LegendTitle(spiderwebplot);
legendtitle.setPosition(RectangleEdge.TOP);
jfreechart.addSubtitle(legendtitle);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ChartUtils.writeChartAsPNG(out, jfreechart, 400, 500);
ImageEntity imageEntity = new ImageEntity(out.toByteArray(), 200, 200);
//word模板相对路径、word生成路径、word生成的文件名称、数据源
HashMap<String, Object> map = new HashMap<>(4);
long startTime = System.currentTimeMillis();
//模拟饼状图数据
HashMap<String, Integer> datas = new HashMap<>(3);
datas.put("一号", 10);
datas.put("二号", 20);
datas.put("三号", 40);
ImageEntity imageEntity1 = JfreeUtil.pieChart("测试", datas, 200, 200);
map.put("picture", imageEntity);
map.put("picture1", imageEntity1);
//模拟其它普通数据
map.put("username", "张三");
map.put("date", "2019-10-10");
map.put("desc", "测试");
map.put("boo", true);
//模拟表格数据
ArrayList<HashMap<String, String>> list = new ArrayList<>(2);
HashMap<String, String> temp = new HashMap<>(3);
temp.put("sn", "1");
temp.put("name", "第一个人");
temp.put("age", "23");
list.add(temp);
for (int i = 0; i < 100; i++) {
temp = new HashMap<>(3);
temp.put("sn", "2");
temp.put("name", "第二个人");
temp.put("age", "24");
list.add(temp);
}
map.put("personlist", list);
// WordUtils.exportWord("C:\\Users\\admin\\Desktop\\template\\demo1.docx", "D:/", "生成文件.docx", map);
}
}
\ No newline at end of file
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.POIColor;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.Style;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFieldRun;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
/**
* @author qilei
* @since 2018-03-20 09:56
*/
public class WordUtil {
public static void insert2PicturesAndDescribeAfter(XWPFDocument docx, XWPFParagraph currentParagraph, InputStream pic1, InputStream pic2, String picDescribe) throws IOException, InvalidFormatException {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
final XWPFParagraph paragraph = docx.insertNewParagraph(xmlCursor);
paragraph.setAlignment(ParagraphAlignment.CENTER);
final XWPFRun run1 = paragraph.createRun();
run1.addPicture(pic1, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(205.208), Units.toEMU(153.906));
run1.addPicture(pic2, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(205.208), Units.toEMU(153.906));
final XmlCursor xmlCursor1 = paragraph.getCTP().newCursor();
xmlCursor1.toNextSibling();
final XWPFParagraph paragraph1 = docx.insertNewParagraph(xmlCursor1);
paragraph1.createRun().setText(picDescribe);
Style.DEFAULT_TABLE_PIC_NAME_STYLE.proccess(paragraph1);
}
public static XWPFParagraph insertPictureAndDescribeAfter(XWPFDocument docx, XWPFParagraph currentParagraph, InputStream picStream, String picDescribe) throws IOException, InvalidFormatException {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
final XWPFParagraph paragraph = docx.insertNewParagraph(xmlCursor);
paragraph.setAlignment(ParagraphAlignment.CENTER);
final XWPFRun run = paragraph.createRun();
run.addPicture(picStream, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(320), Units.toEMU(240));
final XmlCursor xmlCursor1 = paragraph.getCTP().newCursor();
xmlCursor1.toNextSibling();
final XWPFParagraph paragraph1 = docx.insertNewParagraph(xmlCursor1);
final XWPFRun run1 = paragraph1.createRun();
run1.setText(picDescribe);
Style.DEFAULT_TABLE_PIC_NAME_STYLE.proccess(paragraph1);
return paragraph1;
}
/**
* 仅插入图片 不做描述
*
* @param docx
* @param currentParagraph
* @param picStream
* @return
* @throws IOException
* @throws InvalidFormatException
*/
public static XWPFParagraph insertPicture(XWPFDocument docx, XWPFParagraph currentParagraph, InputStream picStream) throws IOException, InvalidFormatException {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
final XWPFParagraph paragraph = docx.insertNewParagraph(xmlCursor);
paragraph.setAlignment(ParagraphAlignment.CENTER);
final XWPFRun run = paragraph.createRun();
run.addPicture(picStream, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(320), Units.toEMU(240));
return paragraph;
}
public static XWPFParagraph insert2Pictures(XWPFDocument docx, XWPFParagraph currentParagraph, InputStream pic1, InputStream pic2) throws IOException, InvalidFormatException {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
final XWPFParagraph paragraph = docx.insertNewParagraph(xmlCursor);
paragraph.setAlignment(ParagraphAlignment.CENTER);
final XWPFRun run1 = paragraph.createRun();
run1.addPicture(pic1, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(205.208), Units.toEMU(153.906));
run1.addPicture(pic2, XWPFDocument.PICTURE_TYPE_PNG, "", Units.toEMU(205.208), Units.toEMU(153.906));
return paragraph;
}
public static XWPFParagraph insertParagraphAfter(XWPFDocument docx, XWPFParagraph currentParagraph) {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
return docx.insertNewParagraph(xmlCursor);
}
public static XWPFParagraph insertParagraphAfter(XWPFDocument docx, XmlCursor xmlCursor) {
xmlCursor.toNextSibling();
return docx.insertNewParagraph(xmlCursor);
}
public static XWPFParagraph insertParagraphAfter(XWPFDocument docx, XWPFTable xwpfTable) {
XmlCursor xmlCursor = xwpfTable.getCTTbl().newCursor();
xmlCursor.toNextSibling();
return docx.insertNewParagraph(xmlCursor);
}
public static XWPFTable insertTableAfter(XWPFDocument docx, XWPFParagraph currentParagraph) {
XmlCursor xmlCursor = currentParagraph.getCTP().newCursor();
xmlCursor.toNextSibling();
return docx.insertNewTbl(xmlCursor);
}
public static XWPFTable insertTableAfter(XWPFDocument docx, XWPFTable xwpfTable) {
XmlCursor xmlCursor = xwpfTable.getCTTbl().newCursor();
xmlCursor.toNextSibling();
return docx.insertNewTbl(xmlCursor);
}
/**
* 移除paragraph中所有的run,不保留run
*
* @param paragraph
*/
public static void clearMe(XWPFParagraph paragraph) {
for (int i = paragraph.getRuns().size(); i > 0; i--) {
paragraph.removeRun(0);
}
}
/**
* 把自己移除
*
* @param paragraph
*/
public static void removeMe(XWPFParagraph paragraph) {
final XWPFDocument document = paragraph.getDocument();
}
/**
* 简单的设置字体和字号,为run设置
*
* @param run
* @param fontSizeMutiply2 字号*2 比如要设置10.5号字,就传入21
* @param englishFont Nullable
* @param chineseFont Nullable
*/
public static void setFontAndSize(XWPFRun run, int fontSizeMutiply2, String englishFont, String chineseFont) {
//todo set color
run.setColor(POIColor.BLUE.toString());
//给字体赋值,避免设置字体时出现null
run.setFontFamily("Times New Roman");
//给字号赋值,避免设置字号时出现null
run.setFontSize(9);
//这地方 因为fontSize不存在小数点,所以很蛋疼,这里的BigInteger是fontSize*2,看源码即可知道。
run.getCTR().getRPr().getSz().setVal(new BigInteger(fontSizeMutiply2 + ""));
//设置英文字体
run.getCTR().getRPr().getRFonts().setAscii(englishFont == null ? "Times New Roman" : englishFont);
//设置中文字体
run.getCTR().getRPr().getRFonts().setEastAsia(chineseFont == null ? "宋体" : chineseFont);
}
}
package cn.wise.sc.energy.power.plant.business.poi;
package cn.wise.sc.energy.power.plant.business.utils.poi;
import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
......@@ -7,7 +7,7 @@ import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
public class WordUtil {
public class WordUtils {
/**
* 导出word
* <p>第一步生成替换后的word文件,只支持docx</p>
......
package cn.wise.sc.energy.power.plant.business.utils.poi.styles;
public interface FieldCodes {
String PIC_DEFAULT = "SEQ 图 \\* ARABIC";
String TABLE_DEFAULT = "SEQ 表 \\* ARABIC";
}
package cn.wise.sc.energy.power.plant.business.utils.poi.xwpftable;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.Style;
import javax.validation.constraints.NotNull;
import java.util.LinkedList;
import java.util.List;
/**
* @author qilei
* @since 2018-05-15 13:45
*/
public class ToolXWPFCell {
/**
* 中间的字符串随便填只要不跟真的文档重复就行了,这个字符应当不会重复的吧。
*/
public final static ToolXWPFCell CONTINUE = new ToolXWPFCell("{{emptyCell");
private List<ToolXwpfRun> runs;
public ToolXWPFCell(String content) {
runs = new LinkedList<>();
runs.add(new ToolXwpfRun(content));
}
public ToolXWPFCell(String content, @NotNull Style style) {
runs = new LinkedList<>();
runs.add(new ToolXwpfRun(content, style));
}
public ToolXWPFCell(ToolXwpfRun... runs) {
this.runs = new LinkedList<>();
for (int i = 0; i < runs.length; i++) {
this.runs.add(new ToolXwpfRun(runs[i].getContent(), runs[i].getStyle()));
}
}
public List<ToolXwpfRun> getRuns() {
return runs;
}
public void setRuns(List<ToolXwpfRun> runs) {
this.runs = runs;
}
}
package cn.wise.sc.energy.power.plant.business.utils.poi.xwpftable;
import cn.wise.sc.energy.power.plant.business.utils.poi.styles.Style;
/**
* @author qilei
* @since 2018-05-22 08:57
* todo 实现深拷贝
*/
public class ToolXwpfRun {
private String content;
private Style style;
public ToolXwpfRun(String content, Style style) {
this.content = content;
this.style = style;
}
public ToolXwpfRun(String content) {
this.content = content;
this.style = Style.DEFAULT_TABLE_CONTENT_STYLE;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Style getStyle() {
return style;
}
public void setStyle(Style style) {
this.style = style;
}
}
......@@ -96,7 +96,7 @@ spring:
# max-idle-per-key: 10
# #每个key对应的连接池最小空闲连接数
# max_idle_per_key: 5
jpa:
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
......
......@@ -49,7 +49,7 @@
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
<maxHistory>1</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
......@@ -179,7 +179,7 @@
<logger name="cn.wise.sc.cement.business.controller" level="debug"/><!-- 修改此处扫描包名 -->
</springProfile>
<root level="debug">
<root level="error">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
......@@ -189,7 +189,7 @@
<!--4.2 生产环境:输出到文档-->
<springProfile name="pro">
<root level="info">
<root level="debug">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment