Commit cd31190d by 周海宝

Merge branch 'dev' into 'master'

Dev

See merge request !2
2 parents 9d44fe6f 69d413c1
Showing 25 changed files with 820 additions and 235 deletions
package cn.com.glsx.common.BussinessFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @author zhouhaibao
* @date 2021/3/8 11:31
*/
public class BussinessFactory implements ApplicationContextAware {
//ApplicationContext对象是Spring开源框架的上下文对象实例,在项目运行时自动装载Handler内的所有信息到内存。
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (BussinessFactory.applicationContext == null) {
BussinessFactory.applicationContext = applicationContext;
}
}
/**
* 获取service子类
*
* @param bustype
* @param requiredType
* @param <T>
* @return
*/
public static <T> T getInstance(String bustype,Class<T> requiredType){
String handerType = BussinessType.getHanderType(bustype);
if(handerType==null){
return null;
}else {
T bean = applicationContext.getBean(handerType, requiredType);
return bean;
}
}
}
package cn.com.glsx.common.BussinessFactory;
/**
* @author zhouhaibao
* @date 2021/3/8 11:32
*/
public enum BussinessType {
tuya_hander("tuya", "deviceService"),
mhome_hander("mhome", "testService");
private String busType;
private String handerImp;
BussinessType(String busType, String handerImp) {
this.busType = busType;
this.handerImp = handerImp;
}
public String getBusType() {
return busType;
}
public void setBusType(String busType) {
this.busType = busType;
}
public String getHanderImp() {
return handerImp;
}
public void setHanderImp(String handerImp) {
this.handerImp = handerImp;
}
public static String getHanderType(String busType) {
for (BussinessType m : BussinessType.values()) {
if (m.getBusType() == busType) {
return m.getHanderImp();
}
}
return null;
}
}
package cn.com.glsx.modules.controller; package cn.com.glsx.modules.controller;
import cn.com.glsx.common.BussinessFactory.BussinessFactory;
import cn.com.glsx.modules.model.param.DeviceInfo;
import cn.com.glsx.modules.model.param.Function;
import cn.com.glsx.modules.service.DeviceService;
import cn.com.glsx.modules.service.abs.BaseDeviceService;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.core.web.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/** /**
* @author zhouhaibao * @author zhouhaibao
...@@ -9,8 +25,75 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -9,8 +25,75 @@ import org.springframework.web.bind.annotation.RequestMapping;
*/ */
@Controller @Controller
@RequestMapping("/device") @RequestMapping("/device")
@Api(value = "设备管理", tags = {"设备管理"})
public class DeviceController { public class DeviceController {
@Autowired
private DeviceService deviceService;
/**
* 获取用户下的设备列表
*
* @return
*/
@RequestMapping(value = "/{uid}/devices", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "获取用户下的设备列表")
public R getAllDevicesByUser(@PathVariable String uid){
List<DeviceInfo> list=deviceService.getAllDevicesByUser(uid);
return R.ok(JSONObject.toJSONString(list));
}
/**
* 获取用户下的设备列表
*
* @return
*/
@RequestMapping(value = "/devices/{device_id}", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根据id获取设备")
public R getDevicesById(@PathVariable String device_id){
DeviceInfo deviceInfo=deviceService.getDevicesById(device_id);
return R.ok(JSONObject.toJSONString(deviceInfo));
}
/**
* 获取用户下的设备列表
*
* @return
*/
@RequestMapping(value = "/devices/{device_id}/functions", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根据id获取指令集")
public R getFunctionsById(@PathVariable String device_id){
Function function =deviceService.getFunctionsById(device_id);
return R.ok(JSONObject.toJSONString(function));
}
/**
* 获取用户下的设备列表
*
* @return
*/
@RequestMapping(value = "/functions/{category}", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根据品类获取指令集")
public R getFunctionsByCat(@PathVariable String category){
Function function =deviceService.getFunctionsByCat(category);
return R.ok(JSONObject.toJSONString(function));
}
/**
* 根据设备下发指令
*
* @return
*/
@RequestMapping(value = "/devices/{device_id}/commands", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "根据设备下发指令")
public R instructionIssue(@PathVariable String device_id,@RequestBody String insjson){
String message = deviceService.instructionIssue(device_id, insjson);
return R.ok(JSONObject.toJSONString(message));
}
} }
...@@ -10,11 +10,7 @@ import io.swagger.annotations.ApiOperation; ...@@ -10,11 +10,7 @@ import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/** /**
* 对接涂鸦用户模块 * 对接涂鸦用户模块
......
package cn.com.glsx.modules.factory;
/**
* @author fengzhi
* @date 2021/3/9 17:05
* @description 平台信息枚举
*/
public enum PlatForm implements PlatformConstants{
TUYA {
@Override
public Integer getCode() {
return 0;
}
@Override
public String getValue() {
return "涂鸦";
}
@Override
public String getBeanName(){
return "oneselfStrategy";
}
},
XIAOMI {
@Override
public Integer getCode() {
return 1;
}
@Override
public String getValue() {
return "小米";
}
@Override
public String getBeanName(){
return "oneselfStrategy";
}
},;
public static String getValueByCode(Integer code) {
for (PlatForm platForm : PlatForm.values()) {
if (platForm.getCode().equals(code)) {
return platForm.getValue();
}
}
return null;
}
public static String getBeanNameByCode(Integer code) {
for (PlatForm platForm : PlatForm.values()) {
if (platForm.getCode().equals(code)) {
return platForm.getBeanName();
}
}
return null;
}
}
package cn.com.glsx.modules.factory;
/**
* @author fengzhi
* @date 2021/3/9 17:05
* @description 平台信息接口
*/
public interface PlatformConstants {
Integer getCode();
String getValue();
String getBeanName();
}
package cn.com.glsx.modules.factory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author fengzhi
* @date 2021/3/9 17:05
* @description 平台接口工厂类
*/
@Service
public class PlatformFactory {
@Autowired
Map<String, PlatformStrategy> strategys = new ConcurrentHashMap<>(3);
public PlatformStrategy getStrategy(Integer platformCode) throws Exception{
PlatformStrategy strategy = strategys.get(PlatForm.getBeanNameByCode(platformCode));
if(strategy == null) {
throw new RuntimeException("no strategy defined");
}
return strategy;
}
}
package cn.com.glsx.modules.factory;
/**
* @author fengzhi
* @date 2021/3/9 17:05
* @description 平台统一对外接口
*/
public interface PlatformStrategy {
}
package cn.com.glsx.modules.factory.strategy;
import cn.com.glsx.modules.factory.PlatformStrategy;
import org.springframework.stereotype.Service;
@Service
public class TuyaStrategy implements PlatformStrategy {
}
...@@ -2,8 +2,6 @@ package cn.com.glsx.modules.model.param; ...@@ -2,8 +2,6 @@ package cn.com.glsx.modules.model.param;
import lombok.Data; import lombok.Data;
import java.util.List;
/** /**
* @author zhouhaibao * @author zhouhaibao
* @date 2021/3/4 10:10 * @date 2021/3/4 10:10
......
package cn.com.glsx.modules.model.param;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.List;
/**
* @author zhouhaibao
* @date 2021/3/5 10:20
*/
@Data
public class DeviceInfo {
private boolean sub;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date create_time;
private String local_key;
private String owner_id;
private String ip;
private Long biz_type;
private Long update_time;
private String icon;
private String time_zone;
private String uuid;
private String product_name;
private String active_time;
private String uid;
private String product_id;
private String category;
private String id;
private List<DeviceOperateInfo> status;
}
package cn.com.glsx.modules.model.param;
import lombok.Data;
/**
* @author zhouhaibao
* @date 2021/3/5 10:24
*/
@Data
public class DeviceOperateInfo {
private String code;
private String value;
}
package cn.com.glsx.modules.model.param;
import lombok.Data;
import java.util.List;
/**
* @author zhouhaibao
* @date 2021/3/5 14:06
*/
@Data
public class Function {
private String category;
private List<FunctionInfo> functions;
}
package cn.com.glsx.modules.model.param;
import lombok.Data;
/**
* @author zhouhaibao
* @date 2021/3/5 14:02
*/
@Data
public class FunctionInfo {
private String name;
private String desc;
private String code;
private String type;
private String values;
}
...@@ -16,4 +16,14 @@ public class ResponseBody { ...@@ -16,4 +16,14 @@ public class ResponseBody {
* 返回的数据 * 返回的数据
*/ */
private String result; private String result;
/**
* 返回code
*/
private Integer code;
/**
* 返回message
*/
private String message;
} }
...@@ -11,6 +11,6 @@ public class UserBo { ...@@ -11,6 +11,6 @@ public class UserBo {
private String username; private String username;
private String password; private String password;
private String username_type; private int username_type;
private String country_code; private String country_code;
} }
...@@ -3,18 +3,10 @@ package cn.com.glsx.modules.service; ...@@ -3,18 +3,10 @@ package cn.com.glsx.modules.service;
import cn.com.glsx.common.Constants; import cn.com.glsx.common.Constants;
import cn.com.glsx.common.redis.AccessTokenRedis; import cn.com.glsx.common.redis.AccessTokenRedis;
import cn.com.glsx.modules.model.param.AccessToken; import cn.com.glsx.modules.model.param.AccessToken;
import cn.com.glsx.modules.model.param.ResponseBody;
import cn.com.glsx.modules.utils.HeaderParamUtils;
import cn.com.glsx.modules.utils.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Map;
/** /**
* 获取涂鸦令牌 * 获取涂鸦令牌
...@@ -29,97 +21,17 @@ public class AccessTokenService { ...@@ -29,97 +21,17 @@ public class AccessTokenService {
@Autowired @Autowired
private AccessTokenRedis accessTokenRedis; private AccessTokenRedis accessTokenRedis;
@Value("${tuya.tokenFlashUrl}")
private String tokenFlashUrl;
@Value("${tuya.sign_method}")
private String sign_method;
@Value("${tuya.client_id}")
private String client_id;
@Value("${tuya.secret}")
private String secret;
@Value("${tuya.getTokenUrl}")
private String getTokenUrl;
@Value("${tuya.registerUserUrl}")
private String registerUserUrl;
/** /**
* 获取涂鸦令牌 * 获取涂鸦令牌
* *
* @return * @return
*/ */
public String getAccessToken() { public String getAccessToken() {
String access_Token = null;
AccessToken accessToken = accessTokenRedis.readCache(Constants.ACCESSTOKEN_REDISKEY); AccessToken accessToken = accessTokenRedis.readCache(Constants.ACCESSTOKEN_REDISKEY);
if (null != accessToken) { if(accessToken==null){
if ((System.currentTimeMillis()-accessToken.getExpire_time()) >= 1000 * 60 * 60 * 2) { return null;
ResponseBody responseBody = sendRequestFlashToken(accessToken.getRefresh_token());
if (responseBody != null && responseBody.isSuccess()) {
String result = responseBody.getResult();
AccessToken token = JSONObject.parseObject(result, AccessToken.class);
token.setExpire_time(System.currentTimeMillis());
accessTokenRedis.add(Constants.ACCESSTOKEN_REDISKEY, token);
access_Token = token.getAccess_token();
} else {
log.info("调用刷新令牌接口异常");
}
} else {
access_Token = accessToken.getAccess_token();
}
} else {
ResponseBody responseBody = sendRequestGetToken();
if (responseBody != null && responseBody.isSuccess()) {
String result = responseBody.getResult();
AccessToken token = JSONObject.parseObject(result, AccessToken.class);
token.setExpire_time(System.currentTimeMillis());
accessTokenRedis.add(Constants.ACCESSTOKEN_REDISKEY, token);
access_Token = token.getAccess_token();
} else {
log.info("调用获取accesstoken接口异常");
}
} }
return access_Token; return accessToken.getAccess_token();
} }
/**
* 发送刷新令牌请求
*
* @return
*/
private ResponseBody sendRequestFlashToken(String flashtoken) {
ResponseBody responseBody = null;
Map<String, String> headerParams = HeaderParamUtils.buildHeaderParams(client_id, secret);
try {
JSONObject jsonObject = HttpUtil.sendGet(tokenFlashUrl + flashtoken, null, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("请求刷新token接口异常,异常信息{}", e);
}
return responseBody;
}
/**
* 发送请求获取涂鸦token
*
* @return
*/
private ResponseBody sendRequestGetToken() {
ResponseBody responseBody = null;
Map<String, String> headerParams = HeaderParamUtils.buildHeaderParams(client_id, secret);
try {
JSONObject jsonObject = HttpUtil.sendGet(getTokenUrl, null, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("请求获取token接口异常,异常信息{}", e);
}
return responseBody;
}
} }
package cn.com.glsx.modules.service;
import cn.com.glsx.modules.model.param.DeviceInfo;
import cn.com.glsx.modules.model.param.Function;
import cn.com.glsx.modules.model.param.ResponseBody;
import cn.com.glsx.modules.service.abs.BaseDeviceService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author zhouhaibao
* @date 2021/3/5 10:17
*/
@Service
@Slf4j
public class DeviceService extends BaseDeviceService {
@Value("${tuya.getAllDevicesByUserUrl}")
private String getAllDevicesByUserUrl;
@Value("${tuya.getFunctionsByIdUrl}")
private String getFunctionsByIdUrl;
@Value("${tuya.getDevicesByIdUrl}")
private String getDevicesByIdUrl;
@Value("${tuya.getFunctionsByCatUrl}")
private String getFunctionsByCatUrl;
@Value("${tuya.instructionIssue}")
private String instructionIssue;
@Autowired
private SendRequestService sendRequestService;
@Override
public List<DeviceInfo> getAllDevicesByUser(String uid) {
List<DeviceInfo> userInfo = null;
ResponseBody responseBody = sendRequestService.sendRequestGet(getAllDevicesByUserUrl.replace("{uid}", uid));
if (responseBody != null && responseBody.isSuccess()) {
String result = responseBody.getResult();
userInfo = JSONObject.parseArray(result, DeviceInfo.class);
} else {
log.info("调用涂鸦获取用户设备接口失败");
}
return userInfo;
}
@Override
public DeviceInfo getDevicesById(String device_id) {
DeviceInfo deviceInfo = null;
ResponseBody responseBody = sendRequestService.sendRequestGet(getDevicesByIdUrl.replace("{device_id}", device_id));
if (responseBody != null && responseBody.isSuccess()) {
String result = responseBody.getResult();
deviceInfo = JSONObject.parseObject(result, DeviceInfo.class);
} else {
log.info("调用涂鸦获取设备接口失败");
}
return deviceInfo;
}
@Override
public Function getFunctionsById(String device_id) {
Function function = null;
ResponseBody responseBody = sendRequestService.sendRequestGet(getFunctionsByIdUrl.replace("{device_id}", device_id));
if (responseBody != null && responseBody.isSuccess()) {
String result = responseBody.getResult();
function = JSONObject.parseObject(result, Function.class);
} else {
log.info("调用涂鸦获取用户设备接口失败");
}
return function;
}
@Override
public Function getFunctionsByCat(String category) {
Function function = null;
ResponseBody responseBody = sendRequestService.sendRequestGet(getFunctionsByCatUrl.replace("{category}", category));
if (responseBody != null && responseBody.isSuccess()) {
String result = responseBody.getResult();
function = JSONObject.parseObject(result, Function.class);
} else {
log.info("调用涂鸦获取用户设备接口失败");
}
return function;
}
@Override
public String instructionIssue(String device_id, String insjson) {
String message = null;
ResponseBody responseBody = sendRequestService.sendRequestPost(instructionIssue.replace("{device_id}", device_id), insjson);
if (responseBody != null && responseBody.isSuccess()) {
message = "下发成功";
} else {
message = "下发失败";
}
return message;
}
}
package cn.com.glsx.modules.service;
import cn.com.glsx.modules.model.param.ResponseBody;
import cn.com.glsx.modules.utils.HeaderParamUtils;
import cn.com.glsx.modules.utils.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Map;
/**
* 发送请求工具类
*
* @author zhouhaibao
* @date 2021/3/5 14:37
*/
@Service
@Slf4j
public class SendRequestService {
@Value("${tuya.client_id}")
private String client_id;
@Value("${tuya.secret}")
private String secret;
@Autowired
private AccessTokenService accessTokenService;
/**
* 向涂鸦发送post请求
*
* @param requesturl 请求url
* @param requestBody 请求体
* @return
*/
public ResponseBody sendRequestPost(String requesturl, String requestBody) {
ResponseBody responseBody = null;
String accessToken = accessTokenService.getAccessToken();
if(StringUtils.isBlank(accessToken)){
log.info("获取token失败");
return responseBody;
}
Map<String, String> headerParams = HeaderParamUtils.buildHeaderParams(client_id, secret, accessToken);
try {
JSONObject jsonObject = HttpUtil.sendPost(requesturl, requestBody, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("调用失败");
}
return responseBody;
}
/**
* 像涂鸦发送get请求
*
* @param requesturl 请求参数
* @return
*/
public ResponseBody sendRequestGet(String requesturl) {
ResponseBody responseBody = null;
String accessToken = accessTokenService.getAccessToken();
if(StringUtils.isBlank(accessToken)){
log.info("获取token失败");
return responseBody;
}
Map<String, String> headerParams = HeaderParamUtils.buildHeaderParams(client_id, secret, accessToken);
try {
JSONObject jsonObject = HttpUtil.sendGet(requesturl, null, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("请求用户信息接口异常,异常信息{}", e);
}
return responseBody;
}
/**
* 向涂鸦发送获取鉴权token请求
*
* @param requesturl 请求链接
* @return
*/
public ResponseBody sendRequestPut(String requesturl,String requestBody) {
ResponseBody responseBody = null;
String accessToken = accessTokenService.getAccessToken();
if(StringUtils.isBlank(accessToken)){
log.info("获取token失败");
return responseBody;
}
Map<String, String> headerParams = HeaderParamUtils.buildHeaderParams(client_id, secret, accessToken);
try {
JSONObject jsonObject = HttpUtil.sendPut(requesturl, requestBody, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("请求用户信息接口异常,异常信息{}", e);
}
return responseBody;
}
public ResponseBody sendRequestDelete(String requesturl) {
ResponseBody responseBody = null;
String accessToken = accessTokenService.getAccessToken();
if(StringUtils.isBlank(accessToken)){
log.info("获取token失败");
return responseBody;
}
Map<String, String> headerParams = HeaderParamUtils.buildHeaderParams(client_id, secret, accessToken);
try {
JSONObject jsonObject = HttpUtil.sendDelete(requesturl, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("请求用户信息接口异常,异常信息{}", e);
}
return responseBody;
}
}
package cn.com.glsx.modules.service; package cn.com.glsx.modules.service;
import cn.com.glsx.modules.mapper.TuyaUserMapper;
import cn.com.glsx.modules.model.param.ResponseBody; import cn.com.glsx.modules.model.param.ResponseBody;
import cn.com.glsx.modules.model.param.UserBo; import cn.com.glsx.modules.model.param.UserBo;
import cn.com.glsx.modules.model.param.UserInfo; import cn.com.glsx.modules.model.param.UserInfo;
import cn.com.glsx.modules.utils.HeaderParamUtils;
import cn.com.glsx.modules.utils.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Map;
/** /**
* @author zhouhaibao * @author zhouhaibao
...@@ -31,14 +24,8 @@ public class UserService { ...@@ -31,14 +24,8 @@ public class UserService {
@Value("${tuya.getUserInfoUrl}") @Value("${tuya.getUserInfoUrl}")
private String getUserInfoUrl; private String getUserInfoUrl;
@Value("${tuya.client_id}")
private String client_id;
@Value("${tuya.secret}")
private String secret;
@Autowired @Autowired
private AccessTokenService accessTokenService; private SendRequestService sendRequestService;
/** /**
* 注册用户 * 注册用户
...@@ -47,34 +34,17 @@ public class UserService { ...@@ -47,34 +34,17 @@ public class UserService {
*/ */
public String registerUser(UserBo userBo) { public String registerUser(UserBo userBo) {
//获取令牌 //获取令牌
String uid=null; String uid = null;
String accessToken = accessTokenService.getAccessToken(); ResponseBody responseBody = sendRequestService.sendRequestPost(registerUserUrl, JSONObject.toJSONString(userBo));
if (StringUtils.isNotBlank(accessToken)) { if (responseBody != null && responseBody.isSuccess()) {
ResponseBody responseBody = sendRequestRegisterUser(accessToken, userBo); String result = responseBody.getResult();
if(responseBody!=null&&responseBody.isSuccess()){ JSONObject jsonObject = JSONObject.parseObject(result);
String result = responseBody.getResult(); uid = jsonObject.getString("uid");
JSONObject jsonObject = JSONObject.parseObject(result);
uid = jsonObject.getString("uid");
}else{
log.info("调用涂鸦失败");
}
} else { } else {
log.info("调用涂鸦鉴权失败"); log.info("调用涂鸦失败");
} }
return uid;
}
private ResponseBody sendRequestRegisterUser(String accessToken, UserBo userBo) { return uid;
ResponseBody responseBody = null;
Map<String, String> headerParams = HeaderParamUtils.buildHeaderParams(client_id, secret, accessToken);
try {
JSONObject jsonObject = HttpUtil.sendPost(registerUserUrl, JSONObject.toJSONString(userBo), headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("调用涂鸦注册用户失败");
}
return responseBody;
} }
/** /**
...@@ -84,31 +54,14 @@ public class UserService { ...@@ -84,31 +54,14 @@ public class UserService {
*/ */
public UserInfo getUserInfo(String id) { public UserInfo getUserInfo(String id) {
UserInfo userInfo = null; UserInfo userInfo = null;
String accessToken = accessTokenService.getAccessToken(); ResponseBody responseBody = sendRequestService.sendRequestGet(getUserInfoUrl.replace("{uid}", id));
if (StringUtils.isNotBlank(accessToken)) { if (responseBody != null && responseBody.isSuccess()) {
ResponseBody responseBody = sendRequestGetUserInfo(id, accessToken); String result = responseBody.getResult() + "";
if (responseBody != null && responseBody.isSuccess()) { userInfo = JSONObject.parseObject(result, UserInfo.class);
String result = responseBody.getResult();
userInfo = JSONObject.parseObject(result, UserInfo.class);
} else {
log.info("调用涂鸦用户信息接口失败");
}
} else { } else {
log.info("调用涂鸦鉴权失败"); log.info("调用涂鸦用户信息接口失败");
} }
return userInfo; return userInfo;
} }
private ResponseBody sendRequestGetUserInfo(String id, String accessToken) {
ResponseBody responseBody = null;
Map<String, String> headerParams = HeaderParamUtils.buildHeaderParams(client_id, secret, accessToken);
try {
JSONObject jsonObject = HttpUtil.sendGet(getUserInfoUrl.replace("{uid}", id), null, headerParams);
responseBody = JSON.toJavaObject(jsonObject, ResponseBody.class);
} catch (IOException e) {
e.printStackTrace();
log.info("请求用户信息接口异常,异常信息{}", e);
}
return responseBody;
}
} }
package cn.com.glsx.modules.service.abs;
import cn.com.glsx.modules.model.param.DeviceInfo;
import cn.com.glsx.modules.model.param.Function;
import cn.com.glsx.modules.model.param.ResponseBody;
import java.util.List;
/**
* @author zhouhaibao
* @date 2021/3/8 9:55
*/
public abstract class BaseDeviceService {
public abstract List<DeviceInfo> getAllDevicesByUser(String uid);
public abstract DeviceInfo getDevicesById(String deviveid);
public abstract Function getFunctionsById(String uid);
public abstract Function getFunctionsByCat(String cat);
public abstract String instructionIssue(String device_id, String insjson);
}
...@@ -9,17 +9,6 @@ import java.util.Map; ...@@ -9,17 +9,6 @@ import java.util.Map;
*/ */
public class HeaderParamUtils { public class HeaderParamUtils {
public static Map<String,String> buildHeaderParams(String client_id,String secret){
long timeMillis = System.currentTimeMillis();
String loginSign = TuyaUtils.getLoginSign(timeMillis, client_id, secret);
Map<String, String> headerParams = new HashMap<>();
headerParams.put("client_id", client_id);
headerParams.put("t", timeMillis + "");
headerParams.put("sign_method", "HMAC-SHA256");
headerParams.put("sign", loginSign);
return headerParams;
}
public static Map<String,String> buildHeaderParams(String client_id,String secret,String accessToken){ public static Map<String,String> buildHeaderParams(String client_id,String secret,String accessToken){
long timeMillis = System.currentTimeMillis(); long timeMillis = System.currentTimeMillis();
String sign = TuyaUtils.getBussinessSign(timeMillis, client_id, secret, accessToken); String sign = TuyaUtils.getBussinessSign(timeMillis, client_id, secret, accessToken);
......
package cn.com.glsx.modules.utils; package cn.com.glsx.modules.utils;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts; import org.apache.http.*;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.config.Registry; import org.apache.http.config.Registry;
...@@ -52,12 +44,7 @@ import java.io.InterruptedIOException; ...@@ -52,12 +44,7 @@ import java.io.InterruptedIOException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.*;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class HttpUtil { public class HttpUtil {
...@@ -175,7 +162,7 @@ public class HttpUtil { ...@@ -175,7 +162,7 @@ public class HttpUtil {
} }
/** /**
* 兼容旧版本工具类 * http发送post请求
* *
* @param url * @param url
* @return * @return
...@@ -234,6 +221,95 @@ public class HttpUtil { ...@@ -234,6 +221,95 @@ public class HttpUtil {
} }
} }
/**
* 作者:sanri <br/>
* 时间:2017-10-19下午2:25:40<br/>
* 功能:向指定 url 提交数据 <br/>
*
* @param url
* @param data
* @return
* @throws IOException
*/
public static String putData(String url, String data, Map<String, String> headerParams) throws IOException, HTTPException {
HttpClient httpClient = getHttpClient();
//请求头,请求体数据封装
HttpPut postMethod = new HttpPut(url);
postMethod.addHeader("Content-Type", "application/json");
if (!headerParams.isEmpty()) {
headerParams.forEach((key, value) -> {
postMethod.addHeader(key, value);
});
}
postMethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
StringEntity dataEntity = new StringEntity(data, JSON_UTF8);
postMethod.setEntity(dataEntity);
HttpResponse response = null;
try {
//开始请求,记录请求数据和请求时间
response = httpClient.execute(postMethod);
//获取响应
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
HTTPException exception = new HTTPException(statusCode);
logger.error("请求地址" + url + "出错,http 状态码为:" + statusCode, exception);
throw exception;
}
String retData = EntityUtils.toString(entity, JSON_UTF8.getCharset());
return retData;
} catch (ClientProtocolException e) {
throw new IllegalArgumentException("客户端协议错误 ,检查 url 配置 url: " + url, e);
} finally {
HttpClientUtils.closeQuietly(response);
}
}
/**
* 作者:sanri <br/>
* 时间:2017-10-19下午2:25:40<br/>
* 功能:向指定 url 提交数据 <br/>
*
* @param url
* @return
* @throws IOException
*/
public static String deleteData(String url, Map<String, String> headerParams) throws IOException, HTTPException {
HttpClient httpClient = getHttpClient();
//请求头,请求体数据封装
HttpDelete httpDelete = new HttpDelete(url);
httpDelete.addHeader("Content-Type", "application/json");
if (!headerParams.isEmpty()) {
headerParams.forEach((key, value) -> {
httpDelete.addHeader(key, value);
});
}
httpDelete.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");
HttpResponse response = null;
try {
//开始请求,记录请求数据和请求时间
response = httpClient.execute(httpDelete);
//获取响应
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
HTTPException exception = new HTTPException(statusCode);
logger.error("请求地址" + url + "出错,http 状态码为:" + statusCode, exception);
throw exception;
}
String retData = EntityUtils.toString(entity, JSON_UTF8.getCharset());
return retData;
} catch (ClientProtocolException e) {
throw new IllegalArgumentException("客户端协议错误 ,检查 url 配置 url: " + url, e);
} finally {
HttpClientUtils.closeQuietly(response);
}
}
/** /**
* 作者:sanri <br/> * 作者:sanri <br/>
* 时间:2018-3-28下午8:57:50<br/> * 时间:2018-3-28下午8:57:50<br/>
...@@ -296,65 +372,54 @@ public class HttpUtil { ...@@ -296,65 +372,54 @@ public class HttpUtil {
return data; return data;
} }
/**
public static JSONObject getJSON(String url, Map<String, String> params, Charset charset, Map<String, String> headerParams) throws IOException { * http发送get请求
String retData = getData(url, params, charset, headerParams); *
* @param url
* @param params
* @param headerParams
* @return
* @throws IOException
*/
public static JSONObject sendGet(String url, Map<String, String> params, Map<String, String> headerParams) throws IOException {
String retData = getData(url, params, Consts.UTF_8, headerParams);
if (StringUtils.isNotBlank(retData)) { if (StringUtils.isNotBlank(retData)) {
return JSONObject.parseObject(retData); return JSONObject.parseObject(retData);
} }
return new JSONObject(); return new JSONObject();
} }
public static String postFormData(String url, Map<String, String> params, Charset charset) throws IOException { /**
CloseableHttpClient httpClient = getHttpClient(); * http的put方法
List<NameValuePair> nameValuePairs = transferParam(params); *
HttpPost postMethod = new HttpPost(url); * @param url 请求url
if (CollectionUtils.isNotEmpty(nameValuePairs)) { * @param json 请求body
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs, charset); * @param headerParams 请求参数
postMethod.setEntity(entity); * @return
} * @throws IOException
//TODO 测试用 */
postMethod.addHeader("Cookie", "JSESSIONID=node0oze509ig0of0vksk2dshvoi12.node0; fileDownload=true"); public static JSONObject sendPut(String url, String json, Map<String, String> headerParams) throws IOException {
postMethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"); String formData = putData(url, json, headerParams);
HttpResponse response = null; if (StringUtils.isNotBlank(formData)) {
try { return JSONObject.parseObject(formData);
response = httpClient.execute(postMethod);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
//解决地址重定向问题
if (statusCode == 302) {
Header firstHeader = response.getFirstHeader("location");
String location = firstHeader.getValue();
return postFormData(location, params, charset);
}
HTTPException exception = new HTTPException(statusCode);
logger.error("请求地址" + url + "出错,http 状态码为:" + statusCode, exception);
throw exception;
}
HttpEntity msgEntity = response.getEntity();
String message = EntityUtils.toString(msgEntity, charset);
return message;
} finally {
HttpClientUtils.closeQuietly(response);
} }
return new JSONObject();
} }
/** /**
* 作者:sanri <br/> * http发送delete请求
* 时间:2017-11-7下午6:24:30<br/>
* 功能:调用地址获取 json 数据 <br/>
* *
* @param url * @param url url
* @param params * @param headerParams 请求参数
* @return * @return
* @throws IllegalArgumentException
* @throws IOException * @throws IOException
*/ */
public static JSONObject sendGet(String url, Map<String, String> params, Map<String, String> headerParams) throws IOException { public static JSONObject sendDelete(String url,Map<String, String> headerParams) throws IOException {
return getJSON(url, params, Consts.UTF_8, headerParams); String retData = deleteData(url,headerParams);
if (StringUtils.isNotBlank(retData)) {
return JSONObject.parseObject(retData);
}
return new JSONObject();
} }
} }
\ No newline at end of file \ No newline at end of file
...@@ -68,6 +68,7 @@ ...@@ -68,6 +68,7 @@
</javaClientGenerator> </javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 --> <!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 -->
<table tableName="tuya_user" domainObjectName="TuyaUser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/> <table tableName="smart_devide_status" domainObjectName="SmartDevideStatus" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"/>
</context> </context>
</generatorConfiguration> </generatorConfiguration>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.modules.service;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class homeServiceTest {
@Autowired
private HomeService homeService;
@Autowired
private AccessTokenService accessTokenService;
@Test
public void addHomeTest() {
String uid = "01";
HomeInfo home = new HomeInfo();
home.setGeo_name("fzsssss");
home.setName("homefz");
home.setLat(11.10);
home.setLon(11.10);
List<String> rooms = new ArrayList<>();
rooms.add("fz1");
rooms.add("fz2");
homeService.addHome(uid,home,rooms);
}
}
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!