├── src ├── main │ ├── filter │ │ └── filter.properties │ ├── java │ │ └── com │ │ │ └── jw │ │ │ └── demo │ │ │ ├── common │ │ │ ├── util │ │ │ │ ├── CacheKeyConstants.java │ │ │ │ └── SnowflakeIdWorker.java │ │ │ ├── response │ │ │ │ ├── DefaultResponse.java │ │ │ │ ├── InfoResponse.java │ │ │ │ ├── ListResponse.java │ │ │ │ ├── FailResponse.java │ │ │ │ ├── Response.java │ │ │ │ └── PageListResponse.java │ │ │ ├── request │ │ │ │ └── Request.java │ │ │ ├── _enum │ │ │ │ ├── CommParamStatusEnum.java │ │ │ │ ├── DeletedEnum.java │ │ │ │ ├── AppStatusEnum.java │ │ │ │ ├── PolicyEnum.java │ │ │ │ ├── CodeTypeEnum.java │ │ │ │ └── ApiResultEnum.java │ │ │ └── entity │ │ │ │ ├── policy │ │ │ │ └── PolicyDivEntity.java │ │ │ │ ├── token │ │ │ │ ├── UserProofEntity.java │ │ │ │ └── TokenEntity.java │ │ │ │ ├── dynamodb │ │ │ │ ├── DevicePropertyLog.java │ │ │ │ ├── DeviceConnectLog.java │ │ │ │ └── AppUserDevice.java │ │ │ │ ├── base │ │ │ │ ├── CommParamConfig.java │ │ │ │ ├── AwsConfig.java │ │ │ │ └── AppUser.java │ │ │ │ └── device │ │ │ │ └── DeviceInfo.java │ │ │ └── app │ │ │ ├── AppBaseException.java │ │ │ ├── service │ │ │ ├── DeviceService.java │ │ │ ├── AppUserDeviceService.java │ │ │ └── impl │ │ │ │ ├── AppUserDeviceServiceImpl.java │ │ │ │ └── DeviceServiceImpl.java │ │ │ ├── dao │ │ │ └── device │ │ │ │ ├── DeviceInfoMapper.java │ │ │ │ └── DeviceInfoMapperImp.java │ │ │ ├── util │ │ │ ├── AppTokenUtil.java │ │ │ └── aws │ │ │ │ ├── s3 │ │ │ │ └── S3Util.java │ │ │ │ ├── iot │ │ │ │ ├── ShadowUtil.java │ │ │ │ └── IotUtil.java │ │ │ │ ├── cognito │ │ │ │ └── IdentityPoolUtil.java │ │ │ │ ├── policy │ │ │ │ └── IotPolicyUtil.java │ │ │ │ └── dynamodb │ │ │ │ └── AppUserDeviceDy.java │ │ │ ├── config │ │ │ └── CorsConfig.java │ │ │ ├── request │ │ │ ├── device │ │ │ │ ├── PropertyGetRequest.java │ │ │ │ ├── CertificateGetRequest.java │ │ │ │ └── ShadowUpdateRequest.java │ │ │ └── appdevice │ │ │ │ ├── AppUnbindDeviceRequest.java │ │ │ │ ├── AppListDeivceRequest.java │ │ │ │ └── AppBindDeviceRequest.java │ │ │ ├── controller │ │ │ ├── BaseController.java │ │ │ ├── UserDeviceController.java │ │ │ └── DeviceController.java │ │ │ ├── StreamLambdaHandler.java │ │ │ └── Application.java │ └── resources │ │ └── application.yaml └── assembly │ └── bin.xml ├── images ├── img5.png ├── Picture1.png ├── Picture3.png └── Picture4.png ├── .idea ├── codeStyles │ ├── codeStyleConfig.xml │ └── Project.xml ├── vcs.xml ├── encodings.xml ├── .gitignore ├── modules.xml ├── misc.xml ├── aws.xml ├── compiler.xml └── jarRepositories.xml ├── gradle └── wrapper │ └── gradle-wrapper.properties ├── sam.yaml ├── output-sam.yaml ├── README.md ├── .gitignore ├── gradlew.bat ├── gradlew ├── CloudConfig_lambda_core.iml └── pom.xml /src/main/filter/filter.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/img5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jianyew/CloudConfig_lambda_core/HEAD/images/img5.png -------------------------------------------------------------------------------- /images/Picture1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jianyew/CloudConfig_lambda_core/HEAD/images/Picture1.png -------------------------------------------------------------------------------- /images/Picture3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jianyew/CloudConfig_lambda_core/HEAD/images/Picture3.png -------------------------------------------------------------------------------- /images/Picture4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jianyew/CloudConfig_lambda_core/HEAD/images/Picture4.png -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/util/CacheKeyConstants.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.util; 2 | 3 | public class CacheKeyConstants { 4 | public static final Long REDIS_KEY_EXPIRE_TWO_HOUR = 2*3600L; 5 | 6 | } 7 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Datasource local storage ignored files 5 | /dataSources/ 6 | /dataSources.local.xml 7 | # Zeppelin ignored files 8 | /ZeppelinRemoteNotebooks/ 9 | # Editor-based HTTP Client requests 10 | /httpRequests/ 11 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/AppBaseException.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app; 2 | 3 | public class AppBaseException extends Exception { 4 | 5 | private Integer errCode; 6 | 7 | 8 | public Integer getErrCode() { 9 | return errCode; 10 | } 11 | 12 | public void setErrCode(Integer errCode) { 13 | this.errCode = errCode; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 80 3 | logging: 4 | level: 5 | root: INFO 6 | spring: 7 | jackson: 8 | serialization: 9 | WRITE_DATES_AS_TIMESTAMPS: true 10 | 11 | aws: 12 | config: 13 | region: ap-southeast-1 14 | account: 964479626419 15 | iotdomain: a1w6jnzc1m4aj1-ats.iot.ap-southeast-1.amazonaws.com 16 | certificatebucket: cconfig-certificate 17 | 18 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/aws.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 16 | 17 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/response/DefaultResponse.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.response; 2 | 3 | /** 4 | * 默认返回响应实体 5 | * 6 | * @author hongyuhao 7 | * @version 0.0.1 8 | */ 9 | public class DefaultResponse extends Response { 10 | /** 11 | * uuid 12 | */ 13 | private static final long serialVersionUID = 2511997005351172247L; 14 | 15 | /** 16 | * 重写tostring 17 | * @return 相应结果json字符串 18 | */ 19 | @Override 20 | public String toString() { 21 | return super.toString(); 22 | } 23 | 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/service/DeviceService.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.service; 2 | 3 | import com.jw.demo.app.request.device.CertificateGetRequest; 4 | import com.jw.demo.app.request.device.PropertyGetRequest; 5 | import com.jw.demo.app.request.device.ShadowUpdateRequest; 6 | import com.jw.demo.common.response.Response; 7 | 8 | public interface DeviceService { 9 | 10 | Response certificateGet(CertificateGetRequest request) throws Exception; 11 | 12 | Response propertyGet(PropertyGetRequest request) throws Exception; 13 | 14 | Response updateShadow(ShadowUpdateRequest request) throws Exception; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/dao/device/DeviceInfoMapper.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.dao.device; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.jw.demo.common.entity.device.DeviceInfo; 7 | 8 | public interface DeviceInfoMapper { 9 | 10 | int deleteByPrimaryKey(Long id); 11 | 12 | int insert(DeviceInfo record); 13 | 14 | int insertSelective(DeviceInfo record); 15 | 16 | DeviceInfo selectByPrimaryKey(Long id); 17 | 18 | List selectByMap(Map params); 19 | 20 | int updateByPrimaryKeySelective(DeviceInfo record); 21 | 22 | int updateByPrimaryKey(DeviceInfo record); 23 | 24 | int updateByMap(Map params); 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/request/Request.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.request; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.jw.demo.common.response.Response; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import java.io.Serializable; 8 | 9 | /** 10 | * 公共参数类 11 | * @author hongyuhao 12 | * @version 0.0.1 13 | */ 14 | public abstract class Request implements Serializable { 15 | 16 | private static final long serialVersionUID = -8345106786789120936L; 17 | 18 | /** 19 | * 解析参数 20 | * @param request 21 | */ 22 | public abstract Response parse(HttpServletRequest request); 23 | protected void parseFixedParams(HttpServletRequest request) { 24 | 25 | } 26 | 27 | @Override 28 | public String toString() { 29 | // TODO Auto-generated method stub 30 | return JSON.toJSONString(this); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/_enum/CommParamStatusEnum.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common._enum; 2 | 3 | /** 4 | * @author: YanLan 5 | * @date: 2019/01/07 6 | */ 7 | public enum CommParamStatusEnum { 8 | /** 9 | * 设置该系统模块字段为有效 10 | */ 11 | VALID(1, "有效"), 12 | 13 | /** 14 | * 设置该系统模块字段为无效 15 | */ 16 | INVALID(2, "无效") 17 | ; 18 | 19 | private int id; 20 | private String name; 21 | 22 | CommParamStatusEnum(int id, String name) { 23 | this.id = id; 24 | this.name = name; 25 | } 26 | 27 | public int getId() { 28 | return id; 29 | } 30 | 31 | public void setId(int id) { 32 | this.id = id; 33 | } 34 | 35 | public String getName() { 36 | return name; 37 | } 38 | 39 | public void setName(String name) { 40 | this.name = name; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/service/AppUserDeviceService.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.service; 2 | 3 | 4 | import com.jw.demo.app.request.appdevice.AppBindDeviceRequest; 5 | import com.jw.demo.app.request.appdevice.AppListDeivceRequest; 6 | import com.jw.demo.common.entity.base.AppUser; 7 | import com.jw.demo.common.response.Response; 8 | 9 | public interface AppUserDeviceService { 10 | /** 11 | * 绑定设备 12 | * @param appuser 13 | * @param request 14 | * @return 15 | * @throws Exception 16 | */ 17 | Response bindAppUserDevice(AppUser appuser, AppBindDeviceRequest request)throws Exception; 18 | 19 | /** 20 | * 用户查询设备 21 | * @param appUser 22 | * @param request 23 | * @return 24 | * @throws Exception 25 | */ 26 | Response listAppUserDevice(AppUser appUser, AppListDeivceRequest request)throws Exception; 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/util/AppTokenUtil.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.util; 2 | 3 | import com.jw.demo.common._enum.DeletedEnum; 4 | import com.jw.demo.common.entity.base.AppUser; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | /** 9 | * token与对象的管理 10 | */ 11 | public class AppTokenUtil { 12 | private static final Logger LOGGER = LoggerFactory.getLogger(AppTokenUtil.class); 13 | 14 | /** 15 | * 获取App用户, mock 16 | * @param token 17 | * @return 18 | */ 19 | 20 | public static AppUser getAppUser(String token)throws Exception{ 21 | AppUser appUserInfo = new AppUser(); 22 | appUserInfo.setId(1L); 23 | appUserInfo.setName("TEST"); 24 | appUserInfo.setAccount("807915e2-b597-440a-8417-cee4927d3d06"); 25 | appUserInfo.setDeleted(DeletedEnum.F.getId()); 26 | return appUserInfo; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | -------------------------------------------------------------------------------- /.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/_enum/DeletedEnum.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common._enum; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public enum DeletedEnum { 7 | 8 | /** 9 | * 否(未删除) 10 | */ 11 | F(0, "否"), 12 | /** 13 | * 是(已删除) 14 | */ 15 | T(1, "是"); 16 | 17 | private int id; 18 | private String name; 19 | 20 | DeletedEnum(int id, String name) { 21 | this.id = id; 22 | this.name = name; 23 | } 24 | 25 | public int getId() { 26 | return id; 27 | } 28 | 29 | public void setId(int id) { 30 | this.id = id; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public void setName(String name) { 38 | this.name = name; 39 | } 40 | 41 | public static Map listAllTypes() { 42 | Map typesMap = new HashMap(); 43 | DeletedEnum[] enums = values(); 44 | for (DeletedEnum object : enums) { 45 | typesMap.put(object.getId(), object.getName()); 46 | } 47 | return typesMap; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/response/InfoResponse.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.response; 2 | 3 | /** 4 | * 信息获取类响应实体 5 | * 6 | * @author hongyuhao 7 | * @version 0.0.1 8 | */ 9 | public class InfoResponse extends Response { 10 | /** 11 | * uuid 12 | */ 13 | private static final long serialVersionUID = 5424773206360048131L; 14 | 15 | public InfoResponse() {} 16 | 17 | public InfoResponse(T info) { 18 | this.info = info; 19 | } 20 | 21 | /** 22 | * 响应实体 23 | */ 24 | private T info; 25 | 26 | /** 27 | * 获取响应实体 28 | * @return 响应实体 29 | */ 30 | public T getInfo() { 31 | return info; 32 | } 33 | 34 | /** 35 | *设置响应实体 36 | * @param info 响应实体 37 | */ 38 | public void setInfo(T info) { 39 | this.info = info; 40 | } 41 | 42 | /** 43 | * 重写tostring 44 | * @return 相应结果json字符串 45 | */ 46 | @Override 47 | public String toString() { 48 | return super.toString(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /sam.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | Description: AWS Serverless Spring Boot 2 API - com.jw.demo.app::CloudConfig_lambda_core 4 | Globals: 5 | Api: 6 | EndpointConfiguration: REGIONAL 7 | 8 | Resources: 9 | MyDomeLambdaAppCoreFunction: 10 | Type: AWS::Serverless::Function 11 | Properties: 12 | Handler: com.jw.demo.app.StreamLambdaHandler::handleRequest 13 | Runtime: java8 14 | CodeUri: target/CloudConfig_lambda_core-1.0-SNAPSHOT-lambda-package.zip 15 | MemorySize: 1024 16 | Role: arn:aws:iam::964479626419:role/iot_lambda_role 17 | Timeout: 900 18 | Events: 19 | GetResource: 20 | Type: Api 21 | Properties: 22 | Path: /{proxy+} 23 | Method: any 24 | 25 | Outputs: 26 | MydemoLambdaAppCoreApi: 27 | Description: URL for application 28 | Value: !Sub 'https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod' 29 | Export: 30 | Name: MydemoLambdaAppCoreApi 31 | -------------------------------------------------------------------------------- /output-sam.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | Description: AWS Serverless Spring Boot 2 API - com.jw.demo.app::CloudConfig_lambda_core 4 | Globals: 5 | Api: 6 | EndpointConfiguration: REGIONAL 7 | Resources: 8 | MyDomeLambdaAppCoreFunction: 9 | Type: AWS::Serverless::Function 10 | Properties: 11 | Handler: com.jw.demo.app.StreamLambdaHandler::handleRequest 12 | Runtime: java8 13 | CodeUri: s3://cloudconfig-mydemo-app/93e76936c1261e3e7b8b79374120bf52 14 | MemorySize: 1024 15 | Role: arn:aws:iam::964479626419:role/iot_lambda_role 16 | Timeout: 900 17 | Events: 18 | GetResource: 19 | Type: Api 20 | Properties: 21 | Path: /{proxy+} 22 | Method: any 23 | Outputs: 24 | MydemoLambdaAppCoreApi: 25 | Description: URL for application 26 | Value: 27 | Fn::Sub: https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod 28 | Export: 29 | Name: MydemoLambdaAppCoreApi 30 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/_enum/AppStatusEnum.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common._enum; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public enum AppStatusEnum { 7 | 8 | /** 9 | * 正常 10 | */ 11 | NORMAL(1, "正常"), 12 | /** 13 | * 停用 14 | */ 15 | STOP(2, "停用"), 16 | /** 17 | * 已注销/已删除 18 | */ 19 | DELETE(3, "已删除"); 20 | 21 | private int id; 22 | private String name; 23 | 24 | AppStatusEnum(int id, String name) { 25 | this.id = id; 26 | this.name = name; 27 | } 28 | 29 | public int getId() { 30 | return id; 31 | } 32 | 33 | public void setId(int id) { 34 | this.id = id; 35 | } 36 | 37 | public String getName() { 38 | return name; 39 | } 40 | 41 | public void setName(String name) { 42 | this.name = name; 43 | } 44 | 45 | public static Map listAllTypes() { 46 | Map typesMap = new HashMap(); 47 | AppStatusEnum[] enums = values(); 48 | for (AppStatusEnum object : enums) { 49 | typesMap.put(object.getId(), object.getName()); 50 | } 51 | return typesMap; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/config/CorsConfig.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.cors.CorsConfiguration; 6 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 7 | import org.springframework.web.filter.CorsFilter; 8 | 9 | @Configuration 10 | public class CorsConfig { 11 | private CorsConfiguration buildConfig() { 12 | CorsConfiguration corsConfiguration = new CorsConfiguration(); 13 | corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用 14 | corsConfiguration.addAllowedHeader("*"); // 2允许任何头 15 | corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等) 16 | return corsConfiguration; 17 | } 18 | 19 | @Bean 20 | public CorsFilter corsFilter() { 21 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 22 | source.registerCorsConfiguration("/**", buildConfig()); // 4 23 | return new CorsFilter(source); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/entity/policy/PolicyDivEntity.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.entity.policy; 2 | 3 | import java.util.List; 4 | 5 | public class PolicyDivEntity { 6 | private String Effect; 7 | private List Action; 8 | private List Resource; 9 | 10 | public String getEffect() { 11 | return Effect; 12 | } 13 | 14 | public List getAction() { 15 | return Action; 16 | } 17 | 18 | public void setEffect(String effect) { 19 | Effect = effect; 20 | } 21 | 22 | public void setAction(List action) { 23 | Action = action; 24 | } 25 | 26 | public List getResource() { 27 | return Resource; 28 | } 29 | 30 | public void setResource(List resource) { 31 | Resource = resource; 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "{" + 37 | "\"Effect\":\"" + Effect + '\"' + 38 | ",\"Action\":" + Action + 39 | ",\"Resource\":" + Resource + 40 | '}'; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/_enum/PolicyEnum.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common._enum; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public enum PolicyEnum { 7 | 8 | /** 9 | * IAM策略 10 | */ 11 | IAM(1, "IAM策略"), 12 | /** 13 | * IOT策略 14 | */ 15 | IOT(2, "IOT策略"); 16 | 17 | private int id; 18 | private String name; 19 | 20 | PolicyEnum(int id, String name) { 21 | this.id = id; 22 | this.name = name; 23 | } 24 | 25 | public int getId() { 26 | return id; 27 | } 28 | 29 | public void setId(int id) { 30 | this.id = id; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public void setName(String name) { 38 | this.name = name; 39 | } 40 | 41 | public static Map listAllTypes() { 42 | Map typesMap = new HashMap(); 43 | PolicyEnum[] enums = values(); 44 | for (PolicyEnum object : enums) { 45 | typesMap.put(object.getId(), object.getName()); 46 | } 47 | return typesMap; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/response/ListResponse.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.response; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | 6 | /** 7 | * 列表查询类响应实体 8 | * 9 | * @author hongyuhao 10 | * @version 0.0.1 11 | */ 12 | public class ListResponse extends Response { 13 | /** 14 | * uuid 15 | */ 16 | private static final long serialVersionUID = -4581672836387766530L; 17 | 18 | public ListResponse() {} 19 | 20 | public ListResponse(List list) { 21 | this.list = list; 22 | } 23 | 24 | /** 25 | * 返回结果列表 26 | */ 27 | private List list = Collections.emptyList(); 28 | 29 | /** 30 | * 获取返回结果列表 31 | * @return 返回结果列表 32 | */ 33 | public List getList() { 34 | return list; 35 | } 36 | 37 | /** 38 | * 设置返回结果列表 39 | * @param list 返回结果列表 40 | */ 41 | public void setList(List list) { 42 | this.list = list; 43 | } 44 | 45 | /** 46 | * 重写tostring 47 | * @return 相应结果json字符串 48 | */ 49 | @Override 50 | public String toString() { 51 | return super.toString(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/assembly/bin.xml: -------------------------------------------------------------------------------- 1 | 4 | lambda-package 5 | 6 | zip 7 | 8 | false 9 | 10 | 11 | 12 | ${project.build.directory}${file.separator}lib 13 | lib 14 | 15 | tomcat-embed* 16 | 17 | 18 | 19 | 20 | ${project.build.directory}${file.separator}classes 21 | 22 | ** 23 | 24 | ${file.separator} 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/entity/token/UserProofEntity.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.entity.token; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * 用户权限凭证 7 | */ 8 | public class UserProofEntity implements Serializable { 9 | private String accessKeyId; 10 | private String expiration; 11 | private String secretKey; 12 | private String sessionToken; 13 | 14 | public String getAccessKeyId() { 15 | return accessKeyId; 16 | } 17 | 18 | public String getExpiration() { 19 | return expiration; 20 | } 21 | 22 | public String getSecretKey() { 23 | return secretKey; 24 | } 25 | 26 | public String getSessionToken() { 27 | return sessionToken; 28 | } 29 | 30 | public void setAccessKeyId(String accessKeyId) { 31 | this.accessKeyId = accessKeyId; 32 | } 33 | 34 | public void setExpiration(String expiration) { 35 | this.expiration = expiration; 36 | } 37 | 38 | public void setSecretKey(String secretKey) { 39 | this.secretKey = secretKey; 40 | } 41 | 42 | public void setSessionToken(String sessionToken) { 43 | this.sessionToken = sessionToken; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/request/device/PropertyGetRequest.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.request.device; 2 | 3 | import com.jw.demo.common._enum.ApiResultEnum; 4 | import com.jw.demo.common.request.Request; 5 | import com.jw.demo.common.response.DefaultResponse; 6 | import com.jw.demo.common.response.FailResponse; 7 | import com.jw.demo.common.response.Response; 8 | import com.jw.demo.common.web.HttpRequestInfo; 9 | 10 | import javax.servlet.http.HttpServletRequest; 11 | 12 | public class PropertyGetRequest extends Request { 13 | 14 | private Long deviceId; // 设备ID 15 | 16 | @Override 17 | public Response parse(HttpServletRequest request) { 18 | HttpRequestInfo requestInfo = new HttpRequestInfo(request); 19 | // 校验:设备ID 20 | this.deviceId = requestInfo.getLongParameter("device_id", 0); 21 | if (deviceId == Long.valueOf(0)) { 22 | return new FailResponse(ApiResultEnum.PARAM_ERROR.getId(), "请选择设备"); 23 | } 24 | return new DefaultResponse(); 25 | } 26 | 27 | public Long getDeviceId() { 28 | return deviceId; 29 | } 30 | 31 | public void setDeviceId(Long deviceId) { 32 | this.deviceId = deviceId; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/response/FailResponse.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.response; 2 | 3 | import com.jw.demo.common._enum.ApiResultEnum; 4 | 5 | /** 6 | * 默认相应失败实体 7 | * 8 | * @author houlong 9 | * @version 0.0.1 10 | */ 11 | public class FailResponse extends Response { 12 | 13 | private static final long serialVersionUID = -1446790741731428665L; 14 | 15 | public FailResponse() { 16 | this.code = ApiResultEnum.FAIL.getId(); 17 | this.tip = ApiResultEnum.FAIL.getName(); 18 | } 19 | 20 | public FailResponse(String tip) { 21 | this.code = ApiResultEnum.FAIL.getId(); 22 | this.tip = tip; 23 | } 24 | 25 | public FailResponse(int code, String tip) { 26 | this.code = code; 27 | this.tip = tip; 28 | } 29 | 30 | public FailResponse(ApiResultEnum apiResultEnum) { 31 | this.code = apiResultEnum.getId(); 32 | this.tip = apiResultEnum.getName(); 33 | } 34 | 35 | public FailResponse(ApiResultEnum apiResultEnum, String tip) { 36 | this.code = apiResultEnum.getId(); 37 | this.tip = tip; 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return super.toString(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/_enum/CodeTypeEnum.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common._enum; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public enum CodeTypeEnum { 7 | 8 | /** 9 | * 注册 10 | */ 11 | REGISTER("REGISTER", "注册"), 12 | /** 13 | * 登录 14 | */ 15 | LOGIN("LOGIN", "登录"), 16 | /** 17 | * 重置密码 18 | */ 19 | PWD_RESET("PWD_RESET", "重置密码"); 20 | 21 | private String key; 22 | private String name; 23 | 24 | CodeTypeEnum(String key, String name) { 25 | this.key = key; 26 | this.name = name; 27 | } 28 | 29 | public String getKey() { 30 | return key; 31 | } 32 | 33 | public void setKey(String key) { 34 | this.key = key; 35 | } 36 | 37 | public String getName() { 38 | return name; 39 | } 40 | 41 | public void setName(String name) { 42 | this.name = name; 43 | } 44 | 45 | public static Map listAllTypes() { 46 | Map typesMap = new HashMap(); 47 | CodeTypeEnum[] enums = values(); 48 | for (CodeTypeEnum object : enums) { 49 | typesMap.put(object.getKey(), object.getName()); 50 | } 51 | return typesMap; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 当客户购买设备回家,第一件事就是配网, 4 | 所以配网是所有物理网公司和客户建立Link的第一步, 5 | 我们来看看如何在亚马逊云上构建设备配网。 6 | Blog:https://aws.amazon.com/cn/blogs/china/smart-home-iot-platform-module-distribution-network/ 7 | 8 | **配网流程** 9 | ![](images/Picture1.png) 10 | 11 | 12 | **架构图** 13 | ![](images/img5.png) 14 | 15 | API调用流程图 16 | ![](images/Picture3.png) 17 | 18 | **1.打包** 19 | 安装配置 AWS CLI 20 | 21 | **2.安装** 22 | 参考 AWS 命令行界面 安装 23 | Win 下载 https://s3.amazonaws.com/aws-cli/AWSCLI64.msi 安装 24 | Mac/Linux 执行 npm install awscli (首先初始化 node) 25 | 26 | **3.配置 AWS CLI** 27 | aws configure 28 | 输入 AWS Access Key ID = (aws子账户id) 29 | AWS Secret Access Key = (aws子账户密钥) 30 | region name = ap-southeast-1(region ) 31 | 32 | **4.创建s3 储存通** 33 | aws s3 mb s3://cloudconfig-mydemo-app --region ap-southeast-1 34 | 进入项目根目录 35 | 36 | **5.本地打包** 37 | mvn package 38 | 39 | **6.cloudformation打包** 40 | aws cloudformation package --template-file sam.yaml --output-template-file output-sam.yaml --s3-bucket cloudconfig-mydemo-app 41 | 42 | **7.部署lambda函数** 43 | aws cloudformation deploy --template-file output-sam.yaml --stack-name cloudconfig-mydemo-app --capabilities CAPABILITY_NAMED_IAM --region=ap-southeast-1 44 | 45 | **8. 获取应用信息** 46 | aws cloudformation describe-stacks --stack-name cloudconfig-mydemo-app --region=ap-southeast-1 47 | 48 | 49 | 50 | ![](images/Picture4.png) -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/dao/device/DeviceInfoMapperImp.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.dao.device; 2 | 3 | import com.jw.demo.common.entity.device.DeviceInfo; 4 | import org.springframework.stereotype.Service; 5 | 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | 10 | /** 11 | * 模拟数据库 12 | * 13 | * 14 | */ 15 | 16 | @Service 17 | public class DeviceInfoMapperImp implements DeviceInfoMapper { 18 | 19 | @Override 20 | public int deleteByPrimaryKey(Long id) { 21 | return 0; 22 | } 23 | 24 | @Override 25 | public int insert(DeviceInfo record) { 26 | return 0; 27 | } 28 | 29 | @Override 30 | public int insertSelective(DeviceInfo record) { 31 | return 0; 32 | } 33 | 34 | @Override 35 | public DeviceInfo selectByPrimaryKey(Long id) { 36 | return null; 37 | } 38 | 39 | @Override 40 | public List selectByMap(Map params) { 41 | return null; 42 | } 43 | 44 | @Override 45 | public int updateByPrimaryKeySelective(DeviceInfo record) { 46 | return 0; 47 | } 48 | 49 | @Override 50 | public int updateByPrimaryKey(DeviceInfo record) { 51 | return 0; 52 | } 53 | 54 | @Override 55 | public int updateByMap(Map params) { 56 | return 0; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/request/appdevice/AppUnbindDeviceRequest.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.request.appdevice; 2 | 3 | import com.jw.demo.common._enum.ApiResultEnum; 4 | import com.jw.demo.common.request.Request; 5 | import com.jw.demo.common.response.DefaultResponse; 6 | import com.jw.demo.common.response.FailResponse; 7 | import com.jw.demo.common.response.Response; 8 | import com.jw.demo.common.web.HttpRequestInfo; 9 | import org.apache.commons.lang3.StringUtils; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | 13 | public class AppUnbindDeviceRequest extends Request { 14 | private Long deviceId; 15 | /** 16 | * 解析参数 17 | * 18 | * @param request 19 | */ 20 | @Override 21 | public Response parse(HttpServletRequest request) { 22 | HttpRequestInfo requestInfo = new HttpRequestInfo(request); 23 | String deviceId = requestInfo.getParameter("deviceId", null); 24 | if (StringUtils.isEmpty(deviceId)){ 25 | return new FailResponse(ApiResultEnum.PARAM_ERROR); 26 | } 27 | this.deviceId = Long.valueOf(deviceId); 28 | return new DefaultResponse(); 29 | } 30 | 31 | public void setDeviceId(Long deviceId) { 32 | this.deviceId = deviceId; 33 | } 34 | 35 | public Long getDeviceId() { 36 | return deviceId; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.controller; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.jw.demo.app.AppBaseException; 5 | import com.jw.demo.common.response.FailResponse; 6 | import com.jw.demo.common.response.Response; 7 | import org.slf4j.Logger; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import java.util.Arrays; 11 | 12 | public class BaseController { 13 | 14 | 15 | public Response getFailResponse(String errorTip, Exception e, Logger log, String methodName, HttpServletRequest request) { 16 | Response response = new FailResponse(); 17 | if (e instanceof AppBaseException) { 18 | response.setCode(((AppBaseException) e).getErrCode()); 19 | response.setTip(e.getMessage()); 20 | log.error("func[{}] parameterMap[{}] response[{}] desc[业务异常]", // 21 | new Object[] { methodName, JSON.toJSONString(request.getParameterMap()), JSON.toJSONString(response) }); 22 | } else { 23 | log.error("func[{}] parameterMap[{}] exception[{} - {}] desc[fail]", // 24 | new Object[] { methodName, JSON.toJSONString(request.getParameterMap()), e.getMessage(), Arrays.deepToString(e.getStackTrace()) }); 25 | response.setTip(errorTip); 26 | } 27 | return response; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/StreamLambdaHandler.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app; 2 | 3 | 4 | import com.amazonaws.serverless.exceptions.ContainerInitializationException; 5 | import com.amazonaws.serverless.proxy.model.AwsProxyRequest; 6 | import com.amazonaws.serverless.proxy.model.AwsProxyResponse; 7 | import com.amazonaws.serverless.proxy.spring.SpringBootLambdaContainerHandler; 8 | import com.amazonaws.services.lambda.runtime.Context; 9 | import com.amazonaws.services.lambda.runtime.RequestStreamHandler; 10 | 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | import java.io.OutputStream; 14 | 15 | 16 | public class StreamLambdaHandler implements RequestStreamHandler { 17 | private static SpringBootLambdaContainerHandler handler; 18 | static { 19 | try { 20 | handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class); 21 | } catch (ContainerInitializationException e) { 22 | // if we fail here. We re-throw the exception to force another cold start 23 | e.printStackTrace(); 24 | throw new RuntimeException("Could not initialize Spring Boot application", e); 25 | } 26 | } 27 | 28 | @Override 29 | public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) 30 | throws IOException { 31 | handler.proxyStream(inputStream, outputStream, context); 32 | } 33 | } -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/entity/token/TokenEntity.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.entity.token; 2 | 3 | import com.jw.demo.common.entity.base.AppUser; 4 | 5 | import java.io.Serializable; 6 | 7 | public class TokenEntity implements Serializable { 8 | //token 9 | private String token; 10 | //刷新token 11 | private String refreshToken; 12 | //有效时间单位秒 13 | private int expiresIn; 14 | //App用户信息 15 | private AppUser appUser; 16 | //用户session 17 | private UserProofEntity session; 18 | 19 | public String getToken() { 20 | return token; 21 | } 22 | 23 | public String getRefreshToken() { 24 | return refreshToken; 25 | } 26 | 27 | public int getExpiresIn() { 28 | return expiresIn; 29 | } 30 | 31 | public AppUser getAppUser() { 32 | return appUser; 33 | } 34 | 35 | public void setToken(String token) { 36 | this.token = token; 37 | } 38 | 39 | public void setRefreshToken(String refreshToken) { 40 | this.refreshToken = refreshToken; 41 | } 42 | 43 | public void setAppUser(AppUser appUser) { 44 | this.appUser = appUser; 45 | } 46 | 47 | public void setExpiresIn(int expiresIn) { 48 | this.expiresIn = expiresIn; 49 | } 50 | 51 | public UserProofEntity getSession() { 52 | return session; 53 | } 54 | 55 | public void setSession(UserProofEntity session) { 56 | this.session = session; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/response/Response.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.response; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.serializer.SerializerFeature; 5 | import com.jw.demo.common._enum.ApiResultEnum; 6 | 7 | import java.io.Serializable; 8 | 9 | /** 10 | * 公共响应类 11 | * 12 | * @author hongyuhao 13 | * @version 0.0.1 14 | */ 15 | public abstract class Response implements Serializable { 16 | /** 17 | * uuid 18 | */ 19 | private static final long serialVersionUID = 2430928175247208189L; 20 | 21 | /** 22 | * 默认返回结果 23 | */ 24 | protected String tip = ApiResultEnum.SUCCESS.getName(); 25 | /** 26 | * 默认状态码 27 | */ 28 | protected int code = ApiResultEnum.SUCCESS.getId(); 29 | 30 | /** 31 | * @return the tip 32 | */ 33 | public String getTip() { 34 | return tip; 35 | } 36 | 37 | /** 38 | * 返回状态码 39 | * 40 | * @return 状态码 41 | * 42 | */ 43 | public void setTip(String tip) { 44 | this.tip = tip; 45 | } 46 | 47 | /** 48 | * 返回状态码 49 | * 50 | * @return 状态码 51 | * 52 | */ 53 | public int getCode() { 54 | return code; 55 | } 56 | 57 | /** 58 | * 设置请求状态码 59 | * 60 | * @param code 请求状态码 61 | * 62 | */ 63 | public void setCode(int code) { 64 | this.code = code; 65 | } 66 | 67 | 68 | /** 69 | * 设置请求状态码 70 | * 71 | * @return 响应体json字符串 72 | * 73 | */ 74 | @Override 75 | public String toString() { 76 | return JSON.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/request/appdevice/AppListDeivceRequest.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.request.appdevice; 2 | 3 | import com.jw.demo.common.request.Request; 4 | import com.jw.demo.common.response.DefaultResponse; 5 | import com.jw.demo.common.response.Response; 6 | import com.jw.demo.common.web.HttpRequestInfo; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | public class AppListDeivceRequest extends Request { 11 | 12 | private String productId; 13 | private Integer type; 14 | private String nickName; 15 | 16 | /** 17 | * 解析参数 18 | * 19 | * @param request 20 | */ 21 | @Override 22 | public Response parse(HttpServletRequest request) { 23 | HttpRequestInfo requestInfo = new HttpRequestInfo(request); 24 | this.nickName = requestInfo.getParameter("nickName",""); 25 | this.productId = requestInfo.getParameter("productId",""); 26 | // this.type = Integer.valueOf(requestInfo.getParameter("type","")); 27 | return new DefaultResponse(); 28 | } 29 | 30 | public String getProductId() { 31 | return productId; 32 | } 33 | 34 | public Integer getType() { 35 | return type; 36 | } 37 | 38 | public String getNickName() { 39 | return nickName; 40 | } 41 | 42 | public void setProductId(String productId) { 43 | this.productId = productId; 44 | } 45 | 46 | public void setType(Integer type) { 47 | this.type = type; 48 | } 49 | 50 | public void setNickName(String nickName) { 51 | this.nickName = nickName; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/Application.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.ComponentScan; 8 | import org.springframework.scheduling.annotation.EnableAsync; 9 | import org.springframework.web.servlet.HandlerAdapter; 10 | import org.springframework.web.servlet.HandlerMapping; 11 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; 12 | import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 13 | 14 | @EnableAsync 15 | @SpringBootApplication 16 | @ComponentScan({"com.jw.demo.common", "com.jw.demo.app"}) 17 | public class Application extends SpringBootServletInitializer { 18 | 19 | /* 20 | * Create required HandlerMapping, to avoid several default HandlerMapping instances being created 21 | */ 22 | @Bean 23 | public HandlerMapping handlerMapping() { 24 | return new RequestMappingHandlerMapping(); 25 | } 26 | 27 | /* 28 | * Create required HandlerAdapter, to avoid several default HandlerAdapter instances being created 29 | */ 30 | @Bean 31 | public HandlerAdapter handlerAdapter() { 32 | return new RequestMappingHandlerAdapter(); 33 | } 34 | 35 | public static void main(String[] args) { 36 | SpringApplication.run(Application.class, args); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/response/PageListResponse.java: -------------------------------------------------------------------------------- 1 | //package com.jw.demo.common.response; 2 | // 3 | // 4 | //import java.util.Collections; 5 | //import java.util.List; 6 | // 7 | ///** 8 | // * 列表查询类响应实体 9 | // * 10 | // * @author hongyuhao 11 | // * @version 0.0.1 12 | // */ 13 | //public class PageListResponse extends Response { 14 | // /** 15 | // * uuid 16 | // */ 17 | // private static final long serialVersionUID = 3579336554342949826L; 18 | // 19 | // /** 20 | // * 返回结果列表 21 | // */ 22 | // private List list = Collections.emptyList(); 23 | // /** 24 | // * 分页信息 25 | // */ 26 | // private PageTurn pageTurn; 27 | // 28 | // /** 29 | // * 获取返回结果列表 30 | // * 31 | // * @return 返回结果列表 32 | // */ 33 | // public List getList() { 34 | // return list; 35 | // } 36 | // 37 | // /** 38 | // * 设置返回结果列表 39 | // * 40 | // * @param list 返回结果列表 41 | // */ 42 | // public void setList(List list) { 43 | // this.list = list; 44 | // } 45 | // 46 | // /** 47 | // * 获取分页信息 48 | // * 49 | // * @return 分页信息 50 | // */ 51 | // public PageTurn getPageTurn() { 52 | // return pageTurn; 53 | // } 54 | // 55 | // /** 56 | // * 设置分页信息 57 | // * 58 | // * @param pageTurn 分页信息 59 | // */ 60 | // public void setPageTurn(PageTurn pageTurn) { 61 | // this.pageTurn = pageTurn; 62 | // } 63 | // 64 | // /** 65 | // * 重写tostring 66 | // * 67 | // * @return 相应结果json字符串 68 | // */ 69 | // @Override 70 | // public String toString() { 71 | // return super.toString(); 72 | // } 73 | // 74 | //} 75 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/request/device/CertificateGetRequest.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.request.device; 2 | 3 | import com.jw.demo.common._enum.ApiResultEnum; 4 | import com.jw.demo.common.request.Request; 5 | import com.jw.demo.common.response.DefaultResponse; 6 | import com.jw.demo.common.response.FailResponse; 7 | import com.jw.demo.common.response.Response; 8 | import com.jw.demo.common.web.HttpRequestInfo; 9 | import org.apache.commons.lang3.StringUtils; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | 13 | public class CertificateGetRequest extends Request { 14 | 15 | private String productKey; // 产品PK 16 | private String mac; // 设备MAC 17 | 18 | @Override 19 | public Response parse(HttpServletRequest request) { 20 | HttpRequestInfo requestInfo = new HttpRequestInfo(request); 21 | // 校验:产品PK 22 | this.productKey = requestInfo.getParameter("productKey", ""); 23 | if (StringUtils.isEmpty(productKey)) { 24 | return new FailResponse(ApiResultEnum.PARAM_ERROR.getId(), "请输入产品PK"); 25 | } 26 | // 校验:设备MAC 27 | this.mac = requestInfo.getParameter("mac", ""); 28 | if (StringUtils.isEmpty(mac)) { 29 | return new FailResponse(ApiResultEnum.PARAM_ERROR.getId(), "请输入设备MAC"); 30 | } 31 | this.mac = mac.replaceAll("-", "").replaceAll(":", "").toUpperCase(); 32 | return new DefaultResponse(); 33 | } 34 | 35 | public String getProductKey() { 36 | return productKey; 37 | } 38 | 39 | public void setProductKey(String productKey) { 40 | this.productKey = productKey; 41 | } 42 | 43 | public String getMac() { 44 | return mac; 45 | } 46 | 47 | public void setMac(String mac) { 48 | this.mac = mac; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/entity/dynamodb/DevicePropertyLog.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.entity.dynamodb; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; 5 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; 6 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; 7 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; 8 | 9 | import java.util.Map; 10 | 11 | @DynamoDBTable(tableName = "devicePropertyLog") 12 | public class DevicePropertyLog { 13 | 14 | @DynamoDBHashKey(attributeName = "mac") 15 | private String mac; // MAC,分区键 16 | 17 | @DynamoDBRangeKey(attributeName = "create_time") 18 | private Long createTime; // 创建时间,排序键 19 | 20 | @DynamoDBAttribute(attributeName = "reported_data") 21 | private Map reportedData; // 上报内容 22 | 23 | public String getMac() { 24 | return mac; 25 | } 26 | 27 | public void setMac(String mac) { 28 | this.mac = mac; 29 | } 30 | 31 | public Long getCreateTime() { 32 | return createTime; 33 | } 34 | 35 | public void setCreateTime(Long createTime) { 36 | this.createTime = createTime; 37 | } 38 | 39 | public Map getReportedData() { 40 | return reportedData; 41 | } 42 | 43 | public void setReportedData(Map reportedData) { 44 | this.reportedData = reportedData; 45 | } 46 | 47 | public JSONObject toJSON() { 48 | JSONObject json = new JSONObject(); 49 | json.put("mac", mac); 50 | json.put("createTime", createTime); 51 | json.put("reported_data", reportedData); 52 | return json; 53 | } 54 | 55 | @Override 56 | public String toString() { 57 | return toJSON().toString(); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/request/appdevice/AppBindDeviceRequest.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.request.appdevice; 2 | 3 | import com.jw.demo.common.request.Request; 4 | import com.jw.demo.common.response.DefaultResponse; 5 | import com.jw.demo.common.response.Response; 6 | import com.jw.demo.common.web.HttpRequestInfo; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | 11 | public class AppBindDeviceRequest extends Request { 12 | 13 | private Long deviceId; 14 | private String mac; 15 | private String deviceNickName; 16 | //private String productKey; 17 | 18 | /** 19 | * 解析参数 20 | * 21 | * @param request 22 | */ 23 | @Override 24 | public Response parse(HttpServletRequest request) { 25 | HttpRequestInfo requestInfo = new HttpRequestInfo(request); 26 | this.deviceId = Long.valueOf(requestInfo.getParameter("deviceId","1000")); 27 | 28 | this.mac = requestInfo.getParameter("mac",""); 29 | this.deviceNickName = requestInfo.getParameter("deviceNickName",""); 30 | // this.productKey =requestInfo.getParameter("productKey","pk001"); 31 | return new DefaultResponse(); 32 | } 33 | 34 | public String getMac() { 35 | return mac; 36 | } 37 | 38 | public String getDeviceNickName() { 39 | return deviceNickName; 40 | } 41 | 42 | public void setMac(String mac) { 43 | this.mac = mac; 44 | } 45 | 46 | public void setDeviceNickName(String deviceNickName) { 47 | this.deviceNickName = deviceNickName; 48 | } 49 | 50 | public Long getDeviceId() { 51 | return deviceId; 52 | } 53 | 54 | public void setDeviceId(Long deviceId) { 55 | this.deviceId = deviceId; 56 | } 57 | 58 | // // public String getProductKey() { 59 | // return productKey; 60 | // } 61 | 62 | // public void setProductKey(String productKey) { 63 | // this.productKey = productKey; 64 | // } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/request/device/ShadowUpdateRequest.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.request.device; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.jw.demo.common._enum.ApiResultEnum; 5 | import com.jw.demo.common.request.Request; 6 | import com.jw.demo.common.response.DefaultResponse; 7 | import com.jw.demo.common.response.FailResponse; 8 | import com.jw.demo.common.response.Response; 9 | import com.jw.demo.common.web.HttpRequestInfo; 10 | import org.apache.commons.lang3.StringUtils; 11 | 12 | import javax.servlet.http.HttpServletRequest; 13 | 14 | 15 | 16 | 17 | public class ShadowUpdateRequest extends Request { 18 | 19 | private Long deviceId; // 设备ID 20 | private String data; // 控制内容,JSON形式 21 | 22 | @Override 23 | public Response parse(HttpServletRequest request) { 24 | HttpRequestInfo requestInfo = new HttpRequestInfo(request); 25 | // 校验:设备ID 26 | this.deviceId = requestInfo.getLongParameter("deviceId", 0); 27 | if (deviceId == Long.valueOf(0)) { 28 | return new FailResponse(ApiResultEnum.PARAM_ERROR.getId(), "请选择设备"); 29 | } 30 | // 校验:控制内容 31 | this.data = requestInfo.getParameter("data", ""); 32 | if (StringUtils.isEmpty(data)) { 33 | return new FailResponse(ApiResultEnum.PARAM_ERROR.getId(), "请输入控制内容"); 34 | } 35 | try { 36 | JSONObject.parseObject(data); 37 | } catch (Exception e) { 38 | return new FailResponse(ApiResultEnum.PARAM_ERROR.getId(), "请输入合法的控制内容"); 39 | } 40 | return new DefaultResponse(); 41 | } 42 | 43 | public Long getDeviceId() { 44 | return deviceId; 45 | } 46 | 47 | public void setDeviceId(Long deviceId) { 48 | this.deviceId = deviceId; 49 | } 50 | 51 | public String getData() { 52 | return data; 53 | } 54 | 55 | public void setData(String data) { 56 | this.data = data; 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/entity/dynamodb/DeviceConnectLog.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.entity.dynamodb; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; 5 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; 6 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; 7 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; 8 | 9 | @DynamoDBTable(tableName = "deviceConnectLog") 10 | public class DeviceConnectLog { 11 | 12 | @DynamoDBHashKey(attributeName = "mac") 13 | private String mac; // MAC,分区键 14 | 15 | @DynamoDBRangeKey(attributeName = "create_time") 16 | private Long createTime; // 创建时间,排序键 17 | 18 | @DynamoDBAttribute(attributeName = "connect") 19 | private String connect; // 连接状态 20 | 21 | @DynamoDBAttribute(attributeName = "product_key") 22 | private String productKey; // 产品密钥 23 | 24 | @DynamoDBAttribute(attributeName = "region") 25 | private String region; // 地区 26 | 27 | public String getMac() { 28 | return mac; 29 | } 30 | 31 | public void setMac(String mac) { 32 | this.mac = mac; 33 | } 34 | 35 | public Long getCreateTime() { 36 | return createTime; 37 | } 38 | 39 | public void setCreateTime(Long createTime) { 40 | this.createTime = createTime; 41 | } 42 | 43 | public String getConnect() { 44 | return connect; 45 | } 46 | 47 | public void setConnect(String connect) { 48 | this.connect = connect; 49 | } 50 | 51 | public String getProductKey() { 52 | return productKey; 53 | } 54 | 55 | public void setProductKey(String productKey) { 56 | this.productKey = productKey; 57 | } 58 | 59 | public String getRegion() { 60 | return region; 61 | } 62 | 63 | public void setRegion(String region) { 64 | this.region = region; 65 | } 66 | 67 | public JSONObject toJSON() { 68 | JSONObject json = new JSONObject(); 69 | json.put("mac", mac); 70 | json.put("createTime", createTime); 71 | json.put("connect", connect); 72 | json.put("productKey", productKey); 73 | json.put("region", region); 74 | return json; 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | return toJSON().toString(); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### Java template 2 | # Compiled class file 3 | *.class 4 | 5 | # Log file 6 | *.log 7 | 8 | # BlueJ files 9 | *.ctxt 10 | 11 | # Mobile Tools for Java (J2ME) 12 | .mtj.tmp/ 13 | 14 | # Package Files # 15 | *.jar 16 | *.war 17 | *.nar 18 | *.ear 19 | *.zip 20 | *.tar.gz 21 | *.rar 22 | 23 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 24 | hs_err_pid* 25 | 26 | ### Maven template 27 | target/ 28 | pom.xml.tag 29 | pom.xml.releaseBackup 30 | pom.xml.versionsBackup 31 | pom.xml.next 32 | release.properties 33 | dependency-reduced-pom.xml 34 | buildNumber.properties 35 | .mvn/timing.properties 36 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar 37 | .mvn/wrapper/maven-wrapper.jar 38 | 39 | ### JetBrains template 40 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 41 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 42 | 43 | # User-specific stuff 44 | .idea/**/workspace.xml 45 | .idea/**/tasks.xml 46 | .idea/**/usage.statistics.xml 47 | .idea/**/dictionaries 48 | .idea/**/shelf 49 | 50 | # Generated files 51 | .idea/**/contentModel.xml 52 | 53 | # Sensitive or high-churn files 54 | .idea/**/dataSources/ 55 | .idea/**/dataSources.ids 56 | .idea/**/dataSources.local.xml 57 | .idea/**/sqlDataSources.xml 58 | .idea/**/dynamic.xml 59 | .idea/**/uiDesigner.xml 60 | .idea/**/dbnavigator.xml 61 | 62 | # Gradle 63 | .idea/**/gradle.xml 64 | .idea/**/libraries 65 | 66 | # Gradle and Maven with auto-import 67 | # When using Gradle or Maven with auto-import, you should exclude module files, 68 | # since they will be recreated, and may cause churn. Uncomment if using 69 | # auto-import. 70 | # .idea/artifacts 71 | # .idea/compiler.xml 72 | # .idea/jarRepositories.xml 73 | # .idea/modules.xml 74 | # .idea/*.iml 75 | # .idea/modules 76 | # *.iml 77 | # *.ipr 78 | 79 | # CMake 80 | cmake-build-*/ 81 | 82 | # Mongo Explorer plugin 83 | .idea/**/mongoSettings.xml 84 | 85 | # File-based project format 86 | *.iws 87 | 88 | # IntelliJ 89 | out/ 90 | 91 | # mpeltonen/sbt-idea plugin 92 | .idea_modules/ 93 | 94 | # JIRA plugin 95 | atlassian-ide-plugin.xml 96 | 97 | # Cursive Clojure plugin 98 | .idea/replstate.xml 99 | 100 | # Crashlytics plugin (for Android Studio and IntelliJ) 101 | com_crashlytics_export_strings.xml 102 | crashlytics.properties 103 | crashlytics-build.properties 104 | fabric.properties 105 | 106 | # Editor-based Rest Client 107 | .idea/httpRequests 108 | 109 | # Android studio 3.1+ serialized cache file 110 | .idea/caches/build_file_checksums.ser 111 | 112 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/controller/UserDeviceController.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.controller; 2 | 3 | import com.jw.demo.app.request.appdevice.AppBindDeviceRequest; 4 | import com.jw.demo.app.request.appdevice.AppListDeivceRequest; 5 | import com.jw.demo.app.service.AppUserDeviceService; 6 | import com.jw.demo.app.util.AppTokenUtil; 7 | import com.jw.demo.common._enum.ApiResultEnum; 8 | import com.jw.demo.common.entity.base.AppUser; 9 | import com.jw.demo.common.response.Response; 10 | 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RestController; 15 | 16 | import javax.annotation.Resource; 17 | import javax.servlet.http.HttpServletRequest; 18 | 19 | @RestController 20 | @RequestMapping("/user/device") 21 | public class UserDeviceController extends BaseController { 22 | private static final Logger LOGGER = LoggerFactory.getLogger(UserDeviceController.class); 23 | 24 | @Resource 25 | private AppUserDeviceService appUserDeviceService; 26 | 27 | @RequestMapping(value = "/bind",produces = "text/json;charset=utf-8") 28 | public String bindDevice(HttpServletRequest request){ 29 | Response response; 30 | try { 31 | AppUser appUser = AppTokenUtil.getAppUser(request.getHeader("token")); 32 | AppBindDeviceRequest appBindDeviceRequest = new AppBindDeviceRequest(); 33 | response = appBindDeviceRequest.parse(request); 34 | if (response.getCode() == ApiResultEnum.SUCCESS.getId()) { 35 | response = appUserDeviceService.bindAppUserDevice(appUser,appBindDeviceRequest); 36 | } 37 | } catch (Exception e) { 38 | response = this.getFailResponse("绑定失败", e, LOGGER, Thread.currentThread().getStackTrace()[1].getMethodName(), 39 | request); 40 | } 41 | return response.toString(); 42 | } 43 | 44 | @RequestMapping(value = "/list",produces = "text/json;charset=utf-8") 45 | public String listDevice(HttpServletRequest request){ 46 | Response response; 47 | try { 48 | AppUser appUser = AppTokenUtil.getAppUser(request.getHeader("token")); 49 | AppListDeivceRequest appListDeivceRequest = new AppListDeivceRequest(); 50 | response = appListDeivceRequest.parse(request); 51 | if (response.getCode() == ApiResultEnum.SUCCESS.getId()) { 52 | response = appUserDeviceService.listAppUserDevice(appUser,appListDeivceRequest); 53 | } 54 | } catch (Exception e) { 55 | response = this.getFailResponse("查询绑定", e, LOGGER, Thread.currentThread().getStackTrace()[1].getMethodName(), 56 | request); 57 | } 58 | return response.toString(); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/util/aws/s3/S3Util.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.util.aws.s3; 2 | 3 | import java.net.URL; 4 | 5 | import com.amazonaws.auth.AWSCredentialsProvider; 6 | import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; 7 | import com.amazonaws.regions.Regions; 8 | import com.jw.demo.common.response.DefaultResponse; 9 | import com.jw.demo.common.response.FailResponse; 10 | import com.jw.demo.common.response.InfoResponse; 11 | import com.jw.demo.common.response.Response; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | 15 | import com.amazonaws.HttpMethod; 16 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 17 | import com.amazonaws.auth.BasicAWSCredentials; 18 | import com.amazonaws.services.s3.AmazonS3; 19 | import com.amazonaws.services.s3.AmazonS3ClientBuilder; 20 | import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest; 21 | 22 | public class S3Util { 23 | private Logger log = LoggerFactory.getLogger(getClass()); 24 | 25 | public static S3Util getInstance() { 26 | return new S3Util(); 27 | } 28 | 29 | /** 30 | * 上传对象 31 | * 32 | * @param accessKey 亚马逊接口凭证 33 | * @param secretKey 亚马逊接口凭证 34 | * @param region 亚马逊区域 35 | * @param bucketName 存储桶名称 36 | * @param objectKey 对象名称 37 | * @param objectContent 对象内容 38 | */ 39 | public Response uploadObject(String region, String bucketName, String objectKey, String objectContent) { 40 | try { 41 | AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(region).build(); 42 | s3Client.putObject(bucketName, objectKey, objectContent); 43 | } catch (Exception e) { 44 | log.error("S3Util.uploadObject", e); 45 | e.printStackTrace(); 46 | return new FailResponse(); 47 | } 48 | return new DefaultResponse(); 49 | } 50 | 51 | /** 52 | * 生成对象预签名URL 53 | * 54 | * @param accessKey 亚马逊接口凭证 55 | * @param secretKey 亚马逊接口凭证 56 | * @param region 亚马逊区域 57 | * @param bucketName 存储桶名称 58 | * @param objectKey 对象名称 59 | * @return 60 | */ 61 | public Response generatePresignedUrl(String region, String bucketName, String objectKey) { 62 | URL url = null; 63 | try { 64 | AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(region).build(); 65 | GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey) 66 | .withMethod(HttpMethod.GET); 67 | url = s3Client.generatePresignedUrl(request); 68 | } catch (Exception e) { 69 | e.printStackTrace(); 70 | return new FailResponse(); 71 | } 72 | return url == null ? new FailResponse() : new InfoResponse<>(url.toString()); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/util/aws/iot/ShadowUtil.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.util.aws.iot; 2 | 3 | import java.nio.ByteBuffer; 4 | 5 | import com.jw.demo.common.response.DefaultResponse; 6 | import com.jw.demo.common.response.FailResponse; 7 | import com.jw.demo.common.response.Response; 8 | import org.apache.http.HttpStatus; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import com.alibaba.fastjson.JSONObject; 13 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 14 | import com.amazonaws.auth.BasicAWSCredentials; 15 | import com.amazonaws.services.iotdata.AWSIotData; 16 | import com.amazonaws.services.iotdata.AWSIotDataClientBuilder; 17 | import com.amazonaws.services.iotdata.model.UpdateThingShadowRequest; 18 | import com.amazonaws.services.iotdata.model.UpdateThingShadowResult; 19 | 20 | public class ShadowUtil { 21 | private Logger log = LoggerFactory.getLogger(getClass()); 22 | 23 | public static ShadowUtil getInstance() { 24 | return new ShadowUtil(); 25 | } 26 | 27 | /** 28 | * 更新设备影子,参考文档:https://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/device-shadow-mqtt.html#update-pub-sub-topic 29 | * 30 | * @param accessKey 亚马逊接口凭证 31 | * @param secretKey 亚马逊接口凭证 32 | * @param region 亚马逊区域 33 | * @param thingName 事物名称 34 | * @param payload 内容,格式JSON。{"state":{"desired":{"属性":"值",...}}} 35 | * @return 36 | */ 37 | public Response updateThingShadow(String accessKey, String secretKey, String region, String thingName, 38 | ByteBuffer payload) { 39 | try { 40 | BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); 41 | AWSIotData iotDataClient = AWSIotDataClientBuilder.standard().withRegion(region) 42 | .withCredentials(new AWSStaticCredentialsProvider(credentials)).build(); 43 | 44 | UpdateThingShadowRequest request = new UpdateThingShadowRequest(); 45 | request.setThingName(thingName); 46 | request.setPayload(payload); 47 | 48 | UpdateThingShadowResult result = iotDataClient.updateThingShadow(request); 49 | if (HttpStatus.SC_OK != result.getSdkHttpMetadata().getHttpStatusCode()) { 50 | return new FailResponse(); 51 | } 52 | } catch (Exception e) { 53 | log.error("ShadowUtil.updateThingShadow", e); 54 | return new FailResponse(); 55 | } 56 | return new DefaultResponse(); 57 | } 58 | 59 | /** 60 | * 更新设备影子,参考文档:https://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/device-shadow-mqtt.html#update-pub-sub-topic 61 | * 62 | * @param accessKey 亚马逊接口凭证 63 | * @param secretKey 亚马逊接口凭证 64 | * @param region 亚马逊区域 65 | * @param thingName 事物名称 66 | * @param payload 内容,格式JSON。{"属性":"值",...} 67 | * @return 68 | */ 69 | public Response updateThingShadow(String accessKey, String secretKey, String region, String thingName, 70 | String data) { 71 | JSONObject dataJson = JSONObject.parseObject(data); 72 | JSONObject stateJson = new JSONObject(); 73 | stateJson.put("desired", dataJson); 74 | JSONObject payloadJson = new JSONObject(); 75 | payloadJson.put("state", stateJson); 76 | ByteBuffer payload = ByteBuffer.wrap(payloadJson.toJSONString().getBytes()); 77 | return updateThingShadow(accessKey, secretKey, region, thingName, payload); 78 | } 79 | 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/controller/DeviceController.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.controller; 2 | 3 | import com.jw.demo.app.request.device.CertificateGetRequest; 4 | import com.jw.demo.app.request.device.PropertyGetRequest; 5 | import com.jw.demo.app.request.device.ShadowUpdateRequest; 6 | import com.jw.demo.app.service.DeviceService; 7 | import com.jw.demo.common._enum.ApiResultEnum; 8 | import com.jw.demo.common.response.Response; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import javax.annotation.Resource; 14 | import javax.servlet.http.HttpServletRequest; 15 | 16 | @RestController 17 | @RequestMapping("/device") 18 | public class DeviceController extends BaseController { 19 | private Logger log = LoggerFactory.getLogger(getClass()); 20 | 21 | /** 获取设备证书 **/ 22 | private static final String REGISTER = "/register"; 23 | /** 获取设备属性 **/ 24 | private static final String PROPERTY_GET = "/property/get"; 25 | /** 更新设备影子 **/ 26 | private static final String SHADOW_UPDATE = "/shadow/update"; 27 | 28 | @Resource 29 | private DeviceService deviceService; 30 | 31 | @PostMapping(value = REGISTER, produces = { "application/json;charset=UTF-8" }) 32 | public String certificateGet(HttpServletRequest request) { 33 | Response response; 34 | try { 35 | CertificateGetRequest certificateGetRequest = new CertificateGetRequest(); 36 | response = certificateGetRequest.parse(request); 37 | if (response.getCode() == ApiResultEnum.SUCCESS.getId()) { 38 | response = deviceService.certificateGet(certificateGetRequest); 39 | } 40 | } catch (Exception e) { 41 | response = this.getFailResponse("获取设备证书失败", e, log, 42 | Thread.currentThread().getStackTrace()[1].getMethodName(), request); 43 | } 44 | return response.toString(); 45 | } 46 | 47 | @PostMapping(value = PROPERTY_GET, produces = { "application/json;charset=UTF-8" }) 48 | public String propertyGet(HttpServletRequest request) { 49 | Response response; 50 | try { 51 | PropertyGetRequest propertyGetRequest = new PropertyGetRequest(); 52 | response = propertyGetRequest.parse(request); 53 | if (response.getCode() == ApiResultEnum.SUCCESS.getId()) { 54 | response = deviceService.propertyGet(propertyGetRequest); 55 | } 56 | } catch (Exception e) { 57 | response = this.getFailResponse("获取设备属性失败", e, log, 58 | Thread.currentThread().getStackTrace()[1].getMethodName(), request); 59 | } 60 | return response.toString(); 61 | } 62 | 63 | @PostMapping(value = SHADOW_UPDATE, produces = { "application/json;charset=UTF-8" }) 64 | public String updateShadow(HttpServletRequest request) { 65 | Response response; 66 | try { 67 | ShadowUpdateRequest shadowUpdateRequest = new ShadowUpdateRequest(); 68 | response = shadowUpdateRequest.parse(request); 69 | if (response.getCode() == ApiResultEnum.SUCCESS.getId()) { 70 | response = deviceService.updateShadow(shadowUpdateRequest); 71 | } 72 | } catch (Exception e) { 73 | response = this.getFailResponse("更新设备影子失败", e, log, 74 | Thread.currentThread().getStackTrace()[1].getMethodName(), request); 75 | } 76 | return response.toString(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/util/aws/cognito/IdentityPoolUtil.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.util.aws.cognito; 2 | 3 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 4 | import com.amazonaws.auth.BasicAWSCredentials; 5 | import com.amazonaws.regions.Regions; 6 | import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentity; 7 | import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient; 8 | import com.amazonaws.services.cognitoidentity.model.GetCredentialsForIdentityRequest; 9 | import com.amazonaws.services.cognitoidentity.model.GetCredentialsForIdentityResult; 10 | import com.amazonaws.services.cognitoidentity.model.GetOpenIdTokenForDeveloperIdentityRequest; 11 | import com.amazonaws.services.cognitoidentity.model.GetOpenIdTokenForDeveloperIdentityResult; 12 | 13 | import java.util.HashMap; 14 | 15 | /** 16 | * 身份池 工具类 17 | */ 18 | public class IdentityPoolUtil { 19 | 20 | private static AmazonCognitoIdentity identityClient = 21 | AmazonCognitoIdentityClient.builder().withRegion(Regions.AP_SOUTHEAST_1).build(); 22 | 23 | public static void main(String[] args) throws Exception { 24 | //身份池ID 25 | String identityPoolId = "ap-southeast-1:b5f91781-ed82-471b-952b-94c42291036e"; 26 | //这个是cognito身份池授权地址,不能改 27 | String providerName = "cognito-identity.amazonaws.com"; 28 | //这是 token的时长限制 单位是秒 29 | long tokenDuration = 86400; 30 | //这个是 身份池 -->身份浏览器 ———> 点击身份ID 进入 ———> 对应 开发人员标识符 的值 31 | String identifier = "zyj_test1111";// 32 | 33 | //获取cognito 的令牌 "mytest" 34 | GetOpenIdTokenForDeveloperIdentityResult token = getOpenIdTokenForDeveloperIdentity(identityPoolId, "mytest", identifier, tokenDuration); 35 | System.err.println("token====="+token.getToken()); 36 | //获取 用户临时凭证(有效时间会返回,但是无法设置) 37 | System.err.println(getCredentialsForIdentity(token.getIdentityId(), providerName,token.getToken())); 38 | getOpenIdTokenForDeveloperIdentity(identityPoolId,"mytest","mytest123",60 * 15l); 39 | } 40 | 41 | /** 42 | * 获取用户验证令牌 43 | * @param identityPoolId 44 | * @param providerName 45 | * @param identifier 46 | * @param tokenDuration 47 | * @return 48 | * @throws Exception 49 | */ 50 | public static GetOpenIdTokenForDeveloperIdentityResult getOpenIdTokenForDeveloperIdentity(String identityPoolId,String providerName,String identifier,Long tokenDuration) throws Exception { 51 | GetOpenIdTokenForDeveloperIdentityRequest request = new GetOpenIdTokenForDeveloperIdentityRequest(); 52 | request.setIdentityPoolId(identityPoolId); 53 | HashMap logins = new HashMap<>(); 54 | logins.put(providerName,identifier); 55 | request.setLogins(logins); 56 | request.setTokenDuration(tokenDuration); 57 | GetOpenIdTokenForDeveloperIdentityResult response = identityClient.getOpenIdTokenForDeveloperIdentity(request); 58 | String identityId = response.getIdentityId(); 59 | String token = response.getToken(); 60 | System.err.println("identityId:"+identityId); 61 | System.err.println("token:"+token); 62 | return response; 63 | } 64 | 65 | /** 66 | * 获取身份ID凭证 67 | * @param identityId 用户身份id 68 | * @param name 验证商名称 69 | * @param token 用户令牌 70 | * @return 71 | */ 72 | public static GetCredentialsForIdentityResult getCredentialsForIdentity(String identityId,String name,String token){ 73 | GetCredentialsForIdentityRequest getCredentialsForIdentityRequest = new GetCredentialsForIdentityRequest(); 74 | getCredentialsForIdentityRequest.setIdentityId(identityId); 75 | HashMap logins = new HashMap<>(); 76 | logins.put(name,token); 77 | getCredentialsForIdentityRequest.setLogins(logins); 78 | System.err.println(identityId+"-"+name+"-"+token); 79 | return identityClient.getCredentialsForIdentity(getCredentialsForIdentityRequest); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/entity/base/CommParamConfig.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.entity.base; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * Database Table Remarks: 7 | * base.t_comm_param_config: 参数配置表 8 | * 9 | * @mbg.generated do_not_delete_during_merge 2021-10-13 17:08:51 10 | */ 11 | public class CommParamConfig { 12 | /** 13 | * Database Column Remarks: 14 | * base.t_comm_param_config.id: 主键 15 | */ 16 | private Long id; 17 | 18 | /** 19 | * Database Column Remarks: 20 | * base.t_comm_param_config.name: 参数名称 21 | */ 22 | private String name; 23 | 24 | /** 25 | * Database Column Remarks: 26 | * base.t_comm_param_config.code: 参数编码 27 | */ 28 | private String code; 29 | 30 | /** 31 | * Database Column Remarks: 32 | * base.t_comm_param_config.content: 参数内容 33 | */ 34 | private String content; 35 | 36 | /** 37 | * Database Column Remarks: 38 | * base.t_comm_param_config.status: 状态:1-有效 2-无效 39 | */ 40 | private Integer status; 41 | 42 | /** 43 | * Database Column Remarks: 44 | * base.t_comm_param_config.create_time: 创建时间 45 | */ 46 | private Date createTime; 47 | 48 | /** 49 | * @return the value of base.t_comm_param_config.id 50 | */ 51 | public Long getId() { 52 | return id; 53 | } 54 | 55 | /** 56 | * @param id the value for base.t_comm_param_config.id 57 | */ 58 | public void setId(Long id) { 59 | this.id = id; 60 | } 61 | 62 | /** 63 | * @return the value of base.t_comm_param_config.name 64 | */ 65 | public String getName() { 66 | return name; 67 | } 68 | 69 | /** 70 | * @param name the value for base.t_comm_param_config.name 71 | */ 72 | public void setName(String name) { 73 | this.name = name == null ? null : name.trim(); 74 | } 75 | 76 | /** 77 | * @return the value of base.t_comm_param_config.code 78 | */ 79 | public String getCode() { 80 | return code; 81 | } 82 | 83 | /** 84 | * @param code the value for base.t_comm_param_config.code 85 | */ 86 | public void setCode(String code) { 87 | this.code = code == null ? null : code.trim(); 88 | } 89 | 90 | /** 91 | * @return the value of base.t_comm_param_config.content 92 | */ 93 | public String getContent() { 94 | return content; 95 | } 96 | 97 | /** 98 | * @param content the value for base.t_comm_param_config.content 99 | */ 100 | public void setContent(String content) { 101 | this.content = content == null ? null : content.trim(); 102 | } 103 | 104 | /** 105 | * @return the value of base.t_comm_param_config.status 106 | */ 107 | public Integer getStatus() { 108 | return status; 109 | } 110 | 111 | /** 112 | * @param status the value for base.t_comm_param_config.status 113 | */ 114 | public void setStatus(Integer status) { 115 | this.status = status; 116 | } 117 | 118 | /** 119 | * @return the value of base.t_comm_param_config.create_time 120 | */ 121 | public Date getCreateTime() { 122 | return createTime; 123 | } 124 | 125 | /** 126 | * @param createTime the value for base.t_comm_param_config.create_time 127 | */ 128 | public void setCreateTime(Date createTime) { 129 | this.createTime = createTime; 130 | } 131 | 132 | @Override 133 | public String toString() { 134 | StringBuilder sb = new StringBuilder(); 135 | sb.append(getClass().getSimpleName()); 136 | sb.append(" ["); 137 | sb.append("Hash = ").append(hashCode()); 138 | sb.append(", id=").append(id); 139 | sb.append(", name=").append(name); 140 | sb.append(", code=").append(code); 141 | sb.append(", content=").append(content); 142 | sb.append(", status=").append(status); 143 | sb.append(", createTime=").append(createTime); 144 | sb.append("]"); 145 | return sb.toString(); 146 | } 147 | } -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/util/aws/policy/IotPolicyUtil.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.util.aws.policy; 2 | 3 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 4 | import com.amazonaws.auth.BasicAWSCredentials; 5 | import com.amazonaws.regions.Regions; 6 | import com.amazonaws.services.iot.AWSIot; 7 | import com.amazonaws.services.iot.AWSIotClient; 8 | import com.amazonaws.services.iot.model.*; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | /** 13 | * Iot 策略工具类 14 | */ 15 | public class IotPolicyUtil { 16 | private static final Logger LOGGER = LoggerFactory.getLogger(IotPolicyUtil.class); 17 | private static final AWSIot awsIot = AWSIotClient.builder().withRegion(Regions.AP_SOUTHEAST_1).build(); 18 | 19 | /** 20 | * 获取策略信息 (非策略内容) 21 | * @param policyName 策略名称 22 | * @return 23 | * @throws Exception 24 | */ 25 | public static GetPolicyResult getPolicy(String policyName)throws Exception{ 26 | 27 | GetPolicyRequest getPolicyRequest = new GetPolicyRequest(); 28 | getPolicyRequest.setPolicyName(policyName); 29 | 30 | return awsIot.getPolicy(getPolicyRequest); 31 | } 32 | 33 | /** 34 | * 创建策略 35 | * @param policyName 策略名称 36 | * @param policyDocument 策略内容 37 | * @return 38 | * @throws Exception 39 | */ 40 | public static CreatePolicyResult createPolicy(String policyName,String policyDocument)throws Exception{ 41 | CreatePolicyRequest createPolicyRequest = new CreatePolicyRequest(); 42 | createPolicyRequest.setPolicyName(policyName); 43 | createPolicyRequest.setPolicyDocument(policyDocument); 44 | System.out.println(policyDocument); 45 | return awsIot.createPolicy(createPolicyRequest); 46 | } 47 | 48 | /** 49 | * 更新策略并设置为默认版本 50 | * @param policyName 策略名称 51 | * @param policyDocument 策略内容 52 | * @return 53 | * @throws Exception 54 | */ 55 | public static CreatePolicyVersionResult createPolicyVersion(String policyName,String policyDocument)throws Exception{ 56 | CreatePolicyVersionRequest createPolicyVersionRequest = new CreatePolicyVersionRequest(); 57 | createPolicyVersionRequest.setPolicyName(policyName); 58 | createPolicyVersionRequest.setPolicyDocument(policyDocument); 59 | createPolicyVersionRequest.setSetAsDefault(true); 60 | return awsIot.createPolicyVersion(createPolicyVersionRequest); 61 | 62 | } 63 | 64 | /** 65 | * 删除策略版本 66 | * @param policyName 策略名称 67 | * @param policyVersionId 策略版本 68 | * @return 69 | * @throws Exception 70 | */ 71 | public static boolean deletePolicyversion(String policyName,String policyVersionId)throws Exception{ 72 | DeletePolicyVersionRequest deletePolicyVersionRequest = new DeletePolicyVersionRequest(); 73 | deletePolicyVersionRequest.setPolicyName(policyName); 74 | deletePolicyVersionRequest.setPolicyVersionId(policyVersionId); 75 | DeletePolicyVersionResult deletePolicyVersionResult = awsIot.deletePolicyVersion(deletePolicyVersionRequest); 76 | if (deletePolicyVersionResult.getSdkHttpMetadata().getHttpStatusCode() == 200){ 77 | return true; 78 | }else{ 79 | return false; 80 | } 81 | } 82 | 83 | /** 84 | * 删除策略 85 | * @param policyName 策略名称 86 | * @return 87 | * @throws Exception 88 | */ 89 | public static boolean deletePolicy(String policyName)throws Exception{ 90 | DeletePolicyRequest deletePolicyRequest = new DeletePolicyRequest(); 91 | deletePolicyRequest.setPolicyName(policyName); 92 | DeletePolicyResult result = awsIot.deletePolicy(deletePolicyRequest); 93 | if (result.getSdkHttpMetadata().getHttpStatusCode() == 200){ 94 | return true; 95 | }else{ 96 | return false; 97 | } 98 | } 99 | 100 | /** 101 | * 附加策略 102 | * @param policyName 策略名称 103 | * @param target 目标身份 104 | * @return 105 | */ 106 | public static boolean attachPlicy(String policyName,String target){ 107 | AttachPolicyRequest attachPolicyRequest = new AttachPolicyRequest(); 108 | attachPolicyRequest.setPolicyName(policyName); 109 | attachPolicyRequest.setTarget(target); 110 | AttachPolicyResult result = awsIot.attachPolicy(attachPolicyRequest); 111 | if (result.getSdkHttpMetadata().getHttpStatusCode() == 200){ 112 | return true; 113 | }else{ 114 | return false; 115 | } 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/entity/dynamodb/AppUserDevice.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.entity.dynamodb; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; 5 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; 6 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; 7 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; 8 | 9 | @DynamoDBTable(tableName = "appuserDevice") 10 | public class AppUserDevice { 11 | /*** 分区键 */ 12 | //主键appuser_id 13 | @DynamoDBHashKey(attributeName = "appuser_id") 14 | private String appuserId; 15 | 16 | /*** 创建时间 */ 17 | @DynamoDBRangeKey(attributeName = "create_time") 18 | private Long createTime; 19 | @DynamoDBAttribute(attributeName = "device_id") 20 | private String deviceId; 21 | /*** 产品id */ 22 | @DynamoDBAttribute(attributeName = "product_id") 23 | private String productId; 24 | /*** 产品密钥 */ 25 | @DynamoDBAttribute(attributeName = "product_key") 26 | private String productKey; 27 | /*** mac */ 28 | @DynamoDBAttribute(attributeName = "mac") 29 | private String mac; 30 | /*** 用户设备名称 */ 31 | @DynamoDBAttribute(attributeName = "device_nickname") 32 | private String deviceNickname; 33 | /*** 用户角色 1所有者 2管理员 3成员 */ 34 | @DynamoDBAttribute(attributeName = "u_type") 35 | private String uType; 36 | /*** 分享人 id 配网则是0 */ 37 | @DynamoDBAttribute(attributeName = "sharer") 38 | private String sharer; 39 | /*** 更新时间 */ 40 | @DynamoDBAttribute(attributeName = "update_time") 41 | private Long updateTime; 42 | 43 | 44 | 45 | public String getAppuserId() { 46 | return appuserId; 47 | } 48 | 49 | public String getDeviceId() { 50 | return deviceId; 51 | } 52 | 53 | public String getProductId() { 54 | return productId; 55 | } 56 | 57 | public String getProductKey() { 58 | return productKey; 59 | } 60 | 61 | public String getMac() { 62 | return mac; 63 | } 64 | 65 | public String getDeviceNickname() { 66 | return deviceNickname; 67 | } 68 | 69 | public Long getUpdateTime() { 70 | return updateTime; 71 | } 72 | 73 | public Long getCreateTime() { 74 | return createTime; 75 | } 76 | 77 | public void setAppuserId(String appuserId) { 78 | this.appuserId = appuserId; 79 | } 80 | 81 | public void setDeviceId(String deviceId) { 82 | this.deviceId = deviceId; 83 | } 84 | 85 | public void setProductId(String productId) { 86 | this.productId = productId; 87 | } 88 | 89 | public void setProductKey(String productKey) { 90 | this.productKey = productKey; 91 | } 92 | 93 | public void setMac(String mac) { 94 | this.mac = mac; 95 | } 96 | 97 | public void setDeviceNickname(String deviceNickname) { 98 | this.deviceNickname = deviceNickname; 99 | } 100 | 101 | public void setUpdateTime(Long updateTime) { 102 | this.updateTime = updateTime; 103 | } 104 | 105 | public void setCreateTime(Long createTime) { 106 | this.createTime = createTime; 107 | } 108 | 109 | public String getuType() { 110 | return uType; 111 | } 112 | 113 | public String getSharer() { 114 | return sharer; 115 | } 116 | 117 | public void setuType(String uType) { 118 | this.uType = uType; 119 | } 120 | 121 | public void setSharer(String sharer) { 122 | this.sharer = sharer; 123 | } 124 | 125 | @Override 126 | public String toString() { 127 | JSONObject appUserDeviceJSON = new JSONObject(); 128 | appUserDeviceJSON.put("appUserId", appuserId); 129 | appUserDeviceJSON.put("deviceId", deviceId); 130 | appUserDeviceJSON.put("productId", productId); 131 | appUserDeviceJSON.put("productKey", productKey); 132 | appUserDeviceJSON.put("mac",mac); 133 | appUserDeviceJSON.put("deviceNickName", deviceNickname); 134 | appUserDeviceJSON.put("type", uType); 135 | appUserDeviceJSON.put("sharer",sharer); 136 | appUserDeviceJSON.put("updateTime", updateTime); 137 | appUserDeviceJSON.put("createTime", createTime); 138 | return appUserDeviceJSON.toString(); 139 | } 140 | 141 | public JSONObject toJSON() { 142 | JSONObject appUserDeviceJSON = new JSONObject(); 143 | appUserDeviceJSON.put("appUserId", appuserId); 144 | appUserDeviceJSON.put("deviceId", deviceId); 145 | appUserDeviceJSON.put("productId", productId); 146 | appUserDeviceJSON.put("productKey", productKey); 147 | appUserDeviceJSON.put("mac",mac); 148 | appUserDeviceJSON.put("deviceNickName", deviceNickname); 149 | appUserDeviceJSON.put("uType", uType); 150 | appUserDeviceJSON.put("sharer",sharer); 151 | appUserDeviceJSON.put("updateTime", updateTime); 152 | appUserDeviceJSON.put("createTime", createTime); 153 | return appUserDeviceJSON; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/service/impl/AppUserDeviceServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.service.impl; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.JSONArray; 5 | import com.amazonaws.services.cognitoidentity.model.GetOpenIdTokenForDeveloperIdentityResult; 6 | import com.amazonaws.services.dynamodbv2.model.QueryResult; 7 | import com.amazonaws.services.iot.model.CreatePolicyResult; 8 | import com.jw.demo.app.dao.device.DeviceInfoMapper; 9 | import com.jw.demo.app.request.appdevice.AppBindDeviceRequest; 10 | import com.jw.demo.app.request.appdevice.AppListDeivceRequest; 11 | import com.jw.demo.app.service.AppUserDeviceService; 12 | import com.jw.demo.app.util.aws.cognito.IdentityPoolUtil; 13 | import com.jw.demo.app.util.aws.dynamodb.AppUserDeviceDy; 14 | import com.jw.demo.app.util.aws.policy.IotPolicyUtil; 15 | import com.jw.demo.common._enum.ApiResultEnum; 16 | import com.jw.demo.common.entity.base.AppUser; 17 | import com.jw.demo.common.entity.dynamodb.AppUserDevice; 18 | import com.jw.demo.common.response.DefaultResponse; 19 | import com.jw.demo.common.response.FailResponse; 20 | import com.jw.demo.common.response.InfoResponse; 21 | import com.jw.demo.common.response.Response; 22 | import com.jw.demo.common.util.CacheKeyConstants; 23 | import org.apache.commons.lang3.StringUtils; 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | import org.springframework.stereotype.Service; 27 | 28 | import javax.annotation.Resource; 29 | import java.util.Date; 30 | import java.util.List; 31 | 32 | @Service 33 | public class AppUserDeviceServiceImpl implements AppUserDeviceService { 34 | private static final Logger LOGGER = LoggerFactory.getLogger(AppUserDeviceServiceImpl.class); 35 | 36 | @Resource 37 | private DeviceInfoMapper deviceInfoMapper; 38 | 39 | /** 40 | * 绑定设备 41 | * 42 | * @param appuser 43 | * @param request 44 | * @return 45 | * @throws Exception 46 | */ 47 | @Override 48 | public Response bindAppUserDevice(AppUser appuser, AppBindDeviceRequest request) throws Exception { 49 | LOGGER.info("用户[{}]->通过MAC绑定设备[{}]",appuser.getId(),request.getMac()); 50 | //开始绑定 51 | if (StringUtils.isEmpty(request.getMac()) ){// || StringUtil.isEmpty(request.getProductKey())){ 52 | return new FailResponse(ApiResultEnum.PARAM_ERROR); 53 | } 54 | 55 | //获取用户绑定列表 56 | // QueryResult queryResult = AppUserDeviceDy.selectUserDevice(appuser.getId()); 57 | // List appUserDeviceList = AppUserDeviceDy.getAppUserDeviceList(queryResult.getItems()); 58 | //建立新的绑定关系 59 | AppUserDevice putAppDevice = new AppUserDevice(); 60 | putAppDevice.setAppuserId(String.valueOf(appuser.getId())); 61 | putAppDevice.setMac(request.getMac()); 62 | putAppDevice.setProductId("000"); 63 | putAppDevice.setProductKey("abc"); 64 | putAppDevice.setDeviceNickname(request.getDeviceNickName()); 65 | putAppDevice.setuType("1"); 66 | putAppDevice.setSharer("0"); 67 | putAppDevice.setDeviceId("1"); 68 | long time = new Date().getTime(); 69 | putAppDevice.setUpdateTime(time); 70 | putAppDevice.setCreateTime(time); 71 | AppUserDeviceDy.createAppUserDevice(putAppDevice); 72 | // appUserDeviceList.add(putAppDevice); 73 | //策略名称 74 | String policyName = appuser.getName()+"_"+request.getMac(); 75 | 76 | //策略内容 77 | String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iot:Connect\"],\"Resource\":[\"arn:aws:iot:*:*:client/${cognito-identity.amazonaws.com:sub}\"]},{\"Effect\":\"Allow\",\"Action\":[\"iot:Receive\",\"iot:Subscribe\",\"iot:GetThingShadow\",\"iot:UpdateThingShadow\",\"iot:Publish\"],\"Resource\":[\"*\"]}]}"; 78 | //TODO 生成新的策略 79 | CreatePolicyResult createPolicyResult = IotPolicyUtil.createPolicy(policyName, policy); 80 | 81 | // //附加策略到用户 82 | // String identityPoolId = "ap-southeast-1:b5f91781-ed82-471b-952b-94c42291036e"; 83 | // String providerName = "mytest"; 84 | // String identifier =appuser.getAccount(); 85 | // //获取用户身份池令牌 86 | // GetOpenIdTokenForDeveloperIdentityResult identity = IdentityPoolUtil.getOpenIdTokenForDeveloperIdentity(identityPoolId, providerName, identifier, (long) CacheKeyConstants.REDIS_KEY_EXPIRE_TWO_HOUR); 87 | // //附加策略到用户 88 | // IotPolicyUtil.attachPlicy(policyName,identity.getIdentityId()); 89 | return new DefaultResponse(); 90 | } 91 | 92 | /** 93 | * 用户查询设备 94 | * 95 | * @param appUser 96 | * @param request 97 | * @return 98 | * @throws Exception 99 | */ 100 | @Override 101 | public Response listAppUserDevice(AppUser appUser, AppListDeivceRequest request) throws Exception { 102 | //获取用户绑定列表 103 | QueryResult queryResult = AppUserDeviceDy.selectUserDevice(appUser.getId()); 104 | List userDevice = AppUserDeviceDy.getAppUserDeviceList(queryResult.getItems()); 105 | InfoResponse infoResponse = new InfoResponse<>(); 106 | infoResponse.setInfo(JSONArray.parseArray(JSON.toJSONString(userDevice))); 107 | return infoResponse; 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/_enum/ApiResultEnum.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common._enum; 2 | 3 | /** 4 | * 通用错误码枚举 5 | * 6 | * @author zyj 7 | * @version 0.0.1 8 | */ 9 | public enum ApiResultEnum { 10 | //写在前面: 11 | // 统一 0-9999 为系统状态码 12 | // 其余按业务划分, 如:用户相关功能状态码则是 10001-10999 13 | // 商户相关状态码为 11001 - 11999 14 | // 其余依次类推 15 | 16 | /** 17 | * 请求结果:成功 18 | */ 19 | SUCCESS(0, "响应成功"), 20 | /** 21 | * 请求结果:失败 22 | */ 23 | FAIL(1, "响应失败"), PARAM_ERROR(1001, "请求参数错误"), 24 | 25 | SYS_ERROR(1016, "系统错误"), 26 | 27 | 28 | 29 | /** 30 | * 通用错误码 31 | */ 32 | COMMON_DATABASE_NOT_EXIST(2001, "数据不存在"), 33 | COMMON_DATABASE_ERROR(2002, "数据错误"), 34 | COMMON_USER_NOT_PERMISSION(2010, "当前用户无权限"), 35 | COMMON_REDIS_LOCK(2001, "正在处理"), 36 | 37 | /** 用户已存在 **/ 38 | APP_USER_EXIST(10001, "用户已存在"), 39 | /** 用户不存在 **/ 40 | APP_USER_NOT_EXIST(10002, "用户不存在"), 41 | /** 密码错误 **/ 42 | APP_USER_PASSWORD_WRONG(10003, "密码错误"), 43 | /** 验证码错误 **/ 44 | APP_CODE_WRONG(10004, "验证码错误"), 45 | /** 未受验证的用户请求 **/ 46 | UNVERIFIED_USER_REQUEST(10005, "未受验证的用户请求"), 47 | /** 未登录 **/ 48 | APP_USER_NOT_LOGIN(10006,"未登录或登录失效"), 49 | /** 未登录 **/ 50 | APP_USER_NOT_TOKEN(10007,"token不存在"), 51 | 52 | /** 商户已存在 **/ 53 | MERCHANT_EXIST(11001, "当前品牌已存在"), 54 | /** 产品已存在 **/ 55 | PRODUCT_EXIST(11001, "当前产品已存在"), 56 | /** 产品下有绑定设备 **/ 57 | PRODUCT_MERCHANT_EXIST(11006,"当前产品下有绑定设备,无法删除"), 58 | /** 商户不存在 **/ 59 | MERCHANT_NOT_EXIST(11002, "品牌不存在"), 60 | /** 商户被禁用 **/ 61 | MERCHANT_IS_DISABLE(11003, "当前品牌无效"), 62 | /** 产品不存在 **/ 63 | PRODUCT_NOT_EXIST(10001, "产品不存在"), 64 | /** 亚马逊配置不存在 **/ 65 | AWS_CONFIG_NOT_EXIST(10001, "AWS配置不存在"), 66 | /** 获取设备证书失败 **/ 67 | DEVICE_CERTIFICATE_GET_FAIL(10001, "设备证书获取失败"), 68 | /** 更新设备影子失败 **/ 69 | DEVICE_SHADOW_UPDATE_FAIL(10001, "设备影子更新失败"), 70 | 71 | 72 | /** 用户重复调用绑定设备 **/ 73 | APP_USER_DEVICE_BIND_SINGLE(12001,"当前账号正在尝试绑定一台设备"), 74 | /** 当前设备正在建立绑定关系 **/ 75 | APP_USER_DEVICE_SINGLE(12002,"当前设备正在绑定中..."), 76 | /** 您未绑定该设备 **/ 77 | APP_USER_DEVICE_NO_BIND(12003,"您未绑定该设备"), 78 | /** **/ 79 | /** **/ 80 | /** **/ 81 | /** **/ 82 | /** 83 | * MerchantInfoService错误码 84 | */ 85 | MERCHANT_INFO_NAME_ALREADY_EXISTED(3001, "商户名已经存在"), 86 | MERCHANT_INFO_NO_OPERATION_ALLOWED(3002, "不允许操作"), 87 | MERCHANT_INFO_PHONE_ALREADY_EXISTED(3003, "手机号已被绑定"), 88 | MERCHANT_INFO_ACCOUNT_ALREADY_EXISTED(3004, "该账号已存在"), 89 | MERCHANT_INFO_SYS_USER_NOT_MERCHANT(3005, "操作用户没有所属商户"), 90 | MERCHANT_INFO_SET_PARENT_ID_NOT_YOUR_SUB_MERCHANT(3006, "输入的商户并非你的子级"), 91 | MERCHANT_INFO_NOT_EXISTED(3007, "商户不存在"), 92 | MERCHANT_INFO_PARENT_MERCHANT_NOT_EXISTED(3008, "设定的上级商户不存在"), 93 | MERCHANT_INFO_PARENT_MERCHANT_FORBIDDEN(3009, "商户被禁用或删除了"), 94 | MERCHANT_INFO_HAS_SUB_MERCHANT(3009, "商户存在子商户"), 95 | MERCHANT_INFO_HAVE_RELATION_PRODUCT_TYPE(3010, "商户存在关联产品线管理数据"), 96 | 97 | /** 98 | * MerchantApikey错误码 99 | */ 100 | MERCHANT_APIKEY_REDIS_LOCK(2001, "正在处理"), 101 | 102 | MERCHANT_APIKEY_USER_NOT_PERMISSION(2002, "当前用户无权限"), 103 | 104 | MERCHANT_APIKEY_DATA_IS_EXIST(2003, "已存在商户开发者密钥"), 105 | MERCHANT_APIKEY_DATA_NOT_EXIST(2004, "商户开发者密钥不存在"), 106 | MERCHANT_APIKEY_DATA_HAVING_MORE(2005, "存在多个商户开发者密钥"), 107 | 108 | MERCHANT_APIKEY_MERCHANT_NOT_EXIST(2006, "商户不存在"), 109 | MERCHANT_APIKEY_MERCHANT_IS_LOCK(2007, "商户已停用"), 110 | MERCHANT_APIKEY_MERCHANT_IS_DELETE(2008, "商户已删除"), 111 | MERCHANT_APIKEY_USER_NOT_EXIST(2009, "用户不存在"), 112 | MERCHANT_APIKEY_USER_TYPE_ERROR(2010, "用户类型不正确"), 113 | MERCHANT_APIKEY_USER_STATUS_ERROR(2011, "用户状态不正确"), 114 | MERCHANT_APIKEY_DATA_ERROR(2012, "数据错误"), 115 | 116 | /** 117 | * index 类错误码 118 | */ 119 | USER_NOT_EXIST(1011, "用户不存在"), 120 | USER_LOGIN_TOMORROW(1024, "今天已不可登录,请明天再试"), 121 | USER_PASSWORD_ERROR(1025, "登录密码错误"), 122 | USER_DELETE(1026, "该账户被删除"), 123 | USER_NOT_ACTIVE(1027, "该账户未激活"), 124 | ROLE_NOT_EXIST(1028,"角色不存在"), 125 | ROLE_ALERADY_DELETE(1029,"角色已经删除"), 126 | ACCOUNT_ALREADY_EXISTED(1030,"该账户已经存在"), 127 | PHONE_ALREADY_BIND(1031,"手机号已经被绑定"), 128 | USER_NOT_DELETE(1032,"该账户不允许被删除"), 129 | NO_OPERATION_ALLOWED(1033,"不允许操作"), 130 | ACCOUNT_OR_PASSWORD_ERROR(1034,"用户名或者密码错误"), 131 | /** 132 | 133 | 134 | /** 设备不存在 **/ 135 | DEVICE_NOT_EXIST(13001,"设备不存在"), 136 | /** **/ 137 | DEVUCE_OFFLINE(13002,"设备离线"), 138 | /** **/ 139 | DEVICE_INACTIVATED(13003,"设备未激活"), 140 | /** **/ 141 | DEVICE_OCCUPIED(13004,"设备已被占用"), 142 | /** **/ 143 | /** **/ 144 | ; 145 | 146 | private int id; 147 | private String name; 148 | 149 | ApiResultEnum(int id, String name) { 150 | this.id = id; 151 | this.name = name; 152 | } 153 | 154 | public int getId() { 155 | return id; 156 | } 157 | 158 | public void setId(int id) { 159 | this.id = id; 160 | } 161 | 162 | public String getName() { 163 | return name; 164 | } 165 | 166 | public void setName(String name) { 167 | this.name = name; 168 | } 169 | 170 | public boolean isSuccess() { 171 | return this.id == ApiResultEnum.SUCCESS.getId(); 172 | } 173 | 174 | public boolean isFail() { 175 | return this.id != ApiResultEnum.SUCCESS.getId(); 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/util/SnowflakeIdWorker.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.util; 2 | 3 | import org.apache.commons.lang3.RandomUtils; 4 | import java.util.Date; 5 | 6 | public class SnowflakeIdWorker { 7 | private static SnowflakeIdWorker idWorker; 8 | static { 9 | idWorker = new SnowflakeIdWorker(1); 10 | } 11 | private static final long twepoch = 1561910400000L; 12 | 13 | /** 14 | * 时间位取& 15 | */ 16 | private static final long timeBit = 0b1111111111111111111111111111111111111111110000000000000000000000L; 17 | 18 | /** 机器id所占的位数 */ 19 | private final long workerIdBits = 10L; 20 | 21 | /** 数据标识id所占的位数 */ 22 | private final long datacenterIdBits = 0L; 23 | 24 | /** 支持的最大机器id,结果是1023 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */ 25 | private final long maxWorkerId = -1L ^ (-1L << workerIdBits); 26 | 27 | /** 支持的最大数据标识id,结果是0 */ 28 | private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); 29 | 30 | /** 序列在id中占的位数 */ 31 | private final long sequenceBits = 12L; 32 | 33 | /** 机器ID向左移12位 */ 34 | private final long workerIdShift = sequenceBits; 35 | 36 | /** 数据标识id向左移22位(12+10) */ 37 | private final long datacenterIdShift = sequenceBits + workerIdBits; 38 | 39 | /** 时间截向左移22位(10+0+12) */ 40 | private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; 41 | 42 | /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */ 43 | private final long sequenceMask = -1L ^ (-1L << sequenceBits); 44 | 45 | /** 工作机器ID(0~1023) */ 46 | private long workerId; 47 | 48 | /** 数据中心ID(0) */ 49 | private long datacenterId; 50 | 51 | /** 毫秒内序列(0~4095) */ 52 | private long sequence; 53 | 54 | private long initSequence; 55 | 56 | /** 上次生成ID的时间截 */ 57 | private long lastTimestamp = -1L; 58 | 59 | //==============================Constructors===================================== 60 | 61 | /** 62 | * 构造函数 63 | * @param workerId 工作ID (0~1023) 64 | */ 65 | private SnowflakeIdWorker(long workerId) { 66 | this(workerId,0); 67 | } 68 | /** 69 | * 构造函数 70 | * @param workerId 工作ID (0~1023) 71 | * @param datacenterId 数据中心ID (0) 72 | */ 73 | private SnowflakeIdWorker(long workerId, long datacenterId) { 74 | if (workerId > maxWorkerId || workerId < 0) { 75 | throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); 76 | } 77 | if (datacenterId > maxDatacenterId || datacenterId < 0) { 78 | throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); 79 | } 80 | this.workerId = workerId; 81 | this.datacenterId = 0; 82 | //随机生成2000种可能 83 | this.initSequence=RandomUtils.nextInt(0,2000); 84 | this.sequence=initSequence; 85 | //FIXME 1ms内有2000种可猜测 86 | } 87 | 88 | // ==============================Methods========================================== 89 | /** 90 | * 获得下一个ID (该方法是线程安全的) 91 | * @return SnowflakeId 92 | */ 93 | private synchronized long nextId() { 94 | long timestamp = timeGen(); 95 | 96 | //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 97 | if (timestamp < lastTimestamp) { 98 | throw new RuntimeException( 99 | String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); 100 | } 101 | 102 | //如果是同一时间生成的,则进行毫秒内序列 103 | if (lastTimestamp == timestamp) { 104 | sequence = (sequence + 1) & sequenceMask; 105 | //毫秒内序列溢出 106 | if (sequence == 0) { 107 | //阻塞到下一个毫秒,获得新的时间戳 108 | timestamp = tilNextMillis(lastTimestamp); 109 | } 110 | } 111 | //时间戳改变,毫秒内序列重置 112 | else { 113 | sequence = initSequence; 114 | } 115 | 116 | //上次生成ID的时间截 117 | lastTimestamp = timestamp; 118 | 119 | //移位并通过或运算拼到一起组成64位的ID 120 | return ((timestamp - twepoch) << timestampLeftShift) // 121 | | (datacenterId << datacenterIdShift) // 122 | | (workerId << workerIdShift) // 123 | | sequence; 124 | } 125 | 126 | /** 127 | * 从ID中获取时间 128 | * @param id 由此类生成的ID 129 | */ 130 | public static Date getTime(long id){ 131 | return new Date(((timeBit&id)>>22)+twepoch); 132 | } 133 | 134 | /** 135 | * 阻塞到下一个毫秒,直到获得新的时间戳 136 | * @param lastTimestamp 上次生成ID的时间截 137 | * @return 当前时间戳 138 | */ 139 | private long tilNextMillis(long lastTimestamp) { 140 | long timestamp = timeGen(); 141 | while (timestamp <= lastTimestamp) { 142 | timestamp = timeGen(); 143 | } 144 | return timestamp; 145 | } 146 | 147 | /** 148 | * 返回以毫秒为单位的当前时间 149 | * @return 当前时间(毫秒) 150 | */ 151 | private long timeGen() { 152 | return System.currentTimeMillis(); 153 | } 154 | 155 | /** 156 | * 获取唯一ID 157 | */ 158 | public static Long getId() { 159 | return idWorker.nextId(); 160 | } 161 | 162 | /** 163 | * 获取随机字符串,length=13 164 | */ 165 | public static String getRandomStr() { 166 | return Long.toString(idWorker.nextId(), Character.MAX_RADIX); 167 | } 168 | 169 | //==============================Test============================================= 170 | /** 测试 */ 171 | public static void main(String[] args) { 172 | for (int i = 0; i < 100; i++) { 173 | long id = SnowflakeIdWorker.getId(); 174 | String strId = SnowflakeIdWorker.getRandomStr(); 175 | 176 | System.out.println(id); 177 | System.out.println(strId); 178 | System.out.println(SnowflakeIdWorker.getTime(id)); 179 | } 180 | } 181 | 182 | } 183 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/service/impl/DeviceServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.service.impl; 2 | 3 | import java.util.*; 4 | 5 | import javax.annotation.Resource; 6 | 7 | import com.amazonaws.regions.Regions; 8 | import com.jw.demo.app.dao.device.DeviceInfoMapper; 9 | import com.jw.demo.common._enum.ApiResultEnum; 10 | import com.jw.demo.common._enum.AppStatusEnum; 11 | import com.jw.demo.common._enum.DeletedEnum; 12 | import com.jw.demo.common.entity.device.DeviceInfo; 13 | import com.jw.demo.common.response.DefaultResponse; 14 | import com.jw.demo.common.response.FailResponse; 15 | import com.jw.demo.common.response.InfoResponse; 16 | import com.jw.demo.common.response.Response; 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | import org.springframework.stereotype.Service; 20 | 21 | import com.alibaba.fastjson.JSONObject; 22 | import com.jw.demo.app.request.device.CertificateGetRequest; 23 | import com.jw.demo.app.request.device.PropertyGetRequest; 24 | import com.jw.demo.app.request.device.ShadowUpdateRequest; 25 | import com.jw.demo.app.service.DeviceService; 26 | import com.jw.demo.app.util.aws.iot.IotUtil; 27 | import com.jw.demo.app.util.aws.iot.ShadowUtil; 28 | import com.jw.demo.app.util.aws.s3.S3Util; 29 | import com.jw.demo.common.util.SnowflakeIdWorker; 30 | import org.springframework.util.CollectionUtils; 31 | 32 | @Service 33 | public class DeviceServiceImpl implements DeviceService { 34 | private Logger log = LoggerFactory.getLogger(getClass()); 35 | 36 | @Resource 37 | private DeviceInfoMapper deviceInfoMapper; 38 | 39 | 40 | @SuppressWarnings("unchecked") 41 | @Override 42 | public Response certificateGet(CertificateGetRequest request) throws Exception { 43 | String productKey = "999999"; 44 | String mac = request.getMac(); 45 | 46 | // String accessKey = "awsConfig.getAccessKey()"; 47 | // String null = "awsConfig.getnull()"; 48 | // String region =" awsConfig.getRegion()"; 49 | String region = Regions.AP_SOUTHEAST_1.getName(); 50 | 51 | // 1. 生成事物 52 | InfoResponse createThingResponse = (InfoResponse) IotUtil.getInstance() 53 | .createThing(region, mac); 54 | if (ApiResultEnum.SUCCESS.getId() != createThingResponse.getCode()) { 55 | log.error("certificateGet -> 创建事物失败"); 56 | return new FailResponse(ApiResultEnum.DEVICE_CERTIFICATE_GET_FAIL); 57 | } 58 | 59 | // 2. 生成证书 60 | InfoResponse createKeysAndCertificateResponse = (InfoResponse) IotUtil.getInstance() 61 | .createKeysAndCertificate(region); 62 | if (ApiResultEnum.SUCCESS.getId() != createKeysAndCertificateResponse.getCode()) { 63 | log.error("certificateGet -> 创建证书失败"); 64 | return new FailResponse(ApiResultEnum.DEVICE_CERTIFICATE_GET_FAIL); 65 | } 66 | String certificateArn = createKeysAndCertificateResponse.getInfo().getString("certificateArn"); 67 | String certificatePem = createKeysAndCertificateResponse.getInfo().getString("certificatePem"); 68 | JSONObject keyPair = createKeysAndCertificateResponse.getInfo().getJSONObject("keyPair"); 69 | String privateKey = keyPair.getString("privateKey"); 70 | 71 | // 3. 生成策略 72 | Response getPolicyResponse = IotUtil.getInstance().getPolicy( region, mac); 73 | if (ApiResultEnum.SUCCESS.getId() != getPolicyResponse.getCode()) { 74 | String policyDocument = IotUtil.generatePolicyDocument(productKey, mac); 75 | InfoResponse createPolicyResponse = (InfoResponse) IotUtil.getInstance() 76 | .createPolicy(region, mac, policyDocument); 77 | if (ApiResultEnum.SUCCESS.getId() != createPolicyResponse.getCode()) { 78 | log.error("certificateGet -> 创建策略失败"); 79 | return new FailResponse(ApiResultEnum.DEVICE_CERTIFICATE_GET_FAIL); 80 | } 81 | } 82 | 83 | // 4. 附加证书策略 84 | Response attachPrincipalPolicyResponse = IotUtil.getInstance().attachPrincipalPolicy(region, mac, certificateArn); 85 | if (ApiResultEnum.SUCCESS.getId() != attachPrincipalPolicyResponse.getCode()) { 86 | log.error("certificateGet -> 附加证书策略失败"); 87 | return new FailResponse(ApiResultEnum.DEVICE_CERTIFICATE_GET_FAIL); 88 | } 89 | 90 | // 5. 附加事物证书 91 | Response attachThingPrincipalResponse = IotUtil.getInstance().attachThingPrincipal(region, certificateArn, mac); 92 | if (ApiResultEnum.SUCCESS.getId() != attachThingPrincipalResponse.getCode()) { 93 | log.error("certificateGet -> 附加事物证书失败"); 94 | return new FailResponse(ApiResultEnum.DEVICE_CERTIFICATE_GET_FAIL); 95 | } 96 | 97 | // 6. 上传设备证书至S3 98 | String s3CertificatePemKey = mac + "_certificatePem"; 99 | Response uploadCertificatePemResponse = S3Util.getInstance().uploadObject( region, 100 | "cconfig-certificate", s3CertificatePemKey, certificatePem); 101 | if (ApiResultEnum.SUCCESS.getId() != uploadCertificatePemResponse.getCode()) { 102 | log.error("certificateGet -> 上传设备证书PEM失败"); 103 | return new FailResponse(ApiResultEnum.DEVICE_CERTIFICATE_GET_FAIL); 104 | } 105 | String s3PrivateKeyKey = mac + "_privateKey"; 106 | Response uploadPrivateKeyResponse = S3Util.getInstance().uploadObject(region, 107 | "cconfig-certificate", s3PrivateKeyKey, privateKey); 108 | if (ApiResultEnum.SUCCESS.getId() != uploadPrivateKeyResponse.getCode()) { 109 | log.error("certificateGet -> 上传设备证书KEY失败"); 110 | return new FailResponse(ApiResultEnum.DEVICE_CERTIFICATE_GET_FAIL); 111 | } 112 | 113 | // 7. 生成设备证书预签名URL 114 | InfoResponse generateCertificatePemPresignedUrlResponse = (InfoResponse) S3Util.getInstance() 115 | .generatePresignedUrl( region, "cconfig-certificate", s3CertificatePemKey); 116 | if (ApiResultEnum.SUCCESS.getId() != generateCertificatePemPresignedUrlResponse.getCode()) { 117 | log.error("certificateGet -> 生成设备证书PEM的预签名地址失败"); 118 | return new FailResponse(ApiResultEnum.DEVICE_CERTIFICATE_GET_FAIL); 119 | } 120 | String certificatePemUrl = generateCertificatePemPresignedUrlResponse.getInfo(); 121 | 122 | InfoResponse generatePrivateKeyPresignedUrlResponse = (InfoResponse) S3Util.getInstance() 123 | .generatePresignedUrl(region, "cconfig-certificate", s3PrivateKeyKey); 124 | if (ApiResultEnum.SUCCESS.getId() != generatePrivateKeyPresignedUrlResponse.getCode()) { 125 | log.error("certificateGet -> 生成设备证书KEY的预签名地址失败"); 126 | return new FailResponse(ApiResultEnum.DEVICE_CERTIFICATE_GET_FAIL); 127 | } 128 | String privateKeyUrl = generatePrivateKeyPresignedUrlResponse.getInfo(); 129 | 130 | // 8. 添加设备 131 | Date nowTime = new Date(); 132 | DeviceInfo deviceInfo; 133 | Map paramsDI = new HashMap(); 134 | paramsDI.put("eqProductKey", privateKey); 135 | paramsDI.put("eqMac", mac); 136 | paramsDI.put("eqDeleted", DeletedEnum.F.getId()); 137 | List deviceInfos = deviceInfoMapper.selectByMap(paramsDI); 138 | if (CollectionUtils.isEmpty(deviceInfos)) { 139 | deviceInfo = new DeviceInfo(); 140 | deviceInfo.setId(SnowflakeIdWorker.getId()); 141 | deviceInfo.setName(mac); 142 | deviceInfo.setMac(mac); 143 | // deviceInfo.setProductId(productInfo.getId()); 144 | // deviceInfo.setProductName(productInfo.getName()); 145 | // deviceInfo.setMerchantId(productInfo.getMerchantId()); 146 | // deviceInfo.setMerchantName(productInfo.getMerchantName()); 147 | deviceInfo.setStatus(AppStatusEnum.NORMAL.getId()); 148 | deviceInfo.setCreateTime(nowTime); 149 | deviceInfo.setUpdateTime(nowTime); 150 | deviceInfo.setDeleted(DeletedEnum.F.getId()); 151 | // deviceInfoMapper.insertSelective(deviceInfo); 152 | System.out.println(deviceInfo); 153 | } 154 | 155 | JSONObject info = new JSONObject(); 156 | info.put("thingName", mac); 157 | info.put("privateKey", privateKeyUrl); 158 | info.put("certificatePem", certificatePemUrl); 159 | info.put("certificateArn", certificateArn); 160 | info.put("region", region); 161 | info.put("regionId", region); 162 | info.put("domain", "a3r68s0rrta0ju-ats.iot.us-west-2.amazonaws.com"); 163 | return new InfoResponse<>(info); 164 | } 165 | 166 | @Override 167 | public Response propertyGet(PropertyGetRequest request) throws Exception { 168 | // TODO Auto-generated method stub 169 | return null; 170 | } 171 | 172 | @Override 173 | public Response updateShadow(ShadowUpdateRequest request) throws Exception { 174 | String accessKey = "awsConfig.getAccessKey()"; 175 | String secretKey =" awsConfig.getSecretKey()"; 176 | String region =" awsConfig.getRegion()"; 177 | Response updateThingShadowResponse = ShadowUtil.getInstance().updateThingShadow(accessKey, secretKey, region, 178 | "mac", request.getData()); 179 | if (ApiResultEnum.SUCCESS.getId() != updateThingShadowResponse.getCode()) { 180 | log.error("updateShadow -> 更新事物影子失败"); 181 | return new FailResponse(ApiResultEnum.DEVICE_SHADOW_UPDATE_FAIL); 182 | } 183 | return new DefaultResponse(); 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /CloudConfig_lambda_core.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/entity/base/AwsConfig.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.entity.base; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * Database Table Remarks: 7 | * base.t_aws_config: 亚马逊配置表 8 | * 9 | * @mbg.generated do_not_delete_during_merge 2021-10-22 12:01:49 10 | */ 11 | public class AwsConfig { 12 | /** 13 | * Database Column Remarks: 14 | * base.t_aws_config.id: 亚马逊配置ID 15 | */ 16 | private Long id; 17 | 18 | /** 19 | * Database Column Remarks: 20 | * base.t_aws_config.iot_endpoint: IOT连接节点 21 | */ 22 | private String iotEndpoint; 23 | 24 | /** 25 | * Database Column Remarks: 26 | * base.t_aws_config.region: 配置区域 27 | */ 28 | private String region; 29 | 30 | /** 31 | * Database Column Remarks: 32 | * base.t_aws_config.access_key: 访问密钥 33 | */ 34 | private String accessKey; 35 | 36 | /** 37 | * Database Column Remarks: 38 | * base.t_aws_config.secret_key: 访问密钥 39 | */ 40 | private String secretKey; 41 | 42 | /** 43 | * Database Column Remarks: 44 | * base.t_aws_config.identity_pool_id: 身份池ID 45 | */ 46 | private String identityPoolId; 47 | 48 | /** 49 | * Database Column Remarks: 50 | * base.t_aws_config.provider_name: 身份池开发者名称 51 | */ 52 | private String providerName; 53 | 54 | /** 55 | * Database Column Remarks: 56 | * base.t_aws_config.remark: 备注 57 | */ 58 | private String remark; 59 | 60 | /** 61 | * Database Column Remarks: 62 | * base.t_aws_config.merchant_id: 商户ID 63 | */ 64 | private Long merchantId; 65 | 66 | /** 67 | * Database Column Remarks: 68 | * base.t_aws_config.merchant_name: 商户名称 69 | */ 70 | private String merchantName; 71 | 72 | /** 73 | * Database Column Remarks: 74 | * base.t_aws_config.status: 状态:【1】启用、【2】禁用 75 | */ 76 | private Integer status; 77 | 78 | /** 79 | * Database Column Remarks: 80 | * base.t_aws_config.create_time: 创建时间 81 | */ 82 | private Date createTime; 83 | 84 | /** 85 | * Database Column Remarks: 86 | * base.t_aws_config.create_by: 创建者ID 87 | */ 88 | private Long createBy; 89 | 90 | /** 91 | * Database Column Remarks: 92 | * base.t_aws_config.update_time: 更新时间 93 | */ 94 | private Date updateTime; 95 | 96 | /** 97 | * Database Column Remarks: 98 | * base.t_aws_config.update_by: 更新者ID 99 | */ 100 | private Long updateBy; 101 | 102 | /** 103 | * Database Column Remarks: 104 | * base.t_aws_config.deleted: 已删除:【0】否、【1】是 105 | */ 106 | private Integer deleted; 107 | 108 | /** 109 | * @return the value of base.t_aws_config.id 110 | */ 111 | public Long getId() { 112 | return id; 113 | } 114 | 115 | /** 116 | * @param id the value for base.t_aws_config.id 117 | */ 118 | public void setId(Long id) { 119 | this.id = id; 120 | } 121 | 122 | /** 123 | * @return the value of base.t_aws_config.iot_endpoint 124 | */ 125 | public String getIotEndpoint() { 126 | return iotEndpoint; 127 | } 128 | 129 | /** 130 | * @param iotEndpoint the value for base.t_aws_config.iot_endpoint 131 | */ 132 | public void setIotEndpoint(String iotEndpoint) { 133 | this.iotEndpoint = iotEndpoint == null ? null : iotEndpoint.trim(); 134 | } 135 | 136 | /** 137 | * @return the value of base.t_aws_config.region 138 | */ 139 | public String getRegion() { 140 | return region; 141 | } 142 | 143 | /** 144 | * @param region the value for base.t_aws_config.region 145 | */ 146 | public void setRegion(String region) { 147 | this.region = region == null ? null : region.trim(); 148 | } 149 | 150 | /** 151 | * @return the value of base.t_aws_config.access_key 152 | */ 153 | public String getAccessKey() { 154 | return accessKey; 155 | } 156 | 157 | /** 158 | * @param accessKey the value for base.t_aws_config.access_key 159 | */ 160 | public void setAccessKey(String accessKey) { 161 | this.accessKey = accessKey == null ? null : accessKey.trim(); 162 | } 163 | 164 | /** 165 | * @return the value of base.t_aws_config.secret_key 166 | */ 167 | public String getSecretKey() { 168 | return secretKey; 169 | } 170 | 171 | /** 172 | * @param secretKey the value for base.t_aws_config.secret_key 173 | */ 174 | public void setSecretKey(String secretKey) { 175 | this.secretKey = secretKey == null ? null : secretKey.trim(); 176 | } 177 | 178 | /** 179 | * @return the value of base.t_aws_config.identity_pool_id 180 | */ 181 | public String getIdentityPoolId() { 182 | return identityPoolId; 183 | } 184 | 185 | /** 186 | * @param identityPoolId the value for base.t_aws_config.identity_pool_id 187 | */ 188 | public void setIdentityPoolId(String identityPoolId) { 189 | this.identityPoolId = identityPoolId == null ? null : identityPoolId.trim(); 190 | } 191 | 192 | /** 193 | * @return the value of base.t_aws_config.provider_name 194 | */ 195 | public String getProviderName() { 196 | return providerName; 197 | } 198 | 199 | /** 200 | * @param providerName the value for base.t_aws_config.provider_name 201 | */ 202 | public void setProviderName(String providerName) { 203 | this.providerName = providerName == null ? null : providerName.trim(); 204 | } 205 | 206 | /** 207 | * @return the value of base.t_aws_config.remark 208 | */ 209 | public String getRemark() { 210 | return remark; 211 | } 212 | 213 | /** 214 | * @param remark the value for base.t_aws_config.remark 215 | */ 216 | public void setRemark(String remark) { 217 | this.remark = remark == null ? null : remark.trim(); 218 | } 219 | 220 | /** 221 | * @return the value of base.t_aws_config.merchant_id 222 | */ 223 | public Long getMerchantId() { 224 | return merchantId; 225 | } 226 | 227 | /** 228 | * @param merchantId the value for base.t_aws_config.merchant_id 229 | */ 230 | public void setMerchantId(Long merchantId) { 231 | this.merchantId = merchantId; 232 | } 233 | 234 | /** 235 | * @return the value of base.t_aws_config.merchant_name 236 | */ 237 | public String getMerchantName() { 238 | return merchantName; 239 | } 240 | 241 | /** 242 | * @param merchantName the value for base.t_aws_config.merchant_name 243 | */ 244 | public void setMerchantName(String merchantName) { 245 | this.merchantName = merchantName == null ? null : merchantName.trim(); 246 | } 247 | 248 | /** 249 | * @return the value of base.t_aws_config.status 250 | */ 251 | public Integer getStatus() { 252 | return status; 253 | } 254 | 255 | /** 256 | * @param status the value for base.t_aws_config.status 257 | */ 258 | public void setStatus(Integer status) { 259 | this.status = status; 260 | } 261 | 262 | /** 263 | * @return the value of base.t_aws_config.create_time 264 | */ 265 | public Date getCreateTime() { 266 | return createTime; 267 | } 268 | 269 | /** 270 | * @param createTime the value for base.t_aws_config.create_time 271 | */ 272 | public void setCreateTime(Date createTime) { 273 | this.createTime = createTime; 274 | } 275 | 276 | /** 277 | * @return the value of base.t_aws_config.create_by 278 | */ 279 | public Long getCreateBy() { 280 | return createBy; 281 | } 282 | 283 | /** 284 | * @param createBy the value for base.t_aws_config.create_by 285 | */ 286 | public void setCreateBy(Long createBy) { 287 | this.createBy = createBy; 288 | } 289 | 290 | /** 291 | * @return the value of base.t_aws_config.update_time 292 | */ 293 | public Date getUpdateTime() { 294 | return updateTime; 295 | } 296 | 297 | /** 298 | * @param updateTime the value for base.t_aws_config.update_time 299 | */ 300 | public void setUpdateTime(Date updateTime) { 301 | this.updateTime = updateTime; 302 | } 303 | 304 | /** 305 | * @return the value of base.t_aws_config.update_by 306 | */ 307 | public Long getUpdateBy() { 308 | return updateBy; 309 | } 310 | 311 | /** 312 | * @param updateBy the value for base.t_aws_config.update_by 313 | */ 314 | public void setUpdateBy(Long updateBy) { 315 | this.updateBy = updateBy; 316 | } 317 | 318 | /** 319 | * @return the value of base.t_aws_config.deleted 320 | */ 321 | public Integer getDeleted() { 322 | return deleted; 323 | } 324 | 325 | /** 326 | * @param deleted the value for base.t_aws_config.deleted 327 | */ 328 | public void setDeleted(Integer deleted) { 329 | this.deleted = deleted; 330 | } 331 | 332 | @Override 333 | public String toString() { 334 | StringBuilder sb = new StringBuilder(); 335 | sb.append(getClass().getSimpleName()); 336 | sb.append(" ["); 337 | sb.append("Hash = ").append(hashCode()); 338 | sb.append(", id=").append(id); 339 | sb.append(", iotEndpoint=").append(iotEndpoint); 340 | sb.append(", region=").append(region); 341 | sb.append(", accessKey=").append(accessKey); 342 | sb.append(", secretKey=").append(secretKey); 343 | sb.append(", identityPoolId=").append(identityPoolId); 344 | sb.append(", providerName=").append(providerName); 345 | sb.append(", remark=").append(remark); 346 | sb.append(", merchantId=").append(merchantId); 347 | sb.append(", merchantName=").append(merchantName); 348 | sb.append(", status=").append(status); 349 | sb.append(", createTime=").append(createTime); 350 | sb.append(", createBy=").append(createBy); 351 | sb.append(", updateTime=").append(updateTime); 352 | sb.append(", updateBy=").append(updateBy); 353 | sb.append(", deleted=").append(deleted); 354 | sb.append("]"); 355 | return sb.toString(); 356 | } 357 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.jw.demo 8 | CloudConfig_lambda_core 9 | 1.0-SNAPSHOT 10 | 11 | jar 12 | 13 | CloudConfig_lambda_core 14 | https://github.com/awslabs/aws-serverless-java-container 15 | 16 | 17 | org.springframework.boot 18 | spring-boot-starter-parent 19 | 2.1.1.RELEASE 20 | 21 | 22 | 23 | 1.8 24 | 1.8 25 | 26 | 27 | 28 | 29 | 30 | com.amazonaws.serverless 31 | aws-serverless-java-container-spring 32 | 1.3 33 | 34 | 35 | jmespath-java 36 | com.amazonaws 37 | 1.12.74 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-web 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | com.alibaba 58 | druid 59 | 1.0.29 60 | 61 | 62 | com.alibaba 63 | fastjson 64 | 1.2.67 65 | 66 | 67 | commons-codec 68 | commons-codec 69 | 1.10 70 | 71 | 72 | org.apache.commons 73 | commons-lang3 74 | 3.5 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | org.postgresql 93 | postgresql 94 | 42.2.11 95 | 96 | 97 | org.apache.poi 98 | poi-ooxml 99 | 3.9 100 | 101 | 102 | commons-codec 103 | commons-codec 104 | 105 | 106 | 107 | 108 | com.fasterxml.jackson.core 109 | jackson-core 110 | 2.9.7 111 | 112 | 113 | junit 114 | junit 115 | 4.13.1 116 | test 117 | 118 | 119 | 120 | com.amazonaws 121 | aws-java-sdk-cognitoidentity 122 | 1.12.74 123 | 124 | 125 | commons-codec 126 | commons-codec 127 | 128 | 129 | 130 | 131 | com.amazonaws 132 | aws-java-sdk-cognitosync 133 | 1.12.74 134 | 135 | 136 | com.amazonaws 137 | aws-java-sdk-cognitoidp 138 | 1.12.74 139 | 140 | 141 | 142 | com.amazonaws 143 | aws-java-sdk-iot 144 | 1.12.74 145 | 146 | 147 | 148 | com.amazonaws 149 | aws-java-sdk-dynamodb 150 | 1.12.74 151 | 152 | 153 | org.springframework.boot 154 | spring-boot-starter-thymeleaf 155 | 156 | 157 | 158 | 159 | 160 | assembly-zip 161 | 162 | true 163 | 164 | 165 | 166 | src/main/filter/filter.properties 167 | 168 | 169 | 170 | 171 | src/main/resources 172 | 173 | application.yaml 174 | 175 | 176 | templates/** 177 | 178 | true 179 | 180 | 181 | 182 | 183 | 184 | 185 | org.apache.maven.plugins 186 | maven-jar-plugin 187 | 3.1.1 188 | 189 | 190 | default-jar 191 | none 192 | 193 | 194 | 195 | 196 | 197 | org.apache.maven.plugins 198 | maven-dependency-plugin 199 | 3.1.1 200 | 201 | 202 | copy-dependencies 203 | package 204 | 205 | copy-dependencies 206 | 207 | 208 | ${project.build.directory}${file.separator}lib 209 | runtime 210 | 211 | 212 | 213 | 214 | 215 | org.apache.maven.plugins 216 | maven-assembly-plugin 217 | 3.1.0 218 | 219 | 220 | zip-assembly 221 | package 222 | 223 | single 224 | 225 | 226 | ${project.artifactId}-${project.version} 227 | 228 | src${file.separator}assembly${file.separator}bin.xml 229 | 230 | false 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/util/aws/iot/IotUtil.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.util.aws.iot; 2 | 3 | import com.jw.demo.common.response.DefaultResponse; 4 | import com.jw.demo.common.response.FailResponse; 5 | import com.jw.demo.common.response.InfoResponse; 6 | import com.jw.demo.common.response.Response; 7 | import org.apache.http.HttpStatus; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import com.alibaba.fastjson.JSONObject; 12 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 13 | import com.amazonaws.auth.BasicAWSCredentials; 14 | import com.amazonaws.services.iot.AWSIot; 15 | import com.amazonaws.services.iot.AWSIotClientBuilder; 16 | import com.amazonaws.services.iot.model.AttachPrincipalPolicyRequest; 17 | import com.amazonaws.services.iot.model.AttachPrincipalPolicyResult; 18 | import com.amazonaws.services.iot.model.AttachThingPrincipalRequest; 19 | import com.amazonaws.services.iot.model.AttachThingPrincipalResult; 20 | import com.amazonaws.services.iot.model.CreateKeysAndCertificateRequest; 21 | import com.amazonaws.services.iot.model.CreateKeysAndCertificateResult; 22 | import com.amazonaws.services.iot.model.CreatePolicyRequest; 23 | import com.amazonaws.services.iot.model.CreatePolicyResult; 24 | import com.amazonaws.services.iot.model.CreatePolicyVersionRequest; 25 | import com.amazonaws.services.iot.model.CreatePolicyVersionResult; 26 | import com.amazonaws.services.iot.model.CreateThingRequest; 27 | import com.amazonaws.services.iot.model.CreateThingResult; 28 | import com.amazonaws.services.iot.model.GetPolicyRequest; 29 | import com.amazonaws.services.iot.model.GetPolicyResult; 30 | 31 | public class IotUtil { 32 | private Logger log = LoggerFactory.getLogger(getClass()); 33 | 34 | public static IotUtil getInstance() { 35 | return new IotUtil(); 36 | } 37 | 38 | /** 39 | * 创建事物,参考文档:https://docs.aws.amazon.com/zh_cn/iot/latest/apireference/API_CreateThing.html 40 | * 41 | * @param accessKey 亚马逊接口凭证 42 | * @param secretKey 亚马逊接口凭证 43 | * @param region 亚马逊区域 44 | * @param thingName 事物名称 45 | * @return 46 | */ 47 | public Response createThing( String region, String thingName) { 48 | CreateThingResult result; 49 | try { 50 | 51 | AWSIot iotClient = AWSIotClientBuilder.standard().withRegion(region).build(); 52 | CreateThingRequest request = new CreateThingRequest(); 53 | request.setThingName(thingName); 54 | result = iotClient.createThing(request); 55 | if (HttpStatus.SC_OK != result.getSdkHttpMetadata().getHttpStatusCode()) { 56 | return new FailResponse(); 57 | } 58 | } catch (Exception e) { 59 | log.error("IotUtil.createThing", e); 60 | return new FailResponse(); 61 | } 62 | JSONObject info = new JSONObject(); 63 | info.put("thingName", result.getThingName()); 64 | info.put("thingArn", result.getThingArn()); 65 | info.put("thingId", result.getThingId()); 66 | return new InfoResponse<>(info); 67 | } 68 | 69 | /** 70 | * 创建证书,参考文档:https://docs.aws.amazon.com/zh_cn/iot/latest/apireference/API_CreateKeysAndCertificate.html 71 | * 72 | * @param accessKey 亚马逊接口凭证 73 | * @param secretKey 亚马逊接口凭证 74 | * @param region 亚马逊区域 75 | * @return 76 | */ 77 | public Response createKeysAndCertificate(String region) { 78 | CreateKeysAndCertificateResult result; 79 | try { 80 | AWSIot iotClient = AWSIotClientBuilder.standard().withRegion(region).build(); 81 | CreateKeysAndCertificateRequest request = new CreateKeysAndCertificateRequest(); 82 | request.setSetAsActive(true); 83 | result = iotClient.createKeysAndCertificate(request); 84 | if (HttpStatus.SC_OK != result.getSdkHttpMetadata().getHttpStatusCode()) { 85 | return new FailResponse(); 86 | } 87 | } catch (Exception e) { 88 | log.error("IotUtil.createKeysAndCertificate", e); 89 | return new FailResponse(); 90 | } 91 | JSONObject info = new JSONObject(); 92 | info.put("certificateArn", result.getCertificateArn()); 93 | info.put("certificateId", result.getCertificateId()); 94 | info.put("certificatePem", result.getCertificatePem()); 95 | info.put("keyPair", result.getKeyPair()); 96 | return new InfoResponse<>(info); 97 | } 98 | 99 | /** 100 | * 附加事物证书,参考文档:https://docs.aws.amazon.com/zh_cn/iot/latest/apireference/API_AttachThingPrincipal.html 101 | * 102 | * @param accessKey 亚马逊接口凭证 103 | * @param secretKey 亚马逊接口凭证 104 | * @param region 亚马逊区域 105 | * @param principal 证书ARN / Cognito ID 106 | * @param thingName 事物名称 107 | * @return 108 | */ 109 | public Response attachThingPrincipal(String region, String principal, 110 | String thingName) { 111 | try { 112 | AWSIot iotClient = AWSIotClientBuilder.standard().withRegion(region).build(); 113 | AttachThingPrincipalRequest request = new AttachThingPrincipalRequest(); 114 | request.setThingName(thingName); 115 | request.setPrincipal(principal); 116 | AttachThingPrincipalResult result = iotClient.attachThingPrincipal(request); 117 | if (HttpStatus.SC_OK != result.getSdkHttpMetadata().getHttpStatusCode()) { 118 | return new FailResponse(); 119 | } 120 | } catch (Exception e) { 121 | log.error("IotUtil.attachThingPrincipal", e); 122 | return new FailResponse(); 123 | } 124 | return new DefaultResponse(); 125 | } 126 | 127 | /** 128 | * 获取策略,参考文档:https://docs.aws.amazon.com/zh_cn/iot/latest/apireference/API_GetPolicy.html 129 | * 130 | * @param accessKey 亚马逊接口凭证 131 | * @param secretKey 亚马逊接口凭证 132 | * @param region 亚马逊区域 133 | * @param policyName 策略名称 134 | * @return 135 | */ 136 | public Response getPolicy(String region, String policyName) { 137 | try { 138 | AWSIot iotClient = AWSIotClientBuilder.standard().withRegion(region).build(); 139 | GetPolicyRequest request = new GetPolicyRequest(); 140 | request.setPolicyName(policyName); 141 | GetPolicyResult result = iotClient.getPolicy(request); 142 | if (HttpStatus.SC_OK != result.getSdkHttpMetadata().getHttpStatusCode()) { 143 | return new FailResponse(); 144 | } 145 | } catch (Exception e) { 146 | log.error("IotUtil.getPolicy", e); 147 | return new FailResponse(); 148 | } 149 | return new DefaultResponse(); 150 | } 151 | 152 | /** 153 | * 创建策略,参考文档:https://docs.aws.amazon.com/zh_cn/iot/latest/apireference/API_CreatePolicy.html 154 | * 155 | * @param accessKey 亚马逊接口凭证 156 | * @param secretKey 亚马逊接口凭证 157 | * @param region 亚马逊区域 158 | * @param policyName 策略名称 159 | * @param policyDocument 策略文件 160 | * @return 161 | */ 162 | public Response createPolicy( String region, String policyName, 163 | String policyDocument) { 164 | CreatePolicyResult result; 165 | try { 166 | AWSIot iotClient = AWSIotClientBuilder.standard().withRegion(region).build(); 167 | CreatePolicyRequest request = new CreatePolicyRequest(); 168 | request.setPolicyName(policyName); 169 | request.setPolicyDocument(policyDocument); 170 | result = iotClient.createPolicy(request); 171 | if (HttpStatus.SC_OK != result.getSdkHttpMetadata().getHttpStatusCode()) { 172 | return new FailResponse(); 173 | } 174 | } catch (Exception e) { 175 | log.error("IotUtil.createPolicy", e); 176 | return new FailResponse(); 177 | } 178 | JSONObject info = new JSONObject(); 179 | info.put("policyArn", result.getPolicyArn()); 180 | info.put("policyDocument", result.getPolicyDocument()); 181 | info.put("policyName", result.getPolicyName()); 182 | info.put("policyVersionId", result.getPolicyVersionId()); 183 | return new InfoResponse<>(info); 184 | } 185 | 186 | /** 187 | * 创建策略版本,参考文档:https://docs.aws.amazon.com/zh_cn/iot/latest/apireference/API_CreatePolicyVersion.html 188 | * 189 | * @param accessKey 亚马逊接口凭证 190 | * @param secretKey 亚马逊接口凭证 191 | * @param region 亚马逊区域 192 | * @param policyName 策略名称 193 | * @param policyDocument 策略文件 194 | * @return 195 | */ 196 | public Response CreatePolicyVersion(String region, String policyName, String policyDocument) { 197 | CreatePolicyVersionResult result; 198 | try { 199 | AWSIot iotClient = AWSIotClientBuilder.standard().withRegion(region) 200 | .build(); 201 | CreatePolicyVersionRequest request = new CreatePolicyVersionRequest(); 202 | request.setPolicyName(policyName); 203 | request.setPolicyDocument(policyDocument); 204 | request.setSetAsDefault(true); 205 | 206 | result = iotClient.createPolicyVersion(request); 207 | if (HttpStatus.SC_OK != result.getSdkHttpMetadata().getHttpStatusCode()) { 208 | return new FailResponse(); 209 | } 210 | } catch (Exception e) { 211 | log.error("IotUtil.CreatePolicyVersion", e); 212 | return new FailResponse(); 213 | } 214 | JSONObject info = new JSONObject(); 215 | info.put("policyArn", result.getPolicyArn()); 216 | info.put("policyDocument", result.getPolicyDocument()); 217 | info.put("policyVersionId", result.getPolicyVersionId()); 218 | return new InfoResponse<>(info); 219 | } 220 | 221 | /** 222 | * 附加证书策略,参考文档:https://docs.aws.amazon.com/zh_cn/iot/latest/apireference/API_AttachPrincipalPolicy.html 223 | * 224 | * @param accessKey 亚马逊接口凭证 225 | * @param secretKey 亚马逊接口凭证 226 | * @param region 亚马逊区域 227 | * @param policyName 策略名称 228 | * @param principal 证书ARN / Cognito ID 229 | * @return 230 | */ 231 | public Response attachPrincipalPolicy(String region, String policyName, 232 | String principal) { 233 | AttachPrincipalPolicyResult result; 234 | try { 235 | AWSIot iotClient = AWSIotClientBuilder.standard().withRegion(region).build(); 236 | 237 | AttachPrincipalPolicyRequest request = new AttachPrincipalPolicyRequest(); 238 | request.setPolicyName(policyName); 239 | request.setPrincipal(principal); 240 | 241 | result = iotClient.attachPrincipalPolicy(request); 242 | if (HttpStatus.SC_OK != result.getSdkHttpMetadata().getHttpStatusCode()) { 243 | return new FailResponse(); 244 | } 245 | } catch (Exception e) { 246 | log.error("IotUtil.attachPrincipalPolicy", e); 247 | return new FailResponse(); 248 | } 249 | return new DefaultResponse(); 250 | } 251 | 252 | /** 253 | * 生成策略文档 254 | * 255 | * @param productKey 产品密钥 256 | * @param thingName 事物名称 257 | * @return 258 | */ 259 | public static String generatePolicyDocument(String productKey,String thingName) { 260 | String policyDocument = 261 | "{" + 262 | " \"Version\": \"2012-10-17\"," + 263 | " \"Statement\": [" + 264 | " {" + 265 | " \"Effect\": \"Allow\"," + 266 | " \"Action\": [" + 267 | " \"iot:Connect\"" + 268 | " ]," + 269 | " \"Resource\": [" + 270 | " \"arn:aws:iot:ap-southeast-1:964479626419:client/thingName\"" + 271 | " ]" + 272 | " }," + 273 | " {" + 274 | " \"Effect\": \"Allow\"," + 275 | " \"Action\": [" + 276 | " \"iot:Publish\"," + 277 | " \"iot:Receive\"" + 278 | " ]," + 279 | " \"Resource\": [" + 280 | " \"arn:aws:iot:ap-southeast-1:964479626419:topic/$aws/things/thingName/shadow/*\"," + 281 | " \"arn:aws:iot:ap-southeast-1:964479626419:topic/productKey/thingName/*\"" + 282 | " ]" + 283 | " }," + 284 | " {" + 285 | " \"Effect\": \"Allow\"," + 286 | " \"Action\": [" + 287 | " \"iot:Subscribe\"" + 288 | " ]," + 289 | " \"Resource\": [" + 290 | " \"arn:aws:iot:ap-southeast-1:964479626419:topicfilter/$aws/things/thingName/shadow/*\"," + 291 | " \"arn:aws:iot:ap-southeast-1:964479626419:topicfilter/productKey/thingName/*\"" + 292 | " ]" + 293 | " }" + 294 | " ]" + 295 | "}"; 296 | return policyDocument.replaceAll("productKey", productKey).replaceAll("thingName", thingName); 297 | } 298 | 299 | public static void main(String[] args) { 300 | 301 | String region = "ap-southeast-1"; 302 | String policyName = "A0000011"; 303 | IotUtil.getInstance().CreatePolicyVersion(region, policyName, generatePolicyDocument("A", "B")); 304 | } 305 | 306 | } 307 | -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/common/entity/device/DeviceInfo.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.common.entity.device; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * Database Table Remarks: 7 | * device.t_device_info: 8 | * 9 | * @mbg.generated do_not_delete_during_merge 2021-10-15 17:04:35 10 | */ 11 | public class DeviceInfo { 12 | /** 13 | * Database Column Remarks: 14 | * device.t_device_info.id: �豸ID 15 | */ 16 | private Long id; 17 | 18 | /** 19 | * Database Column Remarks: 20 | * device.t_device_info.name: �豸���� 21 | */ 22 | private String name; 23 | 24 | /** 25 | * Database Column Remarks: 26 | * device.t_device_info.mac: �豸MAC 27 | */ 28 | private String mac; 29 | 30 | /** 31 | * Database Column Remarks: 32 | * device.t_device_info.country_id: ���ұ�� 33 | */ 34 | private String countryId; 35 | 36 | /** 37 | * Database Column Remarks: 38 | * device.t_device_info.country: �������� 39 | */ 40 | private String country; 41 | 42 | /** 43 | * Database Column Remarks: 44 | * device.t_device_info.province_id: ʡ�ݱ�� 45 | */ 46 | private String provinceId; 47 | 48 | /** 49 | * Database Column Remarks: 50 | * device.t_device_info.province: ʡ������ 51 | */ 52 | private String province; 53 | 54 | /** 55 | * Database Column Remarks: 56 | * device.t_device_info.city_id: ���б�� 57 | */ 58 | private String cityId; 59 | 60 | /** 61 | * Database Column Remarks: 62 | * device.t_device_info.city: �������� 63 | */ 64 | private String city; 65 | 66 | /** 67 | * Database Column Remarks: 68 | * device.t_device_info.area_id: ������� 69 | */ 70 | private String areaId; 71 | 72 | /** 73 | * Database Column Remarks: 74 | * device.t_device_info.area: �������� 75 | */ 76 | private String area; 77 | 78 | /** 79 | * Database Column Remarks: 80 | * device.t_device_info.address: ��ϸ��ַ 81 | */ 82 | private String address; 83 | 84 | /** 85 | * Database Column Remarks: 86 | * device.t_device_info.remark: ��ע 87 | */ 88 | private String remark; 89 | 90 | /** 91 | * Database Column Remarks: 92 | * device.t_device_info.merchant_id: �̻�ID 93 | */ 94 | private Long merchantId; 95 | 96 | /** 97 | * Database Column Remarks: 98 | * device.t_device_info.merchant_name: �̻����� 99 | */ 100 | private String merchantName; 101 | 102 | /** 103 | * Database Column Remarks: 104 | * device.t_device_info.product_id: ��ƷID 105 | */ 106 | private Long productId; 107 | 108 | /** 109 | * Database Column Remarks: 110 | * device.t_device_info.product_name: ��Ʒ���� 111 | */ 112 | private String productName; 113 | 114 | /** 115 | * Database Column Remarks: 116 | * device.t_device_info.status: ״̬����1�����á���2������ 117 | */ 118 | private Integer status; 119 | 120 | /** 121 | * Database Column Remarks: 122 | * device.t_device_info.create_time: ����ʱ�� 123 | */ 124 | private Date createTime; 125 | 126 | /** 127 | * Database Column Remarks: 128 | * device.t_device_info.create_by: ������ID 129 | */ 130 | private Long createBy; 131 | 132 | /** 133 | * Database Column Remarks: 134 | * device.t_device_info.update_time: ����ʱ�� 135 | */ 136 | private Date updateTime; 137 | 138 | /** 139 | * Database Column Remarks: 140 | * device.t_device_info.deleted: ��ɾ������0���񡢡�1���� 141 | */ 142 | private Integer deleted; 143 | 144 | /** 145 | * @return the value of device.t_device_info.id 146 | */ 147 | public Long getId() { 148 | return id; 149 | } 150 | 151 | /** 152 | * @param id the value for device.t_device_info.id 153 | */ 154 | public void setId(Long id) { 155 | this.id = id; 156 | } 157 | 158 | /** 159 | * @return the value of device.t_device_info.name 160 | */ 161 | public String getName() { 162 | return name; 163 | } 164 | 165 | /** 166 | * @param name the value for device.t_device_info.name 167 | */ 168 | public void setName(String name) { 169 | this.name = name == null ? null : name.trim(); 170 | } 171 | 172 | /** 173 | * @return the value of device.t_device_info.mac 174 | */ 175 | public String getMac() { 176 | return mac; 177 | } 178 | 179 | /** 180 | * @param mac the value for device.t_device_info.mac 181 | */ 182 | public void setMac(String mac) { 183 | this.mac = mac == null ? null : mac.trim(); 184 | } 185 | 186 | /** 187 | * @return the value of device.t_device_info.country_id 188 | */ 189 | public String getCountryId() { 190 | return countryId; 191 | } 192 | 193 | /** 194 | * @param countryId the value for device.t_device_info.country_id 195 | */ 196 | public void setCountryId(String countryId) { 197 | this.countryId = countryId == null ? null : countryId.trim(); 198 | } 199 | 200 | /** 201 | * @return the value of device.t_device_info.country 202 | */ 203 | public String getCountry() { 204 | return country; 205 | } 206 | 207 | /** 208 | * @param country the value for device.t_device_info.country 209 | */ 210 | public void setCountry(String country) { 211 | this.country = country == null ? null : country.trim(); 212 | } 213 | 214 | /** 215 | * @return the value of device.t_device_info.province_id 216 | */ 217 | public String getProvinceId() { 218 | return provinceId; 219 | } 220 | 221 | /** 222 | * @param provinceId the value for device.t_device_info.province_id 223 | */ 224 | public void setProvinceId(String provinceId) { 225 | this.provinceId = provinceId == null ? null : provinceId.trim(); 226 | } 227 | 228 | /** 229 | * @return the value of device.t_device_info.province 230 | */ 231 | public String getProvince() { 232 | return province; 233 | } 234 | 235 | /** 236 | * @param province the value for device.t_device_info.province 237 | */ 238 | public void setProvince(String province) { 239 | this.province = province == null ? null : province.trim(); 240 | } 241 | 242 | /** 243 | * @return the value of device.t_device_info.city_id 244 | */ 245 | public String getCityId() { 246 | return cityId; 247 | } 248 | 249 | /** 250 | * @param cityId the value for device.t_device_info.city_id 251 | */ 252 | public void setCityId(String cityId) { 253 | this.cityId = cityId == null ? null : cityId.trim(); 254 | } 255 | 256 | /** 257 | * @return the value of device.t_device_info.city 258 | */ 259 | public String getCity() { 260 | return city; 261 | } 262 | 263 | /** 264 | * @param city the value for device.t_device_info.city 265 | */ 266 | public void setCity(String city) { 267 | this.city = city == null ? null : city.trim(); 268 | } 269 | 270 | /** 271 | * @return the value of device.t_device_info.area_id 272 | */ 273 | public String getAreaId() { 274 | return areaId; 275 | } 276 | 277 | /** 278 | * @param areaId the value for device.t_device_info.area_id 279 | */ 280 | public void setAreaId(String areaId) { 281 | this.areaId = areaId == null ? null : areaId.trim(); 282 | } 283 | 284 | /** 285 | * @return the value of device.t_device_info.area 286 | */ 287 | public String getArea() { 288 | return area; 289 | } 290 | 291 | /** 292 | * @param area the value for device.t_device_info.area 293 | */ 294 | public void setArea(String area) { 295 | this.area = area == null ? null : area.trim(); 296 | } 297 | 298 | /** 299 | * @return the value of device.t_device_info.address 300 | */ 301 | public String getAddress() { 302 | return address; 303 | } 304 | 305 | /** 306 | * @param address the value for device.t_device_info.address 307 | */ 308 | public void setAddress(String address) { 309 | this.address = address == null ? null : address.trim(); 310 | } 311 | 312 | /** 313 | * @return the value of device.t_device_info.remark 314 | */ 315 | public String getRemark() { 316 | return remark; 317 | } 318 | 319 | /** 320 | * @param remark the value for device.t_device_info.remark 321 | */ 322 | public void setRemark(String remark) { 323 | this.remark = remark == null ? null : remark.trim(); 324 | } 325 | 326 | /** 327 | * @return the value of device.t_device_info.merchant_id 328 | */ 329 | public Long getMerchantId() { 330 | return merchantId; 331 | } 332 | 333 | /** 334 | * @param merchantId the value for device.t_device_info.merchant_id 335 | */ 336 | public void setMerchantId(Long merchantId) { 337 | this.merchantId = merchantId; 338 | } 339 | 340 | /** 341 | * @return the value of device.t_device_info.merchant_name 342 | */ 343 | public String getMerchantName() { 344 | return merchantName; 345 | } 346 | 347 | /** 348 | * @param merchantName the value for device.t_device_info.merchant_name 349 | */ 350 | public void setMerchantName(String merchantName) { 351 | this.merchantName = merchantName == null ? null : merchantName.trim(); 352 | } 353 | 354 | /** 355 | * @return the value of device.t_device_info.product_id 356 | */ 357 | public Long getProductId() { 358 | return productId; 359 | } 360 | 361 | /** 362 | * @param productId the value for device.t_device_info.product_id 363 | */ 364 | public void setProductId(Long productId) { 365 | this.productId = productId; 366 | } 367 | 368 | /** 369 | * @return the value of device.t_device_info.product_name 370 | */ 371 | public String getProductName() { 372 | return productName; 373 | } 374 | 375 | /** 376 | * @param productName the value for device.t_device_info.product_name 377 | */ 378 | public void setProductName(String productName) { 379 | this.productName = productName == null ? null : productName.trim(); 380 | } 381 | 382 | /** 383 | * @return the value of device.t_device_info.status 384 | */ 385 | public Integer getStatus() { 386 | return status; 387 | } 388 | 389 | /** 390 | * @param status the value for device.t_device_info.status 391 | */ 392 | public void setStatus(Integer status) { 393 | this.status = status; 394 | } 395 | 396 | /** 397 | * @return the value of device.t_device_info.create_time 398 | */ 399 | public Date getCreateTime() { 400 | return createTime; 401 | } 402 | 403 | /** 404 | * @param createTime the value for device.t_device_info.create_time 405 | */ 406 | public void setCreateTime(Date createTime) { 407 | this.createTime = createTime; 408 | } 409 | 410 | /** 411 | * @return the value of device.t_device_info.create_by 412 | */ 413 | public Long getCreateBy() { 414 | return createBy; 415 | } 416 | 417 | /** 418 | * @param createBy the value for device.t_device_info.create_by 419 | */ 420 | public void setCreateBy(Long createBy) { 421 | this.createBy = createBy; 422 | } 423 | 424 | /** 425 | * @return the value of device.t_device_info.update_time 426 | */ 427 | public Date getUpdateTime() { 428 | return updateTime; 429 | } 430 | 431 | /** 432 | * @param updateTime the value for device.t_device_info.update_time 433 | */ 434 | public void setUpdateTime(Date updateTime) { 435 | this.updateTime = updateTime; 436 | } 437 | 438 | /** 439 | * @return the value of device.t_device_info.deleted 440 | */ 441 | public Integer getDeleted() { 442 | return deleted; 443 | } 444 | 445 | /** 446 | * @param deleted the value for device.t_device_info.deleted 447 | */ 448 | public void setDeleted(Integer deleted) { 449 | this.deleted = deleted; 450 | } 451 | 452 | @Override 453 | public String toString() { 454 | StringBuilder sb = new StringBuilder(); 455 | sb.append(getClass().getSimpleName()); 456 | sb.append(" ["); 457 | sb.append("Hash = ").append(hashCode()); 458 | sb.append(", id=").append(id); 459 | sb.append(", name=").append(name); 460 | sb.append(", mac=").append(mac); 461 | sb.append(", countryId=").append(countryId); 462 | sb.append(", country=").append(country); 463 | sb.append(", provinceId=").append(provinceId); 464 | sb.append(", province=").append(province); 465 | sb.append(", cityId=").append(cityId); 466 | sb.append(", city=").append(city); 467 | sb.append(", areaId=").append(areaId); 468 | sb.append(", area=").append(area); 469 | sb.append(", address=").append(address); 470 | sb.append(", remark=").append(remark); 471 | sb.append(", merchantId=").append(merchantId); 472 | sb.append(", merchantName=").append(merchantName); 473 | sb.append(", productId=").append(productId); 474 | sb.append(", productName=").append(productName); 475 | sb.append(", status=").append(status); 476 | sb.append(", createTime=").append(createTime); 477 | sb.append(", createBy=").append(createBy); 478 | sb.append(", updateTime=").append(updateTime); 479 | sb.append(", deleted=").append(deleted); 480 | sb.append("]"); 481 | return sb.toString(); 482 | } 483 | } -------------------------------------------------------------------------------- /src/main/java/com/jw/demo/app/util/aws/dynamodb/AppUserDeviceDy.java: -------------------------------------------------------------------------------- 1 | package com.jw.demo.app.util.aws.dynamodb; 2 | 3 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 4 | import com.amazonaws.auth.BasicAWSCredentials; 5 | import com.amazonaws.regions.Regions; 6 | import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; 7 | import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; 8 | import com.amazonaws.services.dynamodbv2.model.*; 9 | import com.jw.demo.common.entity.dynamodb.AppUserDevice; 10 | import org.apache.commons.lang3.StringUtils; 11 | 12 | 13 | import java.util.*; 14 | 15 | public class AppUserDeviceDy { 16 | private static final String tableName = "appuserDevice"; 17 | private static final String indexDevice = "device_id-create_time-index"; 18 | 19 | private static AmazonDynamoDBClient dynamoDBClient = (AmazonDynamoDBClient) AmazonDynamoDBClient.builder().withRegion(Regions.AP_SOUTHEAST_1).build(); 20 | public static void main(String[] args) { 21 | // QueryResult x = selectUserDeviceByID(222222L,31313131L); 22 | // QueryResult x = selectDeviceUserByIndex(31313131L); 23 | // QueryResult x = selectUserDevice(222222L); 24 | // System.err.println(x); 25 | // deleteItem("2222221"); 26 | // 27 | // System.err.println(deleteItem("","31313131","")); 28 | // System.err.println(getAppUserDeviceList(x.getItems()).get(0)); 29 | // selectDeviceUserByIndex(31313131L); 30 | // AppUserDevice appUserDevice = new AppUserDevice(); 31 | // appUserDevice.setAppuserId("11"); 32 | // appUserDevice.setCreateTime(1634714051108L); 33 | // AppUserDevice appUserDevice1 = new AppUserDevice(); 34 | // appUserDevice1.setAppuserId("22"); 35 | // appUserDevice1.setCreateTime(1634714751858L); 36 | // List appUserDevices = new ArrayList<>(); 37 | // appUserDevices.add(appUserDevice); 38 | // appUserDevices.add(appUserDevice1); 39 | // deleteItems(appUserDevices); 40 | AppUserDevice putAppDevice = new AppUserDevice(); 41 | putAppDevice.setAppuserId("1"); 42 | putAppDevice.setMac("12345678"); 43 | putAppDevice.setProductId("000"); 44 | putAppDevice.setProductKey("abc"); 45 | putAppDevice.setDeviceNickname("deviceNickName"); 46 | putAppDevice.setuType("1"); 47 | putAppDevice.setSharer("0"); 48 | putAppDevice.setDeviceId("1"); 49 | long time = new Date().getTime(); 50 | putAppDevice.setUpdateTime(time); 51 | putAppDevice.setCreateTime(time); 52 | createAppUserDevice(putAppDevice); 53 | } 54 | /** 55 | * 查询用户所有设备 56 | * @param appUserId 57 | * @return 58 | */ 59 | public static QueryResult selectUserDevice(Long appUserId){ 60 | Map expressionAttributeNames = new HashMap<>(); 61 | expressionAttributeNames.put("#pk", "appuser_id"); 62 | Map expressionAttributeValues = new HashMap<>(); 63 | expressionAttributeValues.put(":pkValue", new AttributeValue().withS(String.valueOf(appUserId))); 64 | 65 | QueryRequest queryRequest = new QueryRequest() 66 | .withTableName(tableName) 67 | .withKeyConditionExpression("#pk = :pkValue") 68 | .withExpressionAttributeNames(expressionAttributeNames) 69 | .withExpressionAttributeValues(expressionAttributeValues); 70 | return dynamoDBClient.query(queryRequest); 71 | } 72 | 73 | 74 | public static QueryResult selectUserDeviceByID(Long appUserId,Long deviceId){ 75 | Map expressionAttributeNames = new HashMap<>(); 76 | expressionAttributeNames.put("#pk", "appuser_id"); 77 | expressionAttributeNames.put("#did", "device_id"); 78 | Map expressionAttributeValues = new HashMap<>(); 79 | expressionAttributeValues.put(":pkValue", new AttributeValue().withS(String.valueOf(appUserId))); 80 | expressionAttributeValues.put(":deviceId", new AttributeValue().withS(String.valueOf(deviceId))); 81 | 82 | QueryRequest queryRequest = new QueryRequest() 83 | .withTableName(tableName) 84 | .withKeyConditionExpression("#pk = :pkValue and #did = :deviceId") 85 | .withExpressionAttributeNames(expressionAttributeNames) 86 | .withExpressionAttributeValues(expressionAttributeValues); 87 | return dynamoDBClient.query(queryRequest); 88 | } 89 | 90 | /** 91 | * 根据设备查询到用户 92 | * @param deviceId 93 | * @return 94 | */ 95 | public static QueryResult selectDeviceUserByIndex(Long deviceId){ 96 | Map expressionAttributeNames = new HashMap<>(); 97 | expressionAttributeNames.put("#pk", "device_id"); 98 | Map expressionAttributeValues = new HashMap<>(); 99 | expressionAttributeValues.put(":pkValue", new AttributeValue().withS(String.valueOf(deviceId))); 100 | 101 | QueryRequest queryRequest = new QueryRequest() 102 | .withTableName(tableName) 103 | .withIndexName(indexDevice) 104 | .withKeyConditionExpression("#pk = :pkValue") 105 | .withExpressionAttributeNames(expressionAttributeNames) 106 | .withExpressionAttributeValues(expressionAttributeValues); 107 | return dynamoDBClient.query(queryRequest); 108 | 109 | } 110 | 111 | /** 112 | * 新增app用户设备 113 | * @param appUserDevice 114 | * @return 115 | */ 116 | public static PutItemResult createAppUserDevice(AppUserDevice appUserDevice){ 117 | PutItemRequest putItemRequest = new PutItemRequest(); 118 | putItemRequest.setTableName(tableName); 119 | Map items = new HashMap<>(); 120 | items.put("appuser_id",new AttributeValue().withS(appUserDevice.getAppuserId())); 121 | // items.put("device_id",new AttributeValue().withS(appUserDevice.getDeviceId())); 122 | items.put("product_id",new AttributeValue().withS(appUserDevice.getProductId())); 123 | items.put("product_key",new AttributeValue().withS(appUserDevice.getProductKey())); 124 | items.put("mac",new AttributeValue().withS(appUserDevice.getMac())); 125 | items.put("device_nickname",new AttributeValue().withS(appUserDevice.getDeviceNickname())); 126 | items.put("u_type",new AttributeValue().withS(appUserDevice.getuType())); 127 | items.put("sharer",new AttributeValue().withS(appUserDevice.getSharer())); 128 | items.put("update_time",new AttributeValue().withN(String.valueOf(appUserDevice.getUpdateTime()))); 129 | items.put("create_time",new AttributeValue().withN(String.valueOf(appUserDevice.getCreateTime()))); 130 | System.out.println(items.toString()); 131 | putItemRequest.setItem(items); 132 | return dynamoDBClient.putItem(putItemRequest); 133 | } 134 | 135 | /** 136 | * 删除app用户设备 137 | * @param appUserId 138 | * @return 139 | */ 140 | public static DeleteItemResult deleteItem(String appUserId){ 141 | Map key = new HashMap<>(); 142 | key.put("appuser_id",new AttributeValue().withS(appUserId)); 143 | return dynamoDBClient.deleteItem(tableName,key); 144 | } 145 | 146 | public static List deleteItems(List appUserDevices ){ 147 | DynamoDBMapper dbMapper = new DynamoDBMapper(dynamoDBClient); 148 | List result = dbMapper.batchDelete(appUserDevices); 149 | return result; 150 | } 151 | 152 | /** 153 | * 修改App用户设备 154 | * @param appUserId 155 | * @param deviceId 156 | * @param mac 157 | * @param appUserDevice 158 | * @return 159 | * @throws Exception 160 | */ 161 | public static UpdateItemResult updateItem(String appUserId,String deviceId,String mac, AppUserDevice appUserDevice)throws Exception{ 162 | UpdateItemRequest updateItemRequest = new UpdateItemRequest(); 163 | updateItemRequest.setTableName(tableName); 164 | 165 | //表达式中的变量和属性值定义 166 | Map attributeValueMap = new HashMap<>(); 167 | StringBuffer itemString = new StringBuffer(); 168 | 169 | attributeValueMap.put(":updateTime",new AttributeValue().withS(String.valueOf(new Date().getTime()))); 170 | itemString.append("set update_time = :updateTime"); 171 | 172 | if (!StringUtils.isEmpty(appUserDevice.getAppuserId())){ 173 | attributeValueMap.put(":appUserId",new AttributeValue().withS(appUserDevice.getAppuserId())); 174 | itemString.append(",appuser_id = :appUserId"); 175 | } 176 | if (!StringUtils.isEmpty(appUserDevice.getDeviceId())){ 177 | attributeValueMap.put(":deviceId",new AttributeValue().withS(appUserDevice.getDeviceId())); 178 | itemString.append(",device_id = :deviceId"); 179 | } 180 | if (!StringUtils.isEmpty(appUserDevice.getProductId())){ 181 | attributeValueMap.put(":productId",new AttributeValue().withS(appUserDevice.getProductId())); 182 | itemString.append(",product_id = :productId"); 183 | } 184 | if (!StringUtils.isEmpty(appUserDevice.getProductKey())){ 185 | attributeValueMap.put(":productKey",new AttributeValue().withS(appUserDevice.getProductKey())); 186 | itemString.append(",product_key = :productKey"); 187 | } 188 | if (!StringUtils.isEmpty(appUserDevice.getMac())){ 189 | attributeValueMap.put(":macStr",new AttributeValue().withS(appUserDevice.getMac())); 190 | itemString.append(",mac = :macStr"); 191 | } 192 | if (!StringUtils.isEmpty(appUserDevice.getDeviceNickname())){ 193 | attributeValueMap.put(":deviceNickname",new AttributeValue().withS(appUserDevice.getDeviceNickname())); 194 | itemString.append(",device_nickname = :deviceNickname"); 195 | } 196 | if (!StringUtils.isEmpty(appUserDevice.getuType())){ 197 | attributeValueMap.put(":ty",new AttributeValue().withS(appUserDevice.getuType())); 198 | itemString.append(",u_type = :ty"); 199 | } 200 | if (!StringUtils.isEmpty(appUserDevice.getSharer())){ 201 | attributeValueMap.put(":share",new AttributeValue().withS(appUserDevice.getSharer())); 202 | itemString.append(",sharer = :share"); 203 | } 204 | 205 | Map key = new HashMap<>(); 206 | if (!StringUtils.isEmpty(appUserId)){ 207 | key.put("appuser_id",new AttributeValue().withS(appUserId)); 208 | } 209 | if (!StringUtils.isEmpty(deviceId)){ 210 | key.put("device_id",new AttributeValue().withS(deviceId)); 211 | } 212 | if (!StringUtils.isEmpty(mac)){ 213 | key.put("mac",new AttributeValue().withS(mac)); 214 | } 215 | updateItemRequest.setKey(key); 216 | updateItemRequest.setUpdateExpression(itemString.toString()); 217 | 218 | updateItemRequest.setExpressionAttributeValues(attributeValueMap); 219 | updateItemRequest.setReturnValues("ALL_OLD");//返回旧的数据 220 | System.err.println("key:"+key); 221 | System.err.println("itemString:"+itemString.toString()); 222 | UpdateItemResult updateItemResult = dynamoDBClient.updateItem(updateItemRequest); 223 | 224 | System.out.println(updateItemResult.toString()); 225 | return updateItemResult; 226 | } 227 | 228 | 229 | //将查询结果转化为 对象 230 | public static AppUserDevice getAppUserDevice(Map item){ 231 | AppUserDevice appUserDevice = new AppUserDevice(); 232 | try { 233 | appUserDevice.setAppuserId(item.get("appuser_id").getS()); 234 | appUserDevice.setDeviceId(item.get("device_id").getS()); 235 | appUserDevice.setProductId(item.get("product_id").getS()); 236 | appUserDevice.setProductKey(item.get("product_key").getS()); 237 | appUserDevice.setMac(item.get("mac").getS()); 238 | appUserDevice.setuType(item.get("u_type").getS()); 239 | appUserDevice.setCreateTime(Long.valueOf(item.get("create_time").getN())); 240 | appUserDevice.setDeviceNickname(item.get("device_nickname").getS()); 241 | appUserDevice.setUpdateTime(Long.valueOf(item.get("update_time").getN())); 242 | appUserDevice.setSharer(item.get("sharer").getS()); 243 | }catch (Exception e){ 244 | e.printStackTrace(); 245 | System.err.println(e.getMessage()); 246 | // continue; 247 | } 248 | return appUserDevice; 249 | } 250 | //将查询结果转化为 对象 251 | public static List getAppUserDeviceList(List> item){ 252 | List appUserDevices = new ArrayList<>(); 253 | for (int i=0;i