java 笔记
校验经纬度
String lonMatch = "[\\-+]?(0?\\d{1,2}|0?\\d{1,2}\\.\\d{1,15}|1[0-7]?\\d|1[0-7]?\\d\\.\\d{1,15}|180|180\\.0{1,15})";
String latMatch = "[\\-+]?([0-8]?\\d|[0-8]?\\d\\.\\d{1,15}|90|90\\.0{1,15})";
Pattern p = Pattern.compile(lonMatch);
Matcher lntM = p.matcher(String.valueOf(lng));
if (!lntM.matches()) {
error.append("经度 不符合规范!");
}
p = Pattern.compile(latMatch);
Matcher latM = p.matcher(String.valueOf(lat));
if (!latM.matches()) {
error.append("纬度 不符合规范!");
}
日期时间戳
LocalDateTime.now().plusDays(1).toEpochSecond(ZoneOffset.of("+8"))
String respjstr=JSONObject.toJSONString(list);
对比两个list的差值
List<String> subtract = (List<String>) CollectionUtils.subtract(title, reListtile);
if (subtract.size() > 0) {
throw new InternalException("导入的模板信息与子任务的模板信息不符");
}
QueryWrapper<GGroupSceneProductArrange> productArrangeQuery = new QueryWrapper<>();
productArrangeQuery.lambda().and(
i -> i.isNull(GGroupSceneProductArrange::getType)
.or().eq(GGroupSceneProductArrange::getType, "未处理"));
String daori = LocalDateTimeUtil.beginOfDay(LocalDateTimeUtil.now()).format(DateTimeFormatter.ofPattern("yyyy-MM"));
productArrangeQuery.apply("到期月份" + " >= TO_DATE({0}, 'yyyy-MM')", daori);
String strRegionIds = busParam.get("region_ids");
if (StringUtils.isEmpty(strRegionIds)) {
String gisId = userInfo.getGisId();
JsonNode gisUserInfo = userService.getUserInfo(gisId);
strRegionIds = gisUserInfo.get("region_id").textValue();
}
List<String> regionIds = Transformation.stringToList(strRegionIds);
List<Map<String, Object>> list = GridKjyyKaoheCntAvgDao.findAllByDate(date);
List<Map<String,Object>> findAllByDate(@Param("date") String date);
BigDecimal a = new BigDecimal(value.get("平均分").asInt());
// tmpVaule.put("value", Integer.parseInt( new java.text.DecimalFormat("0").format(a.doubleValue()) ) ) ;
select * from ( select t.*, rownum from GZT_SYSUSER t ) where rownum <![CDATA[>=]]> 0 and rownum <![CDATA[<=]]> 5
Map<String, String> busParam = new HashMap<>();
userInfo.set("region_name", null == departmentRoleInfo.get("region") ? "" : departmentRoleInfo.get("region").textValue());
# 格式化数字为两位小数
DecimalFormat df = new DecimalFormat("#.##");
if (0 == value.get(tagName.textValue() + "#count2").asDouble(1))
rowNode.put("营销成功率", "0%");
else
rowNode.put("营销成功率", df.format(value.get(tagName.textValue() + "#count0").asDouble(0) / value.get(tagName.textValue() + "#count2").asDouble(1) * 100) + "%");
# 查询windows 端口是否占用的进程
netstat -ano |findstr 8666
taskkill -f -t -im 19952
// 分割字符串
String[] authParam = auth.split("\\.");
for (int i = 0; i < authParam.length; i++) {
switch (i) {
case 0:
patam.put("object_type", authParam[i]);
break;
case 1:
patam.put("action", authParam[i]);
break;
case 2:
patam.put("additional_property", authParam[i]);
break;
}
}
JsonNode range = mapper.readTree(busParam.getOrDefault("range", ""));
Map<String, String> busParam = new HashMap<>();
busParam.putAll(requestParams);
if (null != bodyParams) {
bodyParams.forEach((key, value) -> {
if (value instanceof String)
busParam.put(key, (String) value);
else
busParam.put(key, JSON.toJSONString(value));
});
;
}
attrList.addAll(list);
-- DROP
drop table SJW_KQTZ CASCADE CONSTRAINTS;
-- Create table
create table SJW_KQTZ
(
SHOW_FIELD VARCHAR2(50),
DATA_FIELD VARCHAR2(50),
KIND VARCHAR2(20),
UNIT VARCHAR2(20),
TAG VARCHAR2(20)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255;
http://vpn.zhaohu.co:28885/public/customerGroupAnalysis/exportUser?county_name=柯桥&state=[{"name": "宽带","value": "是"},{"name": "亲情网","value": "是"}]&range=[{"name": "AVG_MOU","value": [50,200]},{"name": "AVG_DOU","value": [50,2000]}]&tags=28话费合约,38档话费合约,惠购38档合约
String yearMonth=busParam.getOrDefault("sms_plan_time", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM")));
item.put("群发申请时间",LocalDateTime.ofEpochSecond((vo.get("property").get("context").get("ctime").asLong()), 0,OffsetDateTime.now().getOffset()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(yearMonthSpil[0]), Integer.parseInt(yearMonthSpil[1]),1);
// 获得年份
int year = c1.get(Calendar.YEAR);
// 获得月份
int month = c1.get(Calendar.MONTH) + 1;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
int sendTimeStart = Integer.parseInt(String.valueOf(sdf.parse(yearMonth).getTime() / 1000)) ;
int sendTimeEnd = Integer.parseInt(String.valueOf(sdf.parse(year+"-"+month).getTime() / 1000)) ;
((ObjectNode)param.get("property")).set("context.send_time",
mapper.createArrayNode()
.add(mapper.createObjectNode().put("$gte",sendTimeStart))
.add(mapper.createObjectNode().put("$lt",sendTimeEnd))
);
}
long yearMonthTime=localDateYearMonth.atStartOfDay().toEpochSecond(OffsetDateTime.now().getOffset());
String year=yearMonthSpil[0];
String month=yearMonthSpil[1];
Date getDate = Calendar.getInstance().getTime();
String dateStr1 = new SimpleDateFormat("yyyy-MM-dd").formatCalendar.getInstance().getTime()
insert_value += "to_date(" + "'" + dateStr1 + "'" +","+"'yyyy-mm-dd'" +")" + ",";
ArrayNode 转为 list
ArrayNode child_area_number = mapper.createArrayNode();
data.set("child_area_number",child_area_number);
List child_area_number = JSONObject.parseArray(String.valueOf((region.get("child_area_number"))));
ArrayNode tmp = mapper.valueToTree(list);
if (null != tmp.get(0)) {
for (JsonNode value : tmp) {
ObjectNode tmpVaule = mapper.createObjectNode();
//tmpVaule.setAll((ObjectNode) value);
tmpVaule.put("name", value.get("NAME").asText());
tmpVaule.put("value", value.get("VALUE").asText());
result.add(tmpVaule);
}
}
Iterator<Map.Entry<String, JsonNode>> entryIterator = result.fields();
while (entryIterator.hasNext()) {
Map.Entry<String, JsonNode> entry = entryIterator.next();
if (0 == entry.getValue().get("总数").asInt()) {
entryIterator.remove();
}
}
Iterator<JsonNode> entries = result.elements();
while (entries.hasNext()) {
ObjectNode entry = (ObjectNode) entries.next();
if (entry.get("value").isEmpty(null)) {
entries.remove();
}
}
StringBuilder condition = new StringBuilder();
for (String key : busParam.keySet()){
condition.append(key);
condition.append(":");
condition.append(busParam.get(key));
condition.append("$");
}
for (Map.Entry<String,String> entry:busParam.entrySet()){
condition.append(entry.getKey());
condition.append(":");
condition.append(entry.getValue());
condition.append("$");
}
JSONObject jsonObject = (JSONObject) object;
for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
Object o = entry.getValue();
if(o instanceof String) {
System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
} else {
jsonLoop(o);
}
}
# 正则
Pattern p = Pattern.compile("^1[345789][0-9]{9}$");
Matcher m = p.matcher(phone);
boolean isMatch = m.matches();
if(!isMatch)
{
throw new InternalException("当前审核账号手机号码格式不正确",3003);
}
where = where.replaceAll("^*and*$", "");
new TextNode(areaNum) 强制格式化string为jsonnode
// 层级关系
private ArrayNode generateTree(ArrayNode departments) {
ObjectNode items = mapper.createObjectNode();
for (JsonNode value: departments) {
items.set(value.get("id").asText(), value);
}
ArrayNode tree = mapper.createArrayNode();
for (JsonNode value: items) {
if (null != items.get(value.get("parent_id").asText())) {
if (null == items.get(value.get("parent_id").asText()).get("child"))
((ObjectNode)items.get(value.get("parent_id").asText())).set("child", mapper.createArrayNode());
((ArrayNode)items.get(value.get("parent_id").asText()).get("child")).add(value);
} else
tree.add(value);
}
return tree;
}
final Base64.Decoder decoder = Base64.getDecoder();
final Base64.Encoder encoder = Base64.getEncoder();
final String text = "字串文字";
final byte[] textByte = text.getBytes("UTF-8");
//编码
final String encodedText = encoder.encodeToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(decoder.decode(encodedText), "UTF-8"));
ObjectNode logParam = mapper.createObjectNode();
logParam.put("type","log_wzqd");
logParam.put("property",mapper.createObjectNode()
.put("type","wzqd_download")
.put("count",list.size())
.put("user_id",userInfo.getAttrs().get("gisId"))
.put("date",LocalDate.now().toString())
.set("create_date",mapper.createObjectNode().put("$date", LocalDateTime.now().toString()))
);
JsonNode res = jsonRpcClient.addObject(logParam);
return list;
绍兴 web服务器和 service 服务器交互
日志目录 235机器
/mnt/data/qiufawen/app/hangzhou_zhyy3_backend_java
依赖包
/mnt/data/qiufawen/java/maven/apache-maven-3.6.3/repository/
qiufawen
3Ccc4i3tquxAovwq
import com.alibaba.fastjson.JSON;
// 将 Map 转换为 实体类
User user = JSON.parseObject(JSON.toJSONString(user01), User.class);
System.out.println(user);
// 将 实体类 转换为 Map
Map map = JSON.parseObject(JSON.toJSONString(user), Map.class);
System.out.println(map);
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<String,Object>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = StringUtils.nvl(field.get(obj));
map.put(fieldName, value);
}
return map;
}
private DataSourceTransactionManager transactionManager;
使用事物
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("planOne-transaction");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus transactionStatus = transactionManager.getTransaction(def);
Boolean res = false;
ObjectNode result = mapper.createObjectNode();
result.put("result", "");
result.put("code", 3003);
try {
res = IDksService.save(reflectTest);
if (res != true) {
return result;
}
transactionManager.commit(transactionStatus);
} catch (Exception e) {
transactionManager.rollback(transactionStatus);
}
result.put("result", reflectTest.getId());
给page 类增加属性
@Transient
@TableField (exist = false)
private Integer countVideo;
Page pages = IDksService.page(new Page(page, limit), queryWrapper);
Iterator<Dks> iterator = pages.getRecords().iterator();
List<Dks> list = new ArrayList<>();
while(iterator.hasNext()) {
Dks next = iterator.next();
if(next.getCountVideo() == null){
Integer count = countVideo(next.getId());
next.setCountVideo(count) ;
}
list.add(next);
}
pages.setRecords(list);
return pages;
Page pages = IDksService.page(new Page(page, limit), queryWrapper);
Iterator<Dks> iterator = pages.getRecords().iterator();
List<Dks> list = new ArrayList<>();
while(iterator.hasNext()) {
Dks next = iterator.next();
if(next.getCountNum() == null){
Integer count = countVideo(next.getId());
next.setCountNum(count) ;
}
if(next.getPicPath() != null){
String sftpWebUrl = serviceProperties.getSftp().getWebUrl();
String [] picpath = next.getPicPath().split(",");
String pic = "";
for (int i = 0; i < picpath.length; i++) {
pic += sftpWebUrl+ "/" + picpath[i] + ",";
}
next.setPicPath(pic) ;
}
if(next.getListPicPath() != null){
String sftpWebUrl = serviceProperties.getSftp().getWebUrl();
String pic = sftpWebUrl+ "/" + next.getListPicPath();
next.setListPicPath(pic) ;
}
if(next.getTopPicPath() != null){
String sftpWebUrl = serviceProperties.getSftp().getWebUrl();
String pic = sftpWebUrl+ "/" + next.getTopPicPath();
next.setTopPicPath(pic);
}
list.add(next);
}
pages.setRecords(list);
Long start = LocalDate.parse(createDateStart).atStartOfDay().toEpochSecond(OffsetDateTime.now().getOffset());
Long end= LocalDate.parse(createDateStart).plusDay(1).atStartOfDay().toEpochSecond(OffsetDateTime.now().getOffset());
LocalDate end = LocalDate.parse(date);
LocalDate start = end.minusDays(30);
LocalDate localDate = LocalDate.parse(date);
LocalDate localStart = LocalDate.parse(month + "-01");
while (localStart.compareTo(localDate) <= 0) {
((ObjectNode)result.get("放号")).put(localStart.toString(), 0);
((ObjectNode)result.get("宽带")).put(localStart.toString(), 0);
((ObjectNode)result.get("预缴")).put(localStart.toString(), 0);
((ObjectNode)result.get("存量")).put(localStart.toString(), 0);
((ObjectNode)result.get("宽带衍生")).put(localStart.toString(), 0);
localStart = localStart.plusDays(1);
}
package util;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.DoubleNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.*;
public class Transformation {
private static final Logger logger = LoggerFactory.getLogger(Transformation.class);
public static List<String> stringToList(String param) throws IOException {
List<String> result = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
if (StringUtils.isEmpty(param))
return result;
if (param.trim().startsWith("[")) {
try {
result = mapper.readValue(param, new TypeReference<List<String>>() {
});
} catch (IOException e) {
logger.error("stringToList failed {}", e);
throw e;
}
} else
result.add(param);
return result;
}
public static Long objectToLong(Object param) {
if (param instanceof Double)
return Math.round((Double) param);
if (param instanceof Integer)
return ((Integer) param).longValue();
if (param instanceof IntNode)
return ((IntNode) param).asLong();
if (param instanceof DoubleNode)
return ((DoubleNode) param).asLong();
throw new NumberFormatException("objectToLong failed");
}
public static ArrayNode listToArrayNode(List<String> param) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ArrayNode result = mapper.createArrayNode();
if (StringUtils.isEmpty(param))
return result;
for (String value : param)
result.add(value);
return result;
}
public static String boolToString(Boolean bool) throws IOException {
if (bool)
return "是";
else
return "否";
}
public static Map<String, String> getAndTransParam(Map<String, String> requestParams, Map<String, Object> bodyParams) {
Map<String, String> busParam = new HashMap<>();
busParam.putAll(requestParams);
if (null != bodyParams) {
bodyParams.forEach((key, value) -> {
if (value instanceof String) {
busParam.put(key, (String) value);
} else {
busParam.put(key, JSON.toJSONString(value));
}
});
}
return busParam;
}
public static ObjectNode mapToJson(Map<String, String> busParam) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode receive = mapper.createObjectNode();
busParam.forEach((key, value) -> {
try {
if (!StringUtils.isEmpty(value))
receive.set(key, mapper.readTree(value));
} catch (IOException e) {
receive.put(key, value);
}
});
return receive;
}
public static boolean checkArr(String type, ArrayNode name) {
for (JsonNode value : name) {
if (type.equals(value.asText())) {
return true;
}
}
return false;
}
// public static Long jsonFormate(Object param, ) {
// if (param instanceof Double)
// return Math.round((Double) param);
// if (param instanceof Integer)
// return ((Integer) param).longValue();
// if (param instanceof IntNode)
// return ((IntNode) param).asLong();
// if (param instanceof DoubleNode)
// return ((DoubleNode) param).asLong();
// throw new NumberFormatException("objectToLong failed");
// }
public static LocalDate dateAfter(LocalDate localDate, Integer days) {
while (days > 0) {
localDate = localDate.plusDays(1);
if (localDate.getDayOfWeek() == DayOfWeek.SATURDAY || localDate.getDayOfWeek() == DayOfWeek.SUNDAY) {
days++;
}
days--;
}
return localDate;
}
public static ObjectNode sortObjectNode(ObjectNode node) throws IOException {
List<JsonNode> listNode = new ArrayList<>();
Iterator<String> filed = node.fieldNames();
ObjectMapper mapper = new ObjectMapper();
while (filed.hasNext()) {
String key = filed.next();
ObjectNode tmp = mapper.createObjectNode();
tmp.put("value", node.get(key).asDouble());
tmp.put("fieldName", key);
listNode.add(tmp);
}
//质差展示排序
listNode.sort(new Comparator<JsonNode>() {
@Override
public int compare(JsonNode o1, JsonNode o2) {
return (int) (o2.get("value").asDouble() - o1.get("value").asDouble());
}
});
ObjectNode result = mapper.createObjectNode();
for (JsonNode value : listNode) {
result.set(value.get("fieldName").asText(), value);
}
return result;
}
public static ObjectNode sortObjectNode(ObjectNode node, String field) throws IOException {
List<JsonNode> listNode = new ArrayList<>();
Iterator<String> filed = node.fieldNames();
while (filed.hasNext()) {
String key = filed.next();
((ObjectNode) node.get(key)).put("fieldName", key);
listNode.add(node.get(key));
}
listNode.sort(new Comparator<JsonNode>() {
@Override
public int compare(JsonNode o1, JsonNode o2) {
return (int) (o2.get(field).asDouble() - o1.get(field).asDouble());
}
});
ObjectMapper mapper = new ObjectMapper();
ObjectNode result = mapper.createObjectNode();
for (JsonNode value : listNode) {
result.set(value.get("fieldName").asText(), value);
}
return result;
}
public static ArrayNode sortArrayNode(ArrayNode node, String field) throws IOException {
List<JsonNode> listNode = new ArrayList<>();
for (JsonNode value : node)
listNode.add(value);
//质差展示排序
listNode.sort(new Comparator<JsonNode>() {
@Override
public int compare(JsonNode o1, JsonNode o2) {
return (int) (o2.get(field).asDouble() - o1.get(field).asDouble());
}
});
ObjectMapper mapper = new ObjectMapper();
ArrayNode result = mapper.createArrayNode();
for (JsonNode value : listNode) {
result.add(value);
}
return result;
}
public static ArrayNode sortArrayNodeAes(ArrayNode node, String field) throws IOException {
List<JsonNode> listNode = new ArrayList<>();
for (JsonNode value : node)
listNode.add(value);
//质差展示排序
listNode.sort(new Comparator<JsonNode>() {
@Override
public int compare(JsonNode o1, JsonNode o2) {
return (int) (o1.get(field).asDouble() - o2.get(field).asDouble());
}
});
ObjectMapper mapper = new ObjectMapper();
ArrayNode result = mapper.createArrayNode();
for (JsonNode value : listNode) {
result.add(value);
}
return result;
}
/**
* 获取模糊的手机号码
*
* @param phone
* @return
*/
public static String getPhone(String phone2) {
return phone2.substring(0, 3) + "****" + phone2.substring(7, phone2.length());
}
public static String fuzzyString(String original, int start, int length) {
if (original.length() > start + length - 1)
return original.substring(0, start) + "****".substring(0, length) + original.substring(start + length, original.length());
else if (original.length() > start)
return original.substring(0, start) + "****".substring(0, length) + original.substring(start + length, original.length());
else
return original;
}
public static String fuzzyStringMid4(String original) {
if (original.length() == 0)
return original;
else if (original.length() == 1)
return original;
else if (original.length() == 2)
return original.substring(0, 1) + "*";
else if (original.length() == 3)
return original.substring(0, 1) + "*" + original.substring(2);
else if (original.length() == 4)
return original.substring(0, 1) + "**" + original.substring(3);
else if (original.length() == 5)
return original.substring(0, 2) + "**" + original.substring(4);
else if (original.length() == 6)
return original.substring(0, 2) + "**" + original.substring(5);
else {
int start = original.length() / 2 - 2;
return original.substring(0, start) + "****" + original.substring(start + 4);
}
}
// 获取过去第几天的日期
public static String getPastDate(int past,Date date,String format) {
format = format.isEmpty() ?"yyyy-MM-dd" : "yyyyMMdd";
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - past);
Date today = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat(format);
String result = sdf.format(today);
return result;
}
/**
* 将指定格式的日期字符串转换为日期对象。
*/
public static Date parseDate(String source, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(source, new ParsePosition(0));
}
}
// 获取当前时间的前3个月的时间
Date dNow = new Date(); //当前时间
Date dBefore = new Date();
Calendar calendar = Calendar.getInstance(); //得到日历
calendar.setTime(dNow);//把当前时间赋给日历
calendar.add(Calendar.MONTH, -3); //设置为前3月
dBefore = calendar.getTime(); //得到前3月的时间
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); // yyyy-MM-dd HH:mm:ss 设置时间格式
String defaultStartDate = sdf.format(dBefore); //格式化前3月的时间
String defaultEndDate = sdf.format(dNow); //格式化当前时间
使用 to_date 函数注意事项
ISODate
additionalProperty.set("create_date", mapper.createObjectNode().put("$date", LocalDateTime.now().toString()));
// mongo时间筛选
ObjectNode timeValue = mapper.createObjectNode();
// "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date startTime = sdf1.parse(start_time+" 00:00:00");
String startTimeS = sdf2.format(startTime);
Date endTime = sdf1.parse(end_time+" 23:59:59");
String endTimeS = sdf2.format(endTime);
timeValue.set("$gte",mapper.createObjectNode().put("$date", startTimeS));;
timeValue.set("$lte",mapper.createObjectNode().put("$date", endTimeS));
property.set("user_info.create_date",timeValue);
模糊搜索
property.set("模板名称", mapper.createObjectNode()
.put("$regex", ".*" + likeTmpName + ".*")
.put("$options", "i"));
倒序
param.set("sort",
mapper.createArrayNode().add(mapper.createArrayNode().add("property.user_info.create_time").add(-1)));
ArrayNode records = jsonRpcClient.findObject(param);
转化为时间戳
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
String deadline = "2012-02=12";
Date deadlineTime = format.parse(deadline).getTime();
转化为时间格式
Long deadline = "145483518";
Date deadlineDate = format.parse(deadline);
queryWrapper.apply(column + " >= TO_DATE({0}, 'yyyy/MM/dd HH24:mi:ss')", field.get(msgBody));
QueryWrapper<BusinessOppt> businessOpptQueryWrapper = new QueryWrapper<>();
businessOpptQueryWrapper.apply( " to_char(上报人时间,'yyyy') = {0} ", defaultEndDate);
import com.alibaba.fastjson.JSONArray;
List<String> numList = new ArrayList<String>();
List<MarketingTaskScene> scene = marketingTaskTag.getScene();
JSONArray sceneJson = (JSONArray) JSONArray.toJSON(scene); || Object sceneJson = JSONObject.toJSON(scene);
JsonNode sceneJsons = mapper.readTree(String.valueOf(sceneJson));
JSONArray sceneJson = (JSONArray) JSONArray.toJSON(scene);
JsonNode sceneJsons = mapper.readTree(String.valueOf(sceneJson));
java 建表 方法
String 是 = "NET_CODE, ORG_ID, ORG_NAME, PARENT_ID, PARENT_NAME, AREA_CODE, AREA_NAME, COUNTY_CODE, COUNTY_NAME, REGION_CODE, REGION_NAME, MANAGER_ID, MANAGER_NAME, MANAGER_PHONE, BUSINESS_CIRCLE_ID, BUSINESS_CIRCLE_NAME, BUSINESS_CIRCLE_TYPE, BUSINESS_LEVEL, CHANNEL_TYPE, 一级类型, CHANNEL_TYPE_DTL, 二级类型, CHANNEL_TYPE_DTL3, 三级类型, ORG_TYPE, ORG_TYPE_DTL, STAR_LEVEL, ORG_STATUS, 渠道状态, STORE_STATUS, 厅店状态, OPERATE_TYPE, SETUP_DATE, BUSINESS_CODE, OWNER_ID_CARD, OWNER_NAME, OWNER_PHONE, CONTACT_PERSON, CONTACT_PHONE, ADDRESS, COUNTRY_CODE, THORPE_CODE, THORPE_NAME, THORPE_LEVEL, LONGITUDE, LATITUDE, SLIGHT_AREA_ID, SLIGHT_AREA_NAME, IS_SPECIALIZED, IS_CHAIN_ORG, CHAIN_ORG_ID, CHAIN_ORG_NAME, CHAIN_ORG_TYPE, REL_BUSI_HALL, REL_BUSI_HALL_NAME, GL_YYT_NAME, 营业督导人员编号, 营业督导名称, 营业督导电话, 营业店长人员编号, 营业店长名称, 营业店长电话";
String s = "create table v_sys_org_area_cfg\n" +
"(";
String[] ss = 是.split(",");
for (int i = 0; i < ss .length; i++) {
s += ss[i] + " varchar2(200), ";
}
s += ")" +
"tablespace USERS" +
" storage" +
" (" +
" initial 64K" +
" minextents 1" +
" maxextents unlimited" +
" );";
result.put("wqqw", s);
# mybatis
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
configuration:
map-underscore-to-camel-case: true
jdbc-type-for-null: 'null'
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
## Swagger :配置相关
访问链接:http//XXX:2020/swagger-ui.html#/
application.yml
swaggerShow:
show: true
SecurityFilter(注释) :
req.getRequestURI().startsWith("/swagger") || req.getRequestURI().startsWith("/v2/api-docs")
## SwaggerConfig 配置文件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2//开启Swagger2的注解
public class SwaggerConfig {
@Bean
public Docket mydocket1(){
//创建一个docket实例
return new Docket(DocumentationType.SWAGGER_2).apiInfo(new ApiInfo(
"绍兴接口文档",
"songmengxin1",
"1.0",
"urn:tos",
new Contact("一组宋梦鑫", "http://www.baidu.com", "1965165473@qq.com"),
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()))
.groupName("项目一组")
.select()
.apis(RequestHandlerSelectors.basePackage("com.heguang.service.controller"))
.build();
}
}
# controller 使用方式
@ApiOperation(value = "增加日志")
@ApiImplicitParams({
@ApiImplicitParam(value="应用平台:large 大屏、medium 中屏",name = "application",dataTypeClass = String.class),
@ApiImplicitParam(value = "网格名称,大屏为空,中屏需要传",name = "gird_name",dataTypeClass = String.class),
})
获取配置文件的值
@Value("${spring.profiles.active}")
String profile;
mybatis-plus:
# 扫描 mapper.xml
mapper-locations: classpath:/mapper/*Mapper.xml
# 支持统配符 * 或者 ; 分割
typeEnumsPackage: com.heguang.service.enums
configuration:
jdbc-type-for-null: 'null'
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
// 将 Map 转换为 实体类
User user = JSON.parseObject(JSON.toJSONString(user01), User.class);
System.out.println(user);
// 将 实体类 转换为 Map
Map map = JSON.parseObject(JSON.toJSONString(user), Map.class);
System.out.println(map);
// 调用远程接口
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
// 设置请求参数
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
postParameters.add("paramjson", mapper.writeValueAsString(param));
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(postParameters, headers);
String resp = "{}";
if (profile.contains("prod")) {
resp = jsonRpcClient.postForObject("http://tz-webdev05.zj.chinamobile.com/wrdpv3/_saas/_app/tzTaskManageV3.app/service/jsonService.db/startProcess.port?open", httpEntity, String.class);
} else
resp = "{\"result\":true}";
// 时间戳 查询
ObjectNode timeValue = mapper.createObjectNode();// "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
if(!StringUtils.isEmpty(smsMonitoringTemplate.getStartDate())){
LocalDateTime startTime =
LocalDateTime.parse(smsMonitoringTemplate.getStartDate()+" 00:00:00",df);
int startTimestamp =
(int)startTime.toEpochSecond(ZoneOffset.of("+8"));
timeValue.put("$gte",startTimestamp);
}
if(!StringUtils.isEmpty(smsMonitoringTemplate.getEndDate())){
LocalDateTime endTime =
LocalDateTime.parse(smsMonitoringTemplate.getEndDate()+" 00:00:00",df);
int endTimestamp =
(int)endTime.toEpochSecond(ZoneOffset.of("+8"));
timeValue.put("$gte",endTimestamp);
}
wrapper.lambda()
.or().or(
w -> w.eq(Zly8ZhkbWgsdb::getCountyname, zly8ZhkbWgsdb.getAreaname())
.isNotNull(Zly8ZhkbWgsdb::getWgid))
.or().or(
w -> w.eq(Zly8ZhkbWgsdb::getWgname, zly8ZhkbWgsdb.getAreaname()));
stream 用法
Set<Long> setUserId = new HashSet<>();
setUserId.add(clueDTO.getUserId());
List<Long> userIds = (new ArrayList<>(setUserId)).stream().collect(Collectors.toMap(SysUserDTO::getUserId, x -> x)
lamda 使用多个字段 如何map
dto.setAssistUserNames( followUpResultAssistUserMap.get(dto.getId()).stream()
.map((SysUserDTO sysUser) -> sysUser.getNickname() + "" + sysUser.getUsername())
.collect(Collectors.joining(";")));
税款计算方法
public static void main(String[] args) {
BigDecimal 初始值 = new BigDecimal("9204");
BigDecimal 累计值 = new BigDecimal("100");
BigDecimal 利率 = new BigDecimal("0.001667");
BigDecimal 利率值 = BigDecimal.ZERO;
BigDecimal 中间值 = BigDecimal.ZERO;
BigDecimal 结果值 = BigDecimal.ZERO;
for (int i = 0; i < 12; i++) {
中间值 = (初始值.add(累计值));
利率值 = 中间值.multiply(利率);
初始值 = (中间值.add(利率值));
System.out.println(i);
System.out.println((利率值.setScale(2, BigDecimal.ROUND_DOWN)));
结果值 = 结果值.add( 利率值.setScale(2, BigDecimal.ROUND_DOWN));
System.out.println(初始值.setScale(2, BigDecimal.ROUND_DOWN));
}
System.out.println("结果值");
System.out.println(结果值);
}