目录
邮件发送
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.6</version>
</dependency>
核心代码如下:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
* @Auther: 薛
* @Date: 2020/4/15 16:14
* @Description:
*/
public class EmailHello {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.host", "smtp.qq.com"); 设置QQ邮件服务器
prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议
prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码
// 关于QQ邮箱,还要设置SSL加密,加上以下代码即可
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//使用JavaMail发送邮件的5个步骤
//创建定义整个应用程序所需的环境信息的 Session 对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication("2509647976@qq.com", "nvqtlvnkfuqfdjhf");
}
});
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和授权码连上邮件服务器
ts.connect("smtp.qq.com", "2509647976@qq.com", "nvqtlvnkfuqfdjhf");
//4、创建邮件
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("2509647976@qq.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress("2509647976@qq.com"));
//邮件的标题
message.setSubject("只包含文本的简单邮件");
//邮件的文本内容
message.setContent("印染服务出现异常,请及时核对", "text/html;charset=UTF-8");
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
}
jdk1.8map嵌套返回集合对象实例
**Map<String, Map<String, String>> listMap = new HashMap<>();
Map<String,String> map=new HashMap<>();
Map<String,String> map2=new HashMap<>();
map.put("2020-03-05 11:22:00","256.45");
map.put("2020-03-05 11:22:00","256.45");
map2.put("2020-03-30 12:45:33","75.5");
map2.put("2020-03-28 15:45:33","647.5");
listMap.put("速度",map);
listMap.put("水瞬时流量",map2);
List<MachineAnalysisDto> collects = (List<MachineAnalysisDto>)listMap.entrySet().stream().map(f -> {
return new MachineAnalysisDto(f.getKey(), new ArrayList() {{
this.add(new IndexValueDto(f.getValue().get("currDate"), f.getValue().get("paramValue")));
}});
}).collect(Collectors.toList());
System.out.println(collects.toString());**
返回一段时间之内的时间点问题
工具类
首先需要将时间转换时间戳用于计算叠加秒数以达到计算时间点问题
public class DateUtils {
private static final Integer dataSize=90;
private DateUtils() {
}
private static DateUtils dateUtils = new DateUtils();
private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//线程限制控制获得日期实例化
public synchronized static SimpleDateFormat getSimpleDates() {
return dateUtils.sf;
}
**算法计算**
public static List<String> getTimeDiffs(String startTimeDate, Long startTime, Long endTime) {
List<String> longs = new LinkedList<>();
longs.add(startTimeDate);
//以秒的时间戳
Long x = endTime - startTime;
//得出平均时间点
Long lengths = x / 30;
Long index = startTime;
for (int i = 0; i < 29; i++) {
//转时分秒戳时间点赋值
//((int)(Math.random() * 10) + 1)
index = index + lengths;
Long demos = index * 1000;
Date date = new Date(Long.parseLong(String.valueOf(demos)));
longs.add(sf.format(date));
}
return longs;
}
/**
* 根据当前时间获取前后3分钟范围时间
* @param longtime
* @return
*/
public static List<String> getWithNowLong(String nowTime) throws Exception {
List<String> timeLists=new LinkedList<>();
Long StartLongTime = sf.parse(nowTime).getTime() / 1000;
Long beforeTime=StartLongTime-dataSize;
Long afterTime=StartLongTime+dataSize;
timeLists.add(getWithNowTime(beforeTime));
timeLists.add(getWithNowTime(afterTime));
return timeLists;
}
业务处理返回数据
将时间转时间戳别忘了除以1000(因为时间戳是以毫秒为单位的)
Long startValueTime = DateUtils.getSimpleDates().parse(startTime).getTime() / 1000;
Long endValueTime = DateUtils.getSimpleDates().parse(endTime).getTime() / 1000;
boolean statisMin = DateUtils.isStatisMin(startValueTime, endValueTime);
判断如果小于5分钟普通查询/反之取时间点
如果时间点也刚好不存在即取3分钟范围之内的数据由此即可展示趋势图了
返回时间格式时差以及格式问题
//设置中国区 时间格式 年月日时分秒
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd'T'HH:mm:ss")
//@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private Timestamp startDate;
查询两个时间段之内的所有月份
/**
*
* @param minDate 最小时间 2015-01
* @param maxDate 最大时间 2015-10
* @return 日期集合 格式为 年-月
* @throws Exception
*/
public static List<String> getMonthBetween(String minDate, String maxDate) throws Exception {
ArrayList<String> result = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
min.setTime(sdf.parse(minDate));
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
max.setTime(sdf.parse(maxDate));
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
Calendar curr = min;
while (curr.before(max)) {
result.add(sdf.format(curr.getTime()).substring(5));
curr.add(Calendar.MONTH, 1);
}
return result;
}
public static void main(String[] args) throws Exception {
String y1 = "2019-08";// 开始时间
String y2 = "2019-12";// 结束时间
List<String> monthBetween = getMonthBetween(y1, y2);
System.out.println(monthBetween.toString());
}
日期叠加遍历
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse("2019-08-07"));
while (calendar.getTime().getTime() <= sdf.parse("2019-08-13").getTime()) {
System.out.println(calendar.getTime().getTime()+"\t"+ sdf.format(new Date(Long.parseLong(String.valueOf(calendar.getTime().getTime())))));
calendar.add(Calendar.DAY_OF_YEAR, 1);
}
根据主表id查询时要求子表按顺序显示给前端
我的现在是一个主表和一个子表(子表存的是set集合)
方法有多种,我这里只演示一种--------根据java自带的比较器排序
比较器:(注意:我这里子表的主键id存的是long类型的)
package com.jux.mtqiushui.dispatching.model.compare;
import com.jux.mtqiushui.dispatching.model.DistributionStationTab1;
import java.util.Comparator;
/**
* 比较器
*/
public class Compare implements Comparator<DistributionStationTab1> {
@Override
public int compare(DistributionStationTab1 o1, DistributionStationTab1 o2) {
return Integer.decode(String.valueOf(o1.getId())) - Integer.decode(String.valueOf(o2.getId()));
}
}
在程序当中使用这个比较器类
核心代码如下:
简单解释:
Set集合默认是无序的,由此这里直接new一个TreeSet(将咱们的比较器作为参数放进去),
添加咱们之前查出来的set集合,之后将排好序的set集合放进去就行了
Set<DistributionStationTab1> distributionStationTab1s=new TreeSet<>(new Compare());
distributionStationTab1s.addAll(distributionStationTab1);
one.setDistributionStationTab1(distributionStationTab1s)
扩展:这个Comparator也可以多个条件排序
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
List<DD> list = new ArrayList<>();
DD dd=new DD();
dd.setSs(2);
dd.setTime("2019-04-18 05:16:58");
list.add(dd);
DD dd1=new DD();
dd1.setSs(6);
dd1.setTime("2019-04-18 05:15:58");
list.add(dd1);
DD dd5=new DD();
dd5.setSs(2);
dd5.setTime("2019-04-18 05:18:58");
list.add(dd5);
DD dd2=new DD();
dd2.setSs(1);
dd2.setTime("2019-04-18 05:15:55");
list.add(dd2);
DD dd55=new DD();
dd55.setSs(2);
dd55.setTime("2019-04-18 05:17:58");
list.add(dd55);
System.out.println(list.toString());
Collections.sort(list, new Comparator<DD>() {
@Override
public int compare(DD o1, DD o2) {
int cr = 0;
//第一个数与第二个数相比较 如果大于后面的数 返回正反之返回负数
//正数表示该数据往后面排反之往前推
int a = o1.getSs() - o2.getSs();
//这里第一个条件 它作为最高级
if (a != 0) {
cr = (a > 0) ? 1 : -1;
} else {
try {
//两个时间
Date parse = simpleDateFormat.parse(o1.getTime());
Date parse2 = simpleDateFormat.parse(o2.getTime());
int i = parse.compareTo(parse2);
if (i!=0){
cr=(i>0)?2:-2;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return cr;
}
});
List转Set
说明:
List集合默认是有序的,而Set集合是无序的
List允许有重复数据,而Set集合有重复数据时会覆盖掉
实例如下:
List<String> set =new ArrayList<>();
set.add("张三");
set.add("李四");
set.add("王五");
set.add("王五");
String [] strings= new String[set.size()];
int x= 0;
for (String s : set) {
strings[x]=s;
x++;
}
for (String string : strings) {
System.out.println(string);
}
//结果如下
/**
*张三
李四
王五
王五
*/
//将List<String> set =new ArrayList<>()替换为
Set<String> set=new HashSet<>();
//结果如下
/**
*李四
张三
王五
*/
复制对象于另一个对象
DD dd=new DD();
dd.setSs(18);
dd.setTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Calendar.getInstance().getTime()));
DD dd1=new DD();
BeanUtils.copyProperties(dd,dd1);
System.out.println(dd.toString());
System.out.println(dd1.toString());
}
//输出结果
/*
*DD{ss=18, time='2019-04-19 09:56:35'}
DD{ss=18, time='2019-04-19 09:56:35'}
*/
分割字符串
String demo="18,19,25";
String[] split = demo.split(",");
for (String s : split) {
System.out.print(s+"\t");
}
//输出结果 18 19 25
json字符串与字符串转对象
字符串转对象
JSON字符串实例:{
"group": {
"property": "stationName",
"direction": "ASC"
}
}
// 使用fastjson解析前端传过来的json字符串
JSONObject jsonObject = JSONObject.parseObject(param);
// 使用Map集合接收jsonObject
Map<String, Object> jsonMap = jsonObject;
// 从map集合中获取addnew对应要添加的计划管理对象
Object addJsonMaterialDefine = jsonMap.get("addnew");
// 把JSONObject的物料定义对象转成JavaBean的计划管理对象
PlanManage addPlanManage = JSONObject.toJavaObject((JSON) addJsonMaterialDefine, PlanManage.class);
//或者直接转
PlanManage addPlanManage = JSONObject.toJavaObject((JSON) addJsonMaterialDefine, PlanManage.class);
json数组转对象
//实例json数组
{
"sort": [{
"property": "userId",
"direction": "DESC"
}]
}
//转换集合
List<TaskNodeEntity> taskNodes = JSONArray.parseArray(sort,TaskNodeEntity.class);
//取值--
获得当前时间
Calendar.getInstance(TimeZone.getTimeZone("GMT+8")).getTime()
判断是否是数字
isNumeric(数据)
//如果是数字 返回true 反之false
如果整数大于Integer的承受范围,你怎么办?
//BigInteger 是java的一个强大的东西,既可以做属性的同时也有加减乘除的方法供你使用。
BigInteger bi1 = new BigInteger("5555555555555555555");
BigInteger bi2 = new BigInteger("5");
//b1.add(b2)->相加
//subtract()->相减
//multiply()->乘
//divide()->除
//它可以很好的解决数字超出范围这种问题
计算时间差(也就是从一个时间段到另一个时间段过了多长时间)
//Mysql 提供了一个函数,既可以计算分,天,年,周==
//这里举例子 为过了多少分钟 u是一张表 里面有三个字段,id,start,end
// TIMESTAMPDIFF(返回的类型,开始时间,结束时间)--
select TIMESTAMPDIFF(MINUTE,u.`start`,u.`end`) as '相差时间' from u
正则表达式校验邮箱是否满足格式
@Test
public void TestEmail() {
String emailIsHave = "^[a-zA-Z0-9]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+$";
String email = "2509647976@QQ.com";
if (email.matches(emailIsHave)) {
System.out.println("合法邮箱地址");
} else {
System.out.println("不合法邮箱地址");
}
}
JAVA计算百分比
DecimalFormat decimalFormat = new DecimalFormat("0.00");
decimalFormat.format(double1/double2)
获取RequestMapping请求参数信息
例:我要获取这个name属性的值
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE,name = "API-USER-delete")
过程如下:
//获得请求方法对象
HandlerMethod handlerMethod=(HandlerMethod) handler;
//获取接口上注解
RequestMapping annotation = handlerMethod.getMethodAnnotation(RequestMapping.class);
//获取name属性
String name = annotation.name();
java判断pdf是否双层或单层
- 引入pom依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
<scope>test</scope>
</dependency>
- java工具类
@Test
public void test11() throws Exception {
//String file="src/main/resources/正确扫描件.pdf";
String file = "src/main/resources/规章制度.pdf";
// Load the PDF document
PDDocument document = PDDocument.load(new File(file));
// Get the number of pages in the document
int pageCount = document.getNumberOfPages();
// Check if the PDF document is single or multiple layer
boolean isSingleLayer = true;
for (int i = 0; i < pageCount; i++) {
PDPage page = document.getPage(i);
Iterable<COSName> extGStateNames = page.getResources().getExtGStateNames();
boolean isHaveExtGState = extGStateNames.iterator().hasNext();
if (isHaveExtGState) {
isSingleLayer = false;
break;
}
// Close the PDF document
document.close();
// Print the result
if (isSingleLayer) {
System.out.println("The PDF document is single layer. ");
} else {
System.out.println("The PDF document is multi layer.");
}
}
}
- 拓展
tika也可以判断pdf是否双层或单层(有文字即双层)