diff --git a/.DS_Store b/.DS_Store index 112b470e..fabfb5f8 100755 Binary files a/.DS_Store and b/.DS_Store differ 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 f4c5579e..72eee3cb 100755 Binary files a/manager/.DS_Store and b/manager/.DS_Store differ 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 5008ddfc..b7222f61 100755 Binary files a/protocol-gateway/.DS_Store and b/protocol-gateway/.DS_Store differ 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 00000000..a3c148ab Binary files /dev/null and b/protocol-gateway/http-biz-component/.DS_Store differ 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