A股项目迁移
This commit is contained in:
22
src/main/java/cn/stock/market/utils/Cons.java
Normal file
22
src/main/java/cn/stock/market/utils/Cons.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
public final class Cons {
|
||||
public class QPlantForm {
|
||||
public static final String USER_APP = "user_app";
|
||||
public static final String SHOP_APP = "shop_app";
|
||||
public static final String SHOP_WEB = "shop_web";
|
||||
}
|
||||
|
||||
/**
|
||||
* 设备类型
|
||||
*/
|
||||
public class QDeviceType {
|
||||
|
||||
public static final String IOS = "ios";
|
||||
public static final String ANDROID = "android";
|
||||
public static final String WEB_PC = "web_pc";
|
||||
|
||||
// 后续扩展 微信公众号、小程序、支付宝
|
||||
}
|
||||
|
||||
}
|
||||
192
src/main/java/cn/stock/market/utils/DateTimeUtil.java
Normal file
192
src/main/java/cn/stock/market/utils/DateTimeUtil.java
Normal file
@@ -0,0 +1,192 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Calendar;
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
import org.joda.time.format.DateTimeFormatter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
public class DateTimeUtil {
|
||||
private static final Logger log = LoggerFactory.getLogger(DateTimeUtil.class);
|
||||
|
||||
|
||||
public static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
|
||||
public static final String YMD_FORMAT = "yyyy-MM-dd";
|
||||
|
||||
|
||||
public static final String HM_FORMAT = "HH:mm";
|
||||
|
||||
|
||||
public static Date getCurrentDate() {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
|
||||
public static Date strToDate(String dateTimeStr, String formatStr) {
|
||||
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
|
||||
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
|
||||
return dateTime.toDate();
|
||||
}
|
||||
|
||||
|
||||
public static String dateToStr(Date date, String formatStr) {
|
||||
if (date == null) {
|
||||
return "";
|
||||
}
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime.toString(formatStr);
|
||||
}
|
||||
|
||||
public static Date strToDate(String dateTimeStr) {
|
||||
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
|
||||
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
|
||||
return dateTime.toDate();
|
||||
}
|
||||
|
||||
/*
|
||||
* 将时间转换为时间戳
|
||||
*/
|
||||
public static String dateToStamp(String time){
|
||||
String stamp = "";
|
||||
if (!"".equals(time)) {//时间不为空
|
||||
try {
|
||||
String res;
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
Date date = simpleDateFormat.parse(time);
|
||||
long ts = date.getTime();
|
||||
res = String.valueOf(ts);
|
||||
return res;
|
||||
} catch (Exception e) {
|
||||
System.out.println("参数为空!");
|
||||
}
|
||||
}else { //时间为空
|
||||
long current_time = System.currentTimeMillis(); //获取当前时间
|
||||
stamp = String.valueOf(current_time/1000);
|
||||
}
|
||||
return stamp;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* 将时间戳转换为时间
|
||||
*/
|
||||
public static String stampToDate(String s){
|
||||
String res;
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
long lt = new Long(s);
|
||||
Date date = new Date(lt);
|
||||
res = simpleDateFormat.format(date);
|
||||
return res;
|
||||
}
|
||||
|
||||
/*获取当前时间戳*/
|
||||
public static String getStampNow() {
|
||||
Long startTs = System.currentTimeMillis(); // 当前时间戳
|
||||
return startTs.toString();
|
||||
}
|
||||
|
||||
|
||||
public static Timestamp searchStrToTimestamp(String dateTimeStr) {
|
||||
return Timestamp.valueOf(dateTimeStr);
|
||||
}
|
||||
|
||||
|
||||
public static String dateToStr(Date date) {
|
||||
if (date == null) {
|
||||
return "";
|
||||
}
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime.toString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
|
||||
public static Date longToDate(Long time) {
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
String d = format.format(time);
|
||||
|
||||
Date date = null;
|
||||
try {
|
||||
date = format.parse(d);
|
||||
} catch (Exception e) {
|
||||
log.error("datetime utils longToDate error");
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
|
||||
public static Date doEndTime(Date begintime, int month) {
|
||||
Long begintimelong = Long.valueOf(begintime.getTime() / 1000L);
|
||||
log.info("计算时间 传入时间 = {} , 时间戳 = {}", dateToStr(begintime), begintimelong);
|
||||
|
||||
Long endtimelong = Long.valueOf(begintimelong.longValue() + (2592000 * month));
|
||||
Date endtimedate = longToDate(Long.valueOf(endtimelong.longValue() * 1000L));
|
||||
|
||||
log.info("endtime 时间戳 = {},时间 = {} , 格式化时间={}", new Object[]{endtimelong, endtimedate,
|
||||
dateToStr(endtimedate)});
|
||||
|
||||
return endtimedate;
|
||||
}
|
||||
|
||||
|
||||
public static String getCurrentTimeMiao() {
|
||||
return String.valueOf(System.currentTimeMillis() / 1000L);
|
||||
}
|
||||
|
||||
|
||||
public static Date parseToDateByMinute(int minuteTimes) {
|
||||
Date nowDate = new Date();
|
||||
Long nowtimes = Long.valueOf(nowDate.getTime() / 1000L);
|
||||
|
||||
Long beginTimesLong = Long.valueOf(nowtimes.longValue() - (minuteTimes * 60));
|
||||
return longToDate(Long.valueOf(beginTimesLong.longValue() * 1000L));
|
||||
}
|
||||
|
||||
|
||||
public static boolean isCanSell(Date buyDate, int maxMinutes) {
|
||||
Long buyDateTimes = Long.valueOf(buyDate.getTime() / 1000L);
|
||||
|
||||
buyDateTimes = Long.valueOf(buyDateTimes.longValue() + (maxMinutes * 60));
|
||||
|
||||
Long nowDateTimes = Long.valueOf((new Date()).getTime() / 1000L);
|
||||
|
||||
if (nowDateTimes.longValue() > buyDateTimes.longValue()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*日期年月日是否相同*/
|
||||
public static boolean sameDate(Date d1, Date d2) {
|
||||
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
|
||||
//fmt.setTimeZone(new TimeZone()); // 如果需要设置时间区域,可以在这里设置
|
||||
return fmt.format(d1).equals(fmt.format(d2));
|
||||
}
|
||||
|
||||
/**
|
||||
* 【参考】https://www.cnblogs.com/zhaoKeju-bokeyuan/p/12125711.html
|
||||
* 基于指定日期增加天数
|
||||
* @param date
|
||||
* @param num 整数往后推,负数往前移
|
||||
* @return
|
||||
*/
|
||||
public static Date addDay(Date date,int num) {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
cal.add(Calendar.DATE, num);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
parseToDateByMinute(10);
|
||||
}
|
||||
}
|
||||
69
src/main/java/cn/stock/market/utils/ExTrans.java
Normal file
69
src/main/java/cn/stock/market/utils/ExTrans.java
Normal file
@@ -0,0 +1,69 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
import org.springframework.transaction.support.DefaultTransactionDefinition;
|
||||
|
||||
import cn.qutaojing.common.utils.SpringUtils;
|
||||
|
||||
/**
|
||||
*
|
||||
* title: TranUtils.java
|
||||
*
|
||||
* @author xlfd
|
||||
* @email xlfd@gmail.com
|
||||
* @version 1.0
|
||||
* @created Aug 27, 2020 2:40:02 PM
|
||||
*/
|
||||
public class ExTrans {
|
||||
static JpaTransactionManager transactionManager;
|
||||
static ExTrans tranUtils;
|
||||
|
||||
public static ExTrans of() {
|
||||
if(tranUtils == null) {
|
||||
tranUtils = new ExTrans();
|
||||
}
|
||||
|
||||
return tranUtils;
|
||||
}
|
||||
|
||||
JpaTransactionManager getJpaTransactionManager() {
|
||||
if(transactionManager == null) {
|
||||
transactionManager = SpringUtils.getBean("transactionManager");
|
||||
}
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
public TransactionStatus requiresNew() {
|
||||
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
|
||||
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
TransactionStatus status = getJpaTransactionManager().getTransaction(def);
|
||||
return status;
|
||||
}
|
||||
|
||||
public void commit(TransactionStatus status) {
|
||||
if(! status.isCompleted()) {
|
||||
getJpaTransactionManager().commit(status);
|
||||
}
|
||||
}
|
||||
|
||||
public void rollback(TransactionStatus status) {
|
||||
if(! status.isCompleted()) {
|
||||
getJpaTransactionManager().rollback(status);
|
||||
}
|
||||
}
|
||||
|
||||
public void exec(Consumer<TransactionStatus> c) {
|
||||
TransactionStatus status = requiresNew();
|
||||
try {
|
||||
c.accept(status);
|
||||
commit(status);
|
||||
} catch(Exception e) {
|
||||
rollback(status);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
182
src/main/java/cn/stock/market/utils/ExceptionHandler.java
Normal file
182
src/main/java/cn/stock/market/utils/ExceptionHandler.java
Normal file
@@ -0,0 +1,182 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.multipart.MultipartException;
|
||||
import org.springframework.web.multipart.support.MissingServletRequestPartException;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.util.ContentCachingRequestWrapper;
|
||||
|
||||
import com.ag.exception.CodeException;
|
||||
import com.ag.exception.CommonCode;
|
||||
import com.ag.utils.CollectionUtils;
|
||||
import com.ag.utils.RequestUtils;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import cn.qutaojing.common.constant.ExceptionHttpStatus;
|
||||
import cn.qutaojing.common.constant.Loggers;
|
||||
import cn.qutaojing.common.utils.R;
|
||||
|
||||
/**
|
||||
*
|
||||
* title: ExceptionHandler.java 异常句柄
|
||||
*
|
||||
* @author rplees
|
||||
* @email rplees.i.ly@gmail.com
|
||||
* @version 1.0
|
||||
* @created 2015年9月16日 下午3:40:35
|
||||
*/
|
||||
public class ExceptionHandler implements HandlerExceptionResolver {
|
||||
HttpStatus httpStatus;
|
||||
public ExceptionHandler(HttpStatus httpStatus) {
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
|
||||
private Object prettyString(String s) {
|
||||
try {
|
||||
return JSON.parse(s);
|
||||
} catch(Exception ex) {
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
private ModelAndView mv(Object handler, Map<String, Object> map) {
|
||||
map.put("status", map.get("code"));
|
||||
map.remove("code");
|
||||
if(handler instanceof HandlerMethod) {
|
||||
HandlerMethod handlerMethod = (HandlerMethod) handler;
|
||||
boolean isResponseBody = handlerMethod.getMethod().isAnnotationPresent(ResponseBody.class)
|
||||
|| handlerMethod.getBeanType().isAnnotationPresent(RestController.class);
|
||||
|
||||
if(isResponseBody) {
|
||||
return new ModelAndView(new FastJsonJsonView(), map);
|
||||
} else {
|
||||
return new ModelAndView("exception", map);
|
||||
}
|
||||
}
|
||||
return new ModelAndView(new FastJsonJsonView(), map);
|
||||
}
|
||||
|
||||
public static CodeException getCodeException(Exception ex) {
|
||||
Throwable throwable = ex;
|
||||
|
||||
while(throwable != null) {
|
||||
if(throwable instanceof CodeException) {
|
||||
return (CodeException) throwable;
|
||||
}
|
||||
|
||||
throwable = throwable.getCause();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
|
||||
Exception ex) {
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
boolean printStackTrace = true;
|
||||
CodeException ce = getCodeException(ex);
|
||||
|
||||
if (ce != null) {// 自定义异常
|
||||
map = ce.toMap();
|
||||
printStackTrace = false;
|
||||
} else if(ex instanceof MissingServletRequestPartException) {
|
||||
map = R.error(-1,"请上传图片");
|
||||
} else if (ex instanceof SQLException || ex instanceof DataAccessException) {
|
||||
if(ex instanceof InvalidDataAccessApiUsageException) {
|
||||
InvalidDataAccessApiUsageException idaau = ((InvalidDataAccessApiUsageException) ex);
|
||||
if(idaau.getCause() != null && idaau.getCause() instanceof IllegalArgumentException) {
|
||||
map = R.error(-1, idaau.getCause().getLocalizedMessage());
|
||||
printStackTrace = false;
|
||||
} else {
|
||||
map = R.error(CommonCode.SQL_EXCEPTION, "哎呀,服务器出错啦!");
|
||||
}
|
||||
} else if(ex instanceof DataIntegrityViolationException) {//违法了唯一约束
|
||||
printStackTrace = true;
|
||||
map = R.error(CommonCode.SQL_EXCEPTION, "请稍后重试");
|
||||
} else {
|
||||
map = R.error(CommonCode.SQL_EXCEPTION, "哎呀,服务器出错啦!");
|
||||
}
|
||||
} else if (ex instanceof MultipartException) {
|
||||
map = R.error(CommonCode.FILE_UPLOAD_ERROR, "文件上传失败,切换网络试试!");
|
||||
} else if (ex instanceof NullPointerException) {
|
||||
map = R.error(CommonCode.NULL_POINT_ERROR, ",服务器出错啦!请稍后重试");
|
||||
} else if (ex instanceof ArrayIndexOutOfBoundsException) {
|
||||
map = R.error(CommonCode.ARRAY_INDEXOUTOF_BOUNDS, "哎呀,服务器出错啦!请稍后重试");
|
||||
} else {
|
||||
map = R.error(-1, ex.getLocalizedMessage());
|
||||
}
|
||||
|
||||
// entry.value 不能为null
|
||||
List<String> nullKeyValueList = Lists.newArrayList();
|
||||
for(Map.Entry<String, Object> e : map.entrySet()) {
|
||||
if(e.getValue() == null) {
|
||||
nullKeyValueList.add(e.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
if(CollectionUtils.isNotEmpty(nullKeyValueList)) {
|
||||
for (String nukkKey : nullKeyValueList) {
|
||||
map.put(nukkKey, "null");
|
||||
}
|
||||
}
|
||||
|
||||
//logger
|
||||
Object p = null;
|
||||
if("POST".equalsIgnoreCase(request.getMethod())) {//POST
|
||||
if(request instanceof ContentCachingRequestWrapper) {
|
||||
ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) request;
|
||||
p = prettyString(new String(requestWrapper.getContentAsByteArray()));
|
||||
} else {
|
||||
p = RequestUtils.getPostParm(request);
|
||||
}
|
||||
} else {
|
||||
p = JSON.toJSON(request.getParameterMap());
|
||||
}
|
||||
|
||||
String message = String.format("请求地址:%s>>>%s<<<,参数:%s, 异常信息:%s,请求头:%s", request.getRequestURI(), request.getMethod(), p, ex.toString(), JSON.toJSONString(RequestUtils.getRequestHeaders(request)));
|
||||
Loggers.EXCEPTION.error(message, printStackTrace ? ex : null);
|
||||
|
||||
//httpstatus
|
||||
HttpStatus httpStatus = this.httpStatus;
|
||||
if(handler instanceof HandlerMethod) {
|
||||
HandlerMethod handlerMethod = (HandlerMethod) handler;
|
||||
boolean hasAnno = handlerMethod.getMethod().isAnnotationPresent(ExceptionHttpStatus.class)
|
||||
|| handlerMethod.getBeanType().isAnnotationPresent(ExceptionHttpStatus.class);
|
||||
|
||||
if(hasAnno) {
|
||||
ExceptionHttpStatus annotation = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), ExceptionHttpStatus.class);
|
||||
if(annotation == null) {
|
||||
annotation = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), ExceptionHttpStatus.class);
|
||||
}
|
||||
|
||||
if(annotation != null) {
|
||||
httpStatus = annotation.status();
|
||||
response.setStatus(httpStatus.value());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//view
|
||||
return mv(handler, map);
|
||||
}
|
||||
}
|
||||
74
src/main/java/cn/stock/market/utils/Exports.java
Normal file
74
src/main/java/cn/stock/market/utils/Exports.java
Normal file
@@ -0,0 +1,74 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import com.ag.utils.CollectionUtils;
|
||||
import com.ag.utils.DateUtils;
|
||||
import com.ag.utils.Jsons;
|
||||
import com.alibaba.excel.EasyExcel;
|
||||
import com.alibaba.excel.ExcelWriter;
|
||||
import com.alibaba.excel.write.metadata.WriteSheet;
|
||||
import com.alibaba.excel.write.metadata.fill.FillWrapper;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
/**
|
||||
* @author xlfd
|
||||
* @email xlfd@gmail.com
|
||||
* @version 1.0
|
||||
* @created Jul 1, 2021 11:26:24 AM
|
||||
*/
|
||||
public final class Exports {
|
||||
|
||||
static void one(JSONObject root, String key, Object value) {
|
||||
if(value instanceof JSONObject) {
|
||||
for(Map.Entry<String, Object> entry : ((JSONObject) value).entrySet()) {
|
||||
String newKey = key + "_" + entry.getKey();
|
||||
one(root, newKey, entry.getValue());
|
||||
}
|
||||
} else {
|
||||
root.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void export(String title, String tmpl, List<T> l, HttpServletResponse response) throws IOException {
|
||||
export(title, tmpl, l, null, response);
|
||||
}
|
||||
|
||||
public static <T> void export(String title, String tmpl, List<T> l, Function<T, Map<String, Object>> func, HttpServletResponse response) throws IOException {
|
||||
List<JSONObject> list = l.stream().map(val -> {
|
||||
JSONObject json = Jsons.toJSON(val);
|
||||
if(func != null) {
|
||||
Map<String, Object> map = func.apply(val);
|
||||
if(CollectionUtils.isNotEmpty(map)) {
|
||||
for(Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
one(json, entry.getKey(), Jsons.toJSON(entry.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return json;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
String fileName = String.format("%s导出%s.xlsx", title, DateUtils.format("yyyyMMddHH", new Date()));
|
||||
|
||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
|
||||
|
||||
InputStream templateInputStream = Exports.class.getResourceAsStream(tmpl);
|
||||
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateInputStream).build();
|
||||
WriteSheet writeSheet = EasyExcel.writerSheet().build();
|
||||
excelWriter.fill(new FillWrapper("list", list), writeSheet);
|
||||
excelWriter.finish();
|
||||
}
|
||||
}
|
||||
109
src/main/java/cn/stock/market/utils/GetPyByChinese.java
Normal file
109
src/main/java/cn/stock/market/utils/GetPyByChinese.java
Normal file
@@ -0,0 +1,109 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Hashtable;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import net.sourceforge.pinyin4j.PinyinHelper;
|
||||
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
|
||||
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
|
||||
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
|
||||
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
|
||||
|
||||
public class GetPyByChinese {
|
||||
public static void main(String[] args) {
|
||||
System.out.println(converterToFirstSpell("长沙市长"));
|
||||
System.out.println(converterToFirstSpell("平安银行"));
|
||||
System.out.println(converterToFirstSpell("老板电器"));
|
||||
}
|
||||
|
||||
public static String converterToFirstSpell(String chines) {
|
||||
StringBuffer pinyinName = new StringBuffer();
|
||||
char[] nameChar = chines.toCharArray();
|
||||
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
|
||||
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
|
||||
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
|
||||
for (int i = 0; i < nameChar.length; i++) {
|
||||
if (nameChar[i] > '') {
|
||||
try {
|
||||
String[] strs = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
|
||||
if (strs != null) {
|
||||
for (int j = 0; j < strs.length; j++) {
|
||||
pinyinName.append(strs[j].charAt(0));
|
||||
if (j != strs.length - 1) {
|
||||
pinyinName.append(",");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (BadHanyuPinyinOutputFormatCombination e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
pinyinName.append(nameChar[i]);
|
||||
}
|
||||
pinyinName.append(" ");
|
||||
}
|
||||
|
||||
return parseTheChineseByObject(discountTheChinese(pinyinName.toString()));
|
||||
}
|
||||
|
||||
|
||||
private static List<Map<String, Integer>> discountTheChinese(String theStr) {
|
||||
List<Map<String, Integer>> mapList = new ArrayList<Map<String, Integer>>();
|
||||
Map<String, Integer> onlyOne = null;
|
||||
String[] firsts = theStr.split(" ");
|
||||
for (String str : firsts) {
|
||||
onlyOne = new Hashtable<String, Integer>();
|
||||
String[] china = str.split(",");
|
||||
for (String s : china) {
|
||||
Integer count = onlyOne.get(s);
|
||||
if (count == null) {
|
||||
onlyOne.put(s, new Integer(1));
|
||||
} else {
|
||||
onlyOne.remove(s);
|
||||
Integer integer1=count,integer2=count=Integer.valueOf(count.intValue() + 1);
|
||||
onlyOne.put(s, count);
|
||||
}
|
||||
}
|
||||
mapList.add(onlyOne);
|
||||
}
|
||||
return mapList;
|
||||
}
|
||||
|
||||
|
||||
private static String parseTheChineseByObject(List<Map<String, Integer>> list) {
|
||||
Map<String, Integer> first = null;
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
Map<String, Integer> temp = new Hashtable<>();
|
||||
if (first != null) {
|
||||
for (String s : first.keySet()) {
|
||||
for (Object s1 : ((Map)list.get(i)).keySet()) {
|
||||
String str = s + s1;
|
||||
temp.put(str, Integer.valueOf(1));
|
||||
}
|
||||
}
|
||||
if (temp != null && temp.size() > 0) {
|
||||
first.clear();
|
||||
}
|
||||
} else {
|
||||
for (Object s : ((Map)list.get(i)).keySet()) {
|
||||
String str = (String) s;
|
||||
temp.put(str, Integer.valueOf(1));
|
||||
}
|
||||
}
|
||||
if (temp != null && temp.size() > 0) {
|
||||
first = temp;
|
||||
}
|
||||
}
|
||||
String returnStr = "";
|
||||
if (first != null) {
|
||||
for (String str : first.keySet()) {
|
||||
returnStr = returnStr + str + ",";
|
||||
}
|
||||
}
|
||||
if (returnStr.length() > 0) {
|
||||
returnStr = returnStr.substring(0, returnStr.length() - 1);
|
||||
}
|
||||
return returnStr;
|
||||
}
|
||||
}
|
||||
190
src/main/java/cn/stock/market/utils/HttpClientRequest.java
Normal file
190
src/main/java/cn/stock/market/utils/HttpClientRequest.java
Normal file
@@ -0,0 +1,190 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.github.pagehelper.StringUtil;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.cookie.Cookie;
|
||||
import org.apache.http.impl.client.BasicCookieStore;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
|
||||
public class HttpClientRequest {
|
||||
public static String doGet(String url) {
|
||||
CloseableHttpClient httpClient = null;
|
||||
CloseableHttpResponse response = null;
|
||||
String result = "";
|
||||
|
||||
try {
|
||||
httpClient = HttpClients.createDefault();
|
||||
|
||||
HttpGet httpGet = new HttpGet(url);
|
||||
|
||||
httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
|
||||
httpGet.setHeader("Referer", "https://finance.sina.com.cn");
|
||||
|
||||
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
|
||||
|
||||
httpGet.setConfig(requestConfig);
|
||||
|
||||
response = httpClient.execute(httpGet);
|
||||
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
result = EntityUtils.toString(entity);
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
|
||||
if (null != response) {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (null != httpClient) {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* 获取cooike
|
||||
* @param url
|
||||
* @return
|
||||
*/
|
||||
public static List<Cookie> getCookie(String url) {
|
||||
CloseableHttpClient httpClient = null;
|
||||
CloseableHttpResponse response = null;
|
||||
String result = "";
|
||||
List<Cookie> cookieList=null;
|
||||
try {
|
||||
|
||||
|
||||
HttpGet httpGet = new HttpGet(url);
|
||||
|
||||
BasicCookieStore store= new BasicCookieStore();
|
||||
httpClient = HttpClients.custom().setDefaultCookieStore(store).build();
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
|
||||
|
||||
httpGet.setConfig(requestConfig);
|
||||
|
||||
response = httpClient.execute(httpGet);
|
||||
cookieList= store.getCookies();
|
||||
System.out.println(cookieList);
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
result = EntityUtils.toString(entity);
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
|
||||
if (null != response) {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (null != httpClient) {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return cookieList;
|
||||
}
|
||||
|
||||
public static String doPost(String url, Map<String, Object> paramMap) {
|
||||
CloseableHttpClient httpClient = null;
|
||||
CloseableHttpResponse httpResponse = null;
|
||||
String result = "";
|
||||
|
||||
httpClient = HttpClients.createDefault();
|
||||
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
|
||||
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
|
||||
|
||||
httpPost.setConfig(requestConfig);
|
||||
|
||||
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
|
||||
|
||||
if (null != paramMap && paramMap.size() > 0) {
|
||||
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
|
||||
|
||||
Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
|
||||
|
||||
Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<String, Object> mapEntry = (Map.Entry) iterator.next();
|
||||
nvps.add(new BasicNameValuePair((String) mapEntry.getKey(), mapEntry.getValue().toString()));
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
httpResponse = httpClient.execute(httpPost);
|
||||
|
||||
HttpEntity entity = httpResponse.getEntity();
|
||||
result = EntityUtils.toString(entity);
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
|
||||
if (null != httpResponse) {
|
||||
try {
|
||||
httpResponse.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (null != httpClient) {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
160
src/main/java/cn/stock/market/utils/HttpRequest.java
Normal file
160
src/main/java/cn/stock/market/utils/HttpRequest.java
Normal file
@@ -0,0 +1,160 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
public class HttpRequest {
|
||||
private static final Logger log = LoggerFactory.getLogger(HttpRequest.class);
|
||||
|
||||
|
||||
public static String doGet(String url, String params) throws Exception {
|
||||
URL localURL = new URL(url + params);
|
||||
URLConnection connection = localURL.openConnection();
|
||||
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
|
||||
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
|
||||
httpURLConnection.setRequestProperty("Content-Type", "application/text");
|
||||
InputStream inputStream = null;
|
||||
InputStreamReader inputStreamReader = null;
|
||||
BufferedReader reader = null;
|
||||
StringBuffer resultBuffer = new StringBuffer();
|
||||
String tempLine = null;
|
||||
|
||||
if (httpURLConnection.getResponseCode() >= 300) {
|
||||
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection
|
||||
|
||||
.getResponseCode());
|
||||
}
|
||||
try {
|
||||
inputStream = httpURLConnection.getInputStream();
|
||||
inputStreamReader = new InputStreamReader(inputStream);
|
||||
reader = new BufferedReader(inputStreamReader);
|
||||
|
||||
while ((tempLine = reader.readLine()) != null) {
|
||||
resultBuffer.append(tempLine);
|
||||
}
|
||||
} finally {
|
||||
if (reader != null) {
|
||||
reader.close();
|
||||
}
|
||||
if (inputStreamReader != null) {
|
||||
inputStreamReader.close();
|
||||
}
|
||||
if (inputStream != null) {
|
||||
inputStream.close();
|
||||
}
|
||||
}
|
||||
return resultBuffer.toString();
|
||||
}
|
||||
|
||||
/*
|
||||
*抓数据专用,
|
||||
*signature:授权码
|
||||
* timestamp:时间戳
|
||||
* url
|
||||
*/
|
||||
public static String doGrabGet(String url) throws Exception {
|
||||
// Request URL: http://gateway.jinyi999.cn/rjhy-news/api/1/tcy/news/hotlist?columnCodes=cjyw&appCode=tcy&showPermission=0&limit=20&hasContent=0&pageNo=1
|
||||
URL localURL = new URL(url);
|
||||
URLConnection connection = localURL.openConnection();
|
||||
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
|
||||
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
|
||||
/*httpURLConnection.setRequestProperty("Access-Control-Allow-Credentials", "true");
|
||||
httpURLConnection.setRequestProperty("Access-Control-Allow-Headers", "X-Requested-With, accept, origin, content-type, signature, timestamp, appcode, whiteList");
|
||||
httpURLConnection.setRequestProperty("Content-Encoding", "gzip");
|
||||
httpURLConnection.setRequestProperty("Content-Language", "zh-CN");
|
||||
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
|
||||
//httpURLConnection.setRequestProperty("Accept", "application/json, text/plain");
|
||||
httpURLConnection.setRequestProperty("Origin", "http://static.sinagp.com");
|
||||
httpURLConnection.setRequestProperty("signature", signature);
|
||||
httpURLConnection.setRequestProperty("timestamp", timestamp);*/
|
||||
InputStream inputStream = null;
|
||||
InputStreamReader inputStreamReader = null;
|
||||
BufferedReader reader = null;
|
||||
StringBuffer resultBuffer = new StringBuffer();
|
||||
String tempLine = null;
|
||||
|
||||
if (httpURLConnection.getResponseCode() >= 300) {
|
||||
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection
|
||||
|
||||
.getResponseCode());
|
||||
}
|
||||
try {
|
||||
inputStream = httpURLConnection.getInputStream();
|
||||
inputStreamReader = new InputStreamReader(inputStream);
|
||||
//reader = new BufferedReader(inputStreamReader);
|
||||
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
|
||||
|
||||
while ((tempLine = reader.readLine()) != null) {
|
||||
resultBuffer.append(tempLine);
|
||||
}
|
||||
} finally {
|
||||
if (reader != null) {
|
||||
reader.close();
|
||||
}
|
||||
if (inputStreamReader != null) {
|
||||
inputStreamReader.close();
|
||||
}
|
||||
if (inputStream != null) {
|
||||
inputStream.close();
|
||||
}
|
||||
}
|
||||
return resultBuffer.toString();
|
||||
}
|
||||
|
||||
|
||||
public static String doPost(String url, Map<String, String> params) throws Exception {
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
|
||||
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
|
||||
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
|
||||
if (params != null) {
|
||||
BasicNameValuePair bnvp = null;
|
||||
for (Map.Entry<String, String> p : params.entrySet()) {
|
||||
bnvp = new BasicNameValuePair((String) p.getKey(), (String) p.getValue());
|
||||
}
|
||||
}
|
||||
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
|
||||
HttpResponse response = defaultHttpClient.execute(httpPost);
|
||||
HttpEntity respEntity = response.getEntity();
|
||||
String text = EntityUtils.toString(respEntity, "UTF-8");
|
||||
|
||||
defaultHttpClient.getConnectionManager().shutdown();
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
String url = "";
|
||||
String ips = "183.32.208.138";
|
||||
|
||||
String getret = "";
|
||||
try {
|
||||
getret = doGet(url, ips);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
log.info("get ret : " + getret);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
37
src/main/java/cn/stock/market/utils/Messages.java
Normal file
37
src/main/java/cn/stock/market/utils/Messages.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
import cn.stock.market.infrastructure.api.JuheApis;
|
||||
|
||||
public class Messages {
|
||||
public static boolean succ(JSONObject json) {
|
||||
return json.getIntValue("error_code") == 0;
|
||||
}
|
||||
|
||||
public static JSONObject warn(String phone) {
|
||||
return JuheApis.send(phone, JuheApis.SMS_WARN, null);
|
||||
}
|
||||
|
||||
public static JSONObject positionAdd(String phone) {
|
||||
return JuheApis.send(phone, JuheApis.SMS_POSITION_ADD, null);
|
||||
}
|
||||
|
||||
public static JSONObject sendCode(String phone, String code) {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("error_code", 0);
|
||||
json.put("tips", "FAKE");
|
||||
return json;
|
||||
// return JuheApis.send(phone, JuheApis.SMS_VERIFY_CODE, "#code#=" + code);
|
||||
}
|
||||
|
||||
public static void recharge(String phone) {
|
||||
JuheApis.send(phone, JuheApis.SMS_RECHARGE, null);
|
||||
}
|
||||
public static void open(String phone) {
|
||||
JuheApis.send(phone, JuheApis.SMS_OPEN, null);
|
||||
}
|
||||
public static void withdrawal(String phone) {
|
||||
JuheApis.send(phone, JuheApis.SMS_WITHDRAWAL, null);
|
||||
}
|
||||
}
|
||||
45
src/main/java/cn/stock/market/utils/PropertiesUtil.java
Normal file
45
src/main/java/cn/stock/market/utils/PropertiesUtil.java
Normal file
@@ -0,0 +1,45 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import cn.stock.market.web.config.Env;
|
||||
|
||||
|
||||
public class PropertiesUtil {
|
||||
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
|
||||
|
||||
// private static Properties props;
|
||||
//
|
||||
// static {
|
||||
// String fileName = "stock2guo.properties";
|
||||
// props = new Properties();
|
||||
// try {
|
||||
// props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName), "UTF-8"));
|
||||
// } catch (IOException e) {
|
||||
// logger.error("配置文件读取异常", e);
|
||||
// }
|
||||
// }
|
||||
|
||||
public static String getProperty(String key) {
|
||||
return getProperty(key, null);
|
||||
}
|
||||
|
||||
|
||||
public static String getProperty(String key, String defaultValue) {
|
||||
Env env = Env.of();
|
||||
if(env == null) {
|
||||
logger.warn("找配置信息 key: {} 时环境未初始化完成! ", env);
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
String value = env.environment().getProperty(key.trim());
|
||||
if (StringUtils.isBlank(value)) {
|
||||
value = defaultValue;
|
||||
}
|
||||
return StringUtils.trim(value);
|
||||
}
|
||||
}
|
||||
|
||||
26
src/main/java/cn/stock/market/utils/QRImpl.java
Normal file
26
src/main/java/cn/stock/market/utils/QRImpl.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.awt.Font;
|
||||
import java.io.InputStream;
|
||||
|
||||
import cn.stock.market.utils.UserQRs.IQR;
|
||||
|
||||
public class QRImpl implements IQR {
|
||||
|
||||
@Override
|
||||
public Font font() {
|
||||
throw new UnsupportedClassVersionError();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream bg() {
|
||||
InputStream inputStream = UserQRs.class.getResourceAsStream("/static/user_qrcode_picture_tmpl.jpg");
|
||||
return inputStream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream qrbg() {
|
||||
throw new UnsupportedClassVersionError();
|
||||
}
|
||||
|
||||
}
|
||||
118
src/main/java/cn/stock/market/utils/RedisGeoUtils.java
Normal file
118
src/main/java/cn/stock/market/utils/RedisGeoUtils.java
Normal file
@@ -0,0 +1,118 @@
|
||||
//package cn.stock.market.utils;
|
||||
//
|
||||
//import java.util.List;
|
||||
//
|
||||
//import org.springframework.data.geo.Circle;
|
||||
//import org.springframework.data.geo.Distance;
|
||||
//import org.springframework.data.geo.GeoResults;
|
||||
//import org.springframework.data.geo.Metric;
|
||||
//import org.springframework.data.geo.Point;
|
||||
//import org.springframework.data.redis.connection.RedisGeoCommands;
|
||||
//import org.springframework.data.redis.core.RedisTemplate;
|
||||
//
|
||||
//import com.ag.utils.CollectionUtils;
|
||||
//
|
||||
//import cn.qutaojing.common.utils.SpringUtils;
|
||||
//
|
||||
///**
|
||||
// *
|
||||
// * title: RedisGeoUtils.java
|
||||
// *
|
||||
// * @author xlfd
|
||||
// * @email xlfd@gmail.com
|
||||
// * @version 1.0
|
||||
// * @created Jul 1, 2021 11:26:34 AM
|
||||
// */
|
||||
//@SuppressWarnings({"deprecation", "unchecked", "rawtypes"})
|
||||
//public class RedisGeoUtils {
|
||||
// public static RedisTemplate redisTemplate() {
|
||||
// return SpringUtils.getBean(RedisTemplate.class);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 添加经纬度信息,时间复杂度为O(log(N))
|
||||
// * redis 命令:geoadd cityGeo 116.405285 39.904989 "北京"
|
||||
// * @param k
|
||||
// * @param point
|
||||
// * @param m
|
||||
// */
|
||||
// public static Long addGeoPoin(Object k, Point point, Object m) {
|
||||
// Long addedNum = redisTemplate().opsForGeo().geoAdd(k, point, m);
|
||||
// return addedNum;
|
||||
// }
|
||||
//
|
||||
// public static Point geoGet(Object k, Object m) {
|
||||
// List<Point> points = geoGet(k, new Object[] { m });
|
||||
//
|
||||
// return CollectionUtils.isNotEmpty(points) ? points.get(0) : null;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 查找指定key的经纬度信息,可以指定多个key,批量返回
|
||||
// * redis命令:geopos cityGeo 北京
|
||||
// * @param k
|
||||
// * @param m
|
||||
// */
|
||||
// public static List<Point> geoGet(Object k, Object... m) {
|
||||
// List<Point> points = redisTemplate().opsForGeo().geoPos(k, m);
|
||||
// return points;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 返回两个地方的距离,可以指定单位,比如米m,千米km,英里mi,英尺ft
|
||||
// * redis命令:geodist cityGeo 北京 上海
|
||||
// * @param k
|
||||
// * @param mk1
|
||||
// * @param mk2
|
||||
// * @param metric
|
||||
// * @return
|
||||
// */
|
||||
// public static Distance geoDist(Object k, Object mk1, Object mk2, Metric metric) {
|
||||
// Distance distance = redisTemplate().opsForGeo().geoDist(k, mk1, mk2, metric);
|
||||
// return distance;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 根据给定的经纬度,返回半径不超过指定距离的元素,时间复杂度为O(N+log(M)),N为指定半径范围内的元素个数,M为要返回的个数
|
||||
// * redis命令:georadius cityGeo 116.405285 39.904989 100 km WITHDIST WITHCOORD ASC COUNT 5
|
||||
// * @param k
|
||||
// * @param circle
|
||||
// * @param args
|
||||
// */
|
||||
// public static GeoResults<RedisGeoCommands.GeoLocation<String>> nearByXY(Object k, Circle circle, RedisGeoCommands.GeoRadiusCommandArgs args) {
|
||||
// //longitude,latitude
|
||||
// //Circle circle = new Circle(116.405285, 39.904989, Metrics.KILOMETERS.getMultiplier());
|
||||
// //RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(5);
|
||||
//
|
||||
// GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate().opsForGeo().geoRadius(k, circle, args);
|
||||
// return results;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 根据指定的地点查询半径在指定范围内的位置,时间复杂度为O(log(N)+M),N为指定半径范围内的元素个数,M为要返回的个数
|
||||
// * redis命令:georadiusbymember cityGeo 北京 100 km WITHDIST WITHCOORD ASC COUNT 5
|
||||
// * @param k
|
||||
// * @param mk
|
||||
// * @param distance
|
||||
// * @param args
|
||||
// * @return
|
||||
// */
|
||||
// public static GeoResults nearByPlace(Object k, Object mk, Distance distance, RedisGeoCommands.GeoRadiusCommandArgs args) {
|
||||
//// Distance distance = new Distance(5, Metrics.KILOMETERS);
|
||||
//// RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(5);
|
||||
// GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate().opsForGeo().geoRadiusByMember(k, mk, distance, args);
|
||||
// return results;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 返回的是geohash值,查找一个位置的时间复杂度为O(log(N))
|
||||
// * redis命令:geohash cityGeo 北京
|
||||
// * @param k
|
||||
// * @param mks
|
||||
// * @return
|
||||
// */
|
||||
// public static List geoHash(Object k, Object... mks) {
|
||||
// List<String> results = redisTemplate().opsForGeo().geoHash(k, mks);
|
||||
// return results;
|
||||
// }
|
||||
//}
|
||||
91
src/main/java/cn/stock/market/utils/RequestCacheUtils.java
Normal file
91
src/main/java/cn/stock/market/utils/RequestCacheUtils.java
Normal file
@@ -0,0 +1,91 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
@Slf4j
|
||||
public class RequestCacheUtils {
|
||||
static Map<String, Cache<String, ServerResponse<?>>> map = Maps.newConcurrentMap();
|
||||
public static List<String> stat() {
|
||||
return map
|
||||
.entrySet()
|
||||
.stream()
|
||||
.map(entry -> entry.getKey() + "-" + entry.getValue().stats())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static Cache<String, ServerResponse<?>> cache(String key) {
|
||||
if(! map.containsKey(key)) {
|
||||
log.info("创建缓存: {}", key);
|
||||
Cache<String, ServerResponse<?>> cache = CacheBuilder.newBuilder()
|
||||
.maximumSize(1000)
|
||||
.expireAfterWrite(500,TimeUnit.MILLISECONDS)
|
||||
.weakValues()
|
||||
.recordStats()
|
||||
.build(
|
||||
// new CacheLoader<String, Object>() {
|
||||
// @Override
|
||||
// public Object load(String key) throws Exception {
|
||||
// return func.apply(key);
|
||||
// }
|
||||
// }
|
||||
);
|
||||
map.put(key, cache);
|
||||
}
|
||||
|
||||
return map.get(key);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@SneakyThrows
|
||||
public static <T> ServerResponse<T> cache(String module, String key, Function<String, ServerResponse<?>> func) {
|
||||
Cache<String, ServerResponse<?>> cache = cache(module);
|
||||
AtomicBoolean bool = new AtomicBoolean(true);
|
||||
ServerResponse<T> response = (ServerResponse<T>) cache.get(key, () -> {
|
||||
bool.set(false);
|
||||
return func.apply(key);
|
||||
});
|
||||
|
||||
if(bool.get()) {
|
||||
log.info("命中缓存 module: {}, key: {}, 时间戳: {}", module, key, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
ServerResponse<Object> response = null;
|
||||
Function<String, ServerResponse<?>> func = (string) -> {
|
||||
System.out.println("LLLLL" + string);
|
||||
return ServerResponse.createBySuccess("TTTT");
|
||||
};
|
||||
response = cache("_test_", "_TEST_KEY", func);
|
||||
System.out.println(JSON.toJSONString(response));
|
||||
|
||||
response = cache("_test_", "_TEST_KEY", func);
|
||||
System.out.println(JSON.toJSONString(response));
|
||||
|
||||
response = cache("_test_", "_TEST_KEY", func);
|
||||
System.out.println(JSON.toJSONString(response));
|
||||
response = cache("_test_", "_TEST_KEY_2", func);
|
||||
System.out.println(JSON.toJSONString(response));
|
||||
|
||||
Thread.sleep(500);
|
||||
|
||||
response = cache("_test_", "_TEST_KEY", func);
|
||||
System.out.println(JSON.toJSONString(response));
|
||||
}
|
||||
}
|
||||
43
src/main/java/cn/stock/market/utils/Requests.java
Normal file
43
src/main/java/cn/stock/market/utils/Requests.java
Normal file
@@ -0,0 +1,43 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.ag.utils.CollectionUtils;
|
||||
|
||||
import cn.stock.market.utils.Cons.QDeviceType;
|
||||
|
||||
public class Requests {
|
||||
|
||||
/**
|
||||
* 获取设备类型 ,与前端约定
|
||||
*
|
||||
* @param qUserAgent
|
||||
* @return
|
||||
*/
|
||||
public static String getDeviceType(String qUserAgent) {
|
||||
|
||||
if (StringUtils.isBlank(qUserAgent)) {
|
||||
return QDeviceType.ANDROID;
|
||||
}
|
||||
if (qUserAgent.contains("-")) {
|
||||
String[] _userAgent = qUserAgent.split("-");
|
||||
if (CollectionUtils.isNotEmpty(_userAgent)) {
|
||||
return _userAgent[0];
|
||||
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static String getDeviceTypeFromUserAgent(HttpServletRequest request) {
|
||||
String deviceType = request.getHeader("DeviceType");
|
||||
if (StringUtils.isBlank(deviceType)) {
|
||||
deviceType = request.getHeader("User-Agent");
|
||||
}
|
||||
|
||||
return getDeviceType(deviceType);
|
||||
}
|
||||
|
||||
}
|
||||
24
src/main/java/cn/stock/market/utils/ResponseCode.java
Normal file
24
src/main/java/cn/stock/market/utils/ResponseCode.java
Normal file
@@ -0,0 +1,24 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
|
||||
public enum ResponseCode {
|
||||
SUCCESS(0, "SUCCESS"),
|
||||
ERROR(1, "ERROR"),
|
||||
NEED_LOGIN(10, "NEED_LOGIN"),
|
||||
ILLEGAL_ARGUMENT(2, "ILLEGAL_ARGUMENT");
|
||||
private int code;
|
||||
private String msg;
|
||||
|
||||
ResponseCode(int code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return this.msg;
|
||||
}
|
||||
}
|
||||
86
src/main/java/cn/stock/market/utils/ServerResponse.java
Normal file
86
src/main/java/cn/stock/market/utils/ServerResponse.java
Normal file
@@ -0,0 +1,86 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.alibaba.fastjson.annotation.JSONField;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
|
||||
public class ServerResponse<T> extends Object implements Serializable {
|
||||
private int status;
|
||||
private String msg;
|
||||
private T data;
|
||||
|
||||
private ServerResponse(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
private ServerResponse(int status, T data) {
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
private ServerResponse(int status, String msg) {
|
||||
this.status = status;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
private ServerResponse(int status, String msg, T data) {
|
||||
this.status = status;
|
||||
this.msg = msg;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ServerResponse serverResponse = new ServerResponse(1, new Object());
|
||||
ServerResponse serverResponse1 = new ServerResponse(1, "abc");
|
||||
System.out.print("ServerResponse");
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@JSONField(serialize = false)
|
||||
public boolean isSuccess() {
|
||||
return (this.status == ResponseCode.SUCCESS.getCode());
|
||||
}
|
||||
|
||||
public int getStatus() {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return (T) this.data;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return this.msg;
|
||||
}
|
||||
|
||||
public static <T> ServerResponse<T> createBySuccess() {
|
||||
return new ServerResponse(ResponseCode.SUCCESS.getCode());
|
||||
}
|
||||
|
||||
public static <T> ServerResponse<T> createBySuccessMsg(String msg) {
|
||||
return new ServerResponse(ResponseCode.SUCCESS.getCode(), msg);
|
||||
}
|
||||
|
||||
public static <T> ServerResponse<T> createBySuccess(T data) {
|
||||
return new ServerResponse(ResponseCode.SUCCESS.getCode(), data);
|
||||
}
|
||||
|
||||
public static <T> ServerResponse<T> createBySuccess(String msg, T data) {
|
||||
return new ServerResponse(ResponseCode.SUCCESS.getCode(), msg, data);
|
||||
}
|
||||
|
||||
public static <T> ServerResponse<T> createByError() {
|
||||
return new ServerResponse(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getMsg());
|
||||
}
|
||||
|
||||
public static <T> ServerResponse<T> createByErrorMsg(String errormsg) {
|
||||
return new ServerResponse(ResponseCode.ERROR.getCode(), errormsg);
|
||||
}
|
||||
|
||||
public static <T> ServerResponse<T> createByErrorCodeMsg(int errorcode, String errormsg) {
|
||||
return new ServerResponse(errorcode, errormsg);
|
||||
}
|
||||
}
|
||||
81
src/main/java/cn/stock/market/utils/StringUtils.java
Normal file
81
src/main/java/cn/stock/market/utils/StringUtils.java
Normal file
@@ -0,0 +1,81 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class StringUtils {
|
||||
/**
|
||||
* unicode编码转换为汉字
|
||||
* @param unicodeStr 待转化的编码
|
||||
* @return 返回转化后的汉子
|
||||
*/
|
||||
public static String UnicodeToCN(String unicodeStr) {
|
||||
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
|
||||
Matcher matcher = pattern.matcher(unicodeStr);
|
||||
char ch;
|
||||
while (matcher.find()) {
|
||||
//group
|
||||
String group = matcher.group(2);
|
||||
//ch:'李四'
|
||||
ch = (char) Integer.parseInt(group, 16);
|
||||
//group1
|
||||
String group1 = matcher.group(1);
|
||||
unicodeStr = unicodeStr.replace(group1, ch + "");
|
||||
}
|
||||
|
||||
return unicodeStr.replace("\\", "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 汉字转化为Unicode编码
|
||||
* @param CN 待转化的中文
|
||||
* @return 返回转化之后的unicode编码
|
||||
*/
|
||||
public static String CNToUnicode(String CN) {
|
||||
|
||||
try {
|
||||
StringBuffer out = new StringBuffer("");
|
||||
//直接获取字符串的unicode二进制
|
||||
byte[] bytes = CN.getBytes("unicode");
|
||||
//然后将其byte转换成对应的16进制表示即可
|
||||
for (int i = 0; i < bytes.length - 1; i += 2) {
|
||||
out.append("\\u");
|
||||
String str = Integer.toHexString(bytes[i + 1] & 0xff);
|
||||
for (int j = str.length(); j < 2; j++) {
|
||||
out.append("0");
|
||||
}
|
||||
String str1 = Integer.toHexString(bytes[i] & 0xff);
|
||||
out.append(str1);
|
||||
out.append(str);
|
||||
}
|
||||
return out.toString();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String delHTMLTag(String htmlStr){
|
||||
String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
|
||||
String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
|
||||
String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式
|
||||
|
||||
Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
|
||||
Matcher m_script=p_script.matcher(htmlStr);
|
||||
htmlStr=m_script.replaceAll(""); //过滤script标签
|
||||
|
||||
Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
|
||||
Matcher m_style=p_style.matcher(htmlStr);
|
||||
htmlStr=m_style.replaceAll(""); //过滤style标签
|
||||
|
||||
Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
|
||||
Matcher m_html=p_html.matcher(htmlStr);
|
||||
htmlStr=m_html.replaceAll(""); //过滤html标签
|
||||
|
||||
return htmlStr.trim(); //返回文本字符串
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
198
src/main/java/cn/stock/market/utils/UserQRs.java
Normal file
198
src/main/java/cn/stock/market/utils/UserQRs.java
Normal file
@@ -0,0 +1,198 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.awt.AlphaComposite;
|
||||
import java.awt.BasicStroke;
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.Graphics;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.Rectangle;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.Transparency;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.geom.Ellipse2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.ColorModel;
|
||||
import java.awt.image.WritableRaster;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import com.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.EncodeHintType;
|
||||
import com.google.zxing.MultiFormatWriter;
|
||||
import com.google.zxing.WriterException;
|
||||
import com.google.zxing.common.BitMatrix;
|
||||
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
|
||||
|
||||
public class UserQRs {
|
||||
public interface IQR {
|
||||
Font font();
|
||||
InputStream bg();
|
||||
InputStream qrbg();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException, WriterException {
|
||||
String shopQr = "https://oto.qutaojing.cn/qr/mini-1112";
|
||||
// String shopImage = "https://f.qutaojing.cn/resources/20211111/2f10670a18f34e8780a2519a93419b7f.png";
|
||||
|
||||
// byte[] logo = FileUtils.readFileToByteArray(new File("/Users/rplees/Desktop/logo.png"));
|
||||
byte[] logo = null;
|
||||
|
||||
byte[] gen = gen(shopQr, logo, new QRImpl());
|
||||
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(gen);
|
||||
BufferedImage image = ImageIO.read(in);
|
||||
|
||||
OutputStream os = new FileOutputStream("/Users/rplees/Desktop/ttt.png");
|
||||
ImageIO.write(image, "png", os);
|
||||
os.close();
|
||||
}
|
||||
|
||||
public static BufferedImage qr(String shopQr, byte[] logo) throws WriterException, IOException {
|
||||
int width = 110; // 图像宽度
|
||||
int height = 110; // 图像高度
|
||||
Map<EncodeHintType, Object> hints = new HashMap<>();
|
||||
// 内容编码格式
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
// 指定纠错等级
|
||||
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
|
||||
// 设置二维码边的空度,非负数
|
||||
hints.put(EncodeHintType.MARGIN, 1);
|
||||
|
||||
BitMatrix bitMatrix = new MultiFormatWriter().encode(shopQr, BarcodeFormat.QR_CODE, width, height, hints);
|
||||
BufferedImage bi = toBufferedImage(bitMatrix);
|
||||
//
|
||||
// Graphics g = bi.getGraphics();
|
||||
|
||||
// int w = 152;
|
||||
// int h = 152;
|
||||
// BufferedImage logoBI = ImageIO.read(new ByteArrayInputStream(logo));
|
||||
// logoBI = resize(logoBI, Math.min(logoBI.getWidth(), logoBI.getHeight()));
|
||||
// logoBI = radius(logoBI, new Double((0.3 * logoBI.getHeight())).intValue(), 0, 0);
|
||||
// g.drawImage(logoBI, (bi.getWidth() - w) / 2, (bi.getHeight() - h) / 2, w, h, null);
|
||||
return bi;
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片设置圆角
|
||||
*
|
||||
* @param srcImage
|
||||
* @param radius
|
||||
* @param border
|
||||
* @param padding
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
@SuppressWarnings("all")
|
||||
public static BufferedImage radius(BufferedImage srcImage, int radius, int border, int padding)
|
||||
throws IOException {
|
||||
int width = srcImage.getWidth();
|
||||
int height = srcImage.getHeight();
|
||||
|
||||
int canvasWidth = width + padding * 2;
|
||||
int canvasHeight = height + padding * 2;
|
||||
|
||||
BufferedImage image = new BufferedImage(srcImage.getWidth(), srcImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
|
||||
|
||||
Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, srcImage.getWidth(), srcImage.getHeight());
|
||||
|
||||
Graphics2D g2 = image.createGraphics();
|
||||
image = g2.getDeviceConfiguration()
|
||||
.createCompatibleImage(srcImage.getWidth(), srcImage.getHeight(), Transparency.TRANSLUCENT);
|
||||
g2 = image.createGraphics();
|
||||
g2.setComposite(AlphaComposite.Clear);
|
||||
g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
|
||||
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
|
||||
g2.setClip(shape);
|
||||
// 使用 setRenderingHint 设置抗锯齿
|
||||
g2 = image.createGraphics();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g2.fillRoundRect(0, 0, srcImage.getWidth(), srcImage.getHeight(), radius, radius);
|
||||
g2.setComposite(AlphaComposite.SrcIn);
|
||||
g2.drawImage(srcImage, 0, 0, srcImage.getWidth(), srcImage.getHeight(), null);
|
||||
|
||||
if (border != 0) {
|
||||
// gs.setColor(Color.GRAY);
|
||||
g2.setColor(Color.GRAY);
|
||||
g2.setStroke(new BasicStroke(border));
|
||||
g2.drawRoundRect(padding, padding, canvasWidth * padding, canvasHeight * padding, radius, radius);
|
||||
}
|
||||
g2.dispose();
|
||||
|
||||
return image;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* BitMatrix 2 BufferedImage
|
||||
*
|
||||
* @param matrix
|
||||
* @return
|
||||
*/
|
||||
private static BufferedImage toBufferedImage(BitMatrix matrix) {
|
||||
int width = matrix.getWidth();
|
||||
int height = matrix.getHeight();
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
public static byte[] gen(String qrContent, byte[] logo, IQR iqr) throws IOException, WriterException {
|
||||
|
||||
InputStream inputStream = iqr.bg();
|
||||
BufferedImage image = ImageIO.read(inputStream);
|
||||
Graphics graphics = image.getGraphics();
|
||||
|
||||
BufferedImage qr = qr(qrContent, logo);
|
||||
graphics.drawImage(qr, 377, 450, 180, 180, null);
|
||||
|
||||
byte[] bs = bufferedImageToByte(image);
|
||||
graphics.dispose();
|
||||
return bs;
|
||||
}
|
||||
|
||||
public static byte[] bufferedImageToByte(BufferedImage image) throws IOException {
|
||||
ByteArrayOutputStream bout = new ByteArrayOutputStream();
|
||||
ImageIO.write(image, "png", bout);
|
||||
bout.close();
|
||||
return bout.toByteArray();
|
||||
}
|
||||
|
||||
public static BufferedImage resize(BufferedImage source, int targetW) {
|
||||
int type = source.getType();
|
||||
BufferedImage target = null;
|
||||
int width = source.getWidth();
|
||||
int height = source.getHeight();
|
||||
|
||||
double sx = (double) targetW / width;
|
||||
int targetH = new Double(height * sx).intValue();
|
||||
double sy = (double) targetH / height;
|
||||
if (type == BufferedImage.TYPE_CUSTOM) {
|
||||
ColorModel cm = source.getColorModel();
|
||||
WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
|
||||
targetH);
|
||||
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
|
||||
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
|
||||
} else {
|
||||
target = new BufferedImage(targetW, targetH, type);
|
||||
}
|
||||
Graphics2D g = target.createGraphics();
|
||||
// smoother than exlax:
|
||||
g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
|
||||
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
|
||||
g.dispose();
|
||||
return target;
|
||||
}
|
||||
}
|
||||
406
src/main/java/cn/stock/market/utils/Utils.java
Normal file
406
src/main/java/cn/stock/market/utils/Utils.java
Normal file
@@ -0,0 +1,406 @@
|
||||
package cn.stock.market.utils;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.Hashtable;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
import com.ag.utils.DateUtils;
|
||||
import com.ag.utils.NumberUtils;
|
||||
import com.ag.utils.SysConstant.BooleanEnum;
|
||||
import com.ag.utils.vo.KVObj;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import cn.hutool.core.net.url.UrlBuilder;
|
||||
import cn.qutaojing.common.constant.Currency;
|
||||
import cn.stock.market.application.Dics;
|
||||
import cn.stock.market.constant.StockSource;
|
||||
import cn.stock.market.infrastructure.api.AliApis;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.sourceforge.pinyin4j.PinyinHelper;
|
||||
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
|
||||
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
|
||||
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
|
||||
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
|
||||
|
||||
/**
|
||||
* @author xlfd
|
||||
* @email xlfd@gmail.com
|
||||
* @version 1.0
|
||||
* @created Jul 1, 2021 11:26:24 AM
|
||||
*/
|
||||
@Slf4j
|
||||
public final class Utils {
|
||||
public static void throwing(KVObj kvObj) {
|
||||
com.ag.utils.Utils.throwing(kvObj);
|
||||
}
|
||||
|
||||
public static String urlWithOutQUeryParameter(String url) {
|
||||
if (StringUtils.isBlank(url)) {
|
||||
return url;
|
||||
}
|
||||
|
||||
try {
|
||||
URI uri = new URI(url);
|
||||
UrlBuilder urlBuilder = UrlBuilder.of(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), null,
|
||||
null, null);
|
||||
return urlBuilder.build();
|
||||
} catch (URISyntaxException e) {
|
||||
log.error("{} 解析错误", url, e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void checkCommunicationPersonal(String acc_no, String idcard, String mobile, String name) {
|
||||
Integer flag = Dics.of().getFromCache("enable.checkCommunicationPersonal", 1);
|
||||
if (BooleanEnum.isOff(flag)) {
|
||||
return;
|
||||
}
|
||||
|
||||
AliApis.of().checkCommunicationPersonal(acc_no, idcard, mobile, name);
|
||||
}
|
||||
|
||||
public static Integer day() {
|
||||
return NumberUtils.parseInt(DateUtils.format(DateUtils.YYYYMMDD, new Date()));
|
||||
}
|
||||
|
||||
public static String fenxi(String code) {
|
||||
return jys(code) + code;
|
||||
}
|
||||
|
||||
public static boolean isShOrSzOrBJ(String code) {
|
||||
String jys = jys(code);
|
||||
return isShOrSzOrBjByJys(jys);
|
||||
}
|
||||
|
||||
public static boolean isShOrSzOrBjByJys(String jxs) {
|
||||
return "sh".equals(jxs) || "sz".equals(jxs) || "bj".equals(jxs);
|
||||
}
|
||||
|
||||
public static String jys(String code) {
|
||||
if (StringUtils.startsWith(code, "600") || StringUtils.startsWith(code, "601")
|
||||
|| StringUtils.startsWith(code, "603")) {
|
||||
return "sh";
|
||||
}
|
||||
if (StringUtils.startsWith(code, "000")) {
|
||||
return "sz";
|
||||
}
|
||||
|
||||
char charAt = StringUtils.substring(code, 0, 1).charAt(0);
|
||||
|
||||
String prefix = "";
|
||||
switch (charAt) {
|
||||
case '0':
|
||||
case '1':
|
||||
case '2':
|
||||
case '3':
|
||||
prefix = "sz";
|
||||
break;
|
||||
case '5':
|
||||
case '6':
|
||||
case '9':
|
||||
prefix = "sh";
|
||||
break;
|
||||
|
||||
case '4':
|
||||
case '8':
|
||||
prefix = "bj";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return prefix;
|
||||
}
|
||||
|
||||
// public static TradeSetting tradeSetting() {
|
||||
// TradeSetting setting = Dics.of().getFromCache("trade", TradeSetting.class);
|
||||
// if(setting == null) {
|
||||
// setting = new TradeSetting();
|
||||
// }
|
||||
// setting.check();
|
||||
// return setting;
|
||||
// }
|
||||
//
|
||||
// public static BigDecimal lostWarn() {
|
||||
// Double d = Dics.of().getFromCache("trade.lostWarn", 0.4);
|
||||
// return BigDecimals.p(d);
|
||||
// }
|
||||
//
|
||||
// public static BigDecimal lostClose() {
|
||||
// Double d = Dics.of().getFromCache("trade.lostClose", 0.2);
|
||||
// return BigDecimals.p(d);
|
||||
// }
|
||||
//
|
||||
// public static BigDecimal preTradingDayCost() {
|
||||
// Double d = Dics.of().getFromCache("trade.preTradingDayCost", 100D);
|
||||
// return BigDecimals.p(d);
|
||||
// }
|
||||
//
|
||||
// public static BigDecimal commission() {
|
||||
// Double d = Dics.of().getFromCache("trade.commission", 0.0004);
|
||||
// return BigDecimals.p(d);
|
||||
// }
|
||||
//
|
||||
// public static BigDecimal stampTax() {
|
||||
// Double d = Dics.of().getFromCache("trade.stampTax", 0.001);
|
||||
// return BigDecimals.p(d);
|
||||
// }
|
||||
|
||||
// public static BigDecimal stampTaxCalc(BigDecimal volume) {
|
||||
// return BigDecimals.multiplys(volume, Utils.tradeSetting().getStampTax()).setScale(2, RoundingMode.HALF_UP);
|
||||
// }
|
||||
//
|
||||
// public static BigDecimal preTradingDayCalc(BigDecimal volume) {
|
||||
// return BigDecimals.multiplys(volume, Utils.tradeSetting().getPreTradingDayCost()).setScale(2, RoundingMode.HALF_UP);
|
||||
// }
|
||||
//
|
||||
// public static BigDecimal commissionCalc(BigDecimal volume) {
|
||||
// return BigDecimals.multiplys(volume, Utils.tradeSetting().getCommission()).setScale(2, RoundingMode.HALF_UP);
|
||||
// }
|
||||
//
|
||||
public static ExTrans t() {
|
||||
return ExTrans.of();
|
||||
}
|
||||
|
||||
public static String getFirstLetter(String string) {
|
||||
if (StringUtils.isBlank(string))
|
||||
return string;
|
||||
|
||||
List<Character> l = Lists.newArrayList();
|
||||
for (int i = 0; i < string.length(); i++) {
|
||||
String[] array = PinyinHelper.toHanyuPinyinStringArray(string.charAt(i));
|
||||
if (array == null) {
|
||||
l.add(string.charAt(i));
|
||||
} else {
|
||||
l.add(array[0].toUpperCase().charAt(0));
|
||||
}
|
||||
}
|
||||
return Joiner.on("").join(l);
|
||||
}
|
||||
|
||||
// public static String pinyin(String string) {
|
||||
// if(StringUtils.isBlank(string))
|
||||
// return string;
|
||||
//// PinyinUtil.getPinyin(string)
|
||||
// List<String> l = Lists.newArrayList();
|
||||
// for(int i = 0; i < string.length(); i++) {
|
||||
// String[] array = PinyinHelper.toHanyuPinyinStringArray(string.charAt(i));
|
||||
// if(array == null) {
|
||||
// l.add(string);
|
||||
// } else {
|
||||
// l.add(array[0]);
|
||||
// }
|
||||
// }
|
||||
// return Joiner.on("").join(l);
|
||||
// }
|
||||
|
||||
public static StockSource toSource(Currency c) {
|
||||
if (c == Currency.CNY) {
|
||||
return StockSource.A;
|
||||
} else if (c == Currency.HKD) {
|
||||
return StockSource.HK;
|
||||
} else if (c == Currency.USD) {
|
||||
return StockSource.US;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param v1 格式 1.0.9
|
||||
* @param v2
|
||||
* @return
|
||||
*/
|
||||
public static boolean highVersion(String v1, String v2) {
|
||||
int v1Int = NumberUtils.parseInt(StringUtils.replace(v1, ".", ""));
|
||||
int v2Int = NumberUtils.parseInt(StringUtils.replace(v2, ".", ""));
|
||||
|
||||
return v1Int > v2Int;
|
||||
}
|
||||
|
||||
// public static BigDecimal multiple() {
|
||||
// return Dics.of().getFromCache("trade.multiple", BigDecimal.valueOf(4));
|
||||
// }
|
||||
|
||||
final static List<LocalTime[]> OPEN_TIME = Lists.newArrayList(
|
||||
new LocalTime[] { LocalTime.of(9, 30), LocalTime.of(11, 30) },
|
||||
new LocalTime[] { LocalTime.of(13, 00), LocalTime.of(15, 00) });
|
||||
|
||||
public static boolean isTradeTime() {
|
||||
if (!inTradeDay()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LocalTime localTime = LocalTime.now();
|
||||
for (LocalTime[] lt : OPEN_TIME) {
|
||||
if (localTime.isAfter(lt[0]) && localTime.isBefore(lt[1])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean inTradeDay() {
|
||||
LocalDate localDate = LocalDate.now();
|
||||
DayOfWeek week = localDate.getDayOfWeek();
|
||||
if (week == DayOfWeek.SATURDAY || week == DayOfWeek.SUNDAY) { // 周末
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isHoliday(localDate)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isHoliday(LocalDate localDate) {
|
||||
return false;
|
||||
|
||||
// String format = localDate.format(DateTimeFormatter.ofPattern("MMdd"));
|
||||
// String cacheKey = "holiday_" + format;
|
||||
// Object object = CacheRepository.of().get(cacheKey);
|
||||
// if(object != null) {
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// String holiday = Dics.of().getFromCache("legal_holiday", String.class);
|
||||
// JSONObject json = Jsons.toJSONAnyway(holiday);
|
||||
// JSONArray array = json.getJSONArray(String.valueOf(localDate.getYear()));
|
||||
// if(array == null) {
|
||||
// log.warn("legal_holiday的{}年未配置", localDate.getYear());
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// for(Object o : array) {
|
||||
// if(StringUtils.equals(String.valueOf(o), format)) {
|
||||
// CacheRepository.of().set(cacheKey, 1, 24, TimeUnit.HOURS);
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return false;
|
||||
}
|
||||
|
||||
public static <T> PageInfo<T> toPageHelperInfo(Page<T> page) {
|
||||
PageInfo<T> pageInfo = new PageInfo<>();
|
||||
pageInfo.setList(page.getContent());
|
||||
pageInfo.setPageSize(page.getSize());
|
||||
pageInfo.setTotal(page.getTotalElements());
|
||||
pageInfo.setPageNum(page.getTotalPages());
|
||||
return pageInfo;
|
||||
}
|
||||
|
||||
public static String converterToFirstSpell(String chines) {
|
||||
StringBuffer pinyinName = new StringBuffer();
|
||||
char[] nameChar = chines.toCharArray();
|
||||
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
|
||||
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
|
||||
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
|
||||
for (int i = 0; i < nameChar.length; i++) {
|
||||
if (nameChar[i] > '€') {
|
||||
try {
|
||||
String[] strs = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
|
||||
if (strs != null) {
|
||||
for (int j = 0; j < strs.length; j++) {
|
||||
pinyinName.append(strs[j].charAt(0));
|
||||
if (j != strs.length - 1) {
|
||||
pinyinName.append(",");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (BadHanyuPinyinOutputFormatCombination e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
pinyinName.append(nameChar[i]);
|
||||
}
|
||||
pinyinName.append(" ");
|
||||
}
|
||||
|
||||
return parseTheChineseByObject(discountTheChinese(pinyinName.toString()));
|
||||
}
|
||||
|
||||
private static List<Map<String, Integer>> discountTheChinese(String theStr) {
|
||||
List<Map<String, Integer>> mapList = new ArrayList<Map<String, Integer>>();
|
||||
Map<String, Integer> onlyOne = null;
|
||||
String[] firsts = theStr.split(" ");
|
||||
for (String str : firsts) {
|
||||
onlyOne = new Hashtable<String, Integer>();
|
||||
String[] china = str.split(",");
|
||||
for (String s : china) {
|
||||
Integer count = onlyOne.get(s);
|
||||
if (count == null) {
|
||||
onlyOne.put(s, new Integer(1));
|
||||
} else {
|
||||
onlyOne.remove(s);
|
||||
Integer integer1 = count, integer2 = count = Integer.valueOf(count.intValue() + 1);
|
||||
onlyOne.put(s, count);
|
||||
}
|
||||
}
|
||||
mapList.add(onlyOne);
|
||||
}
|
||||
return mapList;
|
||||
}
|
||||
|
||||
private static String parseTheChineseByObject(List<Map<String, Integer>> list) {
|
||||
Map<String, Integer> first = null;
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
Map<String, Integer> temp = new Hashtable<>();
|
||||
if (first != null) {
|
||||
for (String s : first.keySet()) {
|
||||
for (Object s1 : ((Map) list.get(i)).keySet()) {
|
||||
String str = s + s1;
|
||||
temp.put(str, Integer.valueOf(1));
|
||||
}
|
||||
}
|
||||
if (temp != null && temp.size() > 0) {
|
||||
first.clear();
|
||||
}
|
||||
} else {
|
||||
for (Object s : ((Map) list.get(i)).keySet()) {
|
||||
String str = (String) s;
|
||||
temp.put(str, Integer.valueOf(1));
|
||||
}
|
||||
}
|
||||
if (temp != null && temp.size() > 0) {
|
||||
first = temp;
|
||||
}
|
||||
}
|
||||
String returnStr = "";
|
||||
if (first != null) {
|
||||
for (String str : first.keySet()) {
|
||||
returnStr = returnStr + str + ",";
|
||||
}
|
||||
}
|
||||
if (returnStr.length() > 0) {
|
||||
returnStr = returnStr.substring(0, returnStr.length() - 1);
|
||||
}
|
||||
return returnStr;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(getFirstLetter("0L神鼎ds飞#@#丹砂"));
|
||||
System.out.println(getFirstLetter("0L神鼎ds飞#@#丹砂"));
|
||||
System.out.println(highVersion("1.0.8", "1.0.9"));
|
||||
System.out.println(highVersion("1.0.9", "1.0.10"));
|
||||
System.out.println(highVersion("1.0.10", "1.0.11"));
|
||||
System.out.println(highVersion("1.0.10", "1.0.9"));
|
||||
|
||||
}
|
||||
}
|
||||
20
src/main/java/cn/stock/market/utils/pushtext/IPushText.java
Normal file
20
src/main/java/cn/stock/market/utils/pushtext/IPushText.java
Normal file
@@ -0,0 +1,20 @@
|
||||
package cn.stock.market.utils.pushtext;
|
||||
|
||||
import com.ag.text.DicText;
|
||||
|
||||
import cn.qutaojing.common.constant.RoleEnum;
|
||||
import cn.stock.market.dto.model.ClickActionInfo;
|
||||
|
||||
public abstract class IPushText implements DicText {
|
||||
public abstract RoleEnum role();
|
||||
public abstract Integer targetId();
|
||||
public abstract ClickActionInfo clickActionInfo();
|
||||
public abstract String event();
|
||||
public boolean pushFlag() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean smsFlag() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
46
src/main/java/cn/stock/market/utils/pushtext/PushTexts.java
Normal file
46
src/main/java/cn/stock/market/utils/pushtext/PushTexts.java
Normal file
@@ -0,0 +1,46 @@
|
||||
package cn.stock.market.utils.pushtext;
|
||||
|
||||
import cn.qutaojing.common.constant.RoleEnum;
|
||||
import cn.stock.market.constant.ClickAction;
|
||||
import cn.stock.market.dto.model.ClickActionInfo;
|
||||
import cn.stock.market.dto.model.UserThumb;
|
||||
|
||||
public final class PushTexts {
|
||||
//~=================user====================
|
||||
public static IPushText userAuditPass(UserThumb user) {
|
||||
return from(RoleEnum.USER, user.getId(), "用户审核通过", "审核通知", "恭喜您,您的账号已审核通过", ClickActionInfo.of(ClickAction.LOGIN, user.getId()));
|
||||
}
|
||||
|
||||
public static IPushText userAuditReject(UserThumb user) {
|
||||
return from(RoleEnum.USER, user.getId(),"用户审核不通过", "审核通知", "非常抱歉,您的账号审核不通过!", ClickActionInfo.of(ClickAction.LOGIN, user.getId()));
|
||||
}
|
||||
|
||||
public static IPushText from(RoleEnum role, Integer targetId, String event, String title, String content, ClickActionInfo info) {
|
||||
return new IPushText() {
|
||||
@Override
|
||||
public String title() {
|
||||
return title;
|
||||
}
|
||||
@Override
|
||||
public String content() {
|
||||
return content;
|
||||
}
|
||||
@Override
|
||||
public String event() {
|
||||
return event;
|
||||
}
|
||||
@Override
|
||||
public ClickActionInfo clickActionInfo() {
|
||||
return info;
|
||||
}
|
||||
@Override
|
||||
public RoleEnum role() {
|
||||
return role;
|
||||
}
|
||||
@Override
|
||||
public Integer targetId() {
|
||||
return targetId;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user