From a0e23dea2b85411f45bebadc16363820a28a3af9 Mon Sep 17 00:00:00 2001 From: xiwa Date: Sun, 24 Apr 2022 04:59:23 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0http=E4=B8=9A=E5=8A=A1?= =?UTF-8?q?=E7=BB=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .DS_Store | Bin 8196 -> 8196 bytes .../iotkit/common/ComponentClassLoader.java | 0 .../java/cc/iotkit/common/utils/JsonUtil.java | 2 +- manager/.DS_Store | Bin 8196 -> 8196 bytes .../manager/config/ResponseResultHandler.java | 58 +++++++++ .../manager/controller/DeviceController.java | 42 ++----- .../controller/ProtocolController.java | 30 +++-- .../aligenie/AligenieDeviceController.java | 44 ------- .../controller/api/DeviceController.java | 77 +----------- .../manager/model/query/DeviceQuery.java | 0 .../java/cc/iotkit/model/InvokeResult.java | 13 +- pom.xml | 9 +- protocol-gateway/.DS_Store | Bin 6148 -> 8196 bytes protocol-gateway/component-server/pom.xml | 5 + .../main/java/cc/iotkit/comps}/ApiTool.java | 99 +++++++++------ .../cc/iotkit/comps/BizComponentManager.java | 6 +- .../cc/iotkit/comps/ComponentManager.java | 48 +++++++ .../iotkit/comps/DeviceComponentManager.java | 3 +- .../cc/iotkit/comps/DeviceMessageHandler.java | 0 .../iotkit/comp/AbstractDeviceComponent.java | 0 .../main/java/cc/iotkit/comp/IComponent.java | 0 .../java/cc/iotkit/comp/IDeviceComponent.java | 0 .../emqx-component/dependency-reduced-pom.xml | 6 +- .../iotkit/comp/emqx/EmqxDeviceComponent.java | 0 protocol-gateway/http-biz-component/.DS_Store | Bin 0 -> 6148 bytes .../dependency-reduced-pom.xml | 69 ++++++++++ protocol-gateway/http-biz-component/pom.xml | 44 ++++++- .../cc/iotkit/comp/biz/HttpBizComponent.java | 119 ++++++++++++------ .../java/cc/iotkit/comp/biz/HttpConfig.java | 0 .../src/main/resources/component.js | 36 ++++++ .../src/main/resources/component.spi | 0 .../java/cc/iotkit/simulator/Application.java | 4 +- .../mqtt-component/dependency-reduced-pom.xml | 4 +- .../iotkit/comp/mqtt/MqttDeviceComponent.java | 0 34 files changed, 449 insertions(+), 269 deletions(-) mode change 100644 => 100755 common/src/main/java/cc/iotkit/common/ComponentClassLoader.java create mode 100644 manager/src/main/java/cc/iotkit/manager/config/ResponseResultHandler.java mode change 100644 => 100755 manager/src/main/java/cc/iotkit/manager/model/query/DeviceQuery.java rename protocol-gateway/{http-biz-component/src/main/java/cc/iotkit/comp/biz => component-server/src/main/java/cc/iotkit/comps}/ApiTool.java (51%) mode change 100644 => 100755 mode change 100644 => 100755 protocol-gateway/component-server/src/main/java/cc/iotkit/comps/BizComponentManager.java create mode 100755 protocol-gateway/component-server/src/main/java/cc/iotkit/comps/ComponentManager.java mode change 100644 => 100755 protocol-gateway/component-server/src/main/java/cc/iotkit/comps/DeviceComponentManager.java mode change 100644 => 100755 protocol-gateway/component-server/src/main/java/cc/iotkit/comps/DeviceMessageHandler.java mode change 100644 => 100755 protocol-gateway/component/src/main/java/cc/iotkit/comp/AbstractDeviceComponent.java mode change 100644 => 100755 protocol-gateway/component/src/main/java/cc/iotkit/comp/IComponent.java mode change 100644 => 100755 protocol-gateway/component/src/main/java/cc/iotkit/comp/IDeviceComponent.java mode change 100755 => 100644 protocol-gateway/emqx-component/dependency-reduced-pom.xml mode change 100644 => 100755 protocol-gateway/emqx-component/src/main/java/cc/iotkit/comp/emqx/EmqxDeviceComponent.java create mode 100644 protocol-gateway/http-biz-component/.DS_Store create mode 100644 protocol-gateway/http-biz-component/dependency-reduced-pom.xml mode change 100644 => 100755 protocol-gateway/http-biz-component/pom.xml mode change 100644 => 100755 protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/HttpBizComponent.java mode change 100644 => 100755 protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/HttpConfig.java create mode 100755 protocol-gateway/http-biz-component/src/main/resources/component.js mode change 100644 => 100755 protocol-gateway/http-biz-component/src/main/resources/component.spi mode change 100755 => 100644 protocol-gateway/mqtt-component/dependency-reduced-pom.xml mode change 100644 => 100755 protocol-gateway/mqtt-component/src/main/java/cc/iotkit/comp/mqtt/MqttDeviceComponent.java diff --git a/.DS_Store b/.DS_Store index 112b470ee475beede4918a3f3f124652bc1d0e1a..fabfb5f84c023be3277bca281be0b42a0010707a 100755 GIT binary patch literal 8196 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 q(uEpfBIac}PIBfCL+ZyvT{4s9oe diff --git a/common/src/main/java/cc/iotkit/common/ComponentClassLoader.java b/common/src/main/java/cc/iotkit/common/ComponentClassLoader.java old mode 100644 new mode 100755 diff --git a/common/src/main/java/cc/iotkit/common/utils/JsonUtil.java b/common/src/main/java/cc/iotkit/common/utils/JsonUtil.java index 8bd2b5e2..a2802ec1 100755 --- a/common/src/main/java/cc/iotkit/common/utils/JsonUtil.java +++ b/common/src/main/java/cc/iotkit/common/utils/JsonUtil.java @@ -41,7 +41,7 @@ public final class JsonUtil { public static Object toObject(ScriptObjectMirror mirror) { if (mirror.isEmpty()) { - return null; + return new Object(); } if (mirror.isArray()) { List list = new ArrayList<>(); diff --git a/manager/.DS_Store b/manager/.DS_Store index f4c5579ecdd5d3f9eda2c6c0a364256f334e1e80..72eee3cb50f059a4234faff053882a53df78afae 100755 GIT binary patch delta 302 zcmZp1XmQw}F5vb#sURn_xWvHV1|t(Q3o9Et2PYRdCpRBAcWiJ*etB?7Vo7PSQ({rP zfJ|^^N@`MKQFvxbNk&L&o@-8OS!$ktkxybt>f{Ik&(vs;hJeJ944@(oWrwT;1`y!n z;EWd#tFAWCQP4H3)lsN6G%z&MQLr#KudU_eYFut$+~E+!!Nxk$9!bWYAIV&W2#oT^eT ioE!p-K!<2RG>3pxCWuxuZDyDF#xnV$h$yjIDwqJ^J5Q4U delta 216 zcmZp1XmQw}E?{^(sURn_xWvHVIwKP^3o9Et2PY>7CogAga7KQ4a7kiGX|YpcQ8b7b zkXVwDlsGw8z|#+`C|*FUy4u*(SVzI2R!5=Q(%4K#!NT0Uww9AaT-DIlGa;PRkA;+&i!-Y>a|m-W0lC7W(LkwuQ7N!s Yk7za1#0H(s>=NHtCTohiVn}HM0DreQ8UO$Q diff --git a/manager/src/main/java/cc/iotkit/manager/config/ResponseResultHandler.java b/manager/src/main/java/cc/iotkit/manager/config/ResponseResultHandler.java new file mode 100644 index 00000000..5108cb33 --- /dev/null +++ b/manager/src/main/java/cc/iotkit/manager/config/ResponseResultHandler.java @@ -0,0 +1,58 @@ +package cc.iotkit.manager.config; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.core.MethodParameter; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; + +import javax.servlet.http.HttpServletRequest; +import java.util.Map; + +@ControllerAdvice +public class ResponseResultHandler implements ResponseBodyAdvice { + @Override + public boolean supports(MethodParameter returnType, Class> converterType) { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); + String wrapResponse = request.getHeader("wrap-response"); + return "json".equals(wrapResponse); + } + + @Override + public Object beforeBodyWrite(Object body, MethodParameter returnType, + MediaType selectedContentType, + Class> selectedConverterType, + ServerHttpRequest request, ServerHttpResponse response) { + if (body instanceof GlobalExceptionHandler.RequestResult) { + GlobalExceptionHandler.RequestResult requestResult = (GlobalExceptionHandler.RequestResult) body; + return new ApiResponse(Integer.parseInt(requestResult.getCode()), requestResult.getMessage(), + "", System.currentTimeMillis()); + } else if (body instanceof Map) { + Map map = (Map) body; + //spring mvc内部异常 + if (map.containsKey("timestamp") && map.containsKey("status") && map.containsKey("error")) { + return new ApiResponse((Integer) map.get("status"), (String) map.get("error"), + "", System.currentTimeMillis()); + } + } + + return new ApiResponse(200, "", body, System.currentTimeMillis()); + } + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static class ApiResponse { + private int status; + private String message; + private Object data; + private long timestamp; + } +} diff --git a/manager/src/main/java/cc/iotkit/manager/controller/DeviceController.java b/manager/src/main/java/cc/iotkit/manager/controller/DeviceController.java index 1dba73a0..42590870 100755 --- a/manager/src/main/java/cc/iotkit/manager/controller/DeviceController.java +++ b/manager/src/main/java/cc/iotkit/manager/controller/DeviceController.java @@ -10,6 +10,7 @@ import cc.iotkit.manager.model.query.DeviceQuery; import cc.iotkit.manager.service.DataOwnerService; import cc.iotkit.manager.service.DeviceService; import cc.iotkit.manager.utils.AuthUtil; +import cc.iotkit.model.InvokeResult; import cc.iotkit.model.Paging; import cc.iotkit.model.device.DeviceInfo; import cc.iotkit.model.device.message.DeviceProperty; @@ -55,44 +56,21 @@ public class DeviceController { private DeviceBehaviourService behaviourService; @PostMapping(Constants.API.DEVICE_INVOKE_SERVICE) - public String invokeService(@PathVariable("deviceId") String deviceId, - @PathVariable("service") String service, - @RequestBody Map args) { + public InvokeResult invokeService(@PathVariable("deviceId") String deviceId, + @PathVariable("service") String service, + @RequestBody Map args) { if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(service)) { throw new RuntimeException("deviceId/service is blank."); } dataOwnerService.checkWriteRole(); - return deviceService.invokeService(deviceId, service, args); + return new InvokeResult(deviceService.invokeService(deviceId, service, args)); } @PostMapping(Constants.API.DEVICE_SET_PROPERTIES) - public String setProperty(@PathVariable("deviceId") String deviceId, - @RequestBody Map args) { + public InvokeResult setProperty(@PathVariable("deviceId") String deviceId, + @RequestBody Map args) { dataOwnerService.checkWriteRole(); - return deviceService.setProperty(deviceId, args); - } - - @PostMapping("/list") - public Paging getDevices(int page, - int size, - String pk, - Boolean online, - String dn) { - Criteria condition = new Criteria(); - if (!AuthUtil.isAdmin()) { - condition.and("uid").is(AuthUtil.getUserId()); - } - if (StringUtils.isNotBlank(pk)) { - condition.and("productKey").is(pk); - } - if (StringUtils.isNotBlank(dn)) { - condition.and("deviceName").regex(".*" + dn + ".*"); - } - if (online != null) { - condition.and("state.online").is(online); - } - - return deviceDao.find(condition, size, page); + return new InvokeResult(deviceService.setProperty(deviceId, args)); } @PostMapping("/list/{size}/{page}") @@ -121,8 +99,8 @@ public class DeviceController { condition.and("deviceName").regex(".*" + dn + ".*"); } String state = query.getState(); - if (state != null) { - condition.and("state.online").is(state); + if (StringUtils.isNotBlank(state)) { + condition.and("state.online").is(state.equals("online")); } return deviceDao.find(condition, size, page); diff --git a/manager/src/main/java/cc/iotkit/manager/controller/ProtocolController.java b/manager/src/main/java/cc/iotkit/manager/controller/ProtocolController.java index 3850cbe0..3dfab8da 100755 --- a/manager/src/main/java/cc/iotkit/manager/controller/ProtocolController.java +++ b/manager/src/main/java/cc/iotkit/manager/controller/ProtocolController.java @@ -3,7 +3,7 @@ package cc.iotkit.manager.controller; import cc.iotkit.common.exception.BizException; import cc.iotkit.common.utils.JsonUtil; import cc.iotkit.common.utils.ReflectUtil; -import cc.iotkit.comps.DeviceComponentManager; +import cc.iotkit.comps.ComponentManager; import cc.iotkit.comps.config.ComponentConfig; import cc.iotkit.dao.ProtocolComponentRepository; import cc.iotkit.dao.ProtocolConverterRepository; @@ -50,7 +50,7 @@ public class ProtocolController { private UserInfoRepository userInfoRepository; @Autowired - private DeviceComponentManager deviceComponentManager; + private ComponentManager componentManager; @PostMapping("/uploadJar") public String uploadJar(@RequestParam("file") MultipartFile file, String id) { @@ -112,8 +112,9 @@ public class ProtocolController { ProtocolComponent oldComponent = getAndCheckComponent(id); component = ReflectUtil.copyNoNulls(component, oldComponent); + try { - deviceComponentManager.deRegister(id); + componentManager.deRegister(id); protocolComponentRepository.save(component); } catch (Throwable e) { throw new BizException("add protocol component error", e); @@ -144,7 +145,7 @@ public class ProtocolController { script = JsonUtil.parse(script, String.class); FileUtils.writeStringToFile(file, script, "UTF-8", false); - deviceComponentManager.deRegister(id); + componentManager.deRegister(id); } catch (Throwable e) { throw new BizException("save protocol component script error", e); } @@ -164,7 +165,7 @@ public class ProtocolController { public void deleteComponent(@PathVariable("id") String id) { ProtocolComponent component = getAndCheckComponent(id); try { - deviceComponentManager.deRegister(id); + componentManager.deRegister(id); Path path = Paths.get(String.format("%s/%s", componentConfig.getComponentDir(), id)) .toAbsolutePath().normalize(); @@ -190,8 +191,10 @@ public class ProtocolController { @PathVariable("page") int page) { Page components = protocolComponentRepository.findAll( PageRequest.of(page - 1, size, Sort.by(Sort.Order.desc("createAt")))); - components.getContent().forEach(c -> c.setState(deviceComponentManager.isRunning(c.getId()) ? - ProtocolComponent.STATE_RUNNING : ProtocolComponent.STATE_STOPPED)); + components.getContent().forEach(c -> c.setState( + componentManager.isRunning(c.getId()) ? + ProtocolComponent.STATE_RUNNING : ProtocolComponent.STATE_STOPPED + )); return new Paging<>(components.getTotalElements(), components.getContent()); } @@ -294,14 +297,17 @@ public class ProtocolController { public void changeComponentState(@PathVariable("id") String id, @PathVariable("state") String state) { ProtocolComponent component = getAndCheckComponent(id); - String converterId = component.getConverter(); - getAndCheckConverter(converterId); + if(ProtocolComponent.TYPE_DEVICE.equals(component.getType())){ + String converterId = component.getConverter(); + getAndCheckConverter(converterId); + } + if (ProtocolComponent.STATE_RUNNING.equals(state)) { - deviceComponentManager.register(component); - deviceComponentManager.start(component.getId()); + componentManager.register(component); + componentManager.start(component.getId()); component.setState(ProtocolComponent.STATE_RUNNING); } else { - deviceComponentManager.deRegister(id); + componentManager.deRegister(id); component.setState(ProtocolComponent.STATE_STOPPED); } protocolComponentRepository.save(component); diff --git a/manager/src/main/java/cc/iotkit/manager/controller/aligenie/AligenieDeviceController.java b/manager/src/main/java/cc/iotkit/manager/controller/aligenie/AligenieDeviceController.java index 08a311ad..8039f0ba 100755 --- a/manager/src/main/java/cc/iotkit/manager/controller/aligenie/AligenieDeviceController.java +++ b/manager/src/main/java/cc/iotkit/manager/controller/aligenie/AligenieDeviceController.java @@ -2,23 +2,17 @@ package cc.iotkit.manager.controller.aligenie; import cc.iotkit.common.Constants; import cc.iotkit.common.exception.BizException; -import cc.iotkit.common.exception.OfflineException; -import cc.iotkit.common.utils.JsonUtil; import cc.iotkit.common.utils.UniqueIdUtil; import cc.iotkit.dao.*; import cc.iotkit.manager.service.DataOwnerService; import cc.iotkit.manager.service.DeviceService; -import cc.iotkit.manager.utils.AuthUtil; -import cc.iotkit.model.InvokeResult; import cc.iotkit.model.UserInfo; import cc.iotkit.model.aligenie.AligenieDevice; import cc.iotkit.model.aligenie.AligenieProduct; import cc.iotkit.model.device.DeviceInfo; import cc.iotkit.model.device.message.ThingModelMessage; -import io.swagger.annotations.ApiOperation; import lombok.Data; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.PulsarClientException; @@ -131,44 +125,6 @@ public class AligenieDeviceController { .build()); } - @ApiOperation("设备服务调用") - @PostMapping("/invoke/{deviceId}/{service}") - public InvokeResult invokeService(@PathVariable("deviceId") String deviceId, - @PathVariable("service") String service, - String args) { - InvokeResult result = new InvokeResult("", InvokeResult.FAILED_UNKNOWN); - AligenieDevice device = aligenieDeviceRepository.findByUidAndDeviceId(AuthUtil.getUserId(), deviceId); - - if (device == null) { - result.setCode(InvokeResult.FAILED_NO_AUTH); - return result; - } - - if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(service)) { - log.error("deviceId/service is blank"); - result.setCode(InvokeResult.FAILED_PARAM_ERROR); - return result; - } - - try { - String requestId; - if ("set".equals(service)) { - requestId = deviceService.setProperty(deviceId, - JsonUtil.parse(args, Map.class), false); - } else { - requestId = deviceService.invokeService(deviceId, - service, JsonUtil.parse(args, Map.class), false); - } - result.setRequestId(requestId); - result.setCode(InvokeResult.SUCCESS); - } catch (OfflineException e) { - log.error("sendMsg failed", e); - result.setCode(InvokeResult.FAILED_OFFLINE); - return result; - } - return result; - } - @Data public static class Device { private String deviceId; diff --git a/manager/src/main/java/cc/iotkit/manager/controller/api/DeviceController.java b/manager/src/main/java/cc/iotkit/manager/controller/api/DeviceController.java index fc6020fa..54bf9d6a 100755 --- a/manager/src/main/java/cc/iotkit/manager/controller/api/DeviceController.java +++ b/manager/src/main/java/cc/iotkit/manager/controller/api/DeviceController.java @@ -1,7 +1,5 @@ package cc.iotkit.manager.controller.api; -import cc.iotkit.common.exception.OfflineException; -import cc.iotkit.common.utils.JsonUtil; import cc.iotkit.dao.AppDesignRepository; import cc.iotkit.dao.DeviceRepository; import cc.iotkit.dao.SpaceDeviceRepository; @@ -10,7 +8,6 @@ import cc.iotkit.manager.model.vo.AppPageNode; import cc.iotkit.manager.service.AppDesignService; import cc.iotkit.manager.service.DeviceService; import cc.iotkit.manager.utils.AuthUtil; -import cc.iotkit.model.InvokeResult; import cc.iotkit.model.device.DeviceInfo; import cc.iotkit.model.space.SpaceDevice; import io.swagger.annotations.ApiImplicitParam; @@ -20,10 +17,12 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; import java.util.List; -import java.util.Map; import java.util.stream.Collectors; @Slf4j @@ -72,74 +71,6 @@ public class DeviceController { .collect(Collectors.toList()); } - @ApiOperation("设备服务调用") - @ApiImplicitParams({ - @ApiImplicitParam(value = "设备ID", name = "deviceId", required = true, dataType = "String"), - @ApiImplicitParam(value = "服务名", name = "service", required = true, dataType = "String"), - @ApiImplicitParam(value = "参数", name = "args", required = true, dataType = "String"), - }) - @PostMapping("/{deviceId}/service/{service}") - public InvokeResult invokeService(@PathVariable("deviceId") String deviceId, - @PathVariable("service") String service, - String args) { - InvokeResult result = new InvokeResult("", InvokeResult.FAILED_UNKNOWN); - SpaceDevice device = checkOwner(deviceId); - - if (device == null) { - result.setCode(InvokeResult.FAILED_NO_AUTH); - return result; - } - - if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(service)) { - log.error("deviceId/service is blank"); - result.setCode(InvokeResult.FAILED_PARAM_ERROR); - return result; - } - - try { - String requestId; - if ("property/set".equals(service)) { - requestId = deviceService.setProperty(deviceId, - JsonUtil.parse(args, Map.class)); - } else { - requestId = deviceService.invokeService(deviceId, service, - JsonUtil.parse(args, Map.class)); - } - result.setRequestId(requestId); - result.setCode(InvokeResult.SUCCESS); - } catch (OfflineException e) { - log.error("sendMsg failed", e); - result.setCode(InvokeResult.FAILED_OFFLINE); - return result; - } - - return result; - } - - @ApiOperation("设备属性调用") - @ApiImplicitParams({ - @ApiImplicitParam(value = "设备ID", name = "deviceId", required = true, dataType = "String"), - @ApiImplicitParam(value = "参数", name = "args", required = true, dataType = "String"), - }) - @PostMapping("/{deviceId}/service/property/set") - public InvokeResult setProperty(@PathVariable("deviceId") String deviceId, - String args) { - checkOwner(deviceId); - if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(args)) { - throw new RuntimeException("deviceId/args is blank."); - } - return invokeService(deviceId, "property/set", args); - } - - /** - * 检查设备是否属于该用户 - */ - private SpaceDevice checkOwner(String deviceId) { - return spaceDeviceRepository.findOne(Example.of(SpaceDevice.builder() - .uid(AuthUtil.getUserId()).deviceId(deviceId).build())) - .orElse(null); - } - @GetMapping("/detailPage/{deviceId}") public List deviceDetailPage(@PathVariable("deviceId") String deviceId) { DeviceInfo device = deviceRepository.findById(deviceId).orElseThrow(() -> new RuntimeException("device not found")); diff --git a/manager/src/main/java/cc/iotkit/manager/model/query/DeviceQuery.java b/manager/src/main/java/cc/iotkit/manager/model/query/DeviceQuery.java old mode 100644 new mode 100755 diff --git a/model/src/main/java/cc/iotkit/model/InvokeResult.java b/model/src/main/java/cc/iotkit/model/InvokeResult.java index a86fa6eb..3bb1c829 100755 --- a/model/src/main/java/cc/iotkit/model/InvokeResult.java +++ b/model/src/main/java/cc/iotkit/model/InvokeResult.java @@ -9,13 +9,12 @@ import lombok.NoArgsConstructor; @AllArgsConstructor public class InvokeResult { - public static final String SUCCESS = "success"; - public static final String FAILED_UNKNOWN = "unknown"; - public static final String FAILED_OFFLINE = "offline"; - public static final String FAILED_PARAM_ERROR = "param_error"; - public static final String FAILED_NO_AUTH = "no_auth"; - private String requestId; - private String code; + private long time; + + public InvokeResult(String requestId) { + this.requestId = requestId; + this.time = System.currentTimeMillis(); + } } diff --git a/pom.xml b/pom.xml index ed2ba9dd..0d2c80eb 100755 --- a/pom.xml +++ b/pom.xml @@ -27,6 +27,7 @@ 1.8 17.0.0 + 4.2.2 @@ -175,25 +176,25 @@ io.vertx vertx-core - 4.2.6 + ${vertx.version} io.vertx vertx-mqtt - 4.2.6 + ${vertx.version} io.vertx vertx-web-proxy - 4.2.6 + ${vertx.version} io.vertx vertx-web-client - 4.2.6 + ${vertx.version} diff --git a/protocol-gateway/.DS_Store b/protocol-gateway/.DS_Store index 5008ddfcf53c02e82d7eee2e57c38e5672ef89f6..b7222f61a338dd7d8d2c5a6d83b3ebf010b31331 100755 GIT binary patch literal 8196 zcmeHMTWl0n82-O)OJ|q}(^_d!H@jtl5-jN!u?8`)^rH3xZD?y-RNB3abmDYo*_qvP ziE&Ld8a3*ZH=;cFVnlti-k!WYX!J?y1H=aniI)d8!50!^;(zAM653MJCqrP)=A7@$ ze>rE*pYNZOf0u~RS;2C!U!ylfT-Q;X_`F#OhGM1C!oS)C+Ez|Xq$#aNQRoASl zRn*m*c0;tUe_-GK!AV^&y2b&+N_%F>=uUfvJE^aAr=8i}tYZ%qjFM^0j%6LIIAgP> zE}OQpMK(6}TGp_6Tv}%fj%5uwuIZVMJu&VXM?Ikv3oTHMA9S69*X1uZZu0uls$T3d zm>16O{YJrMRMpdK8e)}XB$E19mDv5e7KGv`fDq}{Ax=S=(X zK{IFAp82q86x2Gjsv~xK#+a{fT7UB`w??Cjtt+dH7c=IOqUjye6N)1DXpSaSeNK5W z$0yw9)5?g;=aoyeY3-`+sw0n>cHp{0>rnKZ zI%=geh9y_qsqIqqes!!Qk1K@@+8#w6&pIB{CI-}i+{*`h_Y&?*5y}`U;^WNfU z_cTYN6GFZ>mosvTq9iJWNu;*OX(BcCqd)Tll1L?`SQqc_C?%R7_(T9GFVG3zvk%Nf> zToh5l2|R%(@f4oM^LQDr;5D4Yn|KHB;yrwbPw^SPz?V3KAMi7N!LRrY7w~taI-*AE z<@byP*9Q&B=gJsq;Mq#^ARpwx$t&kU?B4r&`}(`C+B`VBMv(u;hMU$k#y4$k+p%+Z z=Ov0PV#Vd`^a&{$=QFXwG@l3y=`FKFi;Xg2jibvYi(V@dOPLqe%^PAdUC>fKZf@bn z2&avFysb5+=~bK*s&AZZ*J64N^IvN3=+HF1niE87@7l%MRh$Y^yC=$83Upm9ybu(1 z<;4C^T7OO7(NFX{6Z#_kgBq+xBjQZuR&-!D6S)iB=)ryr;Q)p)f`>54l+G}zE!fE8 z2ow7R9>rrQ<8eHL=a|+n;6=R3w0<3L;1u4%+c?bxpJRG|gpctF6Z~6zk8_LYJWwIB zM4VqKolC<7+j8u~Y+p%@g-eA`*K7pD-OsH_)c-xp|NieAg+myDFapIqGy3H?nH^ delta 105 zcmZp1XfcprU|?W$DortDU=RQ@Ie-{MGpJ516q~502;ws^0>w5KPGg_gAhnpCgF}!R pBnTAa1`@77th%xAJM(0I8AV3M$)+;eJWLRCKt?lcj^~-f3;-`E4{!hg diff --git a/protocol-gateway/component-server/pom.xml b/protocol-gateway/component-server/pom.xml index a1a0f1cb..c6e3758a 100755 --- a/protocol-gateway/component-server/pom.xml +++ b/protocol-gateway/component-server/pom.xml @@ -42,6 +42,11 @@ slf4j-api + + io.vertx + vertx-web-client + + commons-io commons-io diff --git a/protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/ApiTool.java b/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/ApiTool.java old mode 100644 new mode 100755 similarity index 51% rename from protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/ApiTool.java rename to protocol-gateway/component-server/src/main/java/cc/iotkit/comps/ApiTool.java index 3a3f738a..c986f7e7 --- a/protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/ApiTool.java +++ b/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/ApiTool.java @@ -1,14 +1,16 @@ -package cc.iotkit.comp.biz; +package cc.iotkit.comps; import cc.iotkit.common.Constants; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; +import io.vertx.core.http.HttpMethod; import io.vertx.ext.web.client.HttpRequest; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.client.WebClientOptions; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; +import lombok.extern.slf4j.Slf4j; import java.nio.file.Paths; import java.util.HashMap; @@ -20,6 +22,7 @@ import java.util.concurrent.atomic.AtomicReference; /** * 平台API调用工具类 */ +@Slf4j public class ApiTool { private static final Vertx vertx; @@ -48,17 +51,19 @@ public class ApiTool { ApiTool.timeout = timeout; } + private static String getPath(String path) { + return Paths.get(Constants.API.DEVICE_BASE, path).toString(); + } + /** * 获取用户的设备列表 */ public static ApiResponse getDevices(String token) { HttpRequest request = client - .post(port, host, Paths.get(Constants.API.DEVICE_BASE, Constants.API.DEVICE_LIST - .replace("size", "1000") - .replace("page", "1")).toString()) - .timeout(timeout) - .putHeader("authorization", "Bearer " + token); - return sendJson(request, new HashMap<>()); + .post(port, host, getPath(Constants.API.DEVICE_LIST + .replace("{size}", "1000") + .replace("{page}", "1"))); + return send(token, HttpMethod.POST, request, new HashMap<>()); } /** @@ -66,11 +71,9 @@ public class ApiTool { */ public static ApiResponse getDeviceDetail(String token, String deviceId) { HttpRequest request = client - .post(port, host, Paths.get(Constants.API.DEVICE_BASE, Constants.API.DEVICE_DETAIL - .replace("deviceId", deviceId)).toString()) - .timeout(timeout) - .putHeader("authorization", "Bearer " + token); - return sendJson(request, new HashMap<>()); + .get(port, host, getPath(Constants.API.DEVICE_DETAIL + .replace("{deviceId}", deviceId))); + return send(token, HttpMethod.GET, request, new HashMap<>()); } /** @@ -78,11 +81,9 @@ public class ApiTool { */ public static ApiResponse setProperties(String token, String deviceId, Map properties) { HttpRequest request = client - .post(port, host, Paths.get(Constants.API.DEVICE_BASE, Constants.API.DEVICE_SET_PROPERTIES - .replace("deviceId", deviceId)).toString()) - .timeout(timeout) - .putHeader("authorization", "Bearer " + token); - return sendJson(request, properties); + .post(port, host, getPath(Constants.API.DEVICE_SET_PROPERTIES + .replace("{deviceId}", deviceId))); + return send(token, HttpMethod.POST, request, properties); } /** @@ -90,48 +91,70 @@ public class ApiTool { */ public static ApiResponse invokeService(String token, String deviceId, String service, Map params) { HttpRequest request = client - .post(port, host, Paths.get(Constants.API.DEVICE_BASE, Constants.API.DEVICE_INVOKE_SERVICE - .replace("deviceId", deviceId) - .replace("service", service)).toString()) - .timeout(timeout) - .putHeader("authorization", "Bearer " + token); - return sendJson(request, params); + .post(port, host, getPath(Constants.API.DEVICE_INVOKE_SERVICE + .replace("{deviceId}", deviceId) + .replace("{service}", service))); + return send(token, HttpMethod.POST, request, params); } - private static ApiResponse sendJson(HttpRequest request, Map params) { - AtomicReference apiResponse = new AtomicReference<>(new ApiResponse(500, "", null)); + private static ApiResponse send(String token, HttpMethod method, HttpRequest request, Map params) { + request = request + .timeout(timeout) + .putHeader("wrap-response", "json") + .putHeader("authorization", "Bearer " + token); + + AtomicReference apiResponse = new AtomicReference<>( + new ApiResponse(500, "", null, System.currentTimeMillis())); try { //转为同步模式便于提供给js调用 CountDownLatch wait = new CountDownLatch(1); - request.sendJson(params) - .onSuccess((response) -> { - System.out.println(response.bodyAsString()); - apiResponse.set(response.bodyAsJson(ApiResponse.class)); - wait.countDown(); - }) - .onFailure((err) -> { - err.printStackTrace(); - wait.countDown(); - }); + + if (method == HttpMethod.POST) { + request.sendJson(params) + .onSuccess((response) -> { + System.out.println(response.bodyAsString()); + apiResponse.set(response.bodyAsJson(ApiResponse.class)); + wait.countDown(); + }) + .onFailure((err) -> { + err.printStackTrace(); + wait.countDown(); + }); + } else if (method == HttpMethod.GET) { + request.send() + .onSuccess((response) -> { + apiResponse.set(response.bodyAsJson(ApiResponse.class)); + wait.countDown(); + }) + .onFailure((err) -> { + err.printStackTrace(); + wait.countDown(); + }); + } if (wait.await(timeout, TimeUnit.MILLISECONDS)) { return apiResponse.get(); } else { - apiResponse.get().setCode(500); + apiResponse.get().setStatus(500); apiResponse.get().setMessage("request timeout"); } } catch (Throwable e) { - apiResponse.get().setCode(500); + apiResponse.get().setStatus(500); apiResponse.get().setMessage(e.getMessage()); } return apiResponse.get(); } + public static void log(String msg) { + log.info(msg); + } + @Data @NoArgsConstructor @AllArgsConstructor public static class ApiResponse { - private int code; + private int status; private String message; private Object data; + private long timestamp; } } diff --git a/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/BizComponentManager.java b/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/BizComponentManager.java old mode 100644 new mode 100755 index 9022c14d..84702cce --- a/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/BizComponentManager.java +++ b/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/BizComponentManager.java @@ -61,16 +61,16 @@ public class BizComponentManager { } catch (Throwable e) { throw new BizException("get component instance error"); } - componentInstance.create(new CompConfig(300, component.getConfig())); - try { String componentScript = FileUtils.readFileToString(path. resolve(ProtocolComponent.SCRIPT_FILE_NAME).toFile(), "UTF-8"); componentInstance.setScript(componentScript); - register(id, componentInstance); } catch (IOException e) { throw new BizException("get component script error", e); } + componentInstance.create(new CompConfig(300, component.getConfig())); + + register(id, componentInstance); } public void register(String id, IComponent component) { diff --git a/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/ComponentManager.java b/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/ComponentManager.java new file mode 100755 index 00000000..1827c632 --- /dev/null +++ b/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/ComponentManager.java @@ -0,0 +1,48 @@ +package cc.iotkit.comps; + + +import cc.iotkit.model.protocol.ProtocolComponent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class ComponentManager { + + @Autowired + private BizComponentManager bizComponentManager; + + @Autowired + private DeviceComponentManager deviceComponentManager; + + + public void register(ProtocolComponent component) { + String type = component.getType(); + if (ProtocolComponent.TYPE_BIZ.equals(type)) { + bizComponentManager.register(component); + } else if (ProtocolComponent.TYPE_DEVICE.equals(type)) { + deviceComponentManager.register(component); + } + } + + public void deRegister(String id) { + bizComponentManager.deRegister(id); + deviceComponentManager.deRegister(id); + } + + public void start(String id) { + bizComponentManager.start(id); + deviceComponentManager.start(id); + } + + public void stop(String id) { + bizComponentManager.stop(id); + deviceComponentManager.stop(id); + } + + public boolean isRunning(String id) { + return bizComponentManager.isRunning(id) || deviceComponentManager.isRunning(id); + } + +} diff --git a/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/DeviceComponentManager.java b/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/DeviceComponentManager.java old mode 100644 new mode 100755 index af9b82cc..7b5256a4 --- a/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/DeviceComponentManager.java +++ b/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/DeviceComponentManager.java @@ -50,7 +50,8 @@ public class DeviceComponentManager { @PostConstruct public void init() { try { - List componentList = componentRepository.findByState(ProtocolComponent.STATE_RUNNING); + List componentList = componentRepository.findByStateAndType( + ProtocolComponent.STATE_RUNNING, ProtocolComponent.TYPE_DEVICE); for (ProtocolComponent component : componentList) { register(component); start(component.getId()); diff --git a/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/DeviceMessageHandler.java b/protocol-gateway/component-server/src/main/java/cc/iotkit/comps/DeviceMessageHandler.java old mode 100644 new mode 100755 diff --git a/protocol-gateway/component/src/main/java/cc/iotkit/comp/AbstractDeviceComponent.java b/protocol-gateway/component/src/main/java/cc/iotkit/comp/AbstractDeviceComponent.java old mode 100644 new mode 100755 diff --git a/protocol-gateway/component/src/main/java/cc/iotkit/comp/IComponent.java b/protocol-gateway/component/src/main/java/cc/iotkit/comp/IComponent.java old mode 100644 new mode 100755 diff --git a/protocol-gateway/component/src/main/java/cc/iotkit/comp/IDeviceComponent.java b/protocol-gateway/component/src/main/java/cc/iotkit/comp/IDeviceComponent.java old mode 100644 new mode 100755 diff --git a/protocol-gateway/emqx-component/dependency-reduced-pom.xml b/protocol-gateway/emqx-component/dependency-reduced-pom.xml old mode 100755 new mode 100644 index 04482694..b1d6e872 --- a/protocol-gateway/emqx-component/dependency-reduced-pom.xml +++ b/protocol-gateway/emqx-component/dependency-reduced-pom.xml @@ -43,19 +43,19 @@ io.vertx vertx-core - 4.2.6 + 4.2.2 provided io.vertx vertx-web-proxy - 4.2.6 + 4.2.2 provided io.vertx vertx-mqtt - 4.2.6 + 4.2.2 provided diff --git a/protocol-gateway/emqx-component/src/main/java/cc/iotkit/comp/emqx/EmqxDeviceComponent.java b/protocol-gateway/emqx-component/src/main/java/cc/iotkit/comp/emqx/EmqxDeviceComponent.java old mode 100644 new mode 100755 diff --git a/protocol-gateway/http-biz-component/.DS_Store b/protocol-gateway/http-biz-component/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a3c148ab93c7cf32694845be75a6aeb0e3f13311 GIT binary patch literal 6148 zcmeHK%}V4z5bhpFO$jtL1)mXJuM$2klGVIN>0 zK(D&{9_mB*BHpd)?h%I3qszKfLG@RuuBuMH4*kOzu2#+b_(vp^ARHZ*St_M=Wn z&3F*Gs*x}m^}Cl*Rzwrg>MWfc9vWv`Chpj%A`EO;KQQGAVAw;bd)Cj zw!5%dF-VbF5>R2oOk8{PRZP{&iaWL?{dJW-u z&0#|fHa40KvF?2v4sF|7THQJL-uwCM`sViT_n-R*JqsLuSS4Q!j^GiDF+#3_GS7}=!4+z((fI5|%D+br;;1?#&H&|)Z>5Qw9p^h1un;QyOqk~_laK?R&)Di>4 zz&Ha_`q9PxfBXIW|9BET5d*})f5iZ=Zv|T|_$0HpPJA5hwF2}U6b0idjjt(SsI3@c eaVuT~RRVs22B2@S(g+?9ItVBls38XaDg!TZMq*_E literal 0 HcmV?d00001 diff --git a/protocol-gateway/http-biz-component/dependency-reduced-pom.xml b/protocol-gateway/http-biz-component/dependency-reduced-pom.xml new file mode 100644 index 00000000..f3146daf --- /dev/null +++ b/protocol-gateway/http-biz-component/dependency-reduced-pom.xml @@ -0,0 +1,69 @@ + + + + protocol-gateway + cc.iotkit + 0.1.0-SNAPSHOT + + 4.0.0 + http-biz-component + + + + maven-shade-plugin + 3.2.4 + + + package + + shade + + + + + + + io.vertx:vertx-web-proxy + io.vertx:vertx-web + io.vertx:vertx-bridge-common + io.vertx:vertx-http-proxy + io.vertx:vertx-core + io.netty:netty-codec-http2 + + + + + + maven-compiler-plugin + + 8 + 8 + + + + + + + org.projectlombok + lombok + 1.18.22 + compile + + + io.vertx + vertx-web-proxy + 4.2.2 + provided + + + cc.iotkit + component + 0.1.0-SNAPSHOT + compile + + + + 8 + 8 + + diff --git a/protocol-gateway/http-biz-component/pom.xml b/protocol-gateway/http-biz-component/pom.xml old mode 100644 new mode 100755 index 42f8acda..195d1797 --- a/protocol-gateway/http-biz-component/pom.xml +++ b/protocol-gateway/http-biz-component/pom.xml @@ -28,17 +28,49 @@ vertx-web-proxy - - io.vertx - vertx-web-client - - cc.iotkit component - + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + package + + shade + + + + + + + io.vertx:vertx-web-proxy + io.vertx:vertx-web + io.vertx:vertx-bridge-common + io.vertx:vertx-http-proxy + io.vertx:vertx-core + io.netty:netty-codec-http2 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + + \ No newline at end of file diff --git a/protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/HttpBizComponent.java b/protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/HttpBizComponent.java old mode 100644 new mode 100755 index 0d694b00..0631050b --- a/protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/HttpBizComponent.java +++ b/protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/HttpBizComponent.java @@ -6,6 +6,7 @@ import cc.iotkit.comp.IComponent; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; +import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.Router; @@ -14,16 +15,21 @@ import jdk.nashorn.api.scripting.NashornScriptEngine; import jdk.nashorn.api.scripting.ScriptObjectMirror; import lombok.Data; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FileUtils; import javax.script.ScriptEngineManager; import javax.script.ScriptException; +import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -@Slf4j +import static java.nio.charset.StandardCharsets.UTF_8; + @Data +@Slf4j public class HttpBizComponent implements IComponent { private final Vertx vertx = Vertx.vertx(); @@ -32,7 +38,9 @@ public class HttpBizComponent implements IComponent { private Object scriptObj; - private HttpConfig config; + private CompConfig config; + + private HttpConfig httpConfig; private String script; @@ -40,7 +48,7 @@ public class HttpBizComponent implements IComponent { @Override public void create(CompConfig config) { - this.config = JsonUtil.parse(config.getOther(), HttpConfig.class); + this.httpConfig = JsonUtil.parse(config.getOther(), HttpConfig.class); try { scriptObj = engine.eval(String.format("new (function () {\n%s})()", script)); } catch (ScriptException e) { @@ -54,53 +62,75 @@ public class HttpBizComponent implements IComponent { Router backendRouter = Router.router(vertx); backendRouter.route().handler(BodyHandler.create()) .handler(rc -> { - Map httpHeader = getData(rc.request().headers()); - log.info("request header:{}", JsonUtil.toJsonString(httpHeader)); - Map> httpParams = getListData(rc.request().params()); - log.info("request params:{}", JsonUtil.toJsonString(httpParams)); + try { + Map httpHeader = getData(rc.request().headers()); + log.info("request header:{}", JsonUtil.toJsonString(httpHeader)); + Map> httpParams = getListData(rc.request().params()); + log.info("request params:{}", JsonUtil.toJsonString(httpParams)); - String contentType = rc.request().headers().get("Content-Type"); - JsonObject responseHeader = new JsonObject(); - if ("application/json".equals(contentType)) { - String bodyStr = rc.toString(); - Map body = JsonUtil.parse(bodyStr, Map.class); - log.info("request body:{}", bodyStr); + HttpServerRequest httpRequest = rc.request(); + String contentType = httpRequest.headers().get("Content-Type"); + JsonObject responseHeader = new JsonObject(); + if ("application/json".equals(contentType)) { + String bodyStr = rc.getBody().toString(); + Map body = JsonUtil.parse(bodyStr, Map.class); + log.info("request body:{}", bodyStr); - String response = "unknown error"; - String name = "onReceive"; - if (((ScriptObjectMirror) scriptObj).get(name) != null) { - try { - Object result = engine.invokeMethod(scriptObj, name, body); - Object resultObj = JsonUtil.toObject((ScriptObjectMirror) result); - if (resultObj instanceof Map) { - JsonObject data = JsonObject.mapFrom(resultObj); - responseHeader = data.getJsonObject("header"); - response = data.getString("content"); + String response = "unknown error"; + String name = "onReceive"; + if (((ScriptObjectMirror) scriptObj).get(name) != null) { + try { + Object result = engine.invokeMethod(scriptObj, + name, + httpRequest.method().name(), + httpRequest.path(), + httpHeader, + httpParams, + body); + Object resultObj = JsonUtil.toObject((ScriptObjectMirror) result); + if (resultObj instanceof Map) { + JsonObject data = JsonObject.mapFrom(resultObj); + responseHeader = data.getJsonObject("header"); + response = data.getString("content"); + response = response == null ? "" : response; + } + } catch (Throwable e) { + log.error("invokeMethod onReceive error", e); + response = e.getMessage(); } - } catch (Throwable e) { - log.error("invokeMethod onReceive error", e); - response = e.getMessage(); + } else { + log.error("required [onReceive] method"); } + + HttpServerResponse httpServerResponse = rc.response(); + //设置响应头 + responseHeader.getMap().forEach((key, value) -> { + //大写转换 + key = key.replaceAll("([A-Z])", "-$1").toLowerCase(); + httpServerResponse.putHeader(key, value.toString()); + }); + + log.info("response,header:{},content:{}", responseHeader, response); + //设置响应内容 + httpServerResponse + .end(response); } else { - log.error("required [onReceive] method"); + rc.response().end(""); } - - HttpServerResponse httpServerResponse = rc.response(); - //设置响应头 - responseHeader.getMap().forEach((key, value) -> { - //大写转换 - key = key.replaceAll("([A-Z])", "-$1").toLowerCase(); - httpServerResponse.putHeader(key, value.toString()); - }); - - log.info("response,header:{},content:{}", responseHeader, response); - //设置响应内容 - httpServerResponse - .end(response); + } catch (Throwable e) { + log.error("handle request error", e); + rc.response().end("server error:" + e.getMessage()); } }); - backendServer.requestHandler(backendRouter).listen(config.getPort()); + backendServer.requestHandler(backendRouter) + .listen(httpConfig.getPort(), (http) -> { + if (http.succeeded()) { + log.info("http server create succeed,port:{}", httpConfig.getPort()); + } else { + log.error("http server create failed", http.cause()); + } + }); } @Override @@ -131,4 +161,11 @@ public class HttpBizComponent implements IComponent { return data; } + public static void main(String[] args) throws IOException { + HttpBizComponent component = new HttpBizComponent(); + component.setScript(FileUtils.readFileToString(new File("/Users/sjg/home/gitee/open-source/iotkit-parent/protocol-gateway/http-biz-component/src/main/resources/component.js"), UTF_8)); + component.create(new CompConfig(1000, "{\"port\":9081}")); + component.start(); + } + } diff --git a/protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/HttpConfig.java b/protocol-gateway/http-biz-component/src/main/java/cc/iotkit/comp/biz/HttpConfig.java old mode 100644 new mode 100755 diff --git a/protocol-gateway/http-biz-component/src/main/resources/component.js b/protocol-gateway/http-biz-component/src/main/resources/component.js new file mode 100755 index 00000000..62112b41 --- /dev/null +++ b/protocol-gateway/http-biz-component/src/main/resources/component.js @@ -0,0 +1,36 @@ +//引用api工具类 +var apiTool = Java.type("cc.iotkit.comp.biz.ApiTool"); +//api配置 +apiTool.config("http://localhost",8086,3000); + +this.onReceive=function(method,path,header,params,body){ + //method:post、get、delete... + //path:请求路径 + //header:http请求头数据,结构:{xx:xx,yy:yy} + //params:请求参数,结构:{xx:[...],yy:[...]} + //body:请求体,当提交的数据为json格式时使用,结构:{xx:xx,yy:yy} + apiTool.log("onReceive method:"+method); + apiTool.log("onReceive path:"+path); + apiTool.log("onReceive header:"+header); + apiTool.log("onReceive params:"+params); + apiTool.log("onReceive body:"+body); + var duHeader=body.header; + var namespace=duHeader.namespace; + var requestName=duHeader.name; + var messageId=duHeader.messageId; + var duPayload=duHeader.payload; + var token=duHeader.accessToken; + + //设备发现 + if(namespace=="DuerOS.ConnectedHome.Discovery" && requestName=="DiscoverAppliancesRequest"){ + + } + + return { + url:"xx",//不指定直接作为响应返回 + header:{ + contentType:"xx" + }, + content:"xx" + } +} \ No newline at end of file diff --git a/protocol-gateway/http-biz-component/src/main/resources/component.spi b/protocol-gateway/http-biz-component/src/main/resources/component.spi old mode 100644 new mode 100755 diff --git a/protocol-gateway/mqtt-client-simulator/src/main/java/cc/iotkit/simulator/Application.java b/protocol-gateway/mqtt-client-simulator/src/main/java/cc/iotkit/simulator/Application.java index b693614c..d66aad78 100755 --- a/protocol-gateway/mqtt-client-simulator/src/main/java/cc/iotkit/simulator/Application.java +++ b/protocol-gateway/mqtt-client-simulator/src/main/java/cc/iotkit/simulator/Application.java @@ -11,8 +11,8 @@ public class Application { public static void main(String[] args) throws IOException { if (args.length == 0) { -// Mqtt.broker = "tcp://127.0.0.1:1883"; - Mqtt.broker = "tcp://120.76.96.206:1883"; + Mqtt.broker = "tcp://127.0.0.1:1883"; +// Mqtt.broker = "tcp://120.76.96.206:1883"; } else { Mqtt.broker = args[0]; } diff --git a/protocol-gateway/mqtt-component/dependency-reduced-pom.xml b/protocol-gateway/mqtt-component/dependency-reduced-pom.xml old mode 100755 new mode 100644 index cd6986cf..808e94fc --- a/protocol-gateway/mqtt-component/dependency-reduced-pom.xml +++ b/protocol-gateway/mqtt-component/dependency-reduced-pom.xml @@ -43,13 +43,13 @@ io.vertx vertx-core - 4.2.6 + 4.2.2 provided io.vertx vertx-mqtt - 4.2.6 + 4.2.2 provided diff --git a/protocol-gateway/mqtt-component/src/main/java/cc/iotkit/comp/mqtt/MqttDeviceComponent.java b/protocol-gateway/mqtt-component/src/main/java/cc/iotkit/comp/mqtt/MqttDeviceComponent.java old mode 100644 new mode 100755