1.时间工具类
package com.xlkj.service.utils;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DateUtil {
/**
* 今天所有小时数量
*/
public static String get12Hour() {
StringBuilder hours = new StringBuilder();
String localDate = LocalDate.now().toString();
LocalDateTime now = LocalDateTime.now();
for (int s = 0; s <= now.getHour(); s++) {
hours.append(localDate).append(" ").append(zero(s));
if (s != now.getHour()) {
hours.append(",");
}
}
return hours.toString();
}
/**
* 本周
*/
public static String get12Week() {
StringBuilder days = new StringBuilder();
LocalDate now = LocalDate.now();
for (int s = now.getDayOfWeek().getValue() - 1; s >= 0; s--) {
days.append(now.minusDays(s));
if (s != 0) {
days.append(",");
}
}
return days.toString();
}
/**
* 本月
*/
public static String getDaysByMonth() {
StringBuilder days = new StringBuilder();
LocalDate now = LocalDate.now();
for (int s = now.getDayOfMonth() - 1; s >= 0; s--) {
days.append(now.minusDays(s));
if (s != 0) {
days.append(",");
}
}
return days.toString();
}
/**
* 获取最近12个月
*/
public static String get12Month() {
StringBuilder months = new StringBuilder();
LocalDate today = LocalDate.now();
for (int i = 11; i >= 0; i--) {
LocalDate localDate = today.minusMonths(i);
String month = localDate.toString().substring(0, 7);
months.append(month);
if (i != 0) {
months.append(",");
}
}
return months.toString();
}
/**
* 补零
*/
public static String zero(int time) {
if (time < 10) {
return "0" + time;
} else {
return "" + time;
}
}
//根据开始时间和结束时间计算中间多少天
public static int days (LocalDate start, LocalDate end) {
Period next = Period.between(start, end);
return next.getDays();
}
/**
* 获取指定日期范围内的所有指定星期 包含开始日期和结束日期
* @param weeks 1,3,7表示周一,周三,周日
* @return List<LocalDate>
*/
public static List<LocalDate> getWeekLocalDateListByRange(LocalDate startDay, LocalDate endDay, List<String> weeks) {
List<LocalDate> localDateList = new ArrayList<>();
TemporalField fieldISO = WeekFields.of(DayOfWeek.of(1), 1).dayOfWeek();
LocalDate tempDay;
for (String week : weeks) {
tempDay = startDay.with(fieldISO, Long.parseLong(week));
if (tempDay.isBefore(startDay)) {
tempDay = tempDay.plusWeeks(1);
}
while (tempDay.isBefore(endDay) || tempDay.isEqual(endDay)) {
localDateList.add(tempDay);
tempDay = tempDay.plusWeeks(1);
}
}
return localDateList;
}
/**
* 获取指定日期范围内的所有指定dayOfMonth 包含开始日期和结束日期
* @param months 1,29,31表示每月的1号,29号,31号
* @return List<LocalDate>
*/
public static List<LocalDate> getLocalDateListByMonth(LocalDate startDate, LocalDate endDate, List<String> months){
List<LocalDate> localDateList = new ArrayList<>();
LocalDate localDate;
for(String month : months){
LocalDate tempDate = startDate;
while (tempDate.isBefore(endDate) || tempDate.getMonthValue() == endDate.getMonthValue()){
if(tempDate.lengthOfMonth() >= Integer.valueOf(month)){
localDate = tempDate.withDayOfMonth(Integer.valueOf(month));
if(localDate.isAfter(startDate) || localDate.isEqual(startDate)){
localDate = tempDate.withDayOfMonth(Integer.valueOf(month));
if(localDate.isEqual(endDate) || localDate.isBefore(endDate)){
localDateList.add(localDate);
}
}
}
tempDate = tempDate.plusMonths(1);
}
}
return localDateList;
}
/**
* 获取指定范围内所有日期,包含开始日期和结束日期
* @return List<LocalDate>
*/
public static List<LocalDate> getLocalDateByDay(LocalDate startDate, LocalDate endDate){
List<LocalDate> localDateList = Stream.iterate(startDate, date -> date.plusDays(1)).
limit(ChronoUnit.DAYS.between(startDate, endDate))
.collect(Collectors.toList());
localDateList.add(endDate);
return localDateList;
}
//将时间转换成毫秒级时间戳并转换成double
public static Double timeDouble(LocalDateTime localDateTime){
Timestamp timestamp = Timestamp.valueOf(localDateTime);
//转为毫秒级时间戳
long milliSecondStamp = timestamp.getTime();
double doubleValue = BigDecimal.valueOf(milliSecondStamp).doubleValue();
return doubleValue;
}
//将毫秒级时间戳Double类型数值转换成LocalDateTime类型
public static LocalDateTime doubleTime(Double time){
Long timestamp = Long.valueOf(String.valueOf(BigDecimal.valueOf(time)));
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(zoneId).toLocalDateTime();
return localDateTime;
}
}
2.MQTT链接工具类
package com.xlkj.manage.mqtt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* 实体属性类
*/
@Slf4j
@Configuration
@ConfigurationProperties("mqtt")
public class MqttProperties {
private String brokerUrl;
private String clientId;
private String username;
private String password;
private String host;
private String port;
@Bean
public MqttClient mqttClient() {
MqttClient client = null;
try {
client = new MqttClient(getBrokerUrl(), getClientId()+random, new MemoryPersistence());
MqttConnectOptions option = new MqttConnectOptions();
option.setCleanSession(false);
option.setUserName(getUsername());
option.setPassword(getPassword().toCharArray());
option.setConnectionTimeout(3000);
option.setKeepAliveInterval(10);
option.setAutomaticReconnect(true);
client.setCallback(new MqttPushCallback(client, option));
client.connect(option);
client.subscribe("订阅地址");
} catch (Exception e) {
e.printStackTrace();
}
log.info(getBrokerUrl() + "初始化==================================================" + client);
return client;
}
public String getBrokerUrl() {
return brokerUrl;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public void setBrokerUrl(String brokeUrl) {
this.brokerUrl = brokeUrl;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "MqttProperties{" +
"brokeUrl='" + brokerUrl + '\'' +
", clientId='" + clientId + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
MQTT订阅后接收消息工具类
package com.xlkj.manage.mqtt;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xlkj.manage.mqtt.distribute.ReceiveMessage;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* MQTT 推送回调
*/
@Component
public class MqttPushCallback implements MqttCallback {
private static final Logger log = LoggerFactory.getLogger(MqttPushCallback.class);
@Autowired
private ReceiveMessage receiveMessage1;
private static ReceiveMessage receiveMessage;
@PostConstruct
private void init(){
receiveMessage = receiveMessage1;
}
private MqttClient client;
private MqttConnectOptions option;
public MqttPushCallback() {
}
public MqttPushCallback(MqttClient client, MqttConnectOptions option) {
this.client = client;
this.option = option;
}
@Override
public void connectionLost(Throwable cause) {
log.info("断开连接,建议重连" + cause);
while(true) {
try {
Thread.sleep(30000);
// 重新连接
//MqttFactory.getMqttClient().connect(option);
break;
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
int messageId = token.getMessageId();
String[] topics = token.getTopics();
log.info("消息发布完成,messageid={},topics={}",messageId,topics);
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
log.info("订阅者订阅到了消息,topic={},messageid={},qos={},payload={}",
topic,
message.getId(),
message.getQos(),
new String(message.getPayload()));
}
}
3.Excel2003图片解析工具类
注:图片必须放入在单元格内,一个单元格只能一张图片
package com.xlkj.service.utils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExcelImgUtil {
private static int counter = 0;
/**
* 读取 Excel文件内容
*
* @param inputstream 文件输入流
* @return
* @throws Exception
*/
public static List<Map<String, String>> readExcelByInputStream(InputStream inputstream)
throws Exception {
String proFile = "D:/yljg/uploadPath";//文件存放的路径
// 结果集
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputstream);
String filePath = proFile + "/" + "pic/";//图片保存路径
final HSSFSheet sheet = hssfWorkbook.getSheetAt(0);// 得到Excel工作表对象
Map<String, PictureData> map = ExcelImgUtil.getPictures(sheet,hssfWorkbook);//获取图片和位置
Map<String, String> pathMap = ExcelImgUtil.printImg(map, filePath);//写入图片,并返回图片路径,key:图片坐标,value:图片路径
list = ExcelImgUtil.readData(sheet, pathMap);
return list;
}
/**
* 获取图片和位置 (xlsx)
*
* @param sheet
* @return
* @throws IOException
*/
public static Map<String, PictureData> getPictures(HSSFSheet sheet, HSSFWorkbook workbook) throws IOException {
Map<String, PictureData> map = new HashMap<String, PictureData>();
List<HSSFPictureData> pictures = workbook.getAllPictures();
if (!pictures.isEmpty())
{
for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
{
HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
if (shape instanceof HSSFPicture)
{
HSSFPicture pic = (HSSFPicture) shape;
int pictureIndex = pic.getPictureIndex() - 1;
HSSFPictureData picData = pictures.get(pictureIndex);
String picIndex = String.valueOf(anchor.getRow1()) + "-" + String.valueOf(anchor.getCol1());
map.put(picIndex, picData);
}
}
return map;
}
else
{
return map;
}
}
public static Map<String, String> printImg(Map<String, PictureData> sheetList, String path) throws IOException {
Map<String, String> pathMap = new HashMap<String, String>();
Object[] key = sheetList.keySet().toArray();
File f = new File(path);
if (!f.exists()) {
f.mkdirs(); // 创建目录
}
for (int i = 0; i < sheetList.size(); i++) {
// 获取图片流
PictureData pic = sheetList.get(key[i]);
// 获取图片索引
String picName = key[i].toString();
// 获取图片格式
String ext = pic.suggestFileExtension();
String fileName = encodingFilename(picName);
byte[] data = pic.getData();
// 图片保存路径
String imgPath = path + fileName + "." + ext;
FileOutputStream out = new FileOutputStream(imgPath);
imgPath = imgPath.substring(path.length(), imgPath.length());// 截取图片路径
pathMap.put(picName, imgPath);
out.write(data);
out.close();
}
return pathMap;
}
private static final String encodingFilename(String fileName) {
fileName = fileName.replace("_", " ");
fileName = MD5Util.hash(fileName + System.nanoTime() + counter++);
return fileName;
}
/**
* 读取excel文字
* <p>
* Excel 07版本以上
*
* @param sheet
*/
public static List<Map<String, String>> readData(HSSFSheet sheet, Map<String, String> map) {
List<Map<String, String>> newList = new ArrayList<Map<String, String>>();// 单行数据
try {
int rowNum = sheet.getLastRowNum() + 1;
for (int i = 1; i < rowNum; i++) {// 从第三行开始读取数据,第一行是备注,第二行是标头
Row row = sheet.getRow(i);// 得到Excel工作表的行
if (row != null) {
int col = row.getPhysicalNumberOfCells();
// 单行数据
Map<String, String> mapRes = new HashMap<String, String>();// 每格数据
for (int j = 0; j < col; j++) {
Cell cell = row.getCell(j);
if (cell == null) {
// arrayString.add("");
} else if (cell.getCellType() == 0) {// 当时数字时的处理
mapRes.put(getMapKey(j), String.valueOf(cell.getNumericCellValue()));
} else {// 如果EXCEL表格中的数据类型为字符串型
mapRes.put(getMapKey(j), cell.getStringCellValue().trim());
}
}
// 不是标头列时,添加图片路径
String path = map.get(i + "-17");
mapRes.put(getMapKey(17), path);
String pathTwo = map.get(i + "-18");
mapRes.put(getMapKey(18), pathTwo);
newList.add(mapRes);
}
}
} catch (Exception e) {
}
return newList;
}
public static String getMapKey(int num) {
String res = "";
switch (num) {
case 0:// 所属街道(乡镇)
res = "street";
break;
case 1:// 机构类型
res = "mechanismType";
break;
case 2:// 机构名称
res = "mechanismName";
break;
case 3:// 机构联系电话
res = "phone";
break;
case 4:// 地址
res = "address";
break;
case 5:// 坐标经度
res = "longitude";
break;
case 6:// 坐标纬度
res = "latitude";
break;
case 7:// 成立时间(示例:2002-01-02)
res = "establishedTime";
break;
case 8:// 设施面积(m²)
res = "facilitiesArea";
break;
case 9:// 床位数
res = "bedNum";
break;
case 10:// 已用床位
res = "useBedNum";
break;
case 11:// 机构归属
res = "agenciesBelong";
break;
case 12:// 机构负责人
res = "principal";
break;
case 13:// 机构负责人联系号码
res = "principalPhone";
break;
case 14:// 法人代表
res = "legalPerson";
break;
case 15:// 法人代表联系号码
res = "legalPersonPhone";
break;
case 16:// 统一社会信用编码
res = "socialCreditCode";
break;
case 17:// 营业执照
res = "businessImage";
break;
case 18:// 机构照片
res = "mechanismImage";
break;
default:
break;
}
return res;
}
}
实现
public void uploadFile(MultipartFile upFile) throws Exception{
//文件路径
String path = "D:\\yljg\\uploadPath\\pic\\";
InputStream in = null;
List<Map<String, String>> listob = null;
in = upFile.getInputStream();
listob = ExcelImgUtil.readExcelByInputStream(in);
if (!CollectionUtils.isEmpty(listob)){
for (Map<String, String> map : listob) {
//编写业务逻辑
}
}
}
4.MD5工具类
package com.xlkj.service.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
private static final Logger log = LoggerFactory.getLogger(MD5Util.class);
public static String getMd5(String str){
try {
MessageDigest md=MessageDigest.getInstance("MD5");
byte[] s=md.digest(str.getBytes());
String ss="";
String result="";
for(int i=0;i<s.length;i++){
ss=Integer.toHexString(s[i] & 0xff);
if(ss.length()==1){
result+="0"+ss;
}else{
result+=ss;
}
}
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
private static byte[] md5(String s)
{
MessageDigest algorithm;
try
{
algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(s.getBytes("UTF-8"));
byte[] messageDigest = algorithm.digest();
return messageDigest;
}
catch (Exception e)
{
log.error("MD5 Error...", e);
}
return null;
}
private static final String toHex(byte hash[])
{
if (hash == null)
{
return null;
}
StringBuffer buf = new StringBuffer(hash.length * 2);
int i;
for (i = 0; i < hash.length; i++)
{
if ((hash[i] & 0xff) < 0x10)
{
buf.append("0");
}
buf.append(Long.toString(hash[i] & 0xff, 16));
}
return buf.toString();
}
public static String hash(String s)
{
try
{
return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
}
catch (Exception e)
{
log.error("not supported charset...{}", e);
return s;
}
}
}
5.实体类copy工具类
import com.xlkj.base.ex.BizException;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
public class BeanUtils {
private static final Logger log = LoggerFactory.getLogger(BeanUtils.class);
public BeanUtils() {
}
public static <T> List<NameValuePair> bean2NvList(T t) {
if (t == null) {
return null;
} else {
Field[] fields = t.getClass().getDeclaredFields();
List<NameValuePair> nvList = new ArrayList();
Field[] var3 = fields;
int var4 = fields.length;
for(int var5 = 0; var5 < var4; ++var5) {
Field field = var3[var5];
field.setAccessible(true);
String value = null;
try {
Object o = field.get(t);
if (Objects.isNull(o)) {
continue;
}
value = String.valueOf(o);
} catch (IllegalAccessException var9) {
log.error("bean解析异常", var9);
}
nvList.add(new BasicNameValuePair(field.getName(), value));
}
return nvList;
}
}
public static Map<String, String> bean2MapStrVal(Object bean) {
return bean2MapStrVal(bean, HashMap.class);
}
public static Map<String, String> bean2MapStrVal(Object bean, Class<? extends Map> clz) {
Map<String, String> map = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
map = (Map)clz.getDeclaredConstructor().newInstance();
PropertyDescriptor[] var5 = descriptors;
int var6 = descriptors.length;
for(int var7 = 0; var7 < var6; ++var7) {
PropertyDescriptor descriptor = var5[var7];
String name = descriptor.getName();
Method getter = descriptor.getReadMethod();
Object value = getter.invoke(bean);
if (!StringUtils.equals(name, "class") && value != null) {
map.put(name, value.toString());
}
}
return map;
} catch (Exception var12) {
log.error("bean 2 Map error:", var12);
throw new IllegalStateException("bean 2 Map error");
}
}
public static <T, M> List<M> copyBeanList(List<T> sourceList, Class<M> targetClass) {
return (List)(CollectionUtils.isEmpty(sourceList) ? new ArrayList(0) : (List)sourceList.stream().map((source) -> {
try {
M target = targetClass.newInstance();
org.springframework.beans.BeanUtils.copyProperties(source, target);
return target;
} catch (Exception var3) {
log.error(var3.getMessage());
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toList()));
}
public static <T, M> M copyBean(T source, Class<M> targetClass) {
if (Objects.nonNull(source)) {
try {
M target = targetClass.newInstance();
org.springframework.beans.BeanUtils.copyProperties(source, target);
return target;
} catch (IllegalAccessException | InstantiationException var4) {
log.error("target class new instance error:", var4);
}
}
throw new BizException("数据不存在");
}
}