Commit 23764a4e by xunj

正是上线发布版本

1 parent 63e497db
Showing 25 changed files with 864 additions and 159 deletions
......@@ -4,7 +4,7 @@ public enum MsgCodeEnum {
BALANCE_NO("1001","余额不足"),
OPEN_CATTLE1("2001","该用户不存在"),
OPEN_CATTLE2("2002","福牛红包已被领取"),
OPEN_CATTLE3("2003","开奖时间2020-02-17 20:21:00,请少侠耐心等待"),
OPEN_CATTLE3("2003","开奖时间2020-02-17 20:21:00,少侠请耐心等待"),
//
RED_PACK_RECHAGE_NO("3001","红包雨未结算完成");
......
package com.polysoft.activity.controller;
import com.alibaba.fastjson.JSONObject;
import com.polysoft.activity.constant.CommonTypeEnum;
import com.polysoft.activity.mapper.ActivityMapper;
import com.polysoft.activity.model.dto.AddRedRainDto;
import com.polysoft.activity.service.ActItemService;
import com.polysoft.activity.utils.ApiResult;
import com.polysoft.activity.utils.IPForAddressUtil;
import com.polysoft.activity.utils.IpUtils;
import com.polysoft.activity.utils.SnowFlakeUtil;
import com.polysoft.activity.utils.TestUtils;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
......@@ -37,4 +41,15 @@ public class TestController {
return ApiResult.ok(actItemService.testOne());
}
@GetMapping("/testTwo" )
@ResponseBody
public ApiResult testTwo() {
String ip = IpUtils.getIpAddress(true);
System.out.println(ip);
// IPForAddressUtil.getAddress(ip);
JSONObject object = TestUtils.getAddresssByIP(ip);
return ApiResult.ok(object);
}
}
......@@ -52,16 +52,25 @@ public class UserController {
@PostMapping("/saveUserSign")
@ResponseBody
public ApiResult saveUserSign(@RequestBody UserInfoParam param) {
return userInfoService.saveUserSign(param);
}
@PostMapping("/queryUserSign")
@ResponseBody
public ApiResult queryUserSign(@RequestBody IdQueryParam param) {
return userInfoService.queryUserSignByUserId(param.getId(),null);
}
@PostMapping("/saveZapenTixian")
@ResponseBody
public ApiResult saveZapenTixian(@RequestBody IdQueryParam param) {
return userInfoService.saveZapenTixian(param);
}
@PostMapping("/saveFirstIntoCattle")
@ResponseBody
public ApiResult saveFirstIntoCattle(@RequestBody UserInfoParam param) {
return userInfoService.saveFirstIntoCattle(param);
}
}
......@@ -40,4 +40,7 @@ public interface UserInfoMapper {
List<Long> getNotSignUserToYesterday(@Param("signDate") String signDate);
int updateRedBalaceForFist(@Param("userId") Long userId,@Param("redBalance") BigDecimal redBalance);
int updateFirstRedStatus(@Param("id") Long id);
int getShareToTodayCount(@Param("userId") Long userId);
int saveFirstIntoCattle(@Param("userId") Long userId);
int updateFirstIntoCattle();
}
......@@ -8,4 +8,5 @@ public class UserInfoParam extends PageQuery {
private String phone;
private Long userId;
private Long signId;
private String isFirstShare;
}
......@@ -36,5 +36,7 @@ public class UserInfoVO implements Serializable {
private String cattleTypeNum;
//0 首次分享 1 非首次分享
private String isFirstShare;
//当天是否首次进入牛牌页面 0 首次 1 非首次
private String isFirstToCattle;
}
......@@ -17,4 +17,5 @@ public interface UserInfoService {
ApiResult getFirsetLgoinRed(Long userId);
ApiResult queryUserSignByUserId(Long userId,String signDate);
ApiResult saveZapenTixian(IdQueryParam param);
ApiResult saveFirstIntoCattle(UserInfoParam param);
}
......@@ -37,11 +37,9 @@ import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
......@@ -305,6 +303,31 @@ public class UserInfoServiceImpl implements UserInfoService {
dto.setHammerStatus("1");
return ApiResult.ok(mapper.updateUserStates(dto));
}
@Override
public ApiResult saveFirstIntoCattle(UserInfoParam param) {
CattleBrandVO cattleBrandVO = null;
int k1 = mapper.saveFirstIntoCattle(param.getUserId());
if (k1 < 1) {
throw new BusinessException("ID@@" + param.getUserId() + "@@每日首次进入牛牌活动页发送牛牌异常");
}
CattleBrandConfVO confVO = cattleBrandMapper.queryCattleBrandConf(DateUtil.format(new Date(), "yyyy-MM-dd"));
MathRandom random = new MathRandom(confVO.getRate1(), confVO.getRate2(), confVO.getRate3(), confVO.getRate4(), confVO.getRate5());
List<SaveUserCattleDto> list = new ArrayList<>();
SaveUserCattleDto cattleDto = new SaveUserCattleDto();
cattleDto.setId(SnowFlakeUtil.nextId());
cattleDto.setUserId(param.getUserId());
String barandType = random.PercentageRandom() + "";
cattleBrandVO = cattleBrandMapper.queryCattleBrandList(barandType).get(0);
cattleDto.setCattleBrandId(cattleBrandVO.getCattleId());
list.add(cattleDto);
int k2 = mapper.saveCattleBrand(list);
if (k2 < 1) {
throw new BusinessException("ID@@" + param.getUserId() + "@@每日首次进入牛牌活动页发送牛牌异常");
}
return ApiResult.ok(cattleBrandVO);
}
@Transactional(rollbackFor = Exception.class)
@Override
public ApiResult saveShareCallBack(ShareLinkParam param){
......@@ -324,6 +347,25 @@ public class UserInfoServiceImpl implements UserInfoService {
throw new BusinessException("牛牌分享异常");
}
}
//首次分享发放牛牌
int shareCount = mapper.getShareToTodayCount(param.getUserId());
CattleBrandVO cattleBrandVO = null;
if(shareCount == 0){
CattleBrandConfVO confVO = cattleBrandMapper.queryCattleBrandConf(DateUtil.format(new Date(),"yyyy-MM-dd"));
MathRandom random = new MathRandom(confVO.getRate1(), confVO.getRate2(), confVO.getRate3(), confVO.getRate4(), confVO.getRate5());
List<SaveUserCattleDto> list = new ArrayList<>();
SaveUserCattleDto cattleDto = new SaveUserCattleDto();
cattleDto.setId(SnowFlakeUtil.nextId());
cattleDto.setUserId(param.getUserId());
String barandType = random.PercentageRandom() + "";
cattleBrandVO = cattleBrandMapper.queryCattleBrandList(barandType).get(0);
cattleDto.setCattleBrandId(cattleBrandVO.getCattleId());
list.add(cattleDto);
int k5 = mapper.saveCattleBrand(list);
if (k5 < 1) {
throw new BusinessException("ID@@" + param.getUserId() + "@@美日首次分享发送牛牌异常");
}
}
//存储分享连接
ShareDto shareDto = new ShareDto();
shareDto.setId(SnowFlakeUtil.nextId());
......@@ -335,6 +377,6 @@ public class UserInfoServiceImpl implements UserInfoService {
if(k3 < 1){
throw new BusinessException("牛牌分享异常");
}
return ApiResult.ok();
return ApiResult.ok(cattleBrandVO);
}
}
......@@ -36,7 +36,7 @@ public class CattleBrandCarveUpTask {
// @Scheduled( cron = "0 20 20 * * ? ")
// @Scheduled(initialDelay = 5000, fixedRate = 1*15*60*1000)
@Scheduled( cron = "1 0 20 17 2 ? ") // 2021年2月17号 20时0分1秒 执行
@Scheduled( cron = "0 1 20 17 2 ? ") // 2021年2月17号 20时0分1秒 执行
public void execute() {
try {
sendWechat();
......
......@@ -6,6 +6,7 @@ import com.polysoft.activity.constant.CommonTypeEnum;
import com.polysoft.activity.mapper.UserInfoMapper;
import com.polysoft.activity.model.dto.UserSignDto;
import com.polysoft.activity.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
......@@ -22,6 +23,7 @@ import java.util.List;
*/
@Component
@EnableScheduling
@Slf4j
public class UserSignTask {
@Resource
private UserInfoMapper userInfoMapper;
......@@ -40,6 +42,8 @@ public class UserSignTask {
}
private void sendWechat(){
log.info("补签和修改首次进入牛牌活动页状态任务开始");
try {
//查询前一天未签到的人员
String yesTerDay = DateUtil.format(DateUtil.yesterday(),"yyyy-MM-dd");
List<Long> userIds = userInfoMapper.getNotSignUserToYesterday(yesTerDay);
......@@ -54,6 +58,14 @@ public class UserSignTask {
userSignDto.setCreateTime(date);
list.add(userSignDto);
});
//更新状态为补签
userInfoMapper.saveUserSignBatch(list);
//更新首次进入牛牌活动也状态为0
userInfoMapper.updateFirstIntoCattle();
log.info("补签和修改首次进入牛牌活动页状态任务结束");
} catch (Exception e) {
e.printStackTrace();
}
}
}
......@@ -15,6 +15,7 @@
hammer_status,
cattle_open_status,
is_first_share,
is_first_to_cattle,
(select count(*) from (select tc.cattle_brand_id from t_user_cattle tc where tc.user_id = #{userId} and tc.is_share = '0' GROUP BY tc.cattle_brand_id)tab) as cattleTypeNum
from
......@@ -94,6 +95,12 @@
SET is_flag = '1'
where id = #{id}
</update>
<update id="saveFirstIntoCattle">
UPDATE t_user set is_first_to_cattle = '1' where user_id = #{userId}
</update>
<update id="updateFirstIntoCattle">
update t_user set is_first_to_cattle='0'
</update>
<insert id="saveCattleBrand" parameterType="com.polysoft.activity.model.dto.SaveUserCattleDto">
INSERT into t_user_cattle (
id,
......@@ -192,5 +199,14 @@
WHERE
NOT EXISTS ( SELECT 1 FROM t_user_sign t WHERE t.sign_date = #{signDate} AND t.user_id = tt.user_id )
</select>
<select id="getShareToTodayCount" resultType="java.lang.Integer">
SELECT
count( * )
FROM
t_share
WHERE
share_date = DATE_FORMAT( NOW( ), '%Y-%m-%d' )
AND user_id = #{userId}
</select>
</mapper>
......@@ -68,6 +68,16 @@
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.9.RELEASE</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.common.utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
/**
* IP地址
*
* @author moxi moxi@xi-ai.com
*/
public class IPUtils {
private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
/**
* 获取IP地址
*
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
// //使用代理,则获取第一个IP地址
// if(StringUtils.isEmpty(ip) && ip.length() > 15) {
// if(ip.indexOf(",") > 0) {
// ip = ip.substring(0, ip.indexOf(","));
// }
// }
return ip;
}
}
package com.polysoft.activity.constants;
import java.util.Arrays;
public enum CallType {
CALL_TYPE_0(0, "normalConnection", "正常通话"),
CALL_TYPE_1(1, "cannotConnection", "无法接通"),
CALL_TYPE_2(2, "inputError", "OBS错误"),
CALL_TYPE_3(3, "busy", "客户忙"),
CALL_TYPE_4(4, "invalidNumber", "空号"),
CALL_TYPE_5(5, "outOfService", "暂停服务"),
CALL_TYPE_6(6, "noAnswer", "无人接听"),
CALL_TYPE_7(7, "shutDown", "停机"),
CALL_TYPE_8(8, "fail", "呼叫不成功"),
CALL_TYPE_9(9, "notYet", "未外呼"),
CALL_TYPE_10(10, "phoneIsNull", "手机号为空"),
CALL_TYPE_11(11,"waitCall","待外呼"),
CALL_TYPE_12(12,"voiceMergeError","录音拼接失败"),
CALL_TYPE_13(13,"voiceFile","录音文件下载失败"),
CALL_TYPE_14(14,"error","未知错误"),
CALL_TYPE_15(15,"paramError","参数错误"),
CALL_TYPE_16(16,"voiceNames","未检测到dm返回录音文件名称"),
CALL_TYPE_17(17,"dmError","dm报错"),
CALL_TYPE_18(18,"calling","正在拨打"),
CALL_TYPE_19(19, "turnOff", "关机"),
CALL_TYPE_20(20, "filenameError", "录音名称不存在"),
CALL_TYPE_21(21, "ttsError", "tts合成失败"),
CALL_TYPE_22(22, "sessionIdError", "sessionId已存在"),
CALL_TYPE_23(23, "callTransfer", "呼叫转移"),
CALL_TYPE_24(24, "callWaiting", "呼叫等待"),
CALL_TYPE_25(25, "refuse", "拒接"),
CALL_TYPE_26(26, "userHangUp", "用户挂断");
private Integer callTypeNum;
private String callType;
private String callTypeTitle;
public static CallType getByNum(Integer callTypeNum){
return Arrays.stream(CallType.values()).filter(type -> type.getCallTypeNum().equals(callTypeNum)).findAny().orElse(CALL_TYPE_14);
}
public static CallType getByType(String callType){
return Arrays.stream(CallType.values()).filter(type -> type.getCallType().equals(callType)).findAny().orElse(CALL_TYPE_14);
}
public static String getByCallTypeEn(String callType){
for(CallType type : CallType.values()){
if(type.callType.equals(callType)){
return type.callTypeTitle;
}
}
return "";
}
CallType(Integer callTypeNum, String callType, String callTypeTitle) {
this.callType = callType;
this.callTypeTitle = callTypeTitle;
this.callTypeNum = callTypeNum;
}
public String getCallType() {
return callType;
}
public void setCallType(String callType) {
this.callType = callType;
}
public String getCallTypeTitle() {
return callTypeTitle;
}
public void setCallTypeTitle(String callTypeTitle) {
this.callTypeTitle = callTypeTitle;
}
public Integer getCallTypeNum() {
return callTypeNum;
}
public void setCallTypeNum(Integer callTypeNum) {
this.callTypeNum = callTypeNum;
}
}
package com.polysoft.activity.constants;
/**
* @author by zhangbr
* @date 2020/4/8.
*/
public enum HttpClientHeaderEnum {
/**
* 系统自定义请求header参数
*/
USER_HEADER_USER_ID("userId", "用户ID"),
USER_HEADER_OLD_USER_ID("oldUserId", "老用户ID"),
USER_HEADER_USER_TOKEN("token", "用户token"),
USER_HEADER_MODE("mode", "设备:PC,APP,PAD"),
;
HttpClientHeaderEnum(String code, String name){
this.code = code;
this.name = name;
}
private String name;
private String code;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public static boolean checkHasCode(String key) {
for (HttpClientHeaderEnum c : HttpClientHeaderEnum.values()) {
if (c.getCode().toLowerCase().equals(key.toLowerCase())) {
return true;
}
}
return false;
}
}
package com.polysoft.activity.constants;
/**
* @author by zhangbr
* @date 2020/7/11
*/
public enum MessageEnum {
/**
* 通用提示枚举
*/
SUCCESS(0, "操作成功!"),
FAIL(-100, "操作失败,请稍后再试!"),
FAIL_PARAM(-101, "参数不可为空!"),
FAIL_PARAM_TYPE(-102, "参数类型错误"),
NO_LOGIN(401, "会话超时,请重新登录!"),
HTTP_CLIENT(-104, "http请求失败,请稍后再试!"),
SELECT_HAS_NO(-105, "信息不存在或已被删除,请选择有效数据!"),
NO_SUPPORT_ACTION(-106, "不支持此操作!"),
EXCEL_EXPORT_ERROR(-107, "Excel数据导出失败!"),
FEIGN_CLIENT_DECODE(-108, "远程接口解码失败!"),
MAX_FILE_SIZE(-109, "上传文件超过最大限制!"),
FILE_TYPE_ERROR(-110, "文件类型不允许上传!"),
FILE_UPLOAD_FAIL(-111, "文件上传失败!"),
FILE_DOWN_FAIL(-112, "文件不存在或已被删除!"),
;
private int code;
private String remarks;
MessageEnum(int code, String remarks){
this.code = code;
this.remarks = remarks;
}
public int getCode() {
return code;
}
public String getRemarks() {
return remarks;
}
}
......@@ -52,6 +52,12 @@ public class ApiResult extends HashMap<String, Object> {
r.put("msg", msg);
return r;
}
public static ApiResult ok(int code, String msg) {
ApiResult r = new ApiResult();
r.put("code", code);
r.put("msg", msg);
return r;
}
// public static ApiResult ok(Map<String, Object> map) {
// ApiResult r = new ApiResult();
// r.putAll(map);
......
package com.polysoft.activity.utils;
import com.alibaba.fastjson.JSONObject;
import com.polysoft.activity.constants.HttpClientHeaderEnum;
import com.polysoft.activity.constants.MessageEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.AbstractExecutionAwareRequest;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
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;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author by lvyp
* @date 2021/1/30.
*/
@Slf4j
public class HttpClientUtils {
private static final String POST_FILE_UPLOAD = "HttpClient:POST-FILEUPLOAD";
private static final String POST_JSON = "HttpClient:POST-JSON";
private static final String POST_FORM = "HttpClient:POST-FORM";
private static final String GET = "HttpClient:GET";
private static final RequestConfig REQUEST_CONFIG = RequestConfig.custom()
.setSocketTimeout(1000 * 60)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(1000 * 60)
.build();
/**
* get方式
* @param url url
* @param formParams formParams
* @param headerParams headerParams
* @return String
*/
public static String doGet(String url, Map<String, String> formParams, Map<String, String> headerParams) {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 拼接参数,可以用URIBuilder,也可以直接拼接在?传值,拼在url后面,如下--httpGet = new
// HttpGet(uri+"?id=123");
HttpGet httpGet = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
if (null != formParams && !formParams.isEmpty()) {
for (Map.Entry<String, String> entry : formParams.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
// 或者用
// uriBuilder.setParameter(entry.getKey(), entry.getValue());
//不同:(setParameter会覆盖同名参数的值,addParameter则不会)
}
}
URI uri = uriBuilder.build();
// 创建get请求
httpGet = new HttpGet(uri);
// setHeader
setHeader(httpGet, headerParams);
} catch (URISyntaxException e) {
log.error (e.getMessage (), e);
}
return executeHttpClient(httpClient, httpGet, GET, url);
}
/**
* post请求
* @param url url
* @param formParams formParams
* @param headerParams headerParams
* @return String
*/
public static String doPost(String url, Map<String, String> formParams, Map<String, String> headerParams) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
// 参数键值对
if (null != formParams && !formParams.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair = null;
for (String key : formParams.keySet()) {
pair = new BasicNameValuePair(key, formParams.get(key));
pairs.add(pair);
}
try {
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
httpPost.setEntity(entity);
} catch (UnsupportedEncodingException e) {
log.error (e.getMessage (), e);
}
}
// setHeader
setHeader(httpPost, headerParams);
return executeHttpClient(httpClient, httpPost, POST_FORM, url);
}
/**
* post发送json字符串
* @param url url
* @param params params
* @return String
*/
public static String sendJsonStr(String url, String params, Map<String, String> headerParams) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
if (StringUtils.isNotBlank(params)) {
httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
}
// setHeader
setHeader(httpPost, headerParams);
return executeHttpClient(httpClient, httpPost, POST_JSON, url);
}
/**
* 附件上传
* @param url url
* @param jsonParams jsonParams
* @param headerParams headerParams
* @param files files
* @param fileParName fileParName
* @return String
*/
public static String sendFilesUpload(String url, String jsonParams, Map<String, String> headerParams, MultipartFile[] files, String fileParName){
String result = JSONObject.toJSONString(ApiResult.ok(MessageEnum.HTTP_CLIENT.getCode(), MessageEnum.HTTP_CLIENT.getRemarks()));
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName;
if (files != null && files.length > 0){
try {
for (MultipartFile file : files) {
fileName = file.getOriginalFilename();
// 文件流
builder.addBinaryBody(fileParName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
}
} catch (IOException e) {
log.error (e.getMessage (), e);
}
}
if (StringUtils.isNotBlank(jsonParams)) {
httpPost.setEntity(new StringEntity(jsonParams, Charset.forName("UTF-8")));
}
// setHeader
setHeader(httpPost, headerParams);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return executeHttpClient(httpClient, httpPost, POST_FILE_UPLOAD, url);
}
/**
* 开始执行
* @param httpClient httpClient
* @param requestBase requestBase
* @param httpType httpType
* @param url url
* @return String
*/
private static String executeHttpClient(CloseableHttpClient httpClient, HttpRequestBase requestBase, String httpType, String url){
String result = JSONObject.toJSONString(ApiResult.ok(MessageEnum.HTTP_CLIENT.getCode(), MessageEnum.HTTP_CLIENT.getRemarks()));
if (requestBase == null){
return result;
}
log.debug(httpType + "开始,URL:{}", url);
try {
requestBase.setConfig(REQUEST_CONFIG);
requestBase.addHeader("x-forwarded-for", IpUtils.getIpAddress(false));
HttpResponse response = httpClient.execute(requestBase);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
log.debug(httpType + "返回数据:>>>{}", result);
} else {
log.info(httpType + "请求失败!,url:{}", url);
}
} catch (IOException e) {
log.info(httpType + "请求失败:ERROR!,url:{}", url);
log.info (e.getMessage (), e);
} finally {
// 释放连接
requestBase.releaseConnection();
try {
httpClient.close();
} catch (IOException e) {
log.info(e.getMessage(), e);
}
log.debug(httpType + "结束,URL:{}", url);
}
return result;
}
/**
* 设置httpClient header
* @param httpClient httpClient
* @param headerParams headerParams
*/
private static void setHeader(AbstractExecutionAwareRequest httpClient, Map<String, String> headerParams){
if (headerParams != null) {
for (String key : headerParams.keySet()) {
httpClient.addHeader(key, headerParams.get(key));
}
}
}
/**
* 获取用户自定义header
* @return Map<String, String>
*/
public static Map<String, String> getUserHeaderMap(){
Map<String, String> headerParams = new HashMap<>(0);
HttpServletRequest request = RequestUtils.getRequest();
Enumeration headerNames = RequestUtils.getRequest().getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
if (HttpClientHeaderEnum.checkHasCode(key)){
String value = request.getHeader(key);
headerParams.put(key, value);
}
}
return headerParams;
}
}
package com.polysoft.activity.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
/**
* @author lvyp
* @date 2021/2/7
*/
public class IPForAddressUtil {
/**
* 根据ip获取地址
* @param ip
* @return
*/
public static JSONObject getAddress(String ip) {
String url = "http://ip.360.cn/IPShare/info?ip=" + ip;
System.out.println("真是ip:"+ip);
String str = HttpUtil.get(url);
if(!StrUtil.hasBlank(str)){
String substring = str.substring(str.indexOf("{"), str.indexOf("}")+1);
System.out.println(substring);
JSONObject jsonObject = JSONUtil.parseObj(substring);
String province = jsonObject.getStr("province");
String city = jsonObject.getStr("city");
return jsonObject;
}
return null;
}
}
package com.polysoft.activity.utils;
import javax.servlet.http.HttpServletRequest;
/**
* @author by lvyp
* @date 2021/1/30.
*/
public class IpUtils {
/**
* 获取客户端IP[不真实,可能伪造IP]
* @param split 是否分割截取第一个
* @return String
*/
public static String getIpAddress(boolean split) {
String unknown = "unknown";
String milt = ",";
HttpServletRequest request = RequestUtils.getRequest();
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip != null && ip.length() != 0 && !unknown.equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
if(split && ip.contains(milt)){
ip = ip.split(milt)[0];
}
}
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
package com.polysoft.activity.utils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
/**
* @author by lvyp
* @date 2021/1/30.
*/
public class ListUtils {
/**
* 集合去重
* @param list ID集合
* @return list
*/
public static <T> List<T> repeatList(List<T> list){
if (list == null){
return new ArrayList<>();
} else if (!list.isEmpty()){
HashSet<T> h = new HashSet<>(list);
list.clear();
list.addAll(h);
}
return list;
}
}
package com.polysoft.activity.utils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author by lvyp
* @date 2021/1/30.
*/
public class RedisUtils {
@SuppressWarnings("unchecked")
private static RedisTemplate<String, Object> redisTemplate = SpringUtils.getBean("redisTemplate", RedisTemplate.class);
public RedisUtils(RedisTemplate<String, Object> redisTemplate) {
RedisUtils.redisTemplate = redisTemplate;
}
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public static Object get(String key){
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public static <T> T hGetObject(String key, Class<T> clazz){
Object o = redisTemplate.opsForValue().get(key);
return JSONObject.parseObject((String) o, clazz);
}
public static <T> T hGetObject(String key, String item, Class<T> clazz){
Object o = redisTemplate.opsForHash().get(key, item);
return JSONObject.parseObject((String) o, clazz);
}
public static <T> List<T> hGetList(String key, String item, Class<T> clazz){
Object o = redisTemplate.opsForHash().get(key, item);
return JSONObject.parseArray((String) o, clazz);
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public static boolean hSet(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean hSet(String key, Object value,Long time,TimeUnit unit) {
try {
redisTemplate.opsForValue().set(key, value);
if (time > 0) {
expire(key, time,unit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean hSet(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean expire(String key, long time,TimeUnit unit){
try {
if(time>0){
redisTemplate.expire(key, time, unit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public static void hDel(String key, Object... item){
redisTemplate.opsForHash().delete(key,item);
}
/**
* 删除hash表中的值
* @param key 键 不能为null
*/
public static void hDel(String key){
redisTemplate.delete(key);
}
}
\ No newline at end of file
package com.polysoft.activity.utils;
import com.polysoft.activity.common.exception.BusinessException;
import com.polysoft.activity.constants.HttpClientHeaderEnum;
import com.polysoft.activity.constants.MessageEnum;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author by lvyp
* @date 2021/1/30.
*/
public class RequestUtils {
public static HttpServletRequest getRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
}
public static HttpServletResponse getResponse() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse();
return response;
}
public static Long getUserId(){
String userId = getRequest().getHeader(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode());
if (!StringUtils.isEmpty(userId)){
try {
return Long.valueOf(userId);
} catch (NumberFormatException e) {
return null;
}
}
return null;
}
public static String getToken(){
String token = getRequest().getHeader(HttpClientHeaderEnum.USER_HEADER_USER_TOKEN.getCode());
return StringUtils.isEmpty(token) ? null : token;
}
/**
* 校验是否登录,登录返回用户ID
* @return Long
*/
public static Long checkLoginStatus(){
Long userId = getUserId();
String token = getToken();
if (userId == null || StringUtils.isEmpty(token)){
throw new BusinessException(MessageEnum.NO_LOGIN.getCode(), MessageEnum.NO_LOGIN.getRemarks());
}
return userId;
}
}
package com.polysoft.activity.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
/**
* @author by lvyp
* @date 2021/1/30.
*/
@SuppressWarnings("unchecked")
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
private static <T> T getBean(Class<T> tClass){
return applicationContext.getBean(tClass);
}
public static <T> T getBean(String name, Class<T> type) {
return applicationContext.getBean(name, type);
}
private static HttpServletRequest getCurrentReq() {
ServletRequestAttributes requestAttrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttrs == null) {
return null;
}
return requestAttrs.getRequest();
}
public static String getMessage(String code, Object... args) {
LocaleResolver localeResolver = getBean(LocaleResolver.class);
Locale locale = localeResolver.resolveLocale(getCurrentReq());
return applicationContext.getMessage(code, args, locale);
}
}
package com.polysoft.activity.utils;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* @author lvyp
* @date 2021/2/7
*/
public class TestUtils {
public static JSONObject getAddresssByIP(String ip) {
String ipString = null;
String jsonData = ""; // 请求服务器返回的json字符串数据
try {
ipString = java.net.URLEncoder.encode(ip, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String key = "6773467373849fc0528195d1b1c2782e";// 高德key
// String url = String.format("https://restapi.amap.com/v3/ip?ip="+ipString+"&output=json&key=6773467373849fc0528195d1b1c2782e");// 百度普通IP定位API
String url = String.format("http://whois.pconline.com.cn/ipJson.jsp?ip="+ip+"&json=true"); // 百度普通IP定位API
URL myURL = null;
URLConnection httpsConn = null;
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStreamReader insr = null;
BufferedReader br = null;
try {
httpsConn = myURL.openConnection();// 不使用代理
if (httpsConn != null) {
insr = new InputStreamReader(httpsConn.getInputStream(), "GBK");
br = new BufferedReader(insr);
String data = null;
while ((data = br.readLine()) != null) {
jsonData += data;
}
JSONObject jsonObj = JSONObject.parseObject(jsonData);
return jsonObj;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (insr != null) {
insr.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
System.out.println(TestUtils.getAddresssByIP("223.104.39.138"));
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!