You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@linkis.apache.org by ca...@apache.org on 2022/11/18 13:25:59 UTC
[incubator-linkis] branch dev-1.3.1 updated: style: format restful class (#3840)
This is an automated email from the ASF dual-hosted git repository.
casion pushed a commit to branch dev-1.3.1
in repository https://gitbox.apache.org/repos/asf/incubator-linkis.git
The following commit(s) were added to refs/heads/dev-1.3.1 by this push:
new cefd319f8 style: format restful class (#3840)
cefd319f8 is described below
commit cefd319f8360e00a0992f2a0e810e09b4cf451bf
Author: Jack Xu <xu...@126.com>
AuthorDate: Fri Nov 18 21:25:52 2022 +0800
style: format restful class (#3840)
---
.../apache/linkis/restful/CommonRestfulApi.java | 16 +-
.../server/restful/EnginePluginRestful.java | 447 ++---
.../entrance/restful/EntranceLabelRestfulApi.java | 72 +-
.../entrance/restful/EntranceMetricRestfulApi.java | 151 +-
.../entrance/restful/EntranceRestfulApi.java | 1196 +++++++------
.../am/restful/ECResourceInfoRestfulApi.java | 239 ++-
.../linkis/manager/am/restful/EMRestfulApi.java | 596 ++++---
.../manager/am/restful/EngineRestfulApi.java | 609 ++++---
.../server/restful/DatasourceAccessRestfulApi.java | 159 +-
.../server/restful/DatasourceEnvRestfulApi.java | 134 +-
.../server/restful/DatasourceTypeRestfulApi.java | 143 +-
.../server/restful/ErrorCodeRestfulApi.java | 133 +-
.../server/restful/GatewayAuthTokenRestfulApi.java | 156 +-
.../RmExternalResourceProviderRestfulApi.java | 152 +-
.../server/restful/UdfManagerRestfulApi.java | 139 +-
.../server/restful/UdfTreeRestfulApi.java | 131 +-
.../linkis/bml/restful/BmlProjectRestful.java | 762 ++++----
.../apache/linkis/bml/restful/BmlRestfulApi.java | 1713 +++++++++---------
.../restful/api/ConfigurationRestfulApi.java | 711 ++++----
.../server/restful/ContextHistoryRestfulApi.java | 229 +--
.../cs/server/restful/ContextIDRestfulApi.java | 370 ++--
.../server/restful/ContextListenerRestfulApi.java | 99 +-
.../cs/server/restful/ContextRestfulApi.java | 564 +++---
.../core/restful/DataSourceAdminRestfulApi.java | 634 +++----
.../core/restful/DataSourceCoreRestfulApi.java | 1492 ++++++++--------
.../core/restful/DataSourceOperateRestfulApi.java | 151 +-
.../query/server/restful/MetadataCoreRestful.java | 549 +++---
.../query/server/restful/MetadataQueryRestful.java | 685 ++++----
.../metadata/restful/api/DataSourceRestfulApi.java | 262 +--
.../metadata/restful/api/MdqTableRestfulApi.java | 378 ++--
.../server/restful/LinkisErrorCodeRestful.java | 24 +-
.../instance/label/restful/InstanceRestful.java | 190 +-
.../jobhistory/restful/api/QueryRestfulApi.java | 624 ++++---
.../filesystem/restful/api/BMLFsRestfulApi.java | 277 +--
.../filesystem/restful/api/FsRestfulApi.java | 1832 ++++++++++----------
.../variable/restful/api/VariableRestfulApi.java | 88 +-
pom.xml | 5 -
37 files changed, 8138 insertions(+), 7974 deletions(-)
diff --git a/linkis-commons/linkis-module/src/main/java/org/apache/linkis/restful/CommonRestfulApi.java b/linkis-commons/linkis-module/src/main/java/org/apache/linkis/restful/CommonRestfulApi.java
index 596a48852..c7524e379 100644
--- a/linkis-commons/linkis-module/src/main/java/org/apache/linkis/restful/CommonRestfulApi.java
+++ b/linkis-commons/linkis-module/src/main/java/org/apache/linkis/restful/CommonRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -35,12 +35,12 @@ import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping(path = "/")
public class CommonRestfulApi {
- @Autowired private DiscoveryClient client;
+ @Autowired private DiscoveryClient client;
- @ApiOperation(value = "Offline", notes = "offline this service", response = Message.class)
- @RequestMapping(path = "/offline", method = RequestMethod.GET)
- public Message offline(HttpServletRequest req) {
- DiscoveryManager.getInstance().shutdownComponent();
- return Message.ok().data("msg", "Offline successfully.");
- }
+ @ApiOperation(value = "Offline", notes = "offline this service", response = Message.class)
+ @RequestMapping(path = "/offline", method = RequestMethod.GET)
+ public Message offline(HttpServletRequest req) {
+ DiscoveryManager.getInstance().shutdownComponent();
+ return Message.ok().data("msg", "Offline successfully.");
+ }
}
diff --git a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-plugin-server/src/main/java/org/apache/linkis/engineplugin/server/restful/EnginePluginRestful.java b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-plugin-server/src/main/java/org/apache/linkis/engineplugin/server/restful/EnginePluginRestful.java
index 86600e0fc..ab2b280a7 100644
--- a/linkis-computation-governance/linkis-engineconn/linkis-engineconn-plugin-server/src/main/java/org/apache/linkis/engineplugin/server/restful/EnginePluginRestful.java
+++ b/linkis-computation-governance/linkis-engineconn/linkis-engineconn-plugin-server/src/main/java/org/apache/linkis/engineplugin/server/restful/EnginePluginRestful.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,7 +17,6 @@
package org.apache.linkis.engineplugin.server.restful;
-import com.github.pagehelper.PageInfo;
import org.apache.linkis.bml.protocol.Version;
import org.apache.linkis.common.conf.Configuration;
import org.apache.linkis.engineplugin.server.entity.EngineConnBmlResource;
@@ -30,243 +29,281 @@ import org.apache.linkis.server.utils.ModuleUserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
+import java.util.List;
+
+import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.web.multipart.MultipartFile;
-
-import java.util.List;
@Api(tags = "ECP(engineconn plugin) operation")
@RestController
@RequestMapping(path = "/engineplugin")
public class EnginePluginRestful {
- private static final Logger log = LoggerFactory.getLogger(EnginePluginRestful.class);
+ private static final Logger log = LoggerFactory.getLogger(EnginePluginRestful.class);
- @Autowired private EngineConnResourceService engineConnResourceService;
- @Autowired private EnginePluginAdminService enginePluginAdminService;
+ @Autowired private EngineConnResourceService engineConnResourceService;
+ @Autowired private EnginePluginAdminService enginePluginAdminService;
- @ApiOperation(value = "rollBack", notes = "modify the default bmlResourceVersion of the engineplugin", response = Message.class)
- @RequestMapping(path = "/rollBack", method = RequestMethod.POST)
- public Message rollBackEnginePlugin(HttpServletRequest req,
- @RequestBody EngineConnBmlResource engineConnBmlResource) {
- String username = ModuleUserUtils.getOperationUser(req, "rollBackEnginePlugin");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to rollBack EnginePlugin {} {}", username,engineConnBmlResource.getEngineConnType(),engineConnBmlResource.getVersion());
- try {
- enginePluginAdminService.rollBackEnginePlugin(engineConnBmlResource);
- log.info("{} finished to rollBack EnginePlugin {} {}", username,engineConnBmlResource.getEngineConnType(),engineConnBmlResource.getVersion());
- return Message.ok();
- } catch (Exception e) {
- return Message.error(e.getMessage());
- }
- } else {
- return Message.error("Only administrators can operate");
- }
+ @ApiOperation(
+ value = "rollBack",
+ notes = "modify the default bmlResourceVersion of the engineplugin",
+ response = Message.class)
+ @RequestMapping(path = "/rollBack", method = RequestMethod.POST)
+ public Message rollBackEnginePlugin(
+ HttpServletRequest req, @RequestBody EngineConnBmlResource engineConnBmlResource) {
+ String username = ModuleUserUtils.getOperationUser(req, "rollBackEnginePlugin");
+ if (Configuration.isAdmin(username)) {
+ log.info(
+ "{} start to rollBack EnginePlugin {} {}",
+ username,
+ engineConnBmlResource.getEngineConnType(),
+ engineConnBmlResource.getVersion());
+ try {
+ enginePluginAdminService.rollBackEnginePlugin(engineConnBmlResource);
+ log.info(
+ "{} finished to rollBack EnginePlugin {} {}",
+ username,
+ engineConnBmlResource.getEngineConnType(),
+ engineConnBmlResource.getVersion());
+ return Message.ok();
+ } catch (Exception e) {
+ return Message.error(e.getMessage());
+ }
+ } else {
+ return Message.error("Only administrators can operate");
}
+ }
- @ApiOperation(value = "getVersionList", notes = "get all bmlResourceVersion of engineplugin", response = Message.class)
- @RequestMapping(path = "/getVersionList", method = RequestMethod.GET)
- public Message getVersionList(HttpServletRequest req,
- @RequestParam(value = "ecType", required = false) String ecType,
- @RequestParam(value = "version", required = false) String version,
- @RequestParam(value = "bmlResourceId", required = false) String bmlResourceId) {
- String username = ModuleUserUtils.getOperationUser(req, "getVersionList");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to get all ec resource versionList", username);
- try {
- List<Version> typeList = enginePluginAdminService.getVersionList(username,bmlResourceId);
- log.info("{} finished get all ec resource versionList", username);
- return Message.ok().data("versionList", typeList);
- } catch (Exception e) {
- return Message.error(e.getMessage());
- }
- } else {
- return Message.error("Only administrators can operate");
- }
+ @ApiOperation(
+ value = "getVersionList",
+ notes = "get all bmlResourceVersion of engineplugin",
+ response = Message.class)
+ @RequestMapping(path = "/getVersionList", method = RequestMethod.GET)
+ public Message getVersionList(
+ HttpServletRequest req,
+ @RequestParam(value = "ecType", required = false) String ecType,
+ @RequestParam(value = "version", required = false) String version,
+ @RequestParam(value = "bmlResourceId", required = false) String bmlResourceId) {
+ String username = ModuleUserUtils.getOperationUser(req, "getVersionList");
+ if (Configuration.isAdmin(username)) {
+ log.info("{} start to get all ec resource versionList", username);
+ try {
+ List<Version> typeList = enginePluginAdminService.getVersionList(username, bmlResourceId);
+ log.info("{} finished get all ec resource versionList", username);
+ return Message.ok().data("versionList", typeList);
+ } catch (Exception e) {
+ return Message.error(e.getMessage());
+ }
+ } else {
+ return Message.error("Only administrators can operate");
}
+ }
- @ApiOperation(value = "getTypeList", notes = "get all types of engineplugin", response = Message.class)
- @RequestMapping(path = "/getTypeList", method = RequestMethod.GET)
- public Message getTypeList(HttpServletRequest req) {
- String username = ModuleUserUtils.getOperationUser(req, "getTypeList");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to get all ec resource TypeList", username);
- try {
- List<String> typeList = enginePluginAdminService.getTypeList();
- log.info("{} finished get all ec resource TypeList", username);
- return Message.ok().data("typeList", typeList);
- } catch (Exception e) {
- return Message.error(e.getMessage());
- }
- } else {
- return Message.error("Only administrators can operate");
- }
+ @ApiOperation(
+ value = "getTypeList",
+ notes = "get all types of engineplugin",
+ response = Message.class)
+ @RequestMapping(path = "/getTypeList", method = RequestMethod.GET)
+ public Message getTypeList(HttpServletRequest req) {
+ String username = ModuleUserUtils.getOperationUser(req, "getTypeList");
+ if (Configuration.isAdmin(username)) {
+ log.info("{} start to get all ec resource TypeList", username);
+ try {
+ List<String> typeList = enginePluginAdminService.getTypeList();
+ log.info("{} finished get all ec resource TypeList", username);
+ return Message.ok().data("typeList", typeList);
+ } catch (Exception e) {
+ return Message.error(e.getMessage());
+ }
+ } else {
+ return Message.error("Only administrators can operate");
}
+ }
- @ApiOperation(value = "getTypeVersionList", notes = "get all versions of the engineplgin type", response = Message.class)
- @RequestMapping(path = "/getTypeVersionList/{type}", method = RequestMethod.GET)
- public Message getTypeVersionList(
- @PathVariable("type") String type,
- HttpServletRequest req) {
- String username = ModuleUserUtils.getOperationUser(req, "getTypeList");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to get all ec resource TypeList", username);
- try {
- List<String> typeList = enginePluginAdminService.getTypeVersionList(type);
- log.info("{} finished get all ec resource TypeList", username);
- return Message.ok().data("queryList", typeList);
- } catch (Exception e) {
- return Message.error(e.getMessage());
- }
- } else {
- return Message.error("Only administrators can operate");
- }
+ @ApiOperation(
+ value = "getTypeVersionList",
+ notes = "get all versions of the engineplgin type",
+ response = Message.class)
+ @RequestMapping(path = "/getTypeVersionList/{type}", method = RequestMethod.GET)
+ public Message getTypeVersionList(@PathVariable("type") String type, HttpServletRequest req) {
+ String username = ModuleUserUtils.getOperationUser(req, "getTypeList");
+ if (Configuration.isAdmin(username)) {
+ log.info("{} start to get all ec resource TypeList", username);
+ try {
+ List<String> typeList = enginePluginAdminService.getTypeVersionList(type);
+ log.info("{} finished get all ec resource TypeList", username);
+ return Message.ok().data("queryList", typeList);
+ } catch (Exception e) {
+ return Message.error(e.getMessage());
+ }
+ } else {
+ return Message.error("Only administrators can operate");
}
+ }
- @ApiOperation(value = "updateEnginePluginBML", notes = "Add a new version of the engineplugin", response = Message.class)
- @RequestMapping(path = "/updateEnginePluginBML", method = RequestMethod.POST)
- public Message updateEnginePluginBML(@RequestParam("file") MultipartFile file,
- @RequestParam(value = "ecType") String ecType,
- @RequestParam(value = "version") String version,
- HttpServletRequest req) {
- if(ecType.isEmpty() || ecType.length() == 0 || ecType.equals("null")){
- return Message.error("ecType is not null");
- }else if(version.isEmpty() || version.length() == 0 || version.equals("null")){
- return Message.error("version is not null");
- }
- file.getOriginalFilename().toLowerCase().endsWith(".zip");
- if(file.getOriginalFilename().toLowerCase().endsWith(".zip")){
- String username = ModuleUserUtils.getOperationUser(req, "uploadEnginePluginBML");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to update enginePlugin {} {}", username,ecType,version);
- try {
- enginePluginAdminService.uploadToECHome(file);
- RefreshEngineConnResourceRequest refreshEngineConnResourceRequest =
- new RefreshEngineConnResourceRequest();
- refreshEngineConnResourceRequest.setEngineConnType(ecType);
- refreshEngineConnResourceRequest.setVersion(version);
- engineConnResourceService.refresh(refreshEngineConnResourceRequest);
- } catch (Exception e) {
- return Message.error(e.getMessage());
- }
- log.info("{} finished to update enginePlugin {} {}", username,ecType,version);
- return Message.ok().data("mes", "upload file success");
- } else {
- return Message.error("Only administrators can operate");
- }
- }else {
- return Message.error("Only suppose zip format file");
+ @ApiOperation(
+ value = "updateEnginePluginBML",
+ notes = "Add a new version of the engineplugin",
+ response = Message.class)
+ @RequestMapping(path = "/updateEnginePluginBML", method = RequestMethod.POST)
+ public Message updateEnginePluginBML(
+ @RequestParam("file") MultipartFile file,
+ @RequestParam(value = "ecType") String ecType,
+ @RequestParam(value = "version") String version,
+ HttpServletRequest req) {
+ if (ecType.isEmpty() || ecType.length() == 0 || ecType.equals("null")) {
+ return Message.error("ecType is not null");
+ } else if (version.isEmpty() || version.length() == 0 || version.equals("null")) {
+ return Message.error("version is not null");
+ }
+ file.getOriginalFilename().toLowerCase().endsWith(".zip");
+ if (file.getOriginalFilename().toLowerCase().endsWith(".zip")) {
+ String username = ModuleUserUtils.getOperationUser(req, "uploadEnginePluginBML");
+ if (Configuration.isAdmin(username)) {
+ log.info("{} start to update enginePlugin {} {}", username, ecType, version);
+ try {
+ enginePluginAdminService.uploadToECHome(file);
+ RefreshEngineConnResourceRequest refreshEngineConnResourceRequest =
+ new RefreshEngineConnResourceRequest();
+ refreshEngineConnResourceRequest.setEngineConnType(ecType);
+ refreshEngineConnResourceRequest.setVersion(version);
+ engineConnResourceService.refresh(refreshEngineConnResourceRequest);
+ } catch (Exception e) {
+ return Message.error(e.getMessage());
}
+ log.info("{} finished to update enginePlugin {} {}", username, ecType, version);
+ return Message.ok().data("mes", "upload file success");
+ } else {
+ return Message.error("Only administrators can operate");
+ }
+ } else {
+ return Message.error("Only suppose zip format file");
}
+ }
- @ApiOperation(value = "list", notes = "list all engineplugin", response = Message.class)
- @RequestMapping(path = "/list", method = RequestMethod.GET)
- public Message list(
- @RequestParam(value = "ecType", required = false) String ecType,
- @RequestParam(value = "version", required = false) String version,
- @RequestParam(value = "currentPage", required = false) Integer currentPage,
- @RequestParam(value = "pageSize", required = false) Integer pageSize,
- HttpServletRequest req) {
- String username = ModuleUserUtils.getOperationUser(req, "list");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to list all ec resource", username);
- EnginePluginBMLVo enginePluginBMLVo =
- new EnginePluginBMLVo(
- ecType,version);
- enginePluginBMLVo.setCurrentPage(null != currentPage ? currentPage : 1);
- enginePluginBMLVo.setPageSize(null != pageSize ? pageSize : 10);
- PageInfo<EngineConnBmlResource> engineConnBmlResourcePageInfo = enginePluginAdminService.queryDataSourceInfoPage(enginePluginBMLVo);
- log.info("{} finished to list all ec resource", username);
- List<EngineConnBmlResource> queryList = engineConnBmlResourcePageInfo.getList();
- return Message.ok().data("queryList", queryList)
- .data("totalPage", engineConnBmlResourcePageInfo.getTotal());
- } else {
- return Message.error("Only administrators can operate");
- }
+ @ApiOperation(value = "list", notes = "list all engineplugin", response = Message.class)
+ @RequestMapping(path = "/list", method = RequestMethod.GET)
+ public Message list(
+ @RequestParam(value = "ecType", required = false) String ecType,
+ @RequestParam(value = "version", required = false) String version,
+ @RequestParam(value = "currentPage", required = false) Integer currentPage,
+ @RequestParam(value = "pageSize", required = false) Integer pageSize,
+ HttpServletRequest req) {
+ String username = ModuleUserUtils.getOperationUser(req, "list");
+ if (Configuration.isAdmin(username)) {
+ log.info("{} start to list all ec resource", username);
+ EnginePluginBMLVo enginePluginBMLVo = new EnginePluginBMLVo(ecType, version);
+ enginePluginBMLVo.setCurrentPage(null != currentPage ? currentPage : 1);
+ enginePluginBMLVo.setPageSize(null != pageSize ? pageSize : 10);
+ PageInfo<EngineConnBmlResource> engineConnBmlResourcePageInfo =
+ enginePluginAdminService.queryDataSourceInfoPage(enginePluginBMLVo);
+ log.info("{} finished to list all ec resource", username);
+ List<EngineConnBmlResource> queryList = engineConnBmlResourcePageInfo.getList();
+ return Message.ok()
+ .data("queryList", queryList)
+ .data("totalPage", engineConnBmlResourcePageInfo.getTotal());
+ } else {
+ return Message.error("Only administrators can operate");
}
+ }
- @ApiOperation(value = "uploadEnginePluginBML", notes = "add one engineplugin", response = Message.class)
- @RequestMapping(path = "/uploadEnginePluginBML", method = RequestMethod.POST)
- public Message uploadEnginePluginBML(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
- file.getOriginalFilename().toLowerCase().endsWith(".zip");
- if(file.getOriginalFilename().toLowerCase().endsWith(".zip")){
- String username = ModuleUserUtils.getOperationUser(req, "uploadEnginePluginBML");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to upload enginePlugin", username);
- try {
- enginePluginAdminService.uploadToECHome(file);
- } catch (Exception e) {
- return Message.error(e.getMessage());
- }
- engineConnResourceService.refreshAll(true);
- log.info("{} finished to upload enginePlugin", username);
- return Message.ok().data("mes", "upload file success");
- } else {
- return Message.error("Only administrators can operate");
- }
- }else {
- return Message.error("Only suppose zip format file");
+ @ApiOperation(
+ value = "uploadEnginePluginBML",
+ notes = "add one engineplugin bml",
+ response = Message.class)
+ @RequestMapping(path = "/uploadEnginePluginBML", method = RequestMethod.POST)
+ public Message uploadEnginePluginBML(
+ @RequestParam("file") MultipartFile file, HttpServletRequest req) {
+ file.getOriginalFilename().toLowerCase().endsWith(".zip");
+ if (file.getOriginalFilename().toLowerCase().endsWith(".zip")) {
+ String username = ModuleUserUtils.getOperationUser(req, "uploadEnginePluginBML");
+ if (Configuration.isAdmin(username)) {
+ log.info("{} start to upload enginePlugin", username);
+ try {
+ enginePluginAdminService.uploadToECHome(file);
+ } catch (Exception e) {
+ return Message.error(e.getMessage());
}
+ engineConnResourceService.refreshAll(true);
+ log.info("{} finished to upload enginePlugin", username);
+ return Message.ok().data("mes", "upload file success");
+ } else {
+ return Message.error("Only administrators can operate");
+ }
+ } else {
+ return Message.error("Only suppose zip format file");
}
+ }
- @ApiOperation(value = "deleteEnginePluginBML", notes = "delete one engineplugin", response = Message.class)
- @RequestMapping(path = "/deleteEnginePluginBML", method = RequestMethod.GET)
- public Message deleteEnginePluginBML(HttpServletRequest req,
- @RequestParam(value = "ecType") String ecType,
- @RequestParam(value = "version", required = false) String version) {
- String username = ModuleUserUtils.getOperationUser(req, "deleteEnginePluginBML");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to delete engineplugin {} {}", username,ecType,version);
- try {
- enginePluginAdminService.deleteEnginePluginBML(ecType,version,username);
- } catch (Exception e) {
- return Message.error(e.getMessage());
- }
- log.info("{} finished to delete engineplugin {} {}", username,ecType,version);
- return Message.ok().data("msg", "delete successfully");
- } else {
- return Message.error("Only administrators can operate");
- }
+ @ApiOperation(
+ value = "deleteEnginePluginBML",
+ notes = "delete one engineplugin bml",
+ response = Message.class)
+ @RequestMapping(path = "/deleteEnginePluginBML", method = RequestMethod.GET)
+ public Message deleteEnginePluginBML(
+ HttpServletRequest req,
+ @RequestParam(value = "ecType") String ecType,
+ @RequestParam(value = "version", required = false) String version) {
+ String username = ModuleUserUtils.getOperationUser(req, "deleteEnginePluginBML");
+ if (Configuration.isAdmin(username)) {
+ log.info("{} start to delete engineplugin {} {}", username, ecType, version);
+ try {
+ enginePluginAdminService.deleteEnginePluginBML(ecType, version, username);
+ } catch (Exception e) {
+ return Message.error(e.getMessage());
+ }
+ log.info("{} finished to delete engineplugin {} {}", username, ecType, version);
+ return Message.ok().data("msg", "delete successfully");
+ } else {
+ return Message.error("Only administrators can operate");
}
+ }
- @ApiOperation(value = "refreshAll", notes = "refresh all engineconn resource", response = Message.class)
- @RequestMapping(path = "/refreshAll", method = RequestMethod.GET)
- public Message refreshAll(HttpServletRequest req) {
- String username = ModuleUserUtils.getOperationUser(req, "refreshAll");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to refresh all ec resource", username);
- engineConnResourceService.refreshAll(true);
- log.info("{} finished to refresh all ec resource", username);
- return Message.ok().data("msg", "Refresh successfully");
- } else {
- return Message.error("Only administrators can operate");
- }
+ @ApiOperation(
+ value = "refreshAll",
+ notes = "refresh all engineconn resource",
+ response = Message.class)
+ @RequestMapping(path = "/refreshAll", method = RequestMethod.GET)
+ public Message refreshAll(HttpServletRequest req) {
+ String username = ModuleUserUtils.getOperationUser(req, "refreshAll");
+ if (Configuration.isAdmin(username)) {
+ log.info("{} start to refresh all ec resource", username);
+ engineConnResourceService.refreshAll(true);
+ log.info("{} finished to refresh all ec resource", username);
+ return Message.ok().data("msg", "Refresh successfully");
+ } else {
+ return Message.error("Only administrators can operate");
}
+ }
- @ApiOperation(value = "refreshAll", notes = "refresh one engineconn resource", response = Message.class)
- @RequestMapping(path = "/refresh", method = RequestMethod.GET)
- public Message refreshOne(
- HttpServletRequest req,
- @RequestParam(value = "ecType") String ecType,
- @RequestParam(value = "version", required = false) String version) {
- String username = ModuleUserUtils.getOperationUser(req, "refreshOne");
- if (Configuration.isAdmin(username)) {
- log.info("{} start to refresh {} ec resource", username, ecType);
- RefreshEngineConnResourceRequest refreshEngineConnResourceRequest =
- new RefreshEngineConnResourceRequest();
- refreshEngineConnResourceRequest.setEngineConnType(ecType);
- refreshEngineConnResourceRequest.setVersion(version);
- engineConnResourceService.refresh(refreshEngineConnResourceRequest);
- log.info("{} finished to refresh {} ec resource", username, ecType);
- return Message.ok().data("msg", "Refresh successfully");
- } else {
- return Message.error("Only administrators can operate");
- }
+ @ApiOperation(
+ value = "refreshOne",
+ notes = "refresh one engineconn resource",
+ response = Message.class)
+ @RequestMapping(path = "/refresh", method = RequestMethod.GET)
+ public Message refreshOne(
+ HttpServletRequest req,
+ @RequestParam(value = "ecType") String ecType,
+ @RequestParam(value = "version", required = false) String version) {
+ String username = ModuleUserUtils.getOperationUser(req, "refreshOne");
+ if (Configuration.isAdmin(username)) {
+ log.info("{} start to refresh {} ec resource", username, ecType);
+ RefreshEngineConnResourceRequest refreshEngineConnResourceRequest =
+ new RefreshEngineConnResourceRequest();
+ refreshEngineConnResourceRequest.setEngineConnType(ecType);
+ refreshEngineConnResourceRequest.setVersion(version);
+ engineConnResourceService.refresh(refreshEngineConnResourceRequest);
+ log.info("{} finished to refresh {} ec resource", username, ecType);
+ return Message.ok().data("msg", "Refresh successfully");
+ } else {
+ return Message.error("Only administrators can operate");
}
+ }
}
diff --git a/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceLabelRestfulApi.java b/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceLabelRestfulApi.java
index d10d44e64..6d35a91d5 100644
--- a/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceLabelRestfulApi.java
+++ b/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceLabelRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -29,6 +29,9 @@ import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
+import java.util.HashMap;
+import java.util.Map;
+
import com.fasterxml.jackson.databind.JsonNode;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
@@ -36,47 +39,44 @@ import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.HashMap;
-import java.util.Map;
-
@Api(tags = "entrance lable manager")
@RestController
@RequestMapping(path = "/entrance/operation/label")
public class EntranceLabelRestfulApi {
- private static final Logger logger = LoggerFactory.getLogger(EntranceLabelRestfulApi.class);
+ private static final Logger logger = LoggerFactory.getLogger(EntranceLabelRestfulApi.class);
- @ApiOperation(value = "update", notes = "update route label", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/update", method = RequestMethod.POST)
- public Message updateRouteLabel(HttpServletRequest req, @RequestBody JsonNode jsonNode) {
- String userName = ModuleUserUtils.getOperationUser(req, "updateRouteLabel");
- if (!Configuration.isAdmin(userName)) {
- return Message.error("Non-administrators cannot update Route Label");
- }
- String routeLabel = jsonNode.get("routeLabel").textValue();
- Map<String, Object> labels = new HashMap<String, Object>();
- logger.info("Prepare to update entrance label {}", routeLabel);
- labels.put(LabelKeyConstant.ROUTE_KEY, routeLabel);
- InsLabelRefreshRequest insLabelRefreshRequest = new InsLabelRefreshRequest();
- insLabelRefreshRequest.setLabels(labels);
- insLabelRefreshRequest.setServiceInstance(Sender.getThisServiceInstance());
- InstanceLabelClient.getInstance().refreshLabelsToInstance(insLabelRefreshRequest);
- logger.info("Finished to update entrance label {}", routeLabel);
- return Message.ok();
+ @ApiOperation(value = "update", notes = "update route label", response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/update", method = RequestMethod.POST)
+ public Message updateRouteLabel(HttpServletRequest req, @RequestBody JsonNode jsonNode) {
+ String userName = ModuleUserUtils.getOperationUser(req, "updateRouteLabel");
+ if (!Configuration.isAdmin(userName)) {
+ return Message.error("Non-administrators cannot update Route Label");
}
+ String routeLabel = jsonNode.get("routeLabel").textValue();
+ Map<String, Object> labels = new HashMap<String, Object>();
+ logger.info("Prepare to update entrance label {}", routeLabel);
+ labels.put(LabelKeyConstant.ROUTE_KEY, routeLabel);
+ InsLabelRefreshRequest insLabelRefreshRequest = new InsLabelRefreshRequest();
+ insLabelRefreshRequest.setLabels(labels);
+ insLabelRefreshRequest.setServiceInstance(Sender.getThisServiceInstance());
+ InstanceLabelClient.getInstance().refreshLabelsToInstance(insLabelRefreshRequest);
+ logger.info("Finished to update entrance label {}", routeLabel);
+ return Message.ok();
+ }
- @ApiOperation(value = "markoffline", notes = "add offline label", response = Message.class)
- @RequestMapping(path = "/markoffline", method = RequestMethod.GET)
- public Message updateRouteLabel(HttpServletRequest req) {
- Map<String, Object> labels = new HashMap<String, Object>();
- logger.info("Prepare to modify the routelabel of entry to offline");
- labels.put(LabelKeyConstant.ROUTE_KEY, "offline");
- InsLabelRefreshRequest insLabelRefreshRequest = new InsLabelRefreshRequest();
- insLabelRefreshRequest.setLabels(labels);
- insLabelRefreshRequest.setServiceInstance(Sender.getThisServiceInstance());
- InstanceLabelClient.getInstance().refreshLabelsToInstance(insLabelRefreshRequest);
- logger.info("Finished to modify the routelabel of entry to offline");
- return Message.ok();
- }
+ @ApiOperation(value = "markoffline", notes = "add offline label", response = Message.class)
+ @RequestMapping(path = "/markoffline", method = RequestMethod.GET)
+ public Message updateRouteLabel(HttpServletRequest req) {
+ Map<String, Object> labels = new HashMap<String, Object>();
+ logger.info("Prepare to modify the routelabel of entry to offline");
+ labels.put(LabelKeyConstant.ROUTE_KEY, "offline");
+ InsLabelRefreshRequest insLabelRefreshRequest = new InsLabelRefreshRequest();
+ insLabelRefreshRequest.setLabels(labels);
+ insLabelRefreshRequest.setServiceInstance(Sender.getThisServiceInstance());
+ InstanceLabelClient.getInstance().refreshLabelsToInstance(insLabelRefreshRequest);
+ logger.info("Finished to modify the routelabel of entry to offline");
+ return Message.ok();
+ }
}
diff --git a/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceMetricRestfulApi.java b/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceMetricRestfulApi.java
index 123cd1749..a09f55f23 100644
--- a/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceMetricRestfulApi.java
+++ b/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceMetricRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -47,90 +47,87 @@ import org.slf4j.LoggerFactory;
@RequestMapping(path = "/entrance/operation/metrics")
public class EntranceMetricRestfulApi {
- private EntranceServer entranceServer;
+ private EntranceServer entranceServer;
- private static final Logger logger = LoggerFactory.getLogger(EntranceMetricRestfulApi.class);
+ private static final Logger logger = LoggerFactory.getLogger(EntranceMetricRestfulApi.class);
- @Autowired
- public void setEntranceServer(EntranceServer entranceServer) {
- this.entranceServer = entranceServer;
+ @Autowired
+ public void setEntranceServer(EntranceServer entranceServer) {
+ this.entranceServer = entranceServer;
+ }
+
+ @ApiOperation(value = "taskinfo", notes = "get task info", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "user", dataType = "String", value = "User"),
+ @ApiImplicitParam(name = "creator", dataType = "String", value = "Creator"),
+ @ApiImplicitParam(name = "engineTypeLabel", dataType = "String", value = "engine type lable")
+ })
+ @RequestMapping(path = "/taskinfo", method = RequestMethod.GET)
+ public Message taskinfo(
+ HttpServletRequest req,
+ @RequestParam(value = "user", required = false) String user,
+ @RequestParam(value = "creator", required = false) String creator,
+ @RequestParam(value = "engineTypeLabel", required = false) String engineTypeLabelValue) {
+ String userName = ModuleUserUtils.getOperationUser(req, "taskinfo");
+ String queryUser = user;
+ if (!Configuration.isAdmin(userName)) {
+ if (StringUtils.isBlank(queryUser)) {
+ queryUser = userName;
+ } else if (!userName.equalsIgnoreCase(queryUser)) {
+ return Message.error("Non-administrators cannot view other users' task information");
+ }
+ }
+ String filterWords = creator;
+ if (StringUtils.isNotBlank(filterWords) && StringUtils.isNotBlank(queryUser)) {
+ filterWords = filterWords + "_" + queryUser;
+ } else if (StringUtils.isBlank(creator)) {
+ filterWords = queryUser;
}
+ EntranceJob[] undoneTasks = entranceServer.getAllUndoneTask(filterWords);
+ int taskNumber = 0;
+ int runningNumber = 0;
+ int queuedNumber = 0;
- @ApiOperation(value = "taskinfo", notes = "get task info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "user", required = false, dataType = "String", value = "User"),
- @ApiImplicitParam(name = "creator", required = false, dataType = "String", value = "Creator"),
- @ApiImplicitParam(name = "engineTypeLabel",required = false, dataType = "String", value = "engine type lable")
- })
- @RequestMapping(path = "/taskinfo", method = RequestMethod.GET)
- public Message taskinfo(
- HttpServletRequest req,
- @RequestParam(value = "user", required = false) String user,
- @RequestParam(value = "creator", required = false) String creator,
- @RequestParam(value = "engineTypeLabel", required = false)
- String engineTypeLabelValue) {
- String userName = ModuleUserUtils.getOperationUser(req, "taskinfo");
- String queryUser = user;
- if (!Configuration.isAdmin(userName)) {
- if (StringUtils.isBlank(queryUser)) {
- queryUser = userName;
- } else if (!userName.equalsIgnoreCase(queryUser)) {
- return Message.error(
- "Non-administrators cannot view other users' task information");
- }
+ if (null != undoneTasks) {
+ for (EntranceJob task : undoneTasks) {
+ if (StringUtils.isNotBlank(engineTypeLabelValue)) {
+ EngineTypeLabel engineTypeLabel =
+ LabelUtil.getEngineTypeLabel(task.getJobRequest().getLabels());
+ // Task types do not match, do not count
+ if (null == engineTypeLabel
+ || !engineTypeLabelValue.equalsIgnoreCase(engineTypeLabel.getStringValue())) {
+ continue;
+ }
}
- String filterWords = creator;
- if (StringUtils.isNotBlank(filterWords) && StringUtils.isNotBlank(queryUser)) {
- filterWords = filterWords + "_" + queryUser;
- } else if (StringUtils.isBlank(creator)) {
- filterWords = queryUser;
- }
- EntranceJob[] undoneTasks = entranceServer.getAllUndoneTask(filterWords);
- int taskNumber = 0;
- int runningNumber = 0;
- int queuedNumber = 0;
-
- if (null != undoneTasks) {
- for (EntranceJob task : undoneTasks) {
- if (StringUtils.isNotBlank(engineTypeLabelValue)) {
- EngineTypeLabel engineTypeLabel =
- LabelUtil.getEngineTypeLabel(task.getJobRequest().getLabels());
- // Task types do not match, do not count
- if (null == engineTypeLabel
- || !engineTypeLabelValue.equalsIgnoreCase(
- engineTypeLabel.getStringValue())) {
- continue;
- }
- }
- taskNumber++;
- if (task.isRunning()) {
- runningNumber++;
- } else {
- queuedNumber++;
- }
- }
+ taskNumber++;
+ if (task.isRunning()) {
+ runningNumber++;
+ } else {
+ queuedNumber++;
}
- return Message.ok("success")
- .data("taskNumber", taskNumber)
- .data("runningNumber", runningNumber)
- .data("queuedNumber", queuedNumber);
+ }
}
+ return Message.ok("success")
+ .data("taskNumber", taskNumber)
+ .data("runningNumber", runningNumber)
+ .data("queuedNumber", queuedNumber);
+ }
- @ApiOperation(value = "Status", notes = "get running task number ", response = Message.class)
- @RequestMapping(path = "/runningtask", method = RequestMethod.GET)
- public Message status(HttpServletRequest req) {
+ @ApiOperation(value = "Status", notes = "get running task number ", response = Message.class)
+ @RequestMapping(path = "/runningtask", method = RequestMethod.GET)
+ public Message status(HttpServletRequest req) {
- EntranceJob[] undoneTasks = entranceServer.getAllUndoneTask("");
- Boolean isCompleted = false;
- if (null == undoneTasks || undoneTasks.length < 1) {
- isCompleted = true;
- }
- int runningTaskNumber = 0;
- if (undoneTasks != null) {
- runningTaskNumber = undoneTasks.length;
- }
- return Message.ok("success")
- .data("runningTaskNumber", runningTaskNumber)
- .data("isCompleted", isCompleted);
+ EntranceJob[] undoneTasks = entranceServer.getAllUndoneTask("");
+ Boolean isCompleted = false;
+ if (null == undoneTasks || undoneTasks.length < 1) {
+ isCompleted = true;
+ }
+ int runningTaskNumber = 0;
+ if (undoneTasks != null) {
+ runningTaskNumber = undoneTasks.length;
}
+ return Message.ok("success")
+ .data("runningTaskNumber", runningTaskNumber)
+ .data("isCompleted", isCompleted);
+ }
}
diff --git a/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceRestfulApi.java b/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceRestfulApi.java
index 660e868be..b230bbd9d 100644
--- a/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceRestfulApi.java
+++ b/linkis-computation-governance/linkis-entrance/src/main/java/org/apache/linkis/entrance/restful/EntranceRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -51,15 +51,6 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -69,642 +60,639 @@ import java.util.Optional;
import scala.Option;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
/** Description: an implementation class of EntranceRestfulRemote */
@Api(tags = "task operation")
@RestController
@RequestMapping(path = "/entrance")
public class EntranceRestfulApi implements EntranceRestfulRemote {
- private EntranceServer entranceServer;
+ private EntranceServer entranceServer;
- private static final Logger logger = LoggerFactory.getLogger(EntranceRestfulApi.class);
+ private static final Logger logger = LoggerFactory.getLogger(EntranceRestfulApi.class);
- @Autowired
- public void setEntranceServer(EntranceServer entranceServer) {
- this.entranceServer = entranceServer;
- }
+ @Autowired
+ public void setEntranceServer(EntranceServer entranceServer) {
+ this.entranceServer = entranceServer;
+ }
- /**
- * The execute function handles the request submitted by the user to execute the task, and the
- * execution ID is returned to the user. execute函数处理的是用户提交执行任务的请求,返回给用户的是执行ID json Incoming
- * key-value pair(传入的键值对) Repsonse
- */
- @ApiOperation(value = "execute", notes = "execute the submitted task", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"json"})
- @Override
- @RequestMapping(path = "/execute", method = RequestMethod.POST)
- public Message execute(HttpServletRequest req, @RequestBody Map<String, Object> json) {
- Message message = null;
- logger.info("Begin to get an execID");
- json.put(TaskConstant.EXECUTE_USER, ModuleUserUtils.getOperationUser(req));
- json.put(TaskConstant.SUBMIT_USER, SecurityFilter.getLoginUsername(req));
- HashMap<String, String> map = (HashMap) json.get(TaskConstant.SOURCE);
- if (map == null) {
- map = new HashMap<>();
- json.put(TaskConstant.SOURCE, map);
- }
- String ip = JobHistoryHelper.getRequestIpAddr(req);
- map.put(TaskConstant.REQUEST_IP, ip);
- String jobId = entranceServer.execute(json);
- Job job = entranceServer.getJob(jobId).get();
- JobRequest jobReq = ((EntranceJob) job).getJobRequest();
- Long jobReqId = jobReq.getId();
- ModuleUserUtils.getOperationUser(req, "execute task,id: " + jobReqId);
- pushLog(
- LogUtils.generateInfo(
- "You have submitted a new job, script code (after variable substitution) is"),
- job);
- pushLog(
- "************************************SCRIPT CODE************************************",
- job);
- pushLog(jobReq.getExecutionCode(), job);
- pushLog(
- "************************************SCRIPT CODE************************************",
- job);
- String execID =
- ZuulEntranceUtils.generateExecID(
- jobId,
- Sender.getThisServiceInstance().getApplicationName(),
- new String[] {Sender.getThisInstance()});
- pushLog(
- LogUtils.generateInfo(
- "Your job is accepted, jobID is "
- + execID
- + " and taskID is "
- + jobReqId
- + " in "
- + Sender.getThisServiceInstance().toString()
- + ". Please wait it to be scheduled"),
- job);
- message = Message.ok();
- message.setMethod("/api/entrance/execute");
- message.data("execID", execID);
- message.data("taskID", jobReqId);
- logger.info("End to get an an execID: {}, taskID: {}", execID, jobReqId);
- return message;
+ /**
+ * The execute function handles the request submitted by the user to execute the task, and the
+ * execution ID is returned to the user. execute函数处理的是用户提交执行任务的请求,返回给用户的是执行ID json Incoming
+ * key-value pair(传入的键值对) Repsonse
+ */
+ @ApiOperation(value = "execute", notes = "execute the submitted task", response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"json"})
+ @Override
+ @RequestMapping(path = "/execute", method = RequestMethod.POST)
+ public Message execute(HttpServletRequest req, @RequestBody Map<String, Object> json) {
+ Message message = null;
+ logger.info("Begin to get an execID");
+ json.put(TaskConstant.EXECUTE_USER, ModuleUserUtils.getOperationUser(req));
+ json.put(TaskConstant.SUBMIT_USER, SecurityFilter.getLoginUsername(req));
+ HashMap<String, String> map = (HashMap) json.get(TaskConstant.SOURCE);
+ if (map == null) {
+ map = new HashMap<>();
+ json.put(TaskConstant.SOURCE, map);
}
+ String ip = JobHistoryHelper.getRequestIpAddr(req);
+ map.put(TaskConstant.REQUEST_IP, ip);
+ String jobId = entranceServer.execute(json);
+ Job job = entranceServer.getJob(jobId).get();
+ JobRequest jobReq = ((EntranceJob) job).getJobRequest();
+ Long jobReqId = jobReq.getId();
+ ModuleUserUtils.getOperationUser(req, "execute task,id: " + jobReqId);
+ pushLog(
+ LogUtils.generateInfo(
+ "You have submitted a new job, script code (after variable substitution) is"),
+ job);
+ pushLog(
+ "************************************SCRIPT CODE************************************", job);
+ pushLog(jobReq.getExecutionCode(), job);
+ pushLog(
+ "************************************SCRIPT CODE************************************", job);
+ String execID =
+ ZuulEntranceUtils.generateExecID(
+ jobId,
+ Sender.getThisServiceInstance().getApplicationName(),
+ new String[] {Sender.getThisInstance()});
+ pushLog(
+ LogUtils.generateInfo(
+ "Your job is accepted, jobID is "
+ + execID
+ + " and taskID is "
+ + jobReqId
+ + " in "
+ + Sender.getThisServiceInstance().toString()
+ + ". Please wait it to be scheduled"),
+ job);
+ message = Message.ok();
+ message.setMethod("/api/entrance/execute");
+ message.data("execID", execID);
+ message.data("taskID", jobReqId);
+ logger.info("End to get an an execID: {}, taskID: {}", execID, jobReqId);
+ return message;
+ }
- @ApiOperation(value = "submit", notes = "submit execute job", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"json"})
- @Override
- @RequestMapping(path = "/submit", method = RequestMethod.POST)
- public Message submit(HttpServletRequest req, @RequestBody Map<String, Object> json) {
- Message message = null;
- logger.info("Begin to get an execID");
- json.put(TaskConstant.EXECUTE_USER, ModuleUserUtils.getOperationUser(req));
- json.put(TaskConstant.SUBMIT_USER, SecurityFilter.getLoginUsername(req));
- HashMap<String, String> map = (HashMap) json.get(TaskConstant.SOURCE);
- if (map == null) {
- map = new HashMap<>();
- json.put(TaskConstant.SOURCE, map);
- }
- String ip = JobHistoryHelper.getRequestIpAddr(req);
- map.put(TaskConstant.REQUEST_IP, ip);
- String jobId = entranceServer.execute(json);
- Job job = entranceServer.getJob(jobId).get();
- JobRequest jobRequest = ((EntranceJob) job).getJobRequest();
- Long jobReqId = jobRequest.getId();
- pushLog(
- LogUtils.generateInfo(
- "You have submitted a new job, script code (after variable substitution) is"),
- job);
- pushLog(
- "************************************SCRIPT CODE************************************",
- job);
- pushLog(jobRequest.getExecutionCode(), job);
- pushLog(
- "************************************SCRIPT CODE************************************",
- job);
- pushLog(
- LogUtils.generateInfo(
- "Your job is accepted, jobID is "
- + jobId
- + " and jobReqId is "
- + jobReqId
- + " in "
- + Sender.getThisServiceInstance().toString()
- + ". Please wait it to be scheduled"),
- job);
- String execID =
- ZuulEntranceUtils.generateExecID(
- jobId,
- Sender.getThisServiceInstance().getApplicationName(),
- new String[] {Sender.getThisInstance()});
- message = Message.ok();
- message.setMethod("/api/entrance/submit");
- message.data("execID", execID);
- message.data("taskID", jobReqId);
- logger.info("End to get an an execID: {}, taskID: {}", execID, jobReqId);
- return message;
+ @ApiOperation(value = "submit", notes = "submit execute job", response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"json"})
+ @Override
+ @RequestMapping(path = "/submit", method = RequestMethod.POST)
+ public Message submit(HttpServletRequest req, @RequestBody Map<String, Object> json) {
+ Message message = null;
+ logger.info("Begin to get an execID");
+ json.put(TaskConstant.EXECUTE_USER, ModuleUserUtils.getOperationUser(req));
+ json.put(TaskConstant.SUBMIT_USER, SecurityFilter.getLoginUsername(req));
+ HashMap<String, String> map = (HashMap) json.get(TaskConstant.SOURCE);
+ if (map == null) {
+ map = new HashMap<>();
+ json.put(TaskConstant.SOURCE, map);
}
+ String ip = JobHistoryHelper.getRequestIpAddr(req);
+ map.put(TaskConstant.REQUEST_IP, ip);
+ String jobId = entranceServer.execute(json);
+ Job job = entranceServer.getJob(jobId).get();
+ JobRequest jobRequest = ((EntranceJob) job).getJobRequest();
+ Long jobReqId = jobRequest.getId();
+ pushLog(
+ LogUtils.generateInfo(
+ "You have submitted a new job, script code (after variable substitution) is"),
+ job);
+ pushLog(
+ "************************************SCRIPT CODE************************************", job);
+ pushLog(jobRequest.getExecutionCode(), job);
+ pushLog(
+ "************************************SCRIPT CODE************************************", job);
+ pushLog(
+ LogUtils.generateInfo(
+ "Your job is accepted, jobID is "
+ + jobId
+ + " and jobReqId is "
+ + jobReqId
+ + " in "
+ + Sender.getThisServiceInstance().toString()
+ + ". Please wait it to be scheduled"),
+ job);
+ String execID =
+ ZuulEntranceUtils.generateExecID(
+ jobId,
+ Sender.getThisServiceInstance().getApplicationName(),
+ new String[] {Sender.getThisInstance()});
+ message = Message.ok();
+ message.setMethod("/api/entrance/submit");
+ message.data("execID", execID);
+ message.data("taskID", jobReqId);
+ logger.info("End to get an an execID: {}, taskID: {}", execID, jobReqId);
+ return message;
+ }
- private void pushLog(String log, Job job) {
- entranceServer.getEntranceContext().getOrCreateLogManager().onLogUpdate(job, log);
- }
+ private void pushLog(String log, Job job) {
+ entranceServer.getEntranceContext().getOrCreateLogManager().onLogUpdate(job, log);
+ }
- @ApiOperation(value = "status", notes = "get task stats", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "taskID", required = false, dataType = "String", value = " task id"),
- @ApiImplicitParam(name = "id",required = true, dataType = "String", value = "execute id ")
- })
- @Override
- @RequestMapping(path = "/{id}/status", method = RequestMethod.GET)
- public Message status(
- @PathVariable("id") String id,
- @RequestParam(value = "taskID", required = false) String taskID) {
- Message message = null;
- String realId = ZuulEntranceUtils.parseExecID(id)[3];
- Option<Job> job = Option.apply(null);
- try {
- job = entranceServer.getJob(realId);
- } catch (Exception e) {
- logger.warn("获取任务 {} 状态时出现错误", realId, e.getMessage());
- long realTaskID = Long.parseLong(taskID);
- String status = JobHistoryHelper.getStatusByTaskID(realTaskID);
- message = Message.ok();
- message.setMethod("/api/entrance/" + id + "/status");
- message.data("status", status).data("execID", id);
- return message;
- }
- if (job.isDefined()) {
- if (job.get() instanceof EntranceJob) {
- ((EntranceJob) job.get()).updateNewestAccessByClientTimestamp();
- }
- message = Message.ok();
- message.setMethod("/api/entrance/" + id + "/status");
- message.data("status", job.get().getState().toString()).data("execID", id);
- } else {
- message =
- Message.error(
- "ID The corresponding job is empty and cannot obtain the corresponding task status.(ID 对应的job为空,不能获取相应的任务状态)");
- }
- return message;
+ @ApiOperation(value = "status", notes = "get task stats", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "taskID", required = false, dataType = "String", value = " task id"),
+ @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "execute id ")
+ })
+ @Override
+ @RequestMapping(path = "/{id}/status", method = RequestMethod.GET)
+ public Message status(
+ @PathVariable("id") String id,
+ @RequestParam(value = "taskID", required = false) String taskID) {
+ Message message = null;
+ String realId = ZuulEntranceUtils.parseExecID(id)[3];
+ Option<Job> job = Option.apply(null);
+ try {
+ job = entranceServer.getJob(realId);
+ } catch (Exception e) {
+ logger.warn("获取任务 {} 状态时出现错误", realId, e.getMessage());
+ long realTaskID = Long.parseLong(taskID);
+ String status = JobHistoryHelper.getStatusByTaskID(realTaskID);
+ message = Message.ok();
+ message.setMethod("/api/entrance/" + id + "/status");
+ message.data("status", status).data("execID", id);
+ return message;
+ }
+ if (job.isDefined()) {
+ if (job.get() instanceof EntranceJob) {
+ ((EntranceJob) job.get()).updateNewestAccessByClientTimestamp();
+ }
+ message = Message.ok();
+ message.setMethod("/api/entrance/" + id + "/status");
+ message.data("status", job.get().getState().toString()).data("execID", id);
+ } else {
+ message =
+ Message.error(
+ "ID The corresponding job is empty and cannot obtain the corresponding task status.(ID 对应的job为空,不能获取相应的任务状态)");
}
+ return message;
+ }
- @ApiOperation(value = "progress", notes = "get task progress info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "id",required = true, dataType = "String", value = "exectue id")
- })
- @Override
- @RequestMapping(path = "/{id}/progress", method = RequestMethod.GET)
- public Message progress(@PathVariable("id") String id) {
- Message message = null;
- String realId = ZuulEntranceUtils.parseExecID(id)[3];
- Option<Job> job = null;
- try {
- job = entranceServer.getJob(realId);
- } catch (Exception e) {
- logger.error(e.getMessage());
+ @ApiOperation(value = "progress", notes = "get task progress info", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "exectue id")
+ })
+ @Override
+ @RequestMapping(path = "/{id}/progress", method = RequestMethod.GET)
+ public Message progress(@PathVariable("id") String id) {
+ Message message = null;
+ String realId = ZuulEntranceUtils.parseExecID(id)[3];
+ Option<Job> job = null;
+ try {
+ job = entranceServer.getJob(realId);
+ } catch (Exception e) {
+ logger.error(e.getMessage());
+ }
+ if (job != null && job.isDefined()) {
+ JobProgressInfo[] jobProgressInfos = ((EntranceJob) job.get()).getProgressInfo();
+ if (jobProgressInfos == null) {
+ message =
+ Message.error(
+ "Can not get the corresponding progress information, it may be that the corresponding progress information has not been generated(不能获取相应的进度信息,可能是相应的进度信息还未生成)");
+ message.setMethod("/api/entrance/" + id + "/progress");
+ } else {
+ List<Map<String, Object>> list = new ArrayList<>();
+ for (JobProgressInfo jobProgressInfo : jobProgressInfos) {
+ if ("true".equals(EntranceConfiguration.PROGRESS_PUSH().getValue())
+ || jobProgressInfo.totalTasks() > 0) {
+ setJobProgressInfos(list, jobProgressInfo);
+ }
}
- if (job != null && job.isDefined()) {
- JobProgressInfo[] jobProgressInfos = ((EntranceJob) job.get()).getProgressInfo();
- if (jobProgressInfos == null) {
- message =
- Message.error(
- "Can not get the corresponding progress information, it may be that the corresponding progress information has not been generated(不能获取相应的进度信息,可能是相应的进度信息还未生成)");
- message.setMethod("/api/entrance/" + id + "/progress");
- } else {
- List<Map<String, Object>> list = new ArrayList<>();
- for (JobProgressInfo jobProgressInfo : jobProgressInfos) {
- if ("true".equals(EntranceConfiguration.PROGRESS_PUSH().getValue())
- || jobProgressInfo.totalTasks() > 0) {
- setJobProgressInfos(list, jobProgressInfo);
- }
- }
- message = Message.ok();
- message.setMethod("/api/entrance/" + id + "/progress");
+ message = Message.ok();
+ message.setMethod("/api/entrance/" + id + "/progress");
- message.data("progress", Math.abs(job.get().getProgress()))
- .data("execID", id)
- .data("progressInfo", list);
- }
- } else {
- message =
- Message.error(
- "The job corresponding to the ID is empty, and the corresponding task progress cannot be obtained.(ID 对应的job为空,不能获取相应的任务进度)");
- }
- return message;
+ message
+ .data("progress", Math.abs(job.get().getProgress()))
+ .data("execID", id)
+ .data("progressInfo", list);
+ }
+ } else {
+ message =
+ Message.error(
+ "The job corresponding to the ID is empty, and the corresponding task progress cannot be obtained.(ID 对应的job为空,不能获取相应的任务进度)");
}
+ return message;
+ }
- @ApiOperation(value = "progressWithResource", notes = "get progress and resource info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "execute id")
- })
- @Override
- @RequestMapping(path = "/{id}/progressWithResource", method = RequestMethod.GET)
- public Message progressWithResource(@PathVariable("id") String id) {
- Message message = null;
- String realId = ZuulEntranceUtils.parseExecID(id)[3];
- Option<Job> job = null;
- try {
- job = entranceServer.getJob(realId);
- } catch (Exception e) {
- logger.error(e.getMessage());
+ @ApiOperation(
+ value = "progressWithResource",
+ notes = "get progress and resource info",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "execute id")
+ })
+ @Override
+ @RequestMapping(path = "/{id}/progressWithResource", method = RequestMethod.GET)
+ public Message progressWithResource(@PathVariable("id") String id) {
+ Message message = null;
+ String realId = ZuulEntranceUtils.parseExecID(id)[3];
+ Option<Job> job = null;
+ try {
+ job = entranceServer.getJob(realId);
+ } catch (Exception e) {
+ logger.error(e.getMessage());
+ }
+ if (job != null && job.isDefined()) {
+ JobProgressInfo[] jobProgressInfos = ((EntranceJob) job.get()).getProgressInfo();
+ if (jobProgressInfos == null) {
+ message =
+ Message.error(
+ "Can not get the corresponding progress information, it may be that the corresponding progress information has not been generated(不能获取相应的进度信息,可能是相应的进度信息还未生成)");
+ message.setMethod("/api/entrance/" + id + "/progressWithResource");
+ } else {
+ List<Map<String, Object>> list = new ArrayList<>();
+ for (JobProgressInfo jobProgressInfo : jobProgressInfos) {
+ if ("true".equals(EntranceConfiguration.PROGRESS_PUSH().getValue())
+ || jobProgressInfo.totalTasks() > 0) {
+ setJobProgressInfos(list, jobProgressInfo);
+ }
}
- if (job != null && job.isDefined()) {
- JobProgressInfo[] jobProgressInfos = ((EntranceJob) job.get()).getProgressInfo();
- if (jobProgressInfos == null) {
- message =
- Message.error(
- "Can not get the corresponding progress information, it may be that the corresponding progress information has not been generated(不能获取相应的进度信息,可能是相应的进度信息还未生成)");
- message.setMethod("/api/entrance/" + id + "/progressWithResource");
- } else {
- List<Map<String, Object>> list = new ArrayList<>();
- for (JobProgressInfo jobProgressInfo : jobProgressInfos) {
- if ("true".equals(EntranceConfiguration.PROGRESS_PUSH().getValue())
- || jobProgressInfo.totalTasks() > 0) {
- setJobProgressInfos(list, jobProgressInfo);
- }
- }
- message = Message.ok();
- message.setMethod("/api/entrance/" + id + "/progressWithResource");
-
- JobRequest jobRequest = ((EntranceJob) job.get()).getJobRequest();
- Map<String, Object> metrics = jobRequest.getMetrics();
- Map<String, Object> metricsVo = new HashMap<>();
- if (metrics.containsKey(TaskConstant.ENTRANCEJOB_YARNRESOURCE)) {
- HashMap<String, ResourceWithStatus> resourceMap =
- (HashMap<String, ResourceWithStatus>)
- metrics.get(TaskConstant.ENTRANCEJOB_YARNRESOURCE);
- ArrayList<YarnResourceWithStatusVo> resoureList = new ArrayList<>(12);
- if (null != resourceMap && !resourceMap.isEmpty()) {
- resourceMap.forEach(
- (applicationId, resource) -> {
- resoureList.add(
- new YarnResourceWithStatusVo(applicationId, resource));
- });
- metricsVo.put(TaskConstant.ENTRANCEJOB_YARNRESOURCE, resoureList);
- Optional<Integer> cores =
- resourceMap.values().stream()
- .map(resource -> resource.queueCores())
- .reduce((x, y) -> x + y);
- Optional<Long> memory =
- resourceMap.values().stream()
- .map(resource -> resource.queueMemory())
- .reduce((x, y) -> x + y);
- float corePercent = 0.0f;
- float memoryPercent = 0.0f;
- if (cores.isPresent() && memory.isPresent()) {
- corePercent =
- cores.get().floatValue()
- / EntranceConfiguration.YARN_QUEUE_CORES_MAX()
- .getValue();
- memoryPercent =
- memory.get().floatValue()
- / (EntranceConfiguration.YARN_QUEUE_MEMORY_MAX()
- .getValue()
- .longValue()
- * 1024
- * 1024
- * 1024);
- }
- String coreRGB = RGBUtils.getRGB(corePercent);
- String memoryRGB = RGBUtils.getRGB(memoryPercent);
- metricsVo.put(TaskConstant.ENTRANCEJOB_CORE_PERCENT, corePercent);
- metricsVo.put(TaskConstant.ENTRANCEJOB_MEMORY_PERCENT, memoryPercent);
- metricsVo.put(TaskConstant.ENTRANCEJOB_CORE_RGB, coreRGB);
- metricsVo.put(TaskConstant.ENTRANCEJOB_MEMORY_RGB, memoryRGB);
-
- message.data(TaskConstant.ENTRANCEJOB_YARN_METRICS, metricsVo);
- } else {
- message.data(TaskConstant.ENTRANCEJOB_YARNRESOURCE, null);
- }
- } else {
- message.data(TaskConstant.ENTRANCEJOB_YARNRESOURCE, null);
- }
+ message = Message.ok();
+ message.setMethod("/api/entrance/" + id + "/progressWithResource");
- message.data("progress", Math.abs(job.get().getProgress()))
- .data("execID", id)
- .data("progressInfo", list);
+ JobRequest jobRequest = ((EntranceJob) job.get()).getJobRequest();
+ Map<String, Object> metrics = jobRequest.getMetrics();
+ Map<String, Object> metricsVo = new HashMap<>();
+ if (metrics.containsKey(TaskConstant.ENTRANCEJOB_YARNRESOURCE)) {
+ HashMap<String, ResourceWithStatus> resourceMap =
+ (HashMap<String, ResourceWithStatus>)
+ metrics.get(TaskConstant.ENTRANCEJOB_YARNRESOURCE);
+ ArrayList<YarnResourceWithStatusVo> resoureList = new ArrayList<>(12);
+ if (null != resourceMap && !resourceMap.isEmpty()) {
+ resourceMap.forEach(
+ (applicationId, resource) -> {
+ resoureList.add(new YarnResourceWithStatusVo(applicationId, resource));
+ });
+ metricsVo.put(TaskConstant.ENTRANCEJOB_YARNRESOURCE, resoureList);
+ Optional<Integer> cores =
+ resourceMap.values().stream()
+ .map(resource -> resource.queueCores())
+ .reduce((x, y) -> x + y);
+ Optional<Long> memory =
+ resourceMap.values().stream()
+ .map(resource -> resource.queueMemory())
+ .reduce((x, y) -> x + y);
+ float corePercent = 0.0f;
+ float memoryPercent = 0.0f;
+ if (cores.isPresent() && memory.isPresent()) {
+ corePercent =
+ cores.get().floatValue()
+ / EntranceConfiguration.YARN_QUEUE_CORES_MAX().getValue();
+ memoryPercent =
+ memory.get().floatValue()
+ / (EntranceConfiguration.YARN_QUEUE_MEMORY_MAX().getValue().longValue()
+ * 1024
+ * 1024
+ * 1024);
}
+ String coreRGB = RGBUtils.getRGB(corePercent);
+ String memoryRGB = RGBUtils.getRGB(memoryPercent);
+ metricsVo.put(TaskConstant.ENTRANCEJOB_CORE_PERCENT, corePercent);
+ metricsVo.put(TaskConstant.ENTRANCEJOB_MEMORY_PERCENT, memoryPercent);
+ metricsVo.put(TaskConstant.ENTRANCEJOB_CORE_RGB, coreRGB);
+ metricsVo.put(TaskConstant.ENTRANCEJOB_MEMORY_RGB, memoryRGB);
+
+ message.data(TaskConstant.ENTRANCEJOB_YARN_METRICS, metricsVo);
+ } else {
+ message.data(TaskConstant.ENTRANCEJOB_YARNRESOURCE, null);
+ }
} else {
- message =
- Message.error(
- "The job corresponding to the ID is empty, and the corresponding task progress cannot be obtained.(ID 对应的job为空,不能获取相应的任务进度)");
+ message.data(TaskConstant.ENTRANCEJOB_YARNRESOURCE, null);
}
- return message;
- }
- private void setJobProgressInfos(
- List<Map<String, Object>> list, JobProgressInfo jobProgressInfo) {
- Map<String, Object> map = new HashMap<>();
- map.put("id", jobProgressInfo.id());
- map.put("succeedTasks", jobProgressInfo.succeedTasks());
- map.put("failedTasks", jobProgressInfo.failedTasks());
- map.put("runningTasks", jobProgressInfo.runningTasks());
- map.put("totalTasks", jobProgressInfo.totalTasks());
- list.add(map);
+ message
+ .data("progress", Math.abs(job.get().getProgress()))
+ .data("execID", id)
+ .data("progressInfo", list);
+ }
+ } else {
+ message =
+ Message.error(
+ "The job corresponding to the ID is empty, and the corresponding task progress cannot be obtained.(ID 对应的job为空,不能获取相应的任务进度)");
}
+ return message;
+ }
- @ApiOperation(value = "log", notes = "get task log", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "execute id")
- })
- @Override
- @RequestMapping(path = "/{id}/log", method = RequestMethod.GET)
- public Message log(HttpServletRequest req, @PathVariable("id") String id) {
- String realId = ZuulEntranceUtils.parseExecID(id)[3];
- Option<Job> job = Option.apply(null);
- Message message = null;
- try {
- job = entranceServer.getJob(realId);
- } catch (final Throwable t) {
- message =
- Message.error(
- "The job you just executed has ended. This interface no longer provides a query. It is recommended that you download the log file for viewing.(您刚刚执行的job已经结束,本接口不再提供查询,建议您下载日志文件进行查看)");
- message.setMethod("/api/entrance/" + id + "/log");
- return message;
- }
- if (job.isDefined()) {
- logger.debug(
- "begin to get log for {}(开始获取 {} 的日志)", job.get().getId(), job.get().getId());
- LogReader logReader =
- entranceServer
- .getEntranceContext()
- .getOrCreateLogManager()
- .getLogReader(realId);
- int fromLine = 0;
- int size = 100;
- boolean distinctLevel = true;
- if (req != null) {
- String fromLineStr = req.getParameter("fromLine");
- String sizeStr = req.getParameter("size");
- if (StringUtils.isNotBlank(fromLineStr)) {
- fromLine = Math.max(Integer.parseInt(fromLineStr), 0);
- }
- if (StringUtils.isNotBlank(sizeStr)) {
- size = Integer.parseInt(sizeStr) >= 0 ? Integer.parseInt(sizeStr) : 10000;
- }
- String distinctLevelStr = req.getParameter("distinctLevel");
- if ("false".equals(distinctLevelStr)) {
- distinctLevel = false;
- }
- }
+ private void setJobProgressInfos(
+ List<Map<String, Object>> list, JobProgressInfo jobProgressInfo) {
+ Map<String, Object> map = new HashMap<>();
+ map.put("id", jobProgressInfo.id());
+ map.put("succeedTasks", jobProgressInfo.succeedTasks());
+ map.put("failedTasks", jobProgressInfo.failedTasks());
+ map.put("runningTasks", jobProgressInfo.runningTasks());
+ map.put("totalTasks", jobProgressInfo.totalTasks());
+ list.add(map);
+ }
- Object retLog = null;
- int retFromLine = 0;
- try {
- if (distinctLevel) {
- String[] logs = new String[4];
- retFromLine = logReader.readArray(logs, fromLine, size);
- retLog = new ArrayList<String>(Arrays.asList(logs));
- } else {
- StringBuilder sb = new StringBuilder();
- retFromLine = logReader.read(sb, fromLine, size);
- retLog = sb.toString();
- }
- } catch (IllegalStateException e) {
- logger.debug(
- "Failed to get log information for :{}(为 {} 获取日志失败)",
- job.get().getId(),
- job.get().getId(),
- e);
- message = Message.ok();
- message.setMethod("/api/entrance/" + id + "/log");
- message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine);
- } catch (final IllegalArgumentException e) {
- logger.debug(
- "Failed to get log information for :{}(为 {} 获取日志失败)",
- job.get().getId(),
- job.get().getId(),
- e);
- message = Message.ok();
- message.setMethod("/api/entrance/" + id + "/log");
- message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine);
- return message;
- } catch (final Exception e1) {
- logger.debug(
- "Failed to get log information for :{}(为 {} 获取日志失败)",
- job.get().getId(),
- job.get().getId(),
- e1);
- message = Message.error("Failed to get log information(获取日志信息失败)");
- message.setMethod("/api/entrance/" + id + "/log");
- message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine);
- return message;
- } finally {
- if (null != logReader && job.get().isCompleted()) {
- IOUtils.closeQuietly(logReader);
- }
- }
- message = Message.ok();
- message.setMethod("/api/entrance/" + id + "/log");
- message.data("log", retLog).data("execID", id).data("fromLine", retFromLine + fromLine);
- logger.debug(
- "success to get log for {} (获取 {} 日志成功)", job.get().getId(), job.get().getId());
- } else {
- message =
- Message.error(
- "Can't find execID(不能找到execID): "
- + id
- + "Corresponding job, can not get the corresponding log(对应的job,不能获得对应的日志)");
- message.setMethod("/api/entrance/" + id + "/log");
- }
- return message;
+ @ApiOperation(value = "log", notes = "get task log", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "execute id")
+ })
+ @Override
+ @RequestMapping(path = "/{id}/log", method = RequestMethod.GET)
+ public Message log(HttpServletRequest req, @PathVariable("id") String id) {
+ String realId = ZuulEntranceUtils.parseExecID(id)[3];
+ Option<Job> job = Option.apply(null);
+ Message message = null;
+ try {
+ job = entranceServer.getJob(realId);
+ } catch (final Throwable t) {
+ message =
+ Message.error(
+ "The job you just executed has ended. This interface no longer provides a query. It is recommended that you download the log file for viewing.(您刚刚执行的job已经结束,本接口不再提供查询,建议您下载日志文件进行查看)");
+ message.setMethod("/api/entrance/" + id + "/log");
+ return message;
}
-
- @ApiOperation(value = "killJobs", notes = "kill jobs", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "strongExecId", required = true, dataType = "String", value = "strong execte id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @Override
- @RequestMapping(path = "/{id}/killJobs", method = RequestMethod.POST)
- public Message killJobs(
- HttpServletRequest req,
- @RequestBody JsonNode jsonNode,
- @PathVariable("id") String strongExecId) {
- JsonNode idNode = jsonNode.get("idList");
- JsonNode taskIDNode = jsonNode.get("taskIDList");
- ArrayList<Long> waitToForceKill = new ArrayList<>();
- if (idNode.size() != taskIDNode.size()) {
- return Message.error(
- "The length of the ID list does not match the length of the TASKID list(id列表的长度与taskId列表的长度不一致)");
+ if (job.isDefined()) {
+ logger.debug("begin to get log for {}(开始获取 {} 的日志)", job.get().getId(), job.get().getId());
+ LogReader logReader =
+ entranceServer.getEntranceContext().getOrCreateLogManager().getLogReader(realId);
+ int fromLine = 0;
+ int size = 100;
+ boolean distinctLevel = true;
+ if (req != null) {
+ String fromLineStr = req.getParameter("fromLine");
+ String sizeStr = req.getParameter("size");
+ if (StringUtils.isNotBlank(fromLineStr)) {
+ fromLine = Math.max(Integer.parseInt(fromLineStr), 0);
}
- if (!idNode.isArray() || !taskIDNode.isArray()) {
- return Message.error("Request parameter error, please use array(请求参数错误,请使用数组)");
+ if (StringUtils.isNotBlank(sizeStr)) {
+ size = Integer.parseInt(sizeStr) >= 0 ? Integer.parseInt(sizeStr) : 10000;
}
- ArrayList<Message> messages = new ArrayList<>();
- for (int i = 0; i < idNode.size(); i++) {
- String id = idNode.get(i).asText();
- Long taskID = taskIDNode.get(i).asLong();
- String realId = ZuulEntranceUtils.parseExecID(id)[3];
- Option<Job> job = Option.apply(null);
- try {
- job = entranceServer.getJob(realId);
- } catch (Exception e) {
- logger.warn(
- "can not find a job in entranceServer, will force to kill it",
- e.getMessage());
- // 如果在内存中找不到该任务,那么该任务可能已经完成了,或者就是重启导致的
- waitToForceKill.add(taskID);
- Message message = Message.ok("Forced Kill task (强制杀死任务)");
- message.setMethod("/api/entrance/" + id + "/kill");
- message.setStatus(0);
- messages.add(message);
- continue;
- }
- Message message = null;
- if (job.isEmpty()) {
- logger.warn("can not find a job in entranceServer, will force to kill it");
- waitToForceKill.add(taskID);
- message = Message.ok("Forced Kill task (强制杀死任务)");
- message.setMethod("/api/entrance/" + id + "/killJobs");
- message.setStatus(0);
- messages.add(message);
- } else {
- try {
- logger.info("begin to kill job {} ", job.get().getId());
- job.get().kill();
- message = Message.ok("Successfully killed the job(成功kill了job)");
- message.setMethod("/api/entrance/" + id + "/kill");
- message.setStatus(0);
- message.data("execID", id);
- // ensure the job's state is cancelled in database
- if (job.get() instanceof EntranceJob) {
- EntranceJob entranceJob = (EntranceJob) job.get();
- JobRequest jobReq = entranceJob.getJobRequest();
- entranceJob.updateJobRequestStatus(
- SchedulerEventState.Cancelled().toString());
- jobReq.setProgress("1.0f");
- LogListener logListener = entranceJob.getLogListener().getOrElse(null);
- if (null != logListener) {
- logListener.onLogUpdate(
- entranceJob,
- "Job "
- + jobReq.getId()
- + " was kill by user successfully(任务"
- + jobReq.getId()
- + "已成功取消)");
- }
- this.entranceServer
- .getEntranceContext()
- .getOrCreatePersistenceManager()
- .createPersistenceEngine()
- .updateIfNeeded(jobReq);
- }
- logger.info("end to kill job {} ", job.get().getId());
- } catch (Throwable t) {
- logger.error("kill job {} failed ", job.get().getId(), t);
- message =
- Message.error(
- "An exception occurred while killing the job, kill failed(kill job的时候出现了异常,kill失败)");
- message.setMethod("/api/entrance/" + id + "/kill");
- message.setStatus(1);
- }
- }
- messages.add(message);
+ String distinctLevelStr = req.getParameter("distinctLevel");
+ if ("false".equals(distinctLevelStr)) {
+ distinctLevel = false;
}
- if (!waitToForceKill.isEmpty()) {
- JobHistoryHelper.forceBatchKill(waitToForceKill);
+ }
+
+ Object retLog = null;
+ int retFromLine = 0;
+ try {
+ if (distinctLevel) {
+ String[] logs = new String[4];
+ retFromLine = logReader.readArray(logs, fromLine, size);
+ retLog = new ArrayList<String>(Arrays.asList(logs));
+ } else {
+ StringBuilder sb = new StringBuilder();
+ retFromLine = logReader.read(sb, fromLine, size);
+ retLog = sb.toString();
+ }
+ } catch (IllegalStateException e) {
+ logger.debug(
+ "Failed to get log information for :{}(为 {} 获取日志失败)",
+ job.get().getId(),
+ job.get().getId(),
+ e);
+ message = Message.ok();
+ message.setMethod("/api/entrance/" + id + "/log");
+ message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine);
+ } catch (final IllegalArgumentException e) {
+ logger.debug(
+ "Failed to get log information for :{}(为 {} 获取日志失败)",
+ job.get().getId(),
+ job.get().getId(),
+ e);
+ message = Message.ok();
+ message.setMethod("/api/entrance/" + id + "/log");
+ message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine);
+ return message;
+ } catch (final Exception e1) {
+ logger.debug(
+ "Failed to get log information for :{}(为 {} 获取日志失败)",
+ job.get().getId(),
+ job.get().getId(),
+ e1);
+ message = Message.error("Failed to get log information(获取日志信息失败)");
+ message.setMethod("/api/entrance/" + id + "/log");
+ message.data("log", "").data("execID", id).data("fromLine", retFromLine + fromLine);
+ return message;
+ } finally {
+ if (null != logReader && job.get().isCompleted()) {
+ IOUtils.closeQuietly(logReader);
}
- return Message.ok("success").data("messages", messages);
+ }
+ message = Message.ok();
+ message.setMethod("/api/entrance/" + id + "/log");
+ message.data("log", retLog).data("execID", id).data("fromLine", retFromLine + fromLine);
+ logger.debug("success to get log for {} (获取 {} 日志成功)", job.get().getId(), job.get().getId());
+ } else {
+ message =
+ Message.error(
+ "Can't find execID(不能找到execID): "
+ + id
+ + "Corresponding job, can not get the corresponding log(对应的job,不能获得对应的日志)");
+ message.setMethod("/api/entrance/" + id + "/log");
}
+ return message;
+ }
- @ApiOperation(value = "kill", notes = "kill", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "excute id"),
- @ApiImplicitParam(name = "taskID", required = false, dataType = "String", value = "task id")
- })
- @Override
- @RequestMapping(path = "/{id}/kill", method = RequestMethod.GET)
- public Message kill(
- @PathVariable("id") String id,
- @RequestParam(value = "taskID", required = false) Long taskID) {
- String realId = ZuulEntranceUtils.parseExecID(id)[3];
- Option<Job> job = Option.apply(null);
+ @ApiOperation(value = "killJobs", notes = "kill jobs", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "strongExecId", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @Override
+ @RequestMapping(path = "/{id}/killJobs", method = RequestMethod.POST)
+ public Message killJobs(
+ HttpServletRequest req,
+ @RequestBody JsonNode jsonNode,
+ @PathVariable("id") String strongExecId) {
+ JsonNode idNode = jsonNode.get("idList");
+ JsonNode taskIDNode = jsonNode.get("taskIDList");
+ ArrayList<Long> waitToForceKill = new ArrayList<>();
+ if (idNode.size() != taskIDNode.size()) {
+ return Message.error(
+ "The length of the ID list does not match the length of the TASKID list(id列表的长度与taskId列表的长度不一致)");
+ }
+ if (!idNode.isArray() || !taskIDNode.isArray()) {
+ return Message.error("Request parameter error, please use array(请求参数错误,请使用数组)");
+ }
+ ArrayList<Message> messages = new ArrayList<>();
+ for (int i = 0; i < idNode.size(); i++) {
+ String id = idNode.get(i).asText();
+ Long taskID = taskIDNode.get(i).asLong();
+ String realId = ZuulEntranceUtils.parseExecID(id)[3];
+ Option<Job> job = Option.apply(null);
+ try {
+ job = entranceServer.getJob(realId);
+ } catch (Exception e) {
+ logger.warn("can not find a job in entranceServer, will force to kill it", e.getMessage());
+ // 如果在内存中找不到该任务,那么该任务可能已经完成了,或者就是重启导致的
+ waitToForceKill.add(taskID);
+ Message message = Message.ok("Forced Kill task (强制杀死任务)");
+ message.setMethod("/api/entrance/" + id + "/kill");
+ message.setStatus(0);
+ messages.add(message);
+ continue;
+ }
+ Message message = null;
+ if (job.isEmpty()) {
+ logger.warn("can not find a job in entranceServer, will force to kill it");
+ waitToForceKill.add(taskID);
+ message = Message.ok("Forced Kill task (强制杀死任务)");
+ message.setMethod("/api/entrance/" + id + "/killJobs");
+ message.setStatus(0);
+ messages.add(message);
+ } else {
try {
- job = entranceServer.getJob(realId);
- } catch (Exception e) {
- logger.warn("can not find a job in entranceServer, will force to kill it", e);
- // 如果在内存中找不到该任务,那么该任务可能已经完成了,或者就是重启导致的
- JobHistoryHelper.forceKill(taskID);
- Message message = Message.ok("Forced Kill task (强制杀死任务)");
- message.setMethod("/api/entrance/" + id + "/kill");
- message.setStatus(0);
- return message;
- }
- Message message = null;
- if (job.isEmpty()) {
- logger.warn("can not find a job in entranceServer, will force to kill it");
- // 如果在内存中找不到该任务,那么该任务可能已经完成了,或者就是重启导致的
- JobHistoryHelper.forceKill(taskID);
- message = Message.ok("Forced Kill task (强制杀死任务)");
- message.setMethod("/api/entrance/" + id + "/kill");
- message.setStatus(0);
- return message;
- } else {
- try {
- logger.info("begin to kill job {} ", job.get().getId());
- job.get().kill();
- message = Message.ok("Successfully killed the job(成功kill了job)");
- message.setMethod("/api/entrance/" + id + "/kill");
- message.setStatus(0);
- message.data("execID", id);
- // ensure the job's state is cancelled in database
- if (job.get() instanceof EntranceJob) {
- EntranceJob entranceJob = (EntranceJob) job.get();
- JobRequest jobReq = entranceJob.getJobRequest();
- entranceJob.updateJobRequestStatus(SchedulerEventState.Cancelled().toString());
- this.entranceServer
- .getEntranceContext()
- .getOrCreatePersistenceManager()
- .createPersistenceEngine()
- .updateIfNeeded(jobReq);
- }
- logger.info("end to kill job {} ", job.get().getId());
- } catch (Throwable t) {
- logger.error("kill job {} failed ", job.get().getId(), t);
- message =
- Message.error(
- "An exception occurred while killing the job, kill failed(kill job的时候出现了异常,kill失败)");
- message.setMethod("/api/entrance/" + id + "/kill");
- message.setStatus(1);
+ logger.info("begin to kill job {} ", job.get().getId());
+ job.get().kill();
+ message = Message.ok("Successfully killed the job(成功kill了job)");
+ message.setMethod("/api/entrance/" + id + "/kill");
+ message.setStatus(0);
+ message.data("execID", id);
+ // ensure the job's state is cancelled in database
+ if (job.get() instanceof EntranceJob) {
+ EntranceJob entranceJob = (EntranceJob) job.get();
+ JobRequest jobReq = entranceJob.getJobRequest();
+ entranceJob.updateJobRequestStatus(SchedulerEventState.Cancelled().toString());
+ jobReq.setProgress("1.0f");
+ LogListener logListener = entranceJob.getLogListener().getOrElse(null);
+ if (null != logListener) {
+ logListener.onLogUpdate(
+ entranceJob,
+ "Job "
+ + jobReq.getId()
+ + " was kill by user successfully(任务"
+ + jobReq.getId()
+ + "已成功取消)");
}
+ this.entranceServer
+ .getEntranceContext()
+ .getOrCreatePersistenceManager()
+ .createPersistenceEngine()
+ .updateIfNeeded(jobReq);
+ }
+ logger.info("end to kill job {} ", job.get().getId());
+ } catch (Throwable t) {
+ logger.error("kill job {} failed ", job.get().getId(), t);
+ message =
+ Message.error(
+ "An exception occurred while killing the job, kill failed(kill job的时候出现了异常,kill失败)");
+ message.setMethod("/api/entrance/" + id + "/kill");
+ message.setStatus(1);
}
- return message;
+ }
+ messages.add(message);
+ }
+ if (!waitToForceKill.isEmpty()) {
+ JobHistoryHelper.forceBatchKill(waitToForceKill);
}
+ return Message.ok("success").data("messages", messages);
+ }
- @ApiOperation(value = "pause ", notes = "puase a task job", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "excete id")
- })
- @Override
- @RequestMapping(path = "/{id}/pause", method = RequestMethod.GET)
- public Message pause(@PathVariable("id") String id) {
- String realId = ZuulEntranceUtils.parseExecID(id)[3];
- Option<Job> job = entranceServer.getJob(realId);
- Message message = null;
- if (job.isEmpty()) {
- message =
- Message.error(
- "can not find the job of exexID :"
- + id
- + " can not pause (不能找到execID: "
- + id
- + "对应的job,不能进行pause)");
- message.setMethod("/api/entrance/" + id + "/pause");
- message.setStatus(1);
- } else {
- try {
- // todo job pause 接口还未实现和给出
- // job.pause();
- logger.info("begin to pause job {} ", job.get().getId());
- message = Message.ok("success to pause job (成功pause了job)");
- message.setStatus(0);
- message.data("execID", id);
- message.setMethod("/api/entrance/" + id + "/pause");
- logger.info("end to pause job {} ", job.get().getId());
- } catch (Throwable t) {
- logger.info("pause job {} failed ", job.get().getId());
- message =
- Message.error(
- "Abnormal when pausing job, pause failed(pause job的时候出现了异常,pause失败)");
- message.setMethod("/api/entrance/" + id + "/pause");
- message.setStatus(1);
- }
+ @ApiOperation(value = "kill", notes = "kill", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "excute id"),
+ @ApiImplicitParam(name = "taskID", required = false, dataType = "String", value = "task id")
+ })
+ @Override
+ @RequestMapping(path = "/{id}/kill", method = RequestMethod.GET)
+ public Message kill(
+ @PathVariable("id") String id,
+ @RequestParam(value = "taskID", required = false) Long taskID) {
+ String realId = ZuulEntranceUtils.parseExecID(id)[3];
+ Option<Job> job = Option.apply(null);
+ try {
+ job = entranceServer.getJob(realId);
+ } catch (Exception e) {
+ logger.warn("can not find a job in entranceServer, will force to kill it", e);
+ // 如果在内存中找不到该任务,那么该任务可能已经完成了,或者就是重启导致的
+ JobHistoryHelper.forceKill(taskID);
+ Message message = Message.ok("Forced Kill task (强制杀死任务)");
+ message.setMethod("/api/entrance/" + id + "/kill");
+ message.setStatus(0);
+ return message;
+ }
+ Message message = null;
+ if (job.isEmpty()) {
+ logger.warn("can not find a job in entranceServer, will force to kill it");
+ // 如果在内存中找不到该任务,那么该任务可能已经完成了,或者就是重启导致的
+ JobHistoryHelper.forceKill(taskID);
+ message = Message.ok("Forced Kill task (强制杀死任务)");
+ message.setMethod("/api/entrance/" + id + "/kill");
+ message.setStatus(0);
+ return message;
+ } else {
+ try {
+ logger.info("begin to kill job {} ", job.get().getId());
+ job.get().kill();
+ message = Message.ok("Successfully killed the job(成功kill了job)");
+ message.setMethod("/api/entrance/" + id + "/kill");
+ message.setStatus(0);
+ message.data("execID", id);
+ // ensure the job's state is cancelled in database
+ if (job.get() instanceof EntranceJob) {
+ EntranceJob entranceJob = (EntranceJob) job.get();
+ JobRequest jobReq = entranceJob.getJobRequest();
+ entranceJob.updateJobRequestStatus(SchedulerEventState.Cancelled().toString());
+ this.entranceServer
+ .getEntranceContext()
+ .getOrCreatePersistenceManager()
+ .createPersistenceEngine()
+ .updateIfNeeded(jobReq);
}
+ logger.info("end to kill job {} ", job.get().getId());
+ } catch (Throwable t) {
+ logger.error("kill job {} failed ", job.get().getId(), t);
+ message =
+ Message.error(
+ "An exception occurred while killing the job, kill failed(kill job的时候出现了异常,kill失败)");
+ message.setMethod("/api/entrance/" + id + "/kill");
+ message.setStatus(1);
+ }
+ }
+ return message;
+ }
- return message;
+ @ApiOperation(value = "pause ", notes = "puase a task job", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "id", required = true, dataType = "String", value = "excete id")
+ })
+ @Override
+ @RequestMapping(path = "/{id}/pause", method = RequestMethod.GET)
+ public Message pause(@PathVariable("id") String id) {
+ String realId = ZuulEntranceUtils.parseExecID(id)[3];
+ Option<Job> job = entranceServer.getJob(realId);
+ Message message = null;
+ if (job.isEmpty()) {
+ message =
+ Message.error(
+ "can not find the job of exexID :"
+ + id
+ + " can not pause (不能找到execID: "
+ + id
+ + "对应的job,不能进行pause)");
+ message.setMethod("/api/entrance/" + id + "/pause");
+ message.setStatus(1);
+ } else {
+ try {
+ // todo job pause 接口还未实现和给出
+ // job.pause();
+ logger.info("begin to pause job {} ", job.get().getId());
+ message = Message.ok("success to pause job (成功pause了job)");
+ message.setStatus(0);
+ message.data("execID", id);
+ message.setMethod("/api/entrance/" + id + "/pause");
+ logger.info("end to pause job {} ", job.get().getId());
+ } catch (Throwable t) {
+ logger.info("pause job {} failed ", job.get().getId());
+ message =
+ Message.error("Abnormal when pausing job, pause failed(pause job的时候出现了异常,pause失败)");
+ message.setMethod("/api/entrance/" + id + "/pause");
+ message.setStatus(1);
+ }
}
+
+ return message;
+ }
}
diff --git a/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/ECResourceInfoRestfulApi.java b/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/ECResourceInfoRestfulApi.java
index 61c8eadce..256db9866 100644
--- a/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/ECResourceInfoRestfulApi.java
+++ b/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/ECResourceInfoRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -37,6 +37,8 @@ import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
+import java.util.*;
+
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
@@ -44,135 +46,132 @@ import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
-import java.util.*;
-
@Api(tags = "enginneconn resource info operation")
@RequestMapping(
- path = "/linkisManager/ecinfo",
- produces = {"application/json"})
+ path = "/linkisManager/ecinfo",
+ produces = {"application/json"})
@RestController
public class ECResourceInfoRestfulApi {
- @Autowired private ECResourceInfoService ecResourceInfoService;
+ @Autowired private ECResourceInfoService ecResourceInfoService;
- @ApiOperation(value = "get", notes = "get engineconn info ", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "ticketid", required = true, dataType = "String", value = "ticket id")
- })
- @RequestMapping(path = "/get", method = RequestMethod.GET)
- public Message getECInfo(
- HttpServletRequest req, @RequestParam(value = "ticketid") String ticketid)
- throws AMErrorException {
- String userName = ModuleUserUtils.getOperationUser(req, "getECInfo");
- ECResourceInfoRecord ecResourceInfoRecord =
- ecResourceInfoService.getECResourceInfoRecord(ticketid);
- if (null != ecResourceInfoRecord
- && (userName.equalsIgnoreCase(ecResourceInfoRecord.getCreateUser())
- || Configuration.isAdmin(userName))) {
- return Message.ok().data("ecResourceInfoRecord", ecResourceInfoRecord);
- } else {
- return Message.error("tickedId not exist:" + ticketid);
- }
+ @ApiOperation(value = "get", notes = "get engineconn info ", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "ticketid", required = true, dataType = "String", value = "ticket id")
+ })
+ @RequestMapping(path = "/get", method = RequestMethod.GET)
+ public Message getECInfo(
+ HttpServletRequest req, @RequestParam(value = "ticketid") String ticketid)
+ throws AMErrorException {
+ String userName = ModuleUserUtils.getOperationUser(req, "getECInfo");
+ ECResourceInfoRecord ecResourceInfoRecord =
+ ecResourceInfoService.getECResourceInfoRecord(ticketid);
+ if (null != ecResourceInfoRecord
+ && (userName.equalsIgnoreCase(ecResourceInfoRecord.getCreateUser())
+ || Configuration.isAdmin(userName))) {
+ return Message.ok().data("ecResourceInfoRecord", ecResourceInfoRecord);
+ } else {
+ return Message.error("tickedId not exist:" + ticketid);
}
+ }
- @ApiOperation(value = "delete", notes = "delete engineconn info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "ticketid", required = true, dataType = "String", value = "ticket id")
- })
- @RequestMapping(path = "/delete/{ticketid}}", method = RequestMethod.DELETE)
- public Message deleteECInfo(HttpServletRequest req, @PathVariable("ticketid") String ticketid)
- throws AMErrorException {
- String userName = ModuleUserUtils.getOperationUser(req, "deleteECInfo");
- ECResourceInfoRecord ecResourceInfoRecord =
- ecResourceInfoService.getECResourceInfoRecord(ticketid);
- if (null != ecResourceInfoRecord
- && (userName.equalsIgnoreCase(ecResourceInfoRecord.getCreateUser())
- || Configuration.isAdmin(userName))) {
- ecResourceInfoService.deleteECResourceInfoRecord(ecResourceInfoRecord.getId());
- return Message.ok().data("ecResourceInfoRecord", ecResourceInfoRecord);
- } else {
- return Message.error("tickedId not exist:" + ticketid);
- }
+ @ApiOperation(value = "delete", notes = "delete engineconn info", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "ticketid", required = true, dataType = "String", value = "ticket id")
+ })
+ @RequestMapping(path = "/delete/{ticketid}}", method = RequestMethod.DELETE)
+ public Message deleteECInfo(HttpServletRequest req, @PathVariable("ticketid") String ticketid)
+ throws AMErrorException {
+ String userName = ModuleUserUtils.getOperationUser(req, "deleteECInfo");
+ ECResourceInfoRecord ecResourceInfoRecord =
+ ecResourceInfoService.getECResourceInfoRecord(ticketid);
+ if (null != ecResourceInfoRecord
+ && (userName.equalsIgnoreCase(ecResourceInfoRecord.getCreateUser())
+ || Configuration.isAdmin(userName))) {
+ ecResourceInfoService.deleteECResourceInfoRecord(ecResourceInfoRecord.getId());
+ return Message.ok().data("ecResourceInfoRecord", ecResourceInfoRecord);
+ } else {
+ return Message.error("tickedId not exist:" + ticketid);
}
+ }
- @ApiOperation(value = "ecrHistoryList", notes = "query engineconn resource history info list", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "instance", required = false, dataType = "String", value = "instance"),
- @ApiImplicitParam(name = "creator", required = false, dataType = "String", value = "creator"),
- @ApiImplicitParam(name = "startDate", required = false, dataType = "String", value = "start date"),
- @ApiImplicitParam(name = "endDate", required = false, dataType = "String", value = "end date"),
- @ApiImplicitParam(name = "engineType", required = false, dataType = "String", value = "engine type"),
- @ApiImplicitParam(name = "pageNow", required = false, dataType = "String", value = "page now"),
- @ApiImplicitParam(name = "pageSize", required = false, dataType = "String", value = "page size")
- })
- @RequestMapping(path = "/ecrHistoryList", method = RequestMethod.GET)
- public Message queryEcrHistory(
- HttpServletRequest req,
- @RequestParam(value = "instance", required = false) String instance,
- @RequestParam(value = "creator", required = false) String creator,
- @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- @RequestParam(value = "startDate", required = false)
- Date startDate,
- @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- @RequestParam(
- value = "endDate",
- required = false,
- defaultValue = "#{new java.util.Date()}")
- Date endDate,
- @RequestParam(value = "engineType", required = false) String engineType,
- @RequestParam(value = "pageNow", required = false, defaultValue = "1") Integer pageNow,
- @RequestParam(value = "pageSize", required = false, defaultValue = "20")
- Integer pageSize) {
- String username = SecurityFilter.getLoginUsername(req);
- // Parameter judgment
- instance = ECResourceInfoUtils.strCheckAndDef(instance, null);
- String creatorUser = ECResourceInfoUtils.strCheckAndDef(creator, null);
- engineType = ECResourceInfoUtils.strCheckAndDef(engineType, null);
- if (null != creatorUser && !ECResourceInfoUtils.checkNameValid(creatorUser)) {
- return Message.error("Invalid creator : " + creatorUser);
- }
- if (null == startDate) {
- Calendar calendar = Calendar.getInstance();
- calendar.set(Calendar.HOUR_OF_DAY, 0);
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- startDate = calendar.getTime();
- }
- if (Configuration.isAdmin(username)) {
- username = null;
- if (StringUtils.isNotBlank(creatorUser)) {
- username = creatorUser;
- }
- }
- List<ECResourceInfoRecordVo> list = new ArrayList<>();
- List<ECResourceInfoRecord> queryTasks = null;
+ @ApiOperation(
+ value = "ecrHistoryList",
+ notes = "query engineconn resource history info list",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "instance", dataType = "String", value = "instance"),
+ @ApiImplicitParam(name = "creator", dataType = "String", value = "creator"),
+ @ApiImplicitParam(name = "startDate", dataType = "String", value = "start date"),
+ @ApiImplicitParam(name = "endDate", dataType = "String", value = "end date"),
+ @ApiImplicitParam(name = "engineType", dataType = "String", value = "engine type"),
+ @ApiImplicitParam(name = "pageNow", dataType = "String", value = "page now"),
+ @ApiImplicitParam(name = "pageSize", dataType = "String", value = "page size")
+ })
+ @RequestMapping(path = "/ecrHistoryList", method = RequestMethod.GET)
+ public Message queryEcrHistory(
+ HttpServletRequest req,
+ @RequestParam(value = "instance", required = false) String instance,
+ @RequestParam(value = "creator", required = false) String creator,
+ @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
+ @RequestParam(value = "startDate", required = false)
+ Date startDate,
+ @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
+ @RequestParam(
+ value = "endDate",
+ required = false,
+ defaultValue = "#{new java.util.Date()}")
+ Date endDate,
+ @RequestParam(value = "engineType", required = false) String engineType,
+ @RequestParam(value = "pageNow", required = false, defaultValue = "1") Integer pageNow,
+ @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
+ String username = SecurityFilter.getLoginUsername(req);
+ // Parameter judgment
+ instance = ECResourceInfoUtils.strCheckAndDef(instance, null);
+ String creatorUser = ECResourceInfoUtils.strCheckAndDef(creator, null);
+ engineType = ECResourceInfoUtils.strCheckAndDef(engineType, null);
+ if (null != creatorUser && !ECResourceInfoUtils.checkNameValid(creatorUser)) {
+ return Message.error("Invalid creator : " + creatorUser);
+ }
+ if (null == startDate) {
+ Calendar calendar = Calendar.getInstance();
+ calendar.set(Calendar.HOUR_OF_DAY, 0);
+ calendar.set(Calendar.MINUTE, 0);
+ calendar.set(Calendar.SECOND, 0);
+ startDate = calendar.getTime();
+ }
+ if (Configuration.isAdmin(username)) {
+ username = null;
+ if (StringUtils.isNotBlank(creatorUser)) {
+ username = creatorUser;
+ }
+ }
+ List<ECResourceInfoRecordVo> list = new ArrayList<>();
+ List<ECResourceInfoRecord> queryTasks = null;
- PageHelper.startPage(pageNow, pageSize);
- try {
- queryTasks =
- ecResourceInfoService.getECResourceInfoRecordList(
- instance, endDate, startDate, username, engineType);
- queryTasks.forEach(
- info -> {
- ECResourceInfoRecordVo ecrHistroryListVo = new ECResourceInfoRecordVo();
- BeanUtils.copyProperties(info, ecrHistroryListVo);
- ecrHistroryListVo.setEngineType(
- info.getLabelValue().split(",")[1].split("-")[0]);
- ecrHistroryListVo.setUsedResource(
- ECResourceInfoUtils.getStringToMap(info.getUsedResource(), info));
- ecrHistroryListVo.setReleasedResource(
- ECResourceInfoUtils.getStringToMap(
- info.getReleasedResource(), info));
- ecrHistroryListVo.setRequestResource(
- ECResourceInfoUtils.getStringToMap(
- info.getRequestResource(), info));
- list.add(ecrHistroryListVo);
- });
- } finally {
- PageHelper.clearPage();
- }
- PageInfo<ECResourceInfoRecord> pageInfo = new PageInfo<>(queryTasks);
- long total = pageInfo.getTotal();
- return Message.ok().data("engineList", list).data(JobRequestConstants.TOTAL_PAGE(), total);
+ PageHelper.startPage(pageNow, pageSize);
+ try {
+ queryTasks =
+ ecResourceInfoService.getECResourceInfoRecordList(
+ instance, endDate, startDate, username, engineType);
+ queryTasks.forEach(
+ info -> {
+ ECResourceInfoRecordVo ecrHistroryListVo = new ECResourceInfoRecordVo();
+ BeanUtils.copyProperties(info, ecrHistroryListVo);
+ ecrHistroryListVo.setEngineType(info.getLabelValue().split(",")[1].split("-")[0]);
+ ecrHistroryListVo.setUsedResource(
+ ECResourceInfoUtils.getStringToMap(info.getUsedResource(), info));
+ ecrHistroryListVo.setReleasedResource(
+ ECResourceInfoUtils.getStringToMap(info.getReleasedResource(), info));
+ ecrHistroryListVo.setRequestResource(
+ ECResourceInfoUtils.getStringToMap(info.getRequestResource(), info));
+ list.add(ecrHistroryListVo);
+ });
+ } finally {
+ PageHelper.clearPage();
}
+ PageInfo<ECResourceInfoRecord> pageInfo = new PageInfo<>(queryTasks);
+ long total = pageInfo.getTotal();
+ return Message.ok().data("engineList", list).data(JobRequestConstants.TOTAL_PAGE(), total);
+ }
}
diff --git a/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/EMRestfulApi.java b/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/EMRestfulApi.java
index 7bff30656..f6a9b6cad 100644
--- a/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/EMRestfulApi.java
+++ b/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/EMRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,18 +17,6 @@
package org.apache.linkis.manager.am.restful;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.ArrayUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.linkis.common.ServiceInstance;
import org.apache.linkis.common.utils.JsonUtils;
import org.apache.linkis.manager.am.conf.AMConfiguration;
@@ -56,317 +44,351 @@ import org.apache.linkis.manager.label.exception.LabelErrorException;
import org.apache.linkis.manager.label.service.NodeLabelService;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.exception.ExceptionUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
+
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
@Api(tags = "ECM(engineconnmanager) operation")
@RequestMapping(
- path = "/linkisManager",
- produces = {"application/json"})
+ path = "/linkisManager",
+ produces = {"application/json"})
@RestController
public class EMRestfulApi {
- @Autowired private EMInfoService emInfoService;
+ @Autowired private EMInfoService emInfoService;
- @Autowired private NodeLabelService nodeLabelService;
+ @Autowired private NodeLabelService nodeLabelService;
- @Autowired private DefaultMetricsConverter defaultMetricsConverter;
+ @Autowired private DefaultMetricsConverter defaultMetricsConverter;
- @Autowired private EngineNodeManager engineNodeManager;
+ @Autowired private EngineNodeManager engineNodeManager;
- @Autowired private ECMOperateService ecmOperateService;
+ @Autowired private ECMOperateService ecmOperateService;
- private LabelBuilderFactory stdLabelBuilderFactory =
- LabelBuilderFactoryContext.getLabelBuilderFactory();
+ private LabelBuilderFactory stdLabelBuilderFactory =
+ LabelBuilderFactoryContext.getLabelBuilderFactory();
- private Logger logger = LoggerFactory.getLogger(EMRestfulApi.class);
+ private Logger logger = LoggerFactory.getLogger(EMRestfulApi.class);
- private String[] adminOperations = AMConfiguration.ECM_ADMIN_OPERATIONS().getValue().split(",");
+ private String[] adminOperations = AMConfiguration.ECM_ADMIN_OPERATIONS().getValue().split(",");
- private void checkAdmin(String userName) throws AMErrorException {
- if (!AMConfiguration.isAdmin(userName)) {
- throw new AMErrorException(210003, "Only admin can modify ECMs(只有管理员才能修改ECM).");
- }
+ private void checkAdmin(String userName) throws AMErrorException {
+ if (!AMConfiguration.isAdmin(userName)) {
+ throw new AMErrorException(210003, "Only admin can modify ECMs(只有管理员才能修改ECM).");
}
+ }
- @ApiOperation(value = "listAllEMs", notes = "get all ECM service list", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "instance", required = false, dataType = "String", value = "Instance"),
- @ApiImplicitParam(name = "nodeHealthy", dataType = "String", required = false, value = "node healthy status", example = "Healthy, UnHealthy, WARN, StockAvailable, StockUnavailable"),
- @ApiImplicitParam(name = "owner",required = false, dataType = "String", value = "Owner")
- })
- // todo add healthInfo
- @RequestMapping(path = "/listAllEMs", method = RequestMethod.GET)
- public Message listAllEMs(
- HttpServletRequest req,
- @RequestParam(value = "instance", required = false) String instance,
- @RequestParam(value = "nodeHealthy", required = false) String nodeHealthy,
- @RequestParam(value = "owner", required = false) String owner)
- throws AMErrorException {
- checkAdmin(ModuleUserUtils.getOperationUser(req, "listAllEMs"));
- List<EMNodeVo> emNodeVos = AMUtils.copyToEMVo(emInfoService.getAllEM());
- if (CollectionUtils.isNotEmpty(emNodeVos)){
- Stream<EMNodeVo> stream = emNodeVos.stream();
- if (StringUtils.isNotBlank(instance)){
- stream = stream.filter(em -> em.getInstance().contains(instance));
- }
- if (StringUtils.isNotBlank(nodeHealthy)){
- stream = stream.filter(em -> em.getNodeHealthy() == null || em.getNodeHealthy().equals(NodeHealthy.valueOf(nodeHealthy)));
- }
- if (StringUtils.isNotBlank(owner)){
- stream = stream.filter(em -> em.getOwner().equalsIgnoreCase(owner));
- }
- emNodeVos = stream.collect(Collectors.toList());
- }
- return Message.ok().data("EMs", emNodeVos);
+ @ApiOperation(value = "listAllEMs", notes = "get all ECM service list", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "instance", dataType = "String", value = "Instance"),
+ @ApiImplicitParam(
+ name = "nodeHealthy",
+ dataType = "String",
+ value = "node healthy status",
+ example = "Healthy, UnHealthy, WARN, StockAvailable, StockUnavailable"),
+ @ApiImplicitParam(name = "owner", required = false, dataType = "String", value = "Owner")
+ })
+ // todo add healthInfo
+ @RequestMapping(path = "/listAllEMs", method = RequestMethod.GET)
+ public Message listAllEMs(
+ HttpServletRequest req,
+ @RequestParam(value = "instance", required = false) String instance,
+ @RequestParam(value = "nodeHealthy", required = false) String nodeHealthy,
+ @RequestParam(value = "owner", required = false) String owner)
+ throws AMErrorException {
+ checkAdmin(ModuleUserUtils.getOperationUser(req, "listAllEMs"));
+ List<EMNodeVo> emNodeVos = AMUtils.copyToEMVo(emInfoService.getAllEM());
+ if (CollectionUtils.isNotEmpty(emNodeVos)) {
+ Stream<EMNodeVo> stream = emNodeVos.stream();
+ if (StringUtils.isNotBlank(instance)) {
+ stream = stream.filter(em -> em.getInstance().contains(instance));
+ }
+ if (StringUtils.isNotBlank(nodeHealthy)) {
+ stream =
+ stream.filter(
+ em ->
+ em.getNodeHealthy() == null
+ || em.getNodeHealthy().equals(NodeHealthy.valueOf(nodeHealthy)));
+ }
+ if (StringUtils.isNotBlank(owner)) {
+ stream = stream.filter(em -> em.getOwner().equalsIgnoreCase(owner));
+ }
+ emNodeVos = stream.collect(Collectors.toList());
}
+ return Message.ok().data("EMs", emNodeVos);
+ }
- @ApiOperation(value = "listAllECMHealthyStatus", notes = "get all ECM healthy status", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "onlyEditable", required = false, dataType = "Boolean", value = "only editable")
- })
- @RequestMapping(path = "/listAllECMHealthyStatus", method = RequestMethod.GET)
- public Message listAllNodeHealthyStatus(
- HttpServletRequest req,
- @RequestParam(value = "onlyEditable", required = false) Boolean onlyEditable) {
- NodeHealthy[] nodeHealthy = NodeHealthy.values();
- if (onlyEditable) {
- nodeHealthy =
- new NodeHealthy[] {
- NodeHealthy.Healthy,
- NodeHealthy.UnHealthy,
- NodeHealthy.WARN,
- NodeHealthy.StockAvailable,
- NodeHealthy.StockUnavailable
- };
- }
- return Message.ok().data("nodeHealthy", nodeHealthy);
+ @ApiOperation(
+ value = "listAllECMHealthyStatus",
+ notes = "get all ECM healthy status",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "onlyEditable", dataType = "Boolean", value = "only editable")
+ })
+ @RequestMapping(path = "/listAllECMHealthyStatus", method = RequestMethod.GET)
+ public Message listAllNodeHealthyStatus(
+ HttpServletRequest req,
+ @RequestParam(value = "onlyEditable", required = false) Boolean onlyEditable) {
+ NodeHealthy[] nodeHealthy = NodeHealthy.values();
+ if (onlyEditable) {
+ nodeHealthy =
+ new NodeHealthy[] {
+ NodeHealthy.Healthy,
+ NodeHealthy.UnHealthy,
+ NodeHealthy.WARN,
+ NodeHealthy.StockAvailable,
+ NodeHealthy.StockUnavailable
+ };
}
+ return Message.ok().data("nodeHealthy", nodeHealthy);
+ }
- @ApiOperation(value = "modifyEMInfo", notes = "modify ECM info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "applicationName",required = false, dataType = "String", value = "application name",example = "linkis-cg-engineconnmanager"),
- @ApiImplicitParam(name = "emStatus", required = false, dataType = "String", value = "ecm", example = "Healthy, UnHealthy, WARN, StockAvailable, StockUnavailable"),
- @ApiImplicitParam(name = "instance", required = false, dataType = "String", value = "Instance", example = "bdpujes110003:9102"),
- @ApiImplicitParam(name = "labels",required = false, dataType = "List", value = "Labels"),
- @ApiImplicitParam(name = "labelKey", required = false, dataType = "String", value = "Label_Key", example = "emInstance"),
- @ApiImplicitParam(name = "stringValue", required = false, dataType = "String", value = "String_Value", example = "linkis-cg-engineconnmanager-bdpujes110003:9102")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/modifyEMInfo", method = RequestMethod.PUT)
- @Transactional(rollbackFor = Exception.class)
- public Message modifyEMInfo(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws AMErrorException, LabelErrorException {
- String username = ModuleUserUtils.getOperationUser(req, "modifyEMInfo");
- checkAdmin(username);
- String applicationName = jsonNode.get("applicationName").asText();
- String instance = jsonNode.get("instance").asText();
- if (StringUtils.isEmpty(applicationName)) {
- throw new AMErrorException(
- AMErrorCode.QUERY_PARAM_NULL.getCode(),
- "applicationName cannot be null(请求参数applicationName不能为空)");
- }
- if (StringUtils.isEmpty(instance)) {
- throw new AMErrorException(
- AMErrorCode.QUERY_PARAM_NULL.getCode(),
- "instance cannot be null(请求参数instance不能为空)");
- }
- ServiceInstance serviceInstance = ServiceInstance.apply(applicationName, instance);
- if (serviceInstance == null) {
- throw new AMErrorException(
- AMErrorCode.QUERY_PARAM_NULL.getCode(),
- "serviceInstance:"
- + applicationName
- + " non-existent("
- + applicationName
- + ")");
- }
- String healthyStatus = jsonNode.get("emStatus").asText();
- if (healthyStatus != null) {
- NodeHealthyInfo nodeHealthyInfo = new NodeHealthyInfo();
- nodeHealthyInfo.setNodeHealthy(NodeHealthy.valueOf(healthyStatus));
- emInfoService.updateEMInfo(serviceInstance, nodeHealthyInfo);
- }
- JsonNode labels = jsonNode.get("labels");
- Set<String> labelKeySet = new HashSet<>();
- if (labels != null) {
- ArrayList<Label<?>> newLabelList = new ArrayList<>();
- Iterator<JsonNode> iterator = labels.iterator();
- while (iterator.hasNext()) {
- JsonNode label = iterator.next();
- String labelKey = label.get("labelKey").asText();
- String stringValue = label.get("stringValue").asText();
- Label newLabel = stdLabelBuilderFactory.createLabel(labelKey, stringValue);
- if (newLabel instanceof UserModifiable) {
- ((UserModifiable) newLabel).valueCheck(stringValue);
- }
- labelKeySet.add(labelKey);
- newLabelList.add(newLabel);
- }
- if (labelKeySet.size() != newLabelList.size()) {
- throw new AMErrorException(
- 210003,
- "Failed to update label, include repeat labels(更新label失败,包含重复label)");
- }
- nodeLabelService.updateLabelsToNode(serviceInstance, newLabelList);
- logger.info("success to update label of instance: " + serviceInstance.getInstance());
+ @ApiOperation(value = "modifyEMInfo", notes = "modify ECM info", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(
+ name = "applicationName",
+ dataType = "String",
+ example = "linkis-cg-engineconnmanager"),
+ @ApiImplicitParam(
+ name = "emStatus",
+ dataType = "String",
+ example = "Healthy, UnHealthy, WARN, StockAvailable, StockUnavailable"),
+ @ApiImplicitParam(name = "instance", dataType = "String", example = "bdpujes110:9102"),
+ @ApiImplicitParam(name = "labels", dataType = "List", value = "Labels"),
+ @ApiImplicitParam(name = "labelKey", dataType = "String", example = "emInstance"),
+ @ApiImplicitParam(
+ name = "stringValue",
+ dataType = "String",
+ example = "linkis-cg-engineconn-bdpujes110003:12295")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/modifyEMInfo", method = RequestMethod.PUT)
+ @Transactional(rollbackFor = Exception.class)
+ public Message modifyEMInfo(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws AMErrorException, LabelErrorException {
+ String username = ModuleUserUtils.getOperationUser(req, "modifyEMInfo");
+ checkAdmin(username);
+ String applicationName = jsonNode.get("applicationName").asText();
+ String instance = jsonNode.get("instance").asText();
+ if (StringUtils.isEmpty(applicationName)) {
+ throw new AMErrorException(
+ AMErrorCode.QUERY_PARAM_NULL.getCode(),
+ "applicationName cannot be null(请求参数applicationName不能为空)");
+ }
+ if (StringUtils.isEmpty(instance)) {
+ throw new AMErrorException(
+ AMErrorCode.QUERY_PARAM_NULL.getCode(), "instance cannot be null(请求参数instance不能为空)");
+ }
+ ServiceInstance serviceInstance = ServiceInstance.apply(applicationName, instance);
+ if (serviceInstance == null) {
+ throw new AMErrorException(
+ AMErrorCode.QUERY_PARAM_NULL.getCode(),
+ "serviceInstance:" + applicationName + " non-existent(" + applicationName + ")");
+ }
+ String healthyStatus = jsonNode.get("emStatus").asText();
+ if (healthyStatus != null) {
+ NodeHealthyInfo nodeHealthyInfo = new NodeHealthyInfo();
+ nodeHealthyInfo.setNodeHealthy(NodeHealthy.valueOf(healthyStatus));
+ emInfoService.updateEMInfo(serviceInstance, nodeHealthyInfo);
+ }
+ JsonNode labels = jsonNode.get("labels");
+ Set<String> labelKeySet = new HashSet<>();
+ if (labels != null) {
+ ArrayList<Label<?>> newLabelList = new ArrayList<>();
+ Iterator<JsonNode> iterator = labels.iterator();
+ while (iterator.hasNext()) {
+ JsonNode label = iterator.next();
+ String labelKey = label.get("labelKey").asText();
+ String stringValue = label.get("stringValue").asText();
+ Label newLabel = stdLabelBuilderFactory.createLabel(labelKey, stringValue);
+ if (newLabel instanceof UserModifiable) {
+ ((UserModifiable) newLabel).valueCheck(stringValue);
}
- return Message.ok("success");
+ labelKeySet.add(labelKey);
+ newLabelList.add(newLabel);
+ }
+ if (labelKeySet.size() != newLabelList.size()) {
+ throw new AMErrorException(
+ 210003, "Failed to update label, include repeat labels(更新label失败,包含重复label)");
+ }
+ nodeLabelService.updateLabelsToNode(serviceInstance, newLabelList);
+ logger.info("success to update label of instance: " + serviceInstance.getInstance());
}
+ return Message.ok("success");
+ }
- @ApiOperation(value = "executeECMOperationByEC", notes = "EC execute ECM operation", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/executeECMOperationByEC", method = RequestMethod.POST)
- public Message executeECMOperationByEC(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws AMErrorException {
+ @ApiOperation(
+ value = "executeECMOperationByEC",
+ notes = "EC execute ECM operation",
+ response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/executeECMOperationByEC", method = RequestMethod.POST)
+ public Message executeECMOperationByEC(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws AMErrorException {
- ServiceInstance serviceInstance = EngineRestfulApi.getServiceInstance(jsonNode);
- String userName = ModuleUserUtils.getOperationUser(req, "executeECMOperationByEC");
- logger.info(
- "User {} try to execute ECM Operation by EngineConn {}.",
- userName,
- serviceInstance);
- EngineNode engineNode = engineNodeManager.getEngineNode(serviceInstance);
- Map<String, Object> parameters;
- try {
- parameters =
- JsonUtils.jackson()
- .readValue(
- jsonNode.get("parameters").toString(),
- new TypeReference<Map<String, Object>>() {});
- } catch (JsonProcessingException e) {
- logger.error(
- "Fail to process the operation parameters: [{}] in request",
- jsonNode.get("parameters").toString(),
- e);
- return Message.error(
- "Fail to process the operation parameters, cased by "
- + ExceptionUtils.getRootCauseMessage(e));
- }
- parameters.put(ECMOperateRequest.ENGINE_CONN_INSTANCE_KEY(), serviceInstance.getInstance());
- if (!userName.equals(engineNode.getOwner()) && !AMConfiguration.isAdmin(userName)) {
- return Message.error(
- "You have no permission to execute ECM Operation by this EngineConn "
- + serviceInstance);
- }
- return executeECMOperation(
- engineNode.getEMNode(), new ECMOperateRequest(userName, parameters));
+ ServiceInstance serviceInstance = EngineRestfulApi.getServiceInstance(jsonNode);
+ String userName = ModuleUserUtils.getOperationUser(req, "executeECMOperationByEC");
+ logger.info(
+ "User {} try to execute ECM Operation by EngineConn {}.", userName, serviceInstance);
+ EngineNode engineNode = engineNodeManager.getEngineNode(serviceInstance);
+ Map<String, Object> parameters;
+ try {
+ parameters =
+ JsonUtils.jackson()
+ .readValue(
+ jsonNode.get("parameters").toString(),
+ new TypeReference<Map<String, Object>>() {});
+ } catch (JsonProcessingException e) {
+ logger.error(
+ "Fail to process the operation parameters: [{}] in request",
+ jsonNode.get("parameters").toString(),
+ e);
+ return Message.error(
+ "Fail to process the operation parameters, cased by "
+ + ExceptionUtils.getRootCauseMessage(e));
}
-
- @ApiOperation(value = "executeECMOperation", notes = "execute ECM operation", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/executeECMOperation", method = RequestMethod.POST)
- public Message executeECMOperation(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws AMErrorException {
- String userName = ModuleUserUtils.getOperationUser(req, "executeECMOperation");
- ServiceInstance serviceInstance = EngineRestfulApi.getServiceInstance(jsonNode);
- logger.info("User {} try to execute ECM Operation with {}.", userName, serviceInstance);
- EMNode ecmNode = this.emInfoService.getEM(serviceInstance);
- Map<String, Object> parameters;
- try {
- parameters =
- JsonUtils.jackson()
- .readValue(
- jsonNode.get("parameters").toString(),
- new TypeReference<Map<String, Object>>() {});
- } catch (JsonProcessingException e) {
- logger.error(
- "Fail to process the operation parameters: [{}] in request",
- jsonNode.get("parameters").toString(),
- e);
- return Message.error(
- "Fail to process the operation parameters, cased by "
- + ExceptionUtils.getRootCauseMessage(e));
- }
- return executeECMOperation(ecmNode, new ECMOperateRequest(userName, parameters));
+ parameters.put(ECMOperateRequest.ENGINE_CONN_INSTANCE_KEY(), serviceInstance.getInstance());
+ if (!userName.equals(engineNode.getOwner()) && !AMConfiguration.isAdmin(userName)) {
+ return Message.error(
+ "You have no permission to execute ECM Operation by this EngineConn " + serviceInstance);
}
+ return executeECMOperation(engineNode.getEMNode(), new ECMOperateRequest(userName, parameters));
+ }
- @ApiOperation(value = "openEngineLog", notes = "open Engine log", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "applicationName",required = false, dataType = "String", example = "linkis-cg-engineconn", value = "application name"),
- @ApiImplicitParam(name = "emInstance", required = false, dataType = "String", value = "ecm instance", example = "bdpujes110003:910"),
- @ApiImplicitParam(name = "instance", required = false, dataType = "String", value = "Instance", example = "bdpujes110003:21976"),
- @ApiImplicitParam(name = "parameters", required = false, dataType = "Map", value = "Parameters"),
- @ApiImplicitParam(name = "logType", required = false, dataType = "String", value = "log type", example = "stdout"),
- @ApiImplicitParam(name = "fromLine", required = false, dataType = "String", value = "from line num", example = "0"),
- @ApiImplicitParam(name = "pageSize", required = false, dataType = "String", value = "page size", defaultValue = "1000"),
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/openEngineLog", method = RequestMethod.POST)
- public Message openEngineLog(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws AMErrorException {
- String userName = ModuleUserUtils.getOperationUser(req, "openEngineLog");
- EMNode ecmNode;
- Map<String, Object> parameters;
- try {
- String emInstance = jsonNode.get("emInstance").asText();
- String engineInstance = jsonNode.get("instance").asText();
- ServiceInstance serviceInstance = EngineRestfulApi.getServiceInstance(jsonNode);
- logger.info("User {} try to open engine: {} log.", userName, serviceInstance);
- ecmNode =
- this.emInfoService.getEM(
- ServiceInstance.apply("linkis-cg-engineconnmanager", emInstance));
- logger.info("ecm node info:{}", ecmNode);
- parameters =
- JsonUtils.jackson()
- .readValue(
- jsonNode.get("parameters").toString(),
- new TypeReference<Map<String, Object>>() {});
- String logType = (String) parameters.get("logType");
- if (!logType.equals("stdout") && !logType.equals("stderr")) {
- throw new AMErrorException(
- AMErrorCode.PARAM_ERROR.getCode(), AMErrorCode.PARAM_ERROR.getMessage());
- }
- parameters.put(OperateRequest$.MODULE$.OPERATOR_NAME_KEY(), "engineConnLog");
- parameters.put(ECMOperateRequest$.MODULE$.ENGINE_CONN_INSTANCE_KEY(), engineInstance);
- if (!parameters.containsKey("enableTail")) {
- parameters.put("enableTail", true);
- }
- } catch (JsonProcessingException e) {
- logger.error(
- "Fail to process the operation parameters: [{}] in request",
- jsonNode.get("parameters").toString(),
- e);
- return Message.error(
- "Fail to process the operation parameters, cased by "
- + ExceptionUtils.getRootCauseMessage(e));
- } catch (Exception e) {
- logger.error("Failed to open engine log, error:", e);
- return Message.error(e.getMessage());
- }
- return executeECMOperation(ecmNode, new ECMOperateRequest(userName, parameters));
+ @ApiOperation(
+ value = "executeECMOperation",
+ notes = "execute ECM operation",
+ response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/executeECMOperation", method = RequestMethod.POST)
+ public Message executeECMOperation(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws AMErrorException {
+ String userName = ModuleUserUtils.getOperationUser(req, "executeECMOperation");
+ ServiceInstance serviceInstance = EngineRestfulApi.getServiceInstance(jsonNode);
+ logger.info("User {} try to execute ECM Operation with {}.", userName, serviceInstance);
+ EMNode ecmNode = this.emInfoService.getEM(serviceInstance);
+ Map<String, Object> parameters;
+ try {
+ parameters =
+ JsonUtils.jackson()
+ .readValue(
+ jsonNode.get("parameters").toString(),
+ new TypeReference<Map<String, Object>>() {});
+ } catch (JsonProcessingException e) {
+ logger.error(
+ "Fail to process the operation parameters: [{}] in request",
+ jsonNode.get("parameters").toString(),
+ e);
+ return Message.error(
+ "Fail to process the operation parameters, cased by "
+ + ExceptionUtils.getRootCauseMessage(e));
}
+ return executeECMOperation(ecmNode, new ECMOperateRequest(userName, parameters));
+ }
- private Message executeECMOperation(EMNode ecmNode, ECMOperateRequest ecmOperateRequest) {
- String operationName =
- OperateRequest$.MODULE$.getOperationName(ecmOperateRequest.parameters());
- if (ArrayUtils.contains(adminOperations, operationName)
- && !AMConfiguration.isAdmin(ecmOperateRequest.user())) {
- logger.warn(
- "User {} has no permission to execute {} admin Operation in ECM {}.",
- ecmOperateRequest.user(),
- operationName,
- ecmNode.getServiceInstance());
- return Message.error(
- "You have no permission to execute "
- + operationName
- + " admin Operation in ECM "
- + ecmNode.getServiceInstance());
- }
- ECMOperateResponse engineOperateResponse =
- ecmOperateService.executeOperation(ecmNode, ecmOperateRequest);
+ @ApiOperation(value = "openEngineLog", notes = "open Engine log", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(
+ name = "applicationName",
+ dataType = "String",
+ example = "linkis-cg-engineconn"),
+ @ApiImplicitParam(name = "emInstance", dataType = "String", example = "bdpujes110003:910"),
+ @ApiImplicitParam(name = "instance", dataType = "String", example = "bdpujes110003:21976"),
+ @ApiImplicitParam(name = "parameters", dataType = "Map", value = "Parameters"),
+ @ApiImplicitParam(name = "logType", dataType = "String", example = "stdout"),
+ @ApiImplicitParam(name = "fromLine", dataType = "String", example = "0"),
+ @ApiImplicitParam(name = "pageSize", dataType = "String", defaultValue = "1000"),
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/openEngineLog", method = RequestMethod.POST)
+ public Message openEngineLog(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws AMErrorException {
+ String userName = ModuleUserUtils.getOperationUser(req, "openEngineLog");
+ EMNode ecmNode;
+ Map<String, Object> parameters;
+ try {
+ String emInstance = jsonNode.get("emInstance").asText();
+ String engineInstance = jsonNode.get("instance").asText();
+ ServiceInstance serviceInstance = EngineRestfulApi.getServiceInstance(jsonNode);
+ logger.info("User {} try to open engine: {} log.", userName, serviceInstance);
+ ecmNode =
+ this.emInfoService.getEM(
+ ServiceInstance.apply("linkis-cg-engineconnmanager", emInstance));
+ logger.info("ecm node info:{}", ecmNode);
+ parameters =
+ JsonUtils.jackson()
+ .readValue(
+ jsonNode.get("parameters").toString(),
+ new TypeReference<Map<String, Object>>() {});
+ String logType = (String) parameters.get("logType");
+ if (!logType.equals("stdout") && !logType.equals("stderr")) {
+ throw new AMErrorException(
+ AMErrorCode.PARAM_ERROR.getCode(), AMErrorCode.PARAM_ERROR.getMessage());
+ }
+ parameters.put(OperateRequest$.MODULE$.OPERATOR_NAME_KEY(), "engineConnLog");
+ parameters.put(ECMOperateRequest$.MODULE$.ENGINE_CONN_INSTANCE_KEY(), engineInstance);
+ if (!parameters.containsKey("enableTail")) {
+ parameters.put("enableTail", true);
+ }
+ } catch (JsonProcessingException e) {
+ logger.error(
+ "Fail to process the operation parameters: [{}] in request",
+ jsonNode.get("parameters").toString(),
+ e);
+ return Message.error(
+ "Fail to process the operation parameters, cased by "
+ + ExceptionUtils.getRootCauseMessage(e));
+ } catch (Exception e) {
+ logger.error("Failed to open engine log, error:", e);
+ return Message.error(e.getMessage());
+ }
+ return executeECMOperation(ecmNode, new ECMOperateRequest(userName, parameters));
+ }
- return Message.ok()
- .data("result", engineOperateResponse.getResult())
- .data("errorMsg", engineOperateResponse.errorMsg())
- .data("isError", engineOperateResponse.isError());
+ private Message executeECMOperation(EMNode ecmNode, ECMOperateRequest ecmOperateRequest) {
+ String operationName = OperateRequest$.MODULE$.getOperationName(ecmOperateRequest.parameters());
+ if (ArrayUtils.contains(adminOperations, operationName)
+ && !AMConfiguration.isAdmin(ecmOperateRequest.user())) {
+ logger.warn(
+ "User {} has no permission to execute {} admin Operation in ECM {}.",
+ ecmOperateRequest.user(),
+ operationName,
+ ecmNode.getServiceInstance());
+ return Message.error(
+ "You have no permission to execute "
+ + operationName
+ + " admin Operation in ECM "
+ + ecmNode.getServiceInstance());
}
+ ECMOperateResponse engineOperateResponse =
+ ecmOperateService.executeOperation(ecmNode, ecmOperateRequest);
+
+ return Message.ok()
+ .data("result", engineOperateResponse.getResult())
+ .data("errorMsg", engineOperateResponse.errorMsg())
+ .data("isError", engineOperateResponse.isError());
+ }
}
diff --git a/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/EngineRestfulApi.java b/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/EngineRestfulApi.java
index eef6c495f..77d2e9084 100644
--- a/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/EngineRestfulApi.java
+++ b/linkis-computation-governance/linkis-manager/linkis-application-manager/src/main/java/org/apache/linkis/manager/am/restful/EngineRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -34,7 +34,6 @@ import org.apache.linkis.manager.am.utils.AMUtils;
import org.apache.linkis.manager.am.vo.AMEngineNodeVo;
import org.apache.linkis.manager.common.entity.enumeration.NodeStatus;
import org.apache.linkis.manager.common.entity.node.AMEMNode;
-import org.apache.linkis.manager.common.entity.node.AMEngineNode;
import org.apache.linkis.manager.common.entity.node.EngineNode;
import org.apache.linkis.manager.common.entity.persistence.ECResourceInfoRecord;
import org.apache.linkis.manager.common.protocol.engine.EngineCreateRequest;
@@ -60,6 +59,11 @@ import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -71,323 +75,364 @@ import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.*;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
@Api(tags = "EC(engineconn) operation")
@RequestMapping(
- path = "/linkisManager",
- produces = {"application/json"})
+ path = "/linkisManager",
+ produces = {"application/json"})
@RestController
public class EngineRestfulApi {
- @Autowired private EngineInfoService engineInfoService;
+ @Autowired private EngineInfoService engineInfoService;
- @Autowired private EngineCreateService engineCreateService;
+ @Autowired private EngineCreateService engineCreateService;
- @Autowired private EngineNodeManager engineNodeManager;
+ @Autowired private EngineNodeManager engineNodeManager;
- @Autowired private EngineOperateService engineOperateService;
+ @Autowired private EngineOperateService engineOperateService;
- @Autowired private NodeLabelService nodeLabelService;
+ @Autowired private NodeLabelService nodeLabelService;
- @Autowired private EngineStopService engineStopService;
+ @Autowired private EngineStopService engineStopService;
- @Autowired private ECResourceInfoService ecResourceInfoService;
+ @Autowired private ECResourceInfoService ecResourceInfoService;
- private final ObjectMapper objectMapper = new ObjectMapper();
+ private final ObjectMapper objectMapper = new ObjectMapper();
- private LabelBuilderFactory stdLabelBuilderFactory =
- LabelBuilderFactoryContext.getLabelBuilderFactory();
+ private LabelBuilderFactory stdLabelBuilderFactory =
+ LabelBuilderFactoryContext.getLabelBuilderFactory();
- private static final Logger logger = LoggerFactory.getLogger(EngineRestfulApi.class);
+ private static final Logger logger = LoggerFactory.getLogger(EngineRestfulApi.class);
- @ApiOperation(value = "createEngineConn", notes = "create an engineconn", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/createEngineConn", method = RequestMethod.POST)
- public Message createEngineConn(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws IOException, InterruptedException {
- String userName = ModuleUserUtils.getOperationUser(req, "createEngineConn");
- EngineCreateRequest engineCreateRequest =
- objectMapper.treeToValue(jsonNode, EngineCreateRequest.class);
- engineCreateRequest.setUser(userName);
- long timeout = engineCreateRequest.getTimeOut();
- if (timeout <= 0) {
- timeout = AMConfiguration.ENGINE_CONN_START_REST_MAX_WAIT_TIME().getValue().toLong();
- engineCreateRequest.setTimeOut(timeout);
- }
- logger.info(
- "User {} try to create a engineConn with maxStartTime {}. EngineCreateRequest is {}.",
- userName,
- ByteTimeUtils.msDurationToString(timeout),
- engineCreateRequest);
- Sender sender = Sender.getSender(Sender.getThisServiceInstance());
- EngineNode engineNode;
- try {
- engineNode = engineCreateService.createEngine(engineCreateRequest, sender);
- } catch (LinkisRetryException e) {
- logger.error("User {} create engineConn failed get retry exception. can be Retry", userName, e);
- return Message.error(
- String.format(
- "Create engineConn failed, caused by %s.",
- ExceptionUtils.getRootCauseMessage(e))).data("canRetry", true);
- } catch (Exception e) {
- logger.error(String.format("User %s create engineConn failed.", userName), e);
- return Message.error(
- String.format(
- "Create engineConn failed, caused by %s.",
- ExceptionUtils.getRootCauseMessage(e)));
- }
- logger.info(
- "Finished to create a engineConn for user {}. NodeInfo is {}.",
- userName,
- engineNode);
- // to transform to a map
- Map<String, Object> retEngineNode = new HashMap<>();
- retEngineNode.put("serviceInstance", engineNode.getServiceInstance());
- if (null == engineNode.getNodeStatus()) {
- engineNode.setNodeStatus(NodeStatus.Starting);
- }
- retEngineNode.put("nodeStatus", engineNode.getNodeStatus().toString());
- retEngineNode.put("ticketId", engineNode.getTicketId());
- retEngineNode.put("ecmServiceInstance", engineNode.getEMNode().getServiceInstance());
- return Message.ok("create engineConn succeed.").data("engine", retEngineNode);
+ @ApiOperation(
+ value = "createEngineConn",
+ notes = "create an engineconn",
+ response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/createEngineConn", method = RequestMethod.POST)
+ public Message createEngineConn(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws IOException, InterruptedException {
+ String userName = ModuleUserUtils.getOperationUser(req, "createEngineConn");
+ EngineCreateRequest engineCreateRequest =
+ objectMapper.treeToValue(jsonNode, EngineCreateRequest.class);
+ engineCreateRequest.setUser(userName);
+ long timeout = engineCreateRequest.getTimeOut();
+ if (timeout <= 0) {
+ timeout = AMConfiguration.ENGINE_CONN_START_REST_MAX_WAIT_TIME().getValue().toLong();
+ engineCreateRequest.setTimeOut(timeout);
+ }
+ logger.info(
+ "User {} try to create a engineConn with maxStartTime {}. EngineCreateRequest is {}.",
+ userName,
+ ByteTimeUtils.msDurationToString(timeout),
+ engineCreateRequest);
+ Sender sender = Sender.getSender(Sender.getThisServiceInstance());
+ EngineNode engineNode;
+ try {
+ engineNode = engineCreateService.createEngine(engineCreateRequest, sender);
+ } catch (LinkisRetryException e) {
+ logger.error(
+ "User {} create engineConn failed get retry exception. can be Retry", userName, e);
+ return Message.error(
+ String.format(
+ "Create engineConn failed, caused by %s.", ExceptionUtils.getRootCauseMessage(e)))
+ .data("canRetry", true);
+ } catch (Exception e) {
+ logger.error(String.format("User %s create engineConn failed.", userName), e);
+ return Message.error(
+ String.format(
+ "Create engineConn failed, caused by %s.", ExceptionUtils.getRootCauseMessage(e)));
}
+ logger.info(
+ "Finished to create a engineConn for user {}. NodeInfo is {}.", userName, engineNode);
+ // to transform to a map
+ Map<String, Object> retEngineNode = new HashMap<>();
+ retEngineNode.put("serviceInstance", engineNode.getServiceInstance());
+ if (null == engineNode.getNodeStatus()) {
+ engineNode.setNodeStatus(NodeStatus.Starting);
+ }
+ retEngineNode.put("nodeStatus", engineNode.getNodeStatus().toString());
+ retEngineNode.put("ticketId", engineNode.getTicketId());
+ retEngineNode.put("ecmServiceInstance", engineNode.getEMNode().getServiceInstance());
+ return Message.ok("create engineConn succeed.").data("engine", retEngineNode);
+ }
- @ApiOperation(value = "getEngineConn", notes = "get engineconn", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/getEngineConn", method = RequestMethod.POST)
- public Message getEngineConn(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws AMErrorException {
- String userName = ModuleUserUtils.getOperationUser(req, "getEngineConn");
- ServiceInstance serviceInstance = getServiceInstance(jsonNode);
- JsonNode ticketIdNode = jsonNode.get("ticketId");
- EngineNode engineNode = null;
+ @ApiOperation(value = "getEngineConn", notes = "get engineconn", response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/getEngineConn", method = RequestMethod.POST)
+ public Message getEngineConn(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws AMErrorException {
+ String userName = ModuleUserUtils.getOperationUser(req, "getEngineConn");
+ ServiceInstance serviceInstance = getServiceInstance(jsonNode);
+ JsonNode ticketIdNode = jsonNode.get("ticketId");
+ EngineNode engineNode = null;
+ try {
+ engineNode = engineNodeManager.getEngineNodeInfo(serviceInstance);
+ } catch (Exception e) {
+ logger.info("Instances {} is not exists", serviceInstance.getInstance());
+ }
+ if (null == engineNode) {
+ ECResourceInfoRecord ecInfo = null;
+ if (null != ticketIdNode) {
try {
- engineNode = engineNodeManager.getEngineNodeInfo(serviceInstance);
+ ecInfo = ecResourceInfoService.getECResourceInfoRecord(ticketIdNode.asText());
} catch (Exception e) {
- logger.info("Instances {} is not exists", serviceInstance.getInstance());
+ logger.info("TicketId {} is not exists", ticketIdNode.asText());
}
- if (null == engineNode) {
- ECResourceInfoRecord ecInfo = null;
- if (null != ticketIdNode) {
- try{
- ecInfo = ecResourceInfoService.getECResourceInfoRecord(ticketIdNode.asText());
- } catch (Exception e) {
- logger.info("TicketId {} is not exists", ticketIdNode.asText());
- }
- }
- if (null == ecInfo) {
- ecInfo = ecResourceInfoService.getECResourceInfoRecordByInstance(serviceInstance.getInstance());
- }
- if (null == ecInfo) {
- return Message.error("Instance does not exist " + serviceInstance);
- }
- engineNode = ECResourceInfoUtils.convertECInfoTOECNode(ecInfo);
- }
- if (!userName.equals(engineNode.getOwner()) && !isAdmin(userName)) {
- return Message.error("You have no permission to access EngineConn " + serviceInstance);
- }
- return Message.ok().data("engine", engineNode);
+ }
+ if (null == ecInfo) {
+ ecInfo =
+ ecResourceInfoService.getECResourceInfoRecordByInstance(serviceInstance.getInstance());
+ }
+ if (null == ecInfo) {
+ return Message.error("Instance does not exist " + serviceInstance);
+ }
+ engineNode = ECResourceInfoUtils.convertECInfoTOECNode(ecInfo);
+ }
+ if (!userName.equals(engineNode.getOwner()) && !isAdmin(userName)) {
+ return Message.error("You have no permission to access EngineConn " + serviceInstance);
}
+ return Message.ok().data("engine", engineNode);
+ }
- @ApiOperation(value = "kill egineconn", notes = "kill engineconn", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/killEngineConn", method = RequestMethod.POST)
- public Message killEngineConn(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws Exception {
+ @ApiOperation(value = "kill egineconn", notes = "kill engineconn", response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/killEngineConn", method = RequestMethod.POST)
+ public Message killEngineConn(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws Exception {
- ServiceInstance serviceInstance = getServiceInstance(jsonNode);
- String userName =
- ModuleUserUtils.getOperationUser(req, "killEngineConn:" + serviceInstance);
- logger.info("User {} try to kill engineConn {}.", userName, serviceInstance);
- EngineNode engineNode = engineNodeManager.getEngineNode(serviceInstance);
- if (!userName.equals(engineNode.getOwner()) && !isAdmin(userName)) {
- return Message.error("You have no permission to kill EngineConn " + serviceInstance);
- }
- EngineStopRequest stopEngineRequest = new EngineStopRequest(serviceInstance, userName);
- Sender sender = Sender.getSender(Sender.getThisServiceInstance());
- engineStopService.stopEngine(stopEngineRequest, sender);
- logger.info("Finished to kill engineConn {}.", serviceInstance);
- return Message.ok("Kill engineConn succeed.");
+ ServiceInstance serviceInstance = getServiceInstance(jsonNode);
+ String userName = ModuleUserUtils.getOperationUser(req, "killEngineConn:" + serviceInstance);
+ logger.info("User {} try to kill engineConn {}.", userName, serviceInstance);
+ EngineNode engineNode = engineNodeManager.getEngineNode(serviceInstance);
+ if (!userName.equals(engineNode.getOwner()) && !isAdmin(userName)) {
+ return Message.error("You have no permission to kill EngineConn " + serviceInstance);
}
+ EngineStopRequest stopEngineRequest = new EngineStopRequest(serviceInstance, userName);
+ Sender sender = Sender.getSender(Sender.getThisServiceInstance());
+ engineStopService.stopEngine(stopEngineRequest, sender);
+ logger.info("Finished to kill engineConn {}.", serviceInstance);
+ return Message.ok("Kill engineConn succeed.");
+ }
- @ApiOperation(value = "kill eginecon", notes = "kill one engineconn or more ", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "engineInstance", required = false, dataType = "String", value = "engine instance", example = "bdpujes110003:12295"),
- @ApiImplicitParam(name = "applicationName", required = false, dataType = "String", value = "application name",example = "linkis-cg-engineconn")
- })
- @ApiOperationSupport(ignoreParameters = {"param"})
- @RequestMapping(path = "/rm/enginekill", method = RequestMethod.POST)
- public Message killEngine(HttpServletRequest req, @RequestBody Map<String, String>[] param)
- throws Exception {
- String userName = ModuleUserUtils.getOperationUser(req, "enginekill");
- Sender sender = Sender.getSender(Sender.getThisServiceInstance());
- for (Map<String, String> engineParam : param) {
- String moduleName = engineParam.get("applicationName");
- String engineInstance = engineParam.get("engineInstance");
- EngineStopRequest stopEngineRequest =
- new EngineStopRequest(
- ServiceInstance.apply(moduleName, engineInstance), userName);
- engineStopService.stopEngine(stopEngineRequest, sender);
- logger.info("Finished to kill engines");
- }
- return Message.ok("Kill engineConn succeed.");
+ @ApiOperation(
+ value = "kill eginecon",
+ notes = "kill one engineconn or more ",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(
+ name = "engineInstance",
+ dataType = "String",
+ example = "bdpujes110003:12295"),
+ @ApiImplicitParam(
+ name = "applicationName",
+ dataType = "String",
+ example = "linkis-cg-engineconn")
+ })
+ @ApiOperationSupport(ignoreParameters = {"param"})
+ @RequestMapping(path = "/rm/enginekill", method = RequestMethod.POST)
+ public Message killEngine(HttpServletRequest req, @RequestBody Map<String, String>[] param)
+ throws Exception {
+ String userName = ModuleUserUtils.getOperationUser(req, "enginekill");
+ Sender sender = Sender.getSender(Sender.getThisServiceInstance());
+ for (Map<String, String> engineParam : param) {
+ String moduleName = engineParam.get("applicationName");
+ String engineInstance = engineParam.get("engineInstance");
+ EngineStopRequest stopEngineRequest =
+ new EngineStopRequest(ServiceInstance.apply(moduleName, engineInstance), userName);
+ engineStopService.stopEngine(stopEngineRequest, sender);
+ logger.info("Finished to kill engines");
}
+ return Message.ok("Kill engineConn succeed.");
+ }
- @ApiOperation(value = "listUserEngines", notes = "get user's engineconn list", response = Message.class)
- @RequestMapping(path = "/listUserEngines", method = RequestMethod.GET)
- public Message listUserEngines(HttpServletRequest req) {
- String userName = ModuleUserUtils.getOperationUser(req, "listUserEngines");
- List<EngineNode> engineNodes = engineInfoService.listUserEngines(userName);
- return Message.ok().data("engines", engineNodes);
- }
+ @ApiOperation(
+ value = "listUserEngines",
+ notes = "get user's engineconn list",
+ response = Message.class)
+ @RequestMapping(path = "/listUserEngines", method = RequestMethod.GET)
+ public Message listUserEngines(HttpServletRequest req) {
+ String userName = ModuleUserUtils.getOperationUser(req, "listUserEngines");
+ List<EngineNode> engineNodes = engineInfoService.listUserEngines(userName);
+ return Message.ok().data("engines", engineNodes);
+ }
- @ApiOperation(value = "listEMEngines", notes = "get the list of engineconn under an ECM", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "em", required = false, dataType = "Map", value = "ecm object"),
- @ApiImplicitParam(name = "serviceInstance", required = false, dataType = "Map", value = "service instance"),
- @ApiImplicitParam(name = "applicationName", required = false, dataType = "String", value = "application name", example = "linkis-cg-engineconnmanager"),
- @ApiImplicitParam(name = "instance", required = false, dataType = "String", value = "instance"),
- @ApiImplicitParam(name = "emInstance", required = false, dataType = "String", value = "ecm instance", example = "bdpujes110003:9102"),
- @ApiImplicitParam(name = "engineType", required = false, dataType = "String", value = "engine type"),
- @ApiImplicitParam(name = "nodeStatus", required = false, dataType = "String", value = "node status"),
- @ApiImplicitParam(name = "owner", required = false, dataType = "String", value = "owner"),
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/listEMEngines", method = RequestMethod.POST)
- public Message listEMEngines(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws IOException, AMErrorException {
- String username = ModuleUserUtils.getOperationUser(req, "listEMEngines");
- if (!isAdmin(username)) {
- throw new AMErrorException(
- 210003, "Only admin can search engine information(只有管理员才能查询所有引擎信息).");
- }
- AMEMNode amemNode = objectMapper.treeToValue(jsonNode.get("em"), AMEMNode.class);
- JsonNode emInstace = jsonNode.get("emInstance");
- JsonNode nodeStatus = jsonNode.get("nodeStatus");
- JsonNode engineType = jsonNode.get("engineType");
- JsonNode owner = jsonNode.get("owner");
- List<EngineNode> engineNodes = engineInfoService.listEMEngines(amemNode);
- List<AMEngineNodeVo> allengineNodes = AMUtils.copyToAMEngineNodeVo(engineNodes);
- if (CollectionUtils.isNotEmpty(allengineNodes)) {
- Stream<AMEngineNodeVo> stream = allengineNodes.stream();
- if (null != emInstace) {
- stream = stream.filter(em -> StringUtils.isNotBlank(em.getInstance()) && em.getInstance().contains(emInstace.asText()));
- }
- if (null != nodeStatus && StringUtils.isNotBlank(nodeStatus.asText())) {
- stream = stream.filter(em -> null != em.getNodeStatus() && em.getNodeStatus().equals(NodeStatus.valueOf(nodeStatus.asText())));
- }
- if (null != owner && StringUtils.isNotBlank(owner.asText())) {
- stream = stream.filter(em -> StringUtils.isNotBlank(em.getOwner()) && em.getOwner().equalsIgnoreCase(owner.asText()));
- }
- if (null != engineType && StringUtils.isNotBlank(engineType.asText())) {
- stream = stream.filter(em -> StringUtils.isNotBlank(em.getEngineType()) && em.getEngineType().equalsIgnoreCase(engineType.asText()));
- }
- allengineNodes = stream.collect(Collectors.toList());
- }
- return Message.ok().data("engines", allengineNodes);
+ @ApiOperation(
+ value = "listEMEngines",
+ notes = "get the list of engineconn under an ECM",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "em", required = false, dataType = "Map", value = "ecm object"),
+ @ApiImplicitParam(name = "serviceInstance", dataType = "Map"),
+ @ApiImplicitParam(
+ name = "applicationName",
+ dataType = "String",
+ example = "linkis-cg-engineconnmanager"),
+ @ApiImplicitParam(name = "instance", required = false, dataType = "String", value = "instance"),
+ @ApiImplicitParam(name = "emInstance", dataType = "String", example = "bdpujes110003:9102"),
+ @ApiImplicitParam(name = "engineType", dataType = "String"),
+ @ApiImplicitParam(name = "nodeStatus", dataType = "String"),
+ @ApiImplicitParam(name = "owner", required = false, dataType = "String", value = "owner"),
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/listEMEngines", method = RequestMethod.POST)
+ public Message listEMEngines(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws IOException, AMErrorException {
+ String username = ModuleUserUtils.getOperationUser(req, "listEMEngines");
+ if (!isAdmin(username)) {
+ throw new AMErrorException(
+ 210003, "Only admin can search engine information(只有管理员才能查询所有引擎信息).");
+ }
+ AMEMNode amemNode = objectMapper.treeToValue(jsonNode.get("em"), AMEMNode.class);
+ JsonNode emInstace = jsonNode.get("emInstance");
+ JsonNode nodeStatus = jsonNode.get("nodeStatus");
+ JsonNode engineType = jsonNode.get("engineType");
+ JsonNode owner = jsonNode.get("owner");
+ List<EngineNode> engineNodes = engineInfoService.listEMEngines(amemNode);
+ List<AMEngineNodeVo> allengineNodes = AMUtils.copyToAMEngineNodeVo(engineNodes);
+ if (CollectionUtils.isNotEmpty(allengineNodes)) {
+ Stream<AMEngineNodeVo> stream = allengineNodes.stream();
+ if (null != emInstace) {
+ stream =
+ stream.filter(
+ em ->
+ StringUtils.isNotBlank(em.getInstance())
+ && em.getInstance().contains(emInstace.asText()));
+ }
+ if (null != nodeStatus && StringUtils.isNotBlank(nodeStatus.asText())) {
+ stream =
+ stream.filter(
+ em ->
+ null != em.getNodeStatus()
+ && em.getNodeStatus().equals(NodeStatus.valueOf(nodeStatus.asText())));
+ }
+ if (null != owner && StringUtils.isNotBlank(owner.asText())) {
+ stream =
+ stream.filter(
+ em ->
+ StringUtils.isNotBlank(em.getOwner())
+ && em.getOwner().equalsIgnoreCase(owner.asText()));
+ }
+ if (null != engineType && StringUtils.isNotBlank(engineType.asText())) {
+ stream =
+ stream.filter(
+ em ->
+ StringUtils.isNotBlank(em.getEngineType())
+ && em.getEngineType().equalsIgnoreCase(engineType.asText()));
+ }
+ allengineNodes = stream.collect(Collectors.toList());
}
+ return Message.ok().data("engines", allengineNodes);
+ }
- @ApiOperation(value = "modifyEngineInfo", notes = "modify engineconn info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "applicationName", required = false, dataType = "String", value = "application name", example = "linkis-cg-engineconn"),
- @ApiImplicitParam(name = "emStatus",required = false, dataType = "String", value = "ecm status", example = "Starting,Unlock,Locked,Idle,Busy,Running,ShuttingDown,Failed,Success"),
- @ApiImplicitParam(name = "instance", dataType = "String", required = false, value = "instance", example = "bdpujes110003:12295"),
- @ApiImplicitParam(name = "labels", dataType = "List", required = false, value = "labels"),
- @ApiImplicitParam(name = "labelKey", dataType = "String", required = false, value = "label key", example = "engineInstance"),
- @ApiImplicitParam(name = "stringValue", dataType = "String", required = false, value = "stringValue", example = "linkis-cg-engineconn-bdpujes110003:12295")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/modifyEngineInfo", method = RequestMethod.PUT)
- public Message modifyEngineInfo(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws AMErrorException, LabelErrorException {
- String username = ModuleUserUtils.getOperationUser(req, "modifyEngineInfo");
- if (!isAdmin(username)) {
- throw new AMErrorException(
- 210003, "Only admin can modify engineConn information(只有管理员才能修改引擎信息).");
- }
- ServiceInstance serviceInstance = getServiceInstance(jsonNode);
- JsonNode labels = jsonNode.get("labels");
- Set<String> labelKeySet = new HashSet<>();
- if (labels != null) {
- ArrayList<Label<?>> newLabelList = new ArrayList<>();
- Iterator<JsonNode> iterator = labels.iterator();
- while (iterator.hasNext()) {
- JsonNode label = iterator.next();
- String labelKey = label.get("labelKey").asText();
- String stringValue = label.get("stringValue").asText();
- Label newLabel = stdLabelBuilderFactory.createLabel(labelKey, stringValue);
- if (newLabel instanceof UserModifiable) {
- ((UserModifiable) newLabel).valueCheck(stringValue);
- }
- labelKeySet.add(labelKey);
- newLabelList.add(newLabel);
- }
- if (labelKeySet.size() != newLabelList.size()) {
- throw new AMErrorException(
- 210003,
- "Failed to update label, include repeat label(更新label失败,包含重复label)");
- }
- nodeLabelService.updateLabelsToNode(serviceInstance, newLabelList);
- logger.info("success to update label of instance: " + serviceInstance.getInstance());
+ @ApiOperation(
+ value = "modifyEngineInfo",
+ notes = "modify engineconn info",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(
+ name = "applicationName",
+ dataType = "String",
+ example = "linkis-cg-engineconn"),
+ @ApiImplicitParam(
+ name = "emStatus",
+ dataType = "String",
+ example = "Starting,Unlock,Locked,Idle,Busy,Running,ShuttingDown,Failed,Success"),
+ @ApiImplicitParam(name = "instance", dataType = "String", example = "bdpujes110003:12295"),
+ @ApiImplicitParam(name = "labels", dataType = "List", required = false, value = "labels"),
+ @ApiImplicitParam(name = "labelKey", dataType = "String", example = "engineInstance"),
+ @ApiImplicitParam(name = "stringValue", dataType = "String", example = "linkis-cg:12295")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/modifyEngineInfo", method = RequestMethod.PUT)
+ public Message modifyEngineInfo(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws AMErrorException, LabelErrorException {
+ String username = ModuleUserUtils.getOperationUser(req, "modifyEngineInfo");
+ if (!isAdmin(username)) {
+ throw new AMErrorException(
+ 210003, "Only admin can modify engineConn information(只有管理员才能修改引擎信息).");
+ }
+ ServiceInstance serviceInstance = getServiceInstance(jsonNode);
+ JsonNode labels = jsonNode.get("labels");
+ Set<String> labelKeySet = new HashSet<>();
+ if (labels != null) {
+ ArrayList<Label<?>> newLabelList = new ArrayList<>();
+ Iterator<JsonNode> iterator = labels.iterator();
+ while (iterator.hasNext()) {
+ JsonNode label = iterator.next();
+ String labelKey = label.get("labelKey").asText();
+ String stringValue = label.get("stringValue").asText();
+ Label newLabel = stdLabelBuilderFactory.createLabel(labelKey, stringValue);
+ if (newLabel instanceof UserModifiable) {
+ ((UserModifiable) newLabel).valueCheck(stringValue);
}
- return Message.ok("success to update engine information(更新引擎信息成功)");
+ labelKeySet.add(labelKey);
+ newLabelList.add(newLabel);
+ }
+ if (labelKeySet.size() != newLabelList.size()) {
+ throw new AMErrorException(
+ 210003, "Failed to update label, include repeat label(更新label失败,包含重复label)");
+ }
+ nodeLabelService.updateLabelsToNode(serviceInstance, newLabelList);
+ logger.info("success to update label of instance: " + serviceInstance.getInstance());
}
+ return Message.ok("success to update engine information(更新引擎信息成功)");
+ }
- @ApiOperation(value = "listAllNodeHealthyStatus", notes = "get all node healthy staus list", response = Message.class)
- @RequestMapping(path = "/listAllNodeHealthyStatus", method = RequestMethod.GET)
- public Message listAllNodeHealthyStatus(
- HttpServletRequest req,
- @RequestParam(value = "onlyEditable", required = false) Boolean onlyEditable) {
- NodeStatus[] nodeStatus = NodeStatus.values();
- return Message.ok().data("nodeStatus", nodeStatus);
+ @ApiOperation(
+ value = "listAllNodeHealthyStatus",
+ notes = "get all node healthy staus list",
+ response = Message.class)
+ @RequestMapping(path = "/listAllNodeHealthyStatus", method = RequestMethod.GET)
+ public Message listAllNodeHealthyStatus(
+ HttpServletRequest req,
+ @RequestParam(value = "onlyEditable", required = false) Boolean onlyEditable) {
+ NodeStatus[] nodeStatus = NodeStatus.values();
+ return Message.ok().data("nodeStatus", nodeStatus);
+ }
+
+ @ApiOperation(
+ value = "executeEngineConnOperation",
+ notes = "execute engine conn operation",
+ response = Message.class)
+ @RequestMapping(path = "/executeEngineConnOperation", method = RequestMethod.POST)
+ public Message executeEngineConnOperation(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws Exception {
+ String userName = ModuleUserUtils.getOperationUser(req, "executeEngineConnOperation");
+ ServiceInstance serviceInstance = getServiceInstance(jsonNode);
+ logger.info("User {} try to execute Engine Operation {}.", userName, serviceInstance);
+ EngineNode engineNode = engineNodeManager.getEngineNode(serviceInstance);
+ if (!userName.equals(engineNode.getOwner()) && !isAdmin(userName)) {
+ return Message.error("You have no permission to execute Engine Operation " + serviceInstance);
}
+ Map<String, Object> parameters =
+ objectMapper.convertValue(
+ jsonNode.get("parameters"), new TypeReference<Map<String, Object>>() {});
- @ApiOperation(value = "executeEngineConnOperation", notes = "execute engine conn operation", response = Message.class)
- @RequestMapping(path = "/executeEngineConnOperation", method = RequestMethod.POST)
- public Message executeEngineConnOperation(
- HttpServletRequest req, @RequestBody JsonNode jsonNode) throws Exception {
- String userName = ModuleUserUtils.getOperationUser(req, "executeEngineConnOperation");
- ServiceInstance serviceInstance = getServiceInstance(jsonNode);
- logger.info("User {} try to execute Engine Operation {}.", userName, serviceInstance);
- EngineNode engineNode = engineNodeManager.getEngineNode(serviceInstance);
- if (!userName.equals(engineNode.getOwner()) && !isAdmin(userName)) {
- return Message.error(
- "You have no permission to execute Engine Operation " + serviceInstance);
- }
- Map<String, Object> parameters =
- objectMapper.convertValue(
- jsonNode.get("parameters"), new TypeReference<Map<String, Object>>() {});
+ EngineOperateRequest engineOperateRequest = new EngineOperateRequest(userName, parameters);
+ EngineOperateResponse engineOperateResponse =
+ engineOperateService.executeOperation(engineNode, engineOperateRequest);
+ return Message.ok()
+ .data("result", engineOperateResponse.getResult())
+ .data("errorMsg", engineOperateResponse.errorMsg())
+ .data("isError", engineOperateResponse.isError());
+ }
- EngineOperateRequest engineOperateRequest = new EngineOperateRequest(userName, parameters);
- EngineOperateResponse engineOperateResponse =
- engineOperateService.executeOperation(engineNode, engineOperateRequest);
- return Message.ok()
- .data("result", engineOperateResponse.getResult())
- .data("errorMsg", engineOperateResponse.errorMsg())
- .data("isError", engineOperateResponse.isError());
- }
+ private boolean isAdmin(String user) {
+ return AMConfiguration.isAdmin(user);
+ }
- private boolean isAdmin(String user) {
- return AMConfiguration.isAdmin(user);
+ static ServiceInstance getServiceInstance(JsonNode jsonNode) throws AMErrorException {
+ String applicationName = jsonNode.get("applicationName").asText();
+ String instance = jsonNode.get("instance").asText();
+ if (StringUtils.isEmpty(applicationName)) {
+ throw new AMErrorException(
+ AMErrorCode.QUERY_PARAM_NULL.getCode(),
+ "applicationName cannot be null(请求参数applicationName不能为空)");
}
-
- static ServiceInstance getServiceInstance(JsonNode jsonNode) throws AMErrorException {
- String applicationName = jsonNode.get("applicationName").asText();
- String instance = jsonNode.get("instance").asText();
- if (StringUtils.isEmpty(applicationName)) {
- throw new AMErrorException(
- AMErrorCode.QUERY_PARAM_NULL.getCode(),
- "applicationName cannot be null(请求参数applicationName不能为空)");
- }
- if (StringUtils.isEmpty(instance)) {
- throw new AMErrorException(
- AMErrorCode.QUERY_PARAM_NULL.getCode(),
- "instance cannot be null(请求参数instance不能为空)");
- }
- return ServiceInstance.apply(applicationName, instance);
+ if (StringUtils.isEmpty(instance)) {
+ throw new AMErrorException(
+ AMErrorCode.QUERY_PARAM_NULL.getCode(), "instance cannot be null(请求参数instance不能为空)");
}
+ return ServiceInstance.apply(applicationName, instance);
+ }
}
diff --git a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceAccessRestfulApi.java b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceAccessRestfulApi.java
index ab4306815..dffa31c51 100644
--- a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceAccessRestfulApi.java
+++ b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceAccessRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,93 +14,114 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.linkis.basedatamanager.server.restful;
-import com.github.pagehelper.PageInfo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
import org.apache.linkis.basedatamanager.server.domain.DatasourceAccessEntity;
import org.apache.linkis.basedatamanager.server.service.DatasourceAccessService;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
+
import java.util.Date;
+import com.github.pagehelper.PageInfo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+
@Api(tags = "DatasourceAccessRestfulApi")
@RestController
@RequestMapping(path = "/basedata-manager/datasource-access")
public class DatasourceAccessRestfulApi {
- @Autowired
- DatasourceAccessService datasourceAccessService;
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "")
- })
- @ApiOperation(value = "list", notes = "Query list data of Datasource Access", httpMethod = "GET")
- @RequestMapping(path = "", method = RequestMethod.GET)
- public Message list(HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
- ModuleUserUtils.getOperationUser(request,"Query list data of Datasource Access,search name:"+searchName);
- PageInfo pageList = datasourceAccessService.getListByPage(searchName,currentPage,pageSize);
- return Message.ok("").data("list", pageList);
- }
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request", value = ""),
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "get", notes = "Get a Datasource Access Record", httpMethod = "GET")
- @RequestMapping(path = "/{id}", method = RequestMethod.GET)
- public Message get(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Get a Datasource Access Record,id:"+id.toString());
- DatasourceAccessEntity datasourceAccess = datasourceAccessService.getById(id);
- return Message.ok("").data("item", datasourceAccess);
- }
+ @Autowired DatasourceAccessService datasourceAccessService;
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request", value = ""),
- @ApiImplicitParam(paramType = "body", dataType = "DatasourceAccessEntity", name = "datasourceAccess", value = "")
- })
- @ApiOperation(value = "add", notes = "", httpMethod = "POST")
- @RequestMapping(path = "", method = RequestMethod.POST)
- public Message add(HttpServletRequest request,@RequestBody DatasourceAccessEntity datasourceAccess) {
- ModuleUserUtils.getOperationUser(request, "Add a Datasource Access Record,"+datasourceAccess.toString());
- datasourceAccess.setAccessTime(new Date());
- boolean result = datasourceAccessService.save(datasourceAccess);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request"),
+ @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize")
+ })
+ @ApiOperation(value = "list", notes = "list Datasource Accesses", httpMethod = "GET")
+ @RequestMapping(path = "", method = RequestMethod.GET)
+ public Message list(
+ HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
+ ModuleUserUtils.getOperationUser(
+ request, "Query list data of Datasource Access,search name:" + searchName);
+ PageInfo pageList = datasourceAccessService.getListByPage(searchName, currentPage, pageSize);
+ return Message.ok("").data("list", pageList);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request", value = ""),
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "remove", notes = "Remove a Datasource Access Record", httpMethod = "DELETE")
- @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
- public Message remove(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Remove a Datasource Access Record,id:"+id.toString());
- boolean result = datasourceAccessService.removeById(id);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request"),
+ @ApiImplicitParam(paramType = "path", dataType = "long", name = "id")
+ })
+ @ApiOperation(value = "get", notes = "Get a Datasource Access Record", httpMethod = "GET")
+ @RequestMapping(path = "/{id}", method = RequestMethod.GET)
+ public Message get(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(request, "Get a Datasource Access Record,id:" + id.toString());
+ DatasourceAccessEntity datasourceAccess = datasourceAccessService.getById(id);
+ return Message.ok("").data("item", datasourceAccess);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request", value = ""),
- @ApiImplicitParam(paramType = "body", dataType = "DatasourceAccessEntity", name = "datasourceAccess", value = "")
- })
- @ApiOperation(value = "update", notes = "Update a Datasource Access Record", httpMethod = "PUT")
- @RequestMapping(path = "", method = RequestMethod.PUT)
- public Message update(HttpServletRequest request,@RequestBody DatasourceAccessEntity datasourceAccess) {
- ModuleUserUtils.getOperationUser(request, "Update a Datasource Access Record,id:"+datasourceAccess.getId().toString());
- boolean result = datasourceAccessService.updateById(datasourceAccess);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request"),
+ @ApiImplicitParam(
+ paramType = "body",
+ dataType = "DatasourceAccessEntity",
+ name = "datasourceAccess")
+ })
+ @ApiOperation(value = "add", notes = "", httpMethod = "POST")
+ @RequestMapping(path = "", method = RequestMethod.POST)
+ public Message add(
+ HttpServletRequest request, @RequestBody DatasourceAccessEntity datasourceAccess) {
+ ModuleUserUtils.getOperationUser(
+ request, "Add a Datasource Access Record," + datasourceAccess.toString());
+ datasourceAccess.setAccessTime(new Date());
+ boolean result = datasourceAccessService.save(datasourceAccess);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request"),
+ @ApiImplicitParam(paramType = "path", dataType = "long", name = "id")
+ })
+ @ApiOperation(
+ value = "remove",
+ notes = "Remove a Datasource Access Record",
+ httpMethod = "DELETE")
+ @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
+ public Message remove(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(
+ request, "Remove a Datasource Access Record,id:" + id.toString());
+ boolean result = datasourceAccessService.removeById(id);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "HttpServletRequest", name = "request"),
+ @ApiImplicitParam(
+ paramType = "body",
+ dataType = "DatasourceAccessEntity",
+ name = "datasourceAccess")
+ })
+ @ApiOperation(value = "update", notes = "Update a Datasource Access Record", httpMethod = "PUT")
+ @RequestMapping(path = "", method = RequestMethod.PUT)
+ public Message update(
+ HttpServletRequest request, @RequestBody DatasourceAccessEntity datasourceAccess) {
+ ModuleUserUtils.getOperationUser(
+ request, "Update a Datasource Access Record,id:" + datasourceAccess.getId().toString());
+ boolean result = datasourceAccessService.updateById(datasourceAccess);
+ return Message.ok("").data("result", result);
+ }
}
diff --git a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceEnvRestfulApi.java b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceEnvRestfulApi.java
index 22685f961..42cd29fb4 100644
--- a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceEnvRestfulApi.java
+++ b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceEnvRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,86 +14,94 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.linkis.basedatamanager.server.restful;
-import com.github.pagehelper.PageInfo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
import org.apache.linkis.basedatamanager.server.domain.DatasourceEnvEntity;
import org.apache.linkis.basedatamanager.server.service.DatasourceEnvService;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
+import com.github.pagehelper.PageInfo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+
@Api(tags = "DatasourceEnvRestfulApi")
@RestController
@RequestMapping(path = "/basedata-manager/datasource-env")
public class DatasourceEnvRestfulApi {
- @Autowired
- DatasourceEnvService datasourceEnvService;
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "")
- })
- @ApiOperation(value = "list", notes = "Query list data of Datasource Env by searchName", httpMethod = "GET")
- @RequestMapping(path = "", method = RequestMethod.GET)
- public Message list(HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
- ModuleUserUtils.getOperationUser(request, "Query list data of Datasource Env,search name:"+searchName);
- PageInfo pageList = datasourceEnvService.getListByPage(searchName,currentPage,pageSize);
- return Message.ok("").data("list", pageList);
- }
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "get", notes = "Get a Datasource Env Record by id", httpMethod = "GET")
- @RequestMapping(path = "/{id}", method = RequestMethod.GET)
- public Message get(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Get a Datasource Env Record,id:"+id.toString());
- DatasourceEnvEntity datasourceEnv = datasourceEnvService.getById(id);
- return Message.ok("").data("item", datasourceEnv);
- }
+ @Autowired DatasourceEnvService datasourceEnvService;
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "DatasourceEnvEntity", name = "datasourceEnv", value = "")
- })
- @ApiOperation(value = "add", notes = "Add a Datasource Env Record", httpMethod = "POST")
- @RequestMapping(path = "", method = RequestMethod.POST)
- public Message add(HttpServletRequest request,@RequestBody DatasourceEnvEntity datasourceEnv) {
- ModuleUserUtils.getOperationUser(request, "Add a Datasource Env Record,"+datasourceEnv.toString());
- boolean result = datasourceEnvService.save(datasourceEnv);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize")
+ })
+ @ApiOperation(value = "list", notes = "list Datasource Envs by searchName", httpMethod = "GET")
+ @RequestMapping(path = "", method = RequestMethod.GET)
+ public Message list(
+ HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
+ ModuleUserUtils.getOperationUser(
+ request, "Query list data of Datasource Env,search name:" + searchName);
+ PageInfo pageList = datasourceEnvService.getListByPage(searchName, currentPage, pageSize);
+ return Message.ok("").data("list", pageList);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "remove", notes = "Remove a Datasource Env Record by id", httpMethod = "DELETE")
- @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
- public Message remove(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Remove a Datasource Env Record,id:"+id.toString());
- boolean result = datasourceEnvService.removeById(id);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(value = "get", notes = "Get a Datasource Env Record by id", httpMethod = "GET")
+ @RequestMapping(path = "/{id}", method = RequestMethod.GET)
+ public Message get(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(request, "Get a Datasource Env Record,id:" + id.toString());
+ DatasourceEnvEntity datasourceEnv = datasourceEnvService.getById(id);
+ return Message.ok("").data("item", datasourceEnv);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "DatasourceEnvEntity", name = "datasourceEnv", value = "")
- })
- @ApiOperation(value = "update", notes = "Update a Datasource Env Record", httpMethod = "PUT")
- @RequestMapping(path = "", method = RequestMethod.PUT)
- public Message update(HttpServletRequest request,@RequestBody DatasourceEnvEntity datasourceEnv) {
- ModuleUserUtils.getOperationUser(request, "Update a Datasource Env Record,id:"+datasourceEnv.getId().toString());
- boolean result = datasourceEnvService.updateById(datasourceEnv);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "body", dataType = "DatasourceEnvEntity", name = "datasourceEnv")
+ })
+ @ApiOperation(value = "add", notes = "Add a Datasource Env Record", httpMethod = "POST")
+ @RequestMapping(path = "", method = RequestMethod.POST)
+ public Message add(HttpServletRequest request, @RequestBody DatasourceEnvEntity datasourceEnv) {
+ ModuleUserUtils.getOperationUser(
+ request, "Add a Datasource Env Record," + datasourceEnv.toString());
+ boolean result = datasourceEnvService.save(datasourceEnv);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(
+ value = "remove",
+ notes = "Remove a Datasource Env Record by id",
+ httpMethod = "DELETE")
+ @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
+ public Message remove(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(request, "Remove a Datasource Env Record,id:" + id.toString());
+ boolean result = datasourceEnvService.removeById(id);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "body", dataType = "DatasourceEnvEntity", name = "datasourceEnv")
+ })
+ @ApiOperation(value = "update", notes = "Update a Datasource Env Record", httpMethod = "PUT")
+ @RequestMapping(path = "", method = RequestMethod.PUT)
+ public Message update(
+ HttpServletRequest request, @RequestBody DatasourceEnvEntity datasourceEnv) {
+ ModuleUserUtils.getOperationUser(
+ request, "Update a Datasource Env Record,id:" + datasourceEnv.getId().toString());
+ boolean result = datasourceEnvService.updateById(datasourceEnv);
+ return Message.ok("").data("result", result);
+ }
}
diff --git a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceTypeRestfulApi.java b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceTypeRestfulApi.java
index d85ed8dba..7590fc46b 100644
--- a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceTypeRestfulApi.java
+++ b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/DatasourceTypeRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,86 +14,101 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.linkis.basedatamanager.server.restful;
-import com.github.pagehelper.PageInfo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
import org.apache.linkis.basedatamanager.server.domain.DatasourceTypeEntity;
import org.apache.linkis.basedatamanager.server.service.DatasourceTypeService;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
-@Api(tags="DatasourceTypeRestfulApi")
+import com.github.pagehelper.PageInfo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+
+@Api(tags = "DatasourceTypeRestfulApi")
@RestController
@RequestMapping(path = "/basedata-manager/datasource-type")
public class DatasourceTypeRestfulApi {
- @Autowired
- DatasourceTypeService datasourceTypeService;
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "")
- })
- @ApiOperation(value = "list", notes = "Query list data of Datasource Type", httpMethod = "GET")
- @RequestMapping(path = "", method = RequestMethod.GET)
- public Message list(HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
- ModuleUserUtils.getOperationUser(request, "Query list data of Datasource Type,search name:"+searchName);
- PageInfo pageList = datasourceTypeService.getListByPage(searchName,currentPage,pageSize);
- return Message.ok("").data("list", pageList);
- }
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "get", notes = "Get a Datasource Type Record by id", httpMethod = "GET")
- @RequestMapping(path = "/{id}", method = RequestMethod.GET)
- public Message get(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Get a Datasource Type Record,id:"+id.toString());
- DatasourceTypeEntity datasourceType = datasourceTypeService.getById(id);
- return Message.ok("").data("item", datasourceType);
- }
+ @Autowired DatasourceTypeService datasourceTypeService;
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "DatasourceTypeEntity", name = "datasourceType", value = "")
- })
- @ApiOperation(value = "add", notes = "Add a Datasource Type Record", httpMethod = "POST")
- @RequestMapping(path = "", method = RequestMethod.POST)
- public Message add(HttpServletRequest request,@RequestBody DatasourceTypeEntity datasourceType) {
- ModuleUserUtils.getOperationUser(request, "Add a Datasource Type Record,"+datasourceType.toString());
- boolean result = datasourceTypeService.save(datasourceType);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize")
+ })
+ @ApiOperation(value = "list", notes = "list Datasource Types", httpMethod = "GET")
+ @RequestMapping(path = "", method = RequestMethod.GET)
+ public Message list(
+ HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
+ ModuleUserUtils.getOperationUser(
+ request, "Query list data of Datasource Type,search name:" + searchName);
+ PageInfo pageList = datasourceTypeService.getListByPage(searchName, currentPage, pageSize);
+ return Message.ok("").data("list", pageList);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "remove", notes = "Remove a Datasource Type Record by id", httpMethod = "DELETE")
- @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
- public Message remove(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Remove a Datasource Type Record,id:"+id.toString());
- boolean result = datasourceTypeService.removeById(id);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(value = "get", notes = "Get a Datasource Type by id", httpMethod = "GET")
+ @RequestMapping(path = "/{id}", method = RequestMethod.GET)
+ public Message get(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(request, "Get a Datasource Type Record,id:" + id.toString());
+ DatasourceTypeEntity datasourceType = datasourceTypeService.getById(id);
+ return Message.ok("").data("item", datasourceType);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "DatasourceTypeEntity", name = "datasourceType", value = "")
- })
- @ApiOperation(value = "update", notes = "Update a Datasource Type Record", httpMethod = "PUT")
- @RequestMapping(path = "", method = RequestMethod.PUT)
- public Message update(HttpServletRequest request,@RequestBody DatasourceTypeEntity datasourceType) {
- ModuleUserUtils.getOperationUser(request, "Update a Datasource Type Record,id:"+datasourceType.getId().toString());
- boolean result = datasourceTypeService.updateById(datasourceType);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(
+ paramType = "body",
+ dataType = "DatasourceTypeEntity",
+ name = "datasourceType")
+ })
+ @ApiOperation(value = "add", notes = "Add a Datasource Type Record", httpMethod = "POST")
+ @RequestMapping(path = "", method = RequestMethod.POST)
+ public Message add(HttpServletRequest request, @RequestBody DatasourceTypeEntity datasourceType) {
+ ModuleUserUtils.getOperationUser(
+ request, "Add a Datasource Type Record," + datasourceType.toString());
+ boolean result = datasourceTypeService.save(datasourceType);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(
+ value = "remove",
+ notes = "Remove a Datasource Type Record by id",
+ httpMethod = "DELETE")
+ @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
+ public Message remove(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(
+ request, "Remove a Datasource Type Record,id:" + id.toString());
+ boolean result = datasourceTypeService.removeById(id);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({
+ @ApiImplicitParam(
+ paramType = "body",
+ dataType = "DatasourceTypeEntity",
+ name = "datasourceType")
+ })
+ @ApiOperation(value = "update", notes = "Update a Datasource Type Record", httpMethod = "PUT")
+ @RequestMapping(path = "", method = RequestMethod.PUT)
+ public Message update(
+ HttpServletRequest request, @RequestBody DatasourceTypeEntity datasourceType) {
+ ModuleUserUtils.getOperationUser(
+ request, "Update a Datasource Type Record,id:" + datasourceType.getId().toString());
+ boolean result = datasourceTypeService.updateById(datasourceType);
+ return Message.ok("").data("result", result);
+ }
}
diff --git a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/ErrorCodeRestfulApi.java b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/ErrorCodeRestfulApi.java
index 1b2543d03..5d200cace 100644
--- a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/ErrorCodeRestfulApi.java
+++ b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/ErrorCodeRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,86 +14,91 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.linkis.basedatamanager.server.restful;
-import com.github.pagehelper.PageInfo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
import org.apache.linkis.basedatamanager.server.domain.ErrorCodeEntity;
import org.apache.linkis.basedatamanager.server.service.ErrorCodeService;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
-@Api(tags="ErrorCodeRestfulApi")
+import com.github.pagehelper.PageInfo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+
+@Api(tags = "ErrorCodeRestfulApi")
@RestController
@RequestMapping(path = "/basedata-manager/error-code")
public class ErrorCodeRestfulApi {
- @Autowired
- ErrorCodeService errorCodeService;
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "")
- })
- @ApiOperation(value = "list", notes = "Query list data with page of Error Code", httpMethod = "GET")
- @RequestMapping(path = "", method = RequestMethod.GET)
- public Message list(HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
- ModuleUserUtils.getOperationUser(request, "Query list data of Error Code,search name:"+searchName);
- PageInfo pageList = errorCodeService.getListByPage(searchName,currentPage,pageSize);
- return Message.ok("").data("list", pageList);
- }
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "get", notes = "Get a Error Code Record by id", httpMethod = "GET")
- @RequestMapping(path = "/{id}", method = RequestMethod.GET)
- public Message get(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Get a Error Code Record,id:"+id.toString());
- ErrorCodeEntity errorCode = errorCodeService.getById(id);
- return Message.ok("").data("item", errorCode);
- }
+ @Autowired ErrorCodeService errorCodeService;
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "ErrorCodeEntity", name = "errorCode", value = "")
- })
- @ApiOperation(value = "add", notes = "Add a Datasource Code Record", httpMethod = "POST")
- @RequestMapping(path = "", method = RequestMethod.POST)
- public Message add(HttpServletRequest request,@RequestBody ErrorCodeEntity errorCode) {
- ModuleUserUtils.getOperationUser(request, "Add a Datasource Code Record,"+errorCode.toString());
- boolean result = errorCodeService.save(errorCode);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize")
+ })
+ @ApiOperation(value = "list", notes = "list Error Codes with page", httpMethod = "GET")
+ @RequestMapping(path = "", method = RequestMethod.GET)
+ public Message list(
+ HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
+ ModuleUserUtils.getOperationUser(
+ request, "Query list data of Error Code,search name:" + searchName);
+ PageInfo pageList = errorCodeService.getListByPage(searchName, currentPage, pageSize);
+ return Message.ok("").data("list", pageList);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "remove", notes = "Remove a Datasource Code Record by id", httpMethod = "DELETE")
- @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
- public Message remove(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Remove a Datasource Code Record,id:"+id.toString());
- boolean result = errorCodeService.removeById(id);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(value = "get", notes = "Get an Error Code Record by id", httpMethod = "GET")
+ @RequestMapping(path = "/{id}", method = RequestMethod.GET)
+ public Message get(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(request, "Get a Error Code Record,id:" + id.toString());
+ ErrorCodeEntity errorCode = errorCodeService.getById(id);
+ return Message.ok("").data("item", errorCode);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "ErrorCodeEntity", name = "errorCode", value = "")
- })
- @ApiOperation(value = "update", notes = "Update a Datasource Code Record", httpMethod = "PUT")
- @RequestMapping(path = "", method = RequestMethod.PUT)
- public Message update(HttpServletRequest request,@RequestBody ErrorCodeEntity errorCode) {
- ModuleUserUtils.getOperationUser(request, "Update a Datasource Code Record,id:"+errorCode.getId().toString());
- boolean result = errorCodeService.updateById(errorCode);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "body", dataType = "ErrorCodeEntity", name = "errorCode")
+ })
+ @ApiOperation(value = "add", notes = "Add an Error Code Record", httpMethod = "POST")
+ @RequestMapping(path = "", method = RequestMethod.POST)
+ public Message add(HttpServletRequest request, @RequestBody ErrorCodeEntity errorCode) {
+ ModuleUserUtils.getOperationUser(
+ request, "Add a Datasource Code Record," + errorCode.toString());
+ boolean result = errorCodeService.save(errorCode);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(value = "remove", notes = "Remove an Error Code by id", httpMethod = "DELETE")
+ @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
+ public Message remove(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(
+ request, "Remove a Datasource Code Record,id:" + id.toString());
+ boolean result = errorCodeService.removeById(id);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "body", dataType = "ErrorCodeEntity", name = "errorCode")
+ })
+ @ApiOperation(value = "update", notes = "Update a Error Code Record", httpMethod = "PUT")
+ @RequestMapping(path = "", method = RequestMethod.PUT)
+ public Message update(HttpServletRequest request, @RequestBody ErrorCodeEntity errorCode) {
+ ModuleUserUtils.getOperationUser(
+ request, "Update a Datasource Code Record,id:" + errorCode.getId().toString());
+ boolean result = errorCodeService.updateById(errorCode);
+ return Message.ok("").data("result", result);
+ }
}
diff --git a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/GatewayAuthTokenRestfulApi.java b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/GatewayAuthTokenRestfulApi.java
index afa0c5fda..775170918 100644
--- a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/GatewayAuthTokenRestfulApi.java
+++ b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/GatewayAuthTokenRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,97 +14,111 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.linkis.basedatamanager.server.restful;
-import com.github.pagehelper.PageInfo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
import org.apache.linkis.basedatamanager.server.domain.GatewayAuthTokenEntity;
import org.apache.linkis.basedatamanager.server.service.GatewayAuthTokenService;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
+
import java.util.Date;
-import java.util.HashMap;
+import com.github.pagehelper.PageInfo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
@Api(tags = "GatewayAuthTokenRestfulApi")
@RestController
@RequestMapping(path = "/basedata-manager/gateway-auth-token")
public class GatewayAuthTokenRestfulApi {
- @Autowired
- GatewayAuthTokenService gatewayAuthTokenService;
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "")
- })
- @ApiOperation(value = "list", notes = "Query list data of Gateway Auth Token", httpMethod = "GET")
- @RequestMapping(path = "", method = RequestMethod.GET)
- public Message list(HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
- ModuleUserUtils.getOperationUser(request, "Query list data of Gateway Auth Token,search name:"+searchName);
- PageInfo pageList = gatewayAuthTokenService.getListByPage(searchName,currentPage,pageSize);
- return Message.ok("").data("list", pageList);
- }
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "get", notes = "Get a Gateway Auth Token Record by id", httpMethod = "GET")
- @RequestMapping(path = "/{id}", method = RequestMethod.GET)
- public Message get(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Get a Gateway Auth Token Record,id:"+id.toString());
- GatewayAuthTokenEntity gatewayAuthToken = gatewayAuthTokenService.getById(id);
- return Message.ok("").data("item", gatewayAuthToken);
- }
+ @Autowired GatewayAuthTokenService gatewayAuthTokenService;
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "GatewayAuthTokenEntity", name = "gatewayAuthToken", value = "")
- })
- @ApiOperation(value = "add", notes = "Add a Gateway Auth Token Record", httpMethod = "POST")
- @RequestMapping(path = "", method = RequestMethod.POST)
- public Message add(HttpServletRequest request,@RequestBody GatewayAuthTokenEntity gatewayAuthToken) {
- ModuleUserUtils.getOperationUser(request, "Add a Gateway Auth Token Record,"+gatewayAuthToken.toString());
- gatewayAuthToken.setCreateTime(new Date());
- gatewayAuthToken.setUpdateTime(new Date());
- gatewayAuthToken.setBusinessOwner("BDP");
- gatewayAuthToken.setUpdateBy("LINKIS");
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize")
+ })
+ @ApiOperation(value = "list", notes = "list Gateway Auth Tokens", httpMethod = "GET")
+ @RequestMapping(path = "", method = RequestMethod.GET)
+ public Message list(
+ HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
+ ModuleUserUtils.getOperationUser(
+ request, "Query list data of Gateway Auth Token,search name:" + searchName);
+ PageInfo pageList = gatewayAuthTokenService.getListByPage(searchName, currentPage, pageSize);
+ return Message.ok("").data("list", pageList);
+ }
- ModuleUserUtils.getOperationUser(request, "Add a Gateway Auth Token Record,"+gatewayAuthToken.toString());
- boolean result = gatewayAuthTokenService.save(gatewayAuthToken);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(value = "get", notes = "Get a Gateway Auth Token Record by id", httpMethod = "GET")
+ @RequestMapping(path = "/{id}", method = RequestMethod.GET)
+ public Message get(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(
+ request, "Get a Gateway Auth Token Record,id:" + id.toString());
+ GatewayAuthTokenEntity gatewayAuthToken = gatewayAuthTokenService.getById(id);
+ return Message.ok("").data("item", gatewayAuthToken);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "GatewayAuthTokenEntity", name = "token", value = "")
- })
- @ApiOperation(value = "update", notes = "Update a Gateway Auth Token Record", httpMethod = "PUT")
- @RequestMapping(path = "", method = RequestMethod.PUT)
- public Message update(HttpServletRequest request,@RequestBody GatewayAuthTokenEntity token) {
- ModuleUserUtils.getOperationUser(request, "Update a Gateway Auth Token Record,id:"+token.getId().toString());
- token.setUpdateTime(new Date());
- token.setUpdateBy("LINKIS");
+ @ApiImplicitParams({
+ @ApiImplicitParam(
+ paramType = "body",
+ dataType = "GatewayAuthTokenEntity",
+ name = "gatewayAuthToken")
+ })
+ @ApiOperation(value = "add", notes = "Add a Gateway Auth Token Record", httpMethod = "POST")
+ @RequestMapping(path = "", method = RequestMethod.POST)
+ public Message add(
+ HttpServletRequest request, @RequestBody GatewayAuthTokenEntity gatewayAuthToken) {
+ ModuleUserUtils.getOperationUser(
+ request, "Add a Gateway Auth Token Record," + gatewayAuthToken.toString());
+ gatewayAuthToken.setCreateTime(new Date());
+ gatewayAuthToken.setUpdateTime(new Date());
+ gatewayAuthToken.setBusinessOwner("BDP");
+ gatewayAuthToken.setUpdateBy("LINKIS");
- boolean result = gatewayAuthTokenService.updateById(token);
- return Message.ok("").data("result", result);
- }
+ ModuleUserUtils.getOperationUser(
+ request, "Add a Gateway Auth Token Record," + gatewayAuthToken.toString());
+ boolean result = gatewayAuthTokenService.save(gatewayAuthToken);
+ return Message.ok("").data("result", result);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "string", name = "tokenName", value = "")
- })
- @ApiOperation(value = "remove", notes = "Remove a Gateway Auth Token Record by token name", httpMethod = "DELETE")
- @RequestMapping(path = "", method = RequestMethod.DELETE)
- public Message remove(HttpServletRequest request,Long id) {
- ModuleUserUtils.getOperationUser(request, "Remove a Gateway Auth Token Record,id:"+id);
- boolean result = gatewayAuthTokenService.removeById(id);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "body", dataType = "GatewayAuthTokenEntity", name = "token")
+ })
+ @ApiOperation(value = "update", notes = "Update a Gateway Auth Token Record", httpMethod = "PUT")
+ @RequestMapping(path = "", method = RequestMethod.PUT)
+ public Message update(HttpServletRequest request, @RequestBody GatewayAuthTokenEntity token) {
+ ModuleUserUtils.getOperationUser(
+ request, "Update a Gateway Auth Token Record,id:" + token.getId().toString());
+ token.setUpdateTime(new Date());
+ token.setUpdateBy("LINKIS");
+ boolean result = gatewayAuthTokenService.updateById(token);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "string", name = "tokenName")
+ })
+ @ApiOperation(
+ value = "remove",
+ notes = "Remove a Gateway Auth Token Record by token name",
+ httpMethod = "DELETE")
+ @RequestMapping(path = "", method = RequestMethod.DELETE)
+ public Message remove(HttpServletRequest request, Long id) {
+ ModuleUserUtils.getOperationUser(request, "Remove a Gateway Auth Token Record,id:" + id);
+ boolean result = gatewayAuthTokenService.removeById(id);
+ return Message.ok("").data("result", result);
+ }
}
diff --git a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/RmExternalResourceProviderRestfulApi.java b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/RmExternalResourceProviderRestfulApi.java
index fec1fe833..64bf99b38 100644
--- a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/RmExternalResourceProviderRestfulApi.java
+++ b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/RmExternalResourceProviderRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,13 +14,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.linkis.basedatamanager.server.restful;
import org.apache.linkis.basedatamanager.server.domain.RmExternalResourceProviderEntity;
import org.apache.linkis.basedatamanager.server.service.RmExternalResourceProviderService;
import org.apache.linkis.server.Message;
-
import org.apache.linkis.server.utils.ModuleUserUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@@ -28,78 +29,109 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
+import javax.servlet.http.HttpServletRequest;
+
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
-import javax.servlet.http.HttpServletRequest;
-
@Api(tags = "RmExternalResourceProviderRestfulApi")
@RestController
@RequestMapping(path = "/basedata-manager/rm-external-resource-provider")
public class RmExternalResourceProviderRestfulApi {
- @Autowired
- RmExternalResourceProviderService rmExternalResourceProviderService;
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "")
- })
- @ApiOperation(value = "list", notes = "Query list data of Resource manager External Resource Provider", httpMethod = "GET")
- @RequestMapping(path = "", method = RequestMethod.GET)
- public Message list(HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
- ModuleUserUtils.getOperationUser(request, "Query list data of Resource manager External Resource Provider,search name:"+searchName);
- PageInfo pageList = rmExternalResourceProviderService.getListByPage(searchName,currentPage,pageSize);
- return Message.ok("").data("list", pageList);
- }
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "get", notes = "Get a Resource manager External Resource Provider Record by id", httpMethod = "GET")
- @RequestMapping(path = "/{id}", method = RequestMethod.GET)
- public Message get(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Get a Resource manager External Resource Provider Record,id:"+id.toString());
- RmExternalResourceProviderEntity rmExternalResourceProvider = rmExternalResourceProviderService.getById(id);
- return Message.ok("").data("item", rmExternalResourceProvider);
- }
+ @Autowired RmExternalResourceProviderService rmExternalResourceProviderService;
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "RmExternalResourceProviderEntity", name = "rmExternalResourceProvider", value = "")
- })
- @ApiOperation(value = "add", notes = "Add a Resource manager External Resource Provider Record", httpMethod = "POST")
- @RequestMapping(path = "", method = RequestMethod.POST)
- public Message add(HttpServletRequest request,@RequestBody RmExternalResourceProviderEntity rmExternalResourceProvider) {
- ModuleUserUtils.getOperationUser(request, "Add a Resource manager External Resource Provider Record,"+rmExternalResourceProvider.toString());
- boolean result = rmExternalResourceProviderService.save(rmExternalResourceProvider);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize")
+ })
+ @ApiOperation(
+ value = "list",
+ notes = "list Resource manager External Resource Providers",
+ httpMethod = "GET")
+ @RequestMapping(path = "", method = RequestMethod.GET)
+ public Message list(
+ HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
+ ModuleUserUtils.getOperationUser(
+ request,
+ "Query list data of Resource manager External Resource Provider,search name:" + searchName);
+ PageInfo pageList =
+ rmExternalResourceProviderService.getListByPage(searchName, currentPage, pageSize);
+ return Message.ok("").data("list", pageList);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "remove", notes = "Remove a Resource manager External Resource Provider Record by id", httpMethod = "DELETE")
- @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
- public Message remove(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Remove a Resource manager External Resource Provider Record,id:"+id.toString());
- boolean result = rmExternalResourceProviderService.removeById(id);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(
+ value = "get",
+ notes = "Get a Resource manager External Resource Provider Record by id",
+ httpMethod = "GET")
+ @RequestMapping(path = "/{id}", method = RequestMethod.GET)
+ public Message get(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(
+ request, "Get a Resource manager External Resource Provider Record,id:" + id.toString());
+ RmExternalResourceProviderEntity rmExternalResourceProvider =
+ rmExternalResourceProviderService.getById(id);
+ return Message.ok("").data("item", rmExternalResourceProvider);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "RmExternalResourceProviderEntity", name = "rmExternalResourceProvider", value = "")
- })
- @ApiOperation(value = "update", notes = "Update a Resource manager External Resource Provider Record", httpMethod = "PUT")
- @RequestMapping(path = "", method = RequestMethod.PUT)
- public Message update(HttpServletRequest request,@RequestBody RmExternalResourceProviderEntity rmExternalResourceProvider) {
- ModuleUserUtils.getOperationUser(request, "Update a Resource manager External Resource Provider Record,id:"+rmExternalResourceProvider.getId().toString());
- boolean result = rmExternalResourceProviderService.updateById(rmExternalResourceProvider);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(
+ paramType = "body",
+ dataType = "RmExternalResourceProviderEntity",
+ name = "rmExternalResourceProvider")
+ })
+ @ApiOperation(
+ value = "add",
+ notes = "Add a Resource manager External Resource Provider Record",
+ httpMethod = "POST")
+ @RequestMapping(path = "", method = RequestMethod.POST)
+ public Message add(
+ HttpServletRequest request,
+ @RequestBody RmExternalResourceProviderEntity rmExternalResourceProvider) {
+ ModuleUserUtils.getOperationUser(
+ request,
+ "Add a Resource manager External Resource Provider Record,"
+ + rmExternalResourceProvider.toString());
+ boolean result = rmExternalResourceProviderService.save(rmExternalResourceProvider);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(
+ value = "remove",
+ notes = "Remove a Resource manager External Resource Provider Record by id",
+ httpMethod = "DELETE")
+ @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
+ public Message remove(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(
+ request, "Remove a Resource manager External Resource Provider Record,id:" + id.toString());
+ boolean result = rmExternalResourceProviderService.removeById(id);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({
+ @ApiImplicitParam(
+ paramType = "body",
+ dataType = "RmExternalResourceProviderEntity",
+ name = "rmExternalResourceProvider")
+ })
+ @ApiOperation(
+ value = "update",
+ notes = "Update a Resource manager External Resource Provider Record",
+ httpMethod = "PUT")
+ @RequestMapping(path = "", method = RequestMethod.PUT)
+ public Message update(
+ HttpServletRequest request,
+ @RequestBody RmExternalResourceProviderEntity rmExternalResourceProvider) {
+ ModuleUserUtils.getOperationUser(
+ request,
+ "Update a Resource manager External Resource Provider Record,id:"
+ + rmExternalResourceProvider.getId().toString());
+ boolean result = rmExternalResourceProviderService.updateById(rmExternalResourceProvider);
+ return Message.ok("").data("result", result);
+ }
}
diff --git a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/UdfManagerRestfulApi.java b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/UdfManagerRestfulApi.java
index f4cf843f6..f7a362773 100644
--- a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/UdfManagerRestfulApi.java
+++ b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/UdfManagerRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,86 +14,97 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.linkis.basedatamanager.server.restful;
-import com.github.pagehelper.PageInfo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
import org.apache.linkis.basedatamanager.server.domain.UdfManagerEntity;
import org.apache.linkis.basedatamanager.server.service.UdfManagerService;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
-@Api(tags="UdfManagerRestfulApi")
+import com.github.pagehelper.PageInfo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+
+@Api(tags = "UdfManagerRestfulApi")
@RestController
@RequestMapping(path = "/basedata-manager/udf-manager")
public class UdfManagerRestfulApi {
- @Autowired
- UdfManagerService udfManagerService;
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "")
- })
- @ApiOperation(value = "list", notes = "Query list data of UDF Manager", httpMethod = "GET")
- @RequestMapping(path = "", method = RequestMethod.GET)
- public Message list(HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
- ModuleUserUtils.getOperationUser(request, "Query list data of UDF Manager,search name:"+searchName);
- PageInfo pageList = udfManagerService.getListByPage(searchName,currentPage,pageSize);
- return Message.ok("").data("list", pageList);
- }
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "Get a Datasource UDF Manager", notes = "get data by id", httpMethod = "GET")
- @RequestMapping(path = "/{id}", method = RequestMethod.GET)
- public Message get(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Get a Datasource UDF Manager,id:"+id.toString());
- UdfManagerEntity errorCode = udfManagerService.getById(id);
- return Message.ok("").data("item", errorCode);
- }
+ @Autowired UdfManagerService udfManagerService;
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "UdfManagerEntity", name = "udfManagerEntity", value = "")
- })
- @ApiOperation(value = "add", notes = "Add a UDF Manager Record", httpMethod = "POST")
- @RequestMapping(path = "", method = RequestMethod.POST)
- public Message add(HttpServletRequest request,@RequestBody UdfManagerEntity udfManagerEntity) {
- ModuleUserUtils.getOperationUser(request, "Add a UDF Manager Record,"+udfManagerEntity.toString());
- boolean result = udfManagerService.save(udfManagerEntity);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize")
+ })
+ @ApiOperation(value = "list", notes = "Query list data of UDF Manager", httpMethod = "GET")
+ @RequestMapping(path = "", method = RequestMethod.GET)
+ public Message list(
+ HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
+ ModuleUserUtils.getOperationUser(
+ request, "Query list data of UDF Manager,search name:" + searchName);
+ PageInfo pageList = udfManagerService.getListByPage(searchName, currentPage, pageSize);
+ return Message.ok("").data("list", pageList);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "remove", notes = "Remove a UDF Manager Record by id", httpMethod = "DELETE")
- @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
- public Message remove(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Remove a UDF Manager Record,id:"+id.toString());
- boolean result = udfManagerService.removeById(id);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(
+ value = "Get a Datasource UDF Manager",
+ notes = "get data by id",
+ httpMethod = "GET")
+ @RequestMapping(path = "/{id}", method = RequestMethod.GET)
+ public Message get(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(request, "Get a Datasource UDF Manager,id:" + id.toString());
+ UdfManagerEntity errorCode = udfManagerService.getById(id);
+ return Message.ok("").data("item", errorCode);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "UdfManagerEntity", name = "udfManagerEntity", value = "")
- })
- @ApiOperation(value = "update", notes = "Update a Datasource Access Record", httpMethod = "PUT")
- @RequestMapping(path = "", method = RequestMethod.PUT)
- public Message update(HttpServletRequest request,@RequestBody UdfManagerEntity udfManagerEntity) {
- ModuleUserUtils.getOperationUser(request, "Update a Datasource Access Record,id:"+udfManagerEntity.getId().toString());
- boolean result = udfManagerService.updateById(udfManagerEntity);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "body", dataType = "UdfManagerEntity", name = "udfManagerEntity")
+ })
+ @ApiOperation(value = "add", notes = "Add a UDF Manager Record", httpMethod = "POST")
+ @RequestMapping(path = "", method = RequestMethod.POST)
+ public Message add(HttpServletRequest request, @RequestBody UdfManagerEntity udfManagerEntity) {
+ ModuleUserUtils.getOperationUser(
+ request, "Add a UDF Manager Record," + udfManagerEntity.toString());
+ boolean result = udfManagerService.save(udfManagerEntity);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(
+ value = "remove",
+ notes = "Remove a UDF Manager Record by id",
+ httpMethod = "DELETE")
+ @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
+ public Message remove(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(request, "Remove a UDF Manager Record,id:" + id.toString());
+ boolean result = udfManagerService.removeById(id);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "body", dataType = "UdfManagerEntity", name = "udfManagerEntity")
+ })
+ @ApiOperation(value = "update", notes = "Update a Datasource Access Record", httpMethod = "PUT")
+ @RequestMapping(path = "", method = RequestMethod.PUT)
+ public Message update(
+ HttpServletRequest request, @RequestBody UdfManagerEntity udfManagerEntity) {
+ ModuleUserUtils.getOperationUser(
+ request, "Update a Datasource Access Record,id:" + udfManagerEntity.getId().toString());
+ boolean result = udfManagerService.updateById(udfManagerEntity);
+ return Message.ok("").data("result", result);
+ }
}
diff --git a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/UdfTreeRestfulApi.java b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/UdfTreeRestfulApi.java
index b3a03be3b..d0b496d47 100644
--- a/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/UdfTreeRestfulApi.java
+++ b/linkis-public-enhancements/linkis-basedata-manager/src/main/java/org/apache/linkis/basedatamanager/server/restful/UdfTreeRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,86 +14,89 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.linkis.basedatamanager.server.restful;
-import com.github.pagehelper.PageInfo;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
import org.apache.linkis.basedatamanager.server.domain.UdfTreeEntity;
import org.apache.linkis.basedatamanager.server.service.UdfTreeService;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
-@Api(tags="UdfTreeRestfulApi")
+import com.github.pagehelper.PageInfo;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+
+@Api(tags = "UdfTreeRestfulApi")
@RestController
@RequestMapping(path = "/basedata-manager/udf-tree")
public class UdfTreeRestfulApi {
- @Autowired
- UdfTreeService udfTreeService;
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage", value = ""),
- @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize", value = "")
- })
- @ApiOperation(value = "list", notes = "Query list data of UDF Tree", httpMethod = "GET")
- @RequestMapping(path = "", method = RequestMethod.GET)
- public Message list(HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
- ModuleUserUtils.getOperationUser(request, "Query list data of UDF Tree,search name:"+searchName);
- PageInfo pageList = udfTreeService.getListByPage(searchName,currentPage,pageSize);
- return Message.ok("").data("list", pageList);
- }
-
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "get", notes = "Get a UDF Tree Record by id", httpMethod = "GET")
- @RequestMapping(path = "/{id}", method = RequestMethod.GET)
- public Message get(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Get a UDF Tree Record,id:"+id.toString());
- UdfTreeEntity errorCode = udfTreeService.getById(id);
- return Message.ok("").data("item", errorCode);
- }
+ @Autowired UdfTreeService udfTreeService;
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "UdfTreeEntity", name = "udfTreeEntity", value = "")
- })
- @ApiOperation(value = "add", notes = "Add a UDF Tree Record", httpMethod = "POST")
- @RequestMapping(path = "", method = RequestMethod.POST)
- public Message add(HttpServletRequest request,@RequestBody UdfTreeEntity udfTreeEntity) {
- ModuleUserUtils.getOperationUser(request, "Add a UDF Tree Record,"+udfTreeEntity.toString());
- boolean result = udfTreeService.save(udfTreeEntity);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchName"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "currentPage"),
+ @ApiImplicitParam(paramType = "query", dataType = "int", name = "pageSize")
+ })
+ @ApiOperation(value = "list", notes = "Query list data of UDF Tree", httpMethod = "GET")
+ @RequestMapping(path = "", method = RequestMethod.GET)
+ public Message list(
+ HttpServletRequest request, String searchName, Integer currentPage, Integer pageSize) {
+ ModuleUserUtils.getOperationUser(
+ request, "Query list data of UDF Tree,search name:" + searchName);
+ PageInfo pageList = udfTreeService.getListByPage(searchName, currentPage, pageSize);
+ return Message.ok("").data("list", pageList);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "")
- })
- @ApiOperation(value = "remove", notes = "Remove a UDF Tree Record by id", httpMethod = "DELETE")
- @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
- public Message remove(HttpServletRequest request,@PathVariable("id") Long id) {
- ModuleUserUtils.getOperationUser(request, "Remove a UDF Tree Record,id:"+id.toString());
- boolean result = udfTreeService.removeById(id);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(value = "get", notes = "Get a UDF Tree Record by id", httpMethod = "GET")
+ @RequestMapping(path = "/{id}", method = RequestMethod.GET)
+ public Message get(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(request, "Get a UDF Tree Record,id:" + id.toString());
+ UdfTreeEntity errorCode = udfTreeService.getById(id);
+ return Message.ok("").data("item", errorCode);
+ }
- @ApiImplicitParams({
- @ApiImplicitParam(paramType = "body", dataType = "UdfTreeEntity", name = "udfTreeEntity", value = "")
- })
- @ApiOperation(value = "update", notes = "Update a UDF Tree Record", httpMethod = "PUT")
- @RequestMapping(path = "", method = RequestMethod.PUT)
- public Message update(HttpServletRequest request,@RequestBody UdfTreeEntity udfTreeEntity) {
- ModuleUserUtils.getOperationUser(request, "Update a UDF Tree Record,id:"+udfTreeEntity.getId().toString());
- boolean result = udfTreeService.updateById(udfTreeEntity);
- return Message.ok("").data("result", result);
- }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "body", dataType = "UdfTreeEntity", name = "udfTreeEntity")
+ })
+ @ApiOperation(value = "add", notes = "Add a UDF Tree Record", httpMethod = "POST")
+ @RequestMapping(path = "", method = RequestMethod.POST)
+ public Message add(HttpServletRequest request, @RequestBody UdfTreeEntity udfTreeEntity) {
+ ModuleUserUtils.getOperationUser(request, "Add a UDF Tree Record," + udfTreeEntity.toString());
+ boolean result = udfTreeService.save(udfTreeEntity);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({@ApiImplicitParam(paramType = "path", dataType = "long", name = "id")})
+ @ApiOperation(value = "remove", notes = "Remove a UDF Tree Record by id", httpMethod = "DELETE")
+ @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
+ public Message remove(HttpServletRequest request, @PathVariable("id") Long id) {
+ ModuleUserUtils.getOperationUser(request, "Remove a UDF Tree Record,id:" + id.toString());
+ boolean result = udfTreeService.removeById(id);
+ return Message.ok("").data("result", result);
+ }
+ @ApiImplicitParams({
+ @ApiImplicitParam(paramType = "body", dataType = "UdfTreeEntity", name = "udfTreeEntity")
+ })
+ @ApiOperation(value = "update", notes = "Update a UDF Tree Record", httpMethod = "PUT")
+ @RequestMapping(path = "", method = RequestMethod.PUT)
+ public Message update(HttpServletRequest request, @RequestBody UdfTreeEntity udfTreeEntity) {
+ ModuleUserUtils.getOperationUser(
+ request, "Update a UDF Tree Record,id:" + udfTreeEntity.getId().toString());
+ boolean result = udfTreeService.updateById(udfTreeEntity);
+ return Message.ok("").data("result", result);
+ }
}
diff --git a/linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/restful/BmlProjectRestful.java b/linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/restful/BmlProjectRestful.java
index 1c5482f08..e11db0da4 100644
--- a/linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/restful/BmlProjectRestful.java
+++ b/linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/restful/BmlProjectRestful.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -43,6 +43,9 @@ import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.*;
+
import com.fasterxml.jackson.databind.JsonNode;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
@@ -52,9 +55,6 @@ import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.*;
-
import static org.apache.linkis.bml.errorcode.BmlServerErrorCodeSummary.FAILED_DOWNLOAD_RESOURCE;
@Api(tags = "bml(bigdata material library) project opreation")
@@ -62,403 +62,397 @@ import static org.apache.linkis.bml.errorcode.BmlServerErrorCodeSummary.FAILED_D
@RestController
public class BmlProjectRestful {
- private static final Logger LOGGER = LoggerFactory.getLogger(BmlProjectRestful.class);
-
- private static final String PROJECT_NAME_STR = "projectName";
- private static final String EDIT_USERS_STR = "editUsers";
- private static final String ACCESS_USERS_STR = "accessUsers";
- public static final String DEFAULT_PROXY_USER =
- BmlServerConfiguration.BML_DEFAULT_PROXY_USER().getValue();
+ private static final Logger LOGGER = LoggerFactory.getLogger(BmlProjectRestful.class);
- @Autowired private BmlProjectService bmlProjectService;
+ private static final String PROJECT_NAME_STR = "projectName";
+ private static final String EDIT_USERS_STR = "editUsers";
+ private static final String ACCESS_USERS_STR = "accessUsers";
+ public static final String DEFAULT_PROXY_USER =
+ BmlServerConfiguration.BML_DEFAULT_PROXY_USER().getValue();
- @Autowired private TaskService taskService;
+ @Autowired private BmlProjectService bmlProjectService;
- @Autowired private VersionService versionService;
+ @Autowired private TaskService taskService;
- @Autowired private ResourceService resourceService;
+ @Autowired private VersionService versionService;
- @Autowired private DownloadService downloadService;
+ @Autowired private ResourceService resourceService;
- @ApiOperation(value = "createBmlProject", notes = "create Bml project", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "projectName",required = true, dataType = "String", value = "project name"),
- @ApiImplicitParam(name = "editUsers", required = true, dataType = "String", value = "edit users"),
- @ApiImplicitParam(name = "accessUsers", required = true, dataType = "String", value = "access users")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "createBmlProject", method = RequestMethod.POST)
- public Message createBmlProject(HttpServletRequest request, @RequestBody JsonNode jsonNode) {
+ @Autowired private DownloadService downloadService;
- String projectName = jsonNode.get(PROJECT_NAME_STR).textValue();
- String username =
- ModuleUserUtils.getOperationUser(request, "createBmlProject" + projectName);
- LOGGER.info("{} begins to create a project {} in bml", username, projectName);
- JsonNode editUserNode = jsonNode.get(EDIT_USERS_STR);
- JsonNode accessUserNode = jsonNode.get(ACCESS_USERS_STR);
- List<String> accessUsers = new ArrayList<>();
- List<String> editUsers = new ArrayList<>();
- if (editUserNode.isArray()) {
- for (JsonNode node : editUserNode) {
- editUsers.add(node.textValue());
- }
- }
- if (accessUserNode.isArray()) {
- for (JsonNode node : accessUserNode) {
- accessUsers.add(node.textValue());
- }
- }
- bmlProjectService.createBmlProject(projectName, username, editUsers, accessUsers);
+ @ApiOperation(value = "createBmlProject", notes = "create Bml project", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "projectName", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "editUsers", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "accessUsers", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "createBmlProject", method = RequestMethod.POST)
+ public Message createBmlProject(HttpServletRequest request, @RequestBody JsonNode jsonNode) {
- return Message.ok("success to create project(创建工程ok)");
+ String projectName = jsonNode.get(PROJECT_NAME_STR).textValue();
+ String username = ModuleUserUtils.getOperationUser(request, "createBmlProject" + projectName);
+ LOGGER.info("{} begins to create a project {} in bml", username, projectName);
+ JsonNode editUserNode = jsonNode.get(EDIT_USERS_STR);
+ JsonNode accessUserNode = jsonNode.get(ACCESS_USERS_STR);
+ List<String> accessUsers = new ArrayList<>();
+ List<String> editUsers = new ArrayList<>();
+ if (editUserNode.isArray()) {
+ for (JsonNode node : editUserNode) {
+ editUsers.add(node.textValue());
+ }
}
-
- @ApiOperation(value = "uploadShareResource",notes = "upload share resource", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "system", required = false, dataType = "String", value = "system"),
- @ApiImplicitParam(name = "resourceHeader", required = false, dataType = "String", value = "resource header"),
- @ApiImplicitParam(name = "isExpire", required = false, dataType = "String", value = "is expire"),
- @ApiImplicitParam(name = "expireType", required = false, dataType = "String", value = "expire type"),
- @ApiImplicitParam(name = "expireTime", required = false, dataType = "String", value = "expire time"),
- @ApiImplicitParam(name = "maxVersion", required = false, dataType = "Integer", value = "max version"),
- @ApiImplicitParam(name = "projectName", required = true, dataType = "String", value = "project name"),
- @ApiImplicitParam(name = "file", required = true, dataType = "List<MultipartFile>", value = "flie list")
- })
- @RequestMapping(path = "uploadShareResource", method = RequestMethod.POST)
- public Message uploadShareResource(
- HttpServletRequest request,
- @RequestParam(name = "system", required = false) String system,
- @RequestParam(name = "resourceHeader", required = false) String resourceHeader,
- @RequestParam(name = "isExpire", required = false) String isExpire,
- @RequestParam(name = "expireType", required = false) String expireType,
- @RequestParam(name = "expireTime", required = false) String expireTime,
- @RequestParam(name = "maxVersion", required = false) Integer maxVersion,
- @RequestParam(name = "projectName") String projectName,
- @RequestParam(name = "file") List<MultipartFile> files)
- throws ErrorException {
- String username = ModuleUserUtils.getOperationUser(request, "uploadShareResource");
- Message message;
- try {
- LOGGER.info(
- "User {} starts uploading shared resources and is proxied as a Hadoop user for uploading(用户 {} 开始上传共享资源,会被代理成hadoop用户进行上传)",
- username,
- username);
- if (!bmlProjectService.checkEditPriv(projectName, username)) {
- LOGGER.error(
- "{} does not have edit permission on project {}. Upload resource failed ({} 对工程 {} 没有编辑权限, 上传资源失败)",
- username,
- projectName,
- username,
- projectName);
- throw new BmlProjectNoEditException(
- username
- + "does not have edit permission on project "
- + projectName
- + ". Upload resource failed"
- + username
- + " 对工程 { "
- + projectName
- + " }没有编辑权限,上传资源失败");
- }
- Map<String, Object> properties = new HashMap<>();
- properties.put("system", system);
- properties.put("resourceHeader", resourceHeader);
- properties.put("isExpire", isExpire);
- properties.put("expireType", expireType);
- properties.put("expireTime", expireTime);
- properties.put("maxVersion", maxVersion);
- String clientIp = HttpRequestHelper.getIp(request);
- properties.put("clientIp", clientIp);
- ResourceTask resourceTask =
- taskService.createUploadTask(files, DEFAULT_PROXY_USER, properties);
- bmlProjectService.addProjectResource(resourceTask.getResourceId(), projectName);
- message =
- Message.ok(
- "The task of submitting and uploading resources was successful(提交上传资源任务成功)");
- message.data("resourceId", resourceTask.getResourceId());
- message.data("version", resourceTask.getVersion());
- message.data("taskId", resourceTask.getId());
- LOGGER.info(
- "The task of submitting and uploading resources was successful (用户 {} 提交上传资源任务成功), resourceId is {}",
- username,
- resourceTask.getResourceId());
- } catch (final Exception e) {
- LOGGER.error("upload resource for user : {} failed, reason:", username, e);
- ErrorException exception =
- new ErrorException(
- 50073,
- "The commit upload resource task failed: (提交上传资源任务失败)"
- + e.getMessage());
- exception.initCause(e);
- throw exception;
- }
- return message;
+ if (accessUserNode.isArray()) {
+ for (JsonNode node : accessUserNode) {
+ accessUsers.add(node.textValue());
+ }
}
+ bmlProjectService.createBmlProject(projectName, username, editUsers, accessUsers);
- @ApiOperation(value = "updateShareResource", notes = "update share resource", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = true, dataType = "String", value = "resource Id"),
- @ApiImplicitParam(name = "file", required = true, dataType = "MultipartFile", value = "file")
- })
- @RequestMapping(path = "updateShareResource", method = RequestMethod.POST)
- public Message updateShareResource(
- HttpServletRequest request,
- @RequestParam("resourceId") String resourceId,
- @RequestParam("file") MultipartFile file)
- throws ErrorException {
- String username =
- ModuleUserUtils.getOperationUser(request, "updateShareResource:" + resourceId);
- if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
- LOGGER.error("the error resourceId is {} ", resourceId);
- throw new BmlServerParaErrorException(
- "the resourceId: "
- + resourceId
- + " is Null, illegal, or deleted (resourceId: "
- + resourceId
- + " 为空,非法或者已被删除!)");
- }
- if (StringUtils.isEmpty(versionService.getNewestVersion(resourceId))) {
- LOGGER.error(
- "If the material has not been uploaded or has been deleted, please call the upload interface first(resourceId:{} 之前未上传物料,或物料已被删除,请先调用上传接口.)",
- resourceId);
- throw new BmlServerParaErrorException(
- "If the material has not been uploaded or has been deleted, please call the upload interface first (resourceId: "
- + resourceId
- + " 之前未上传物料,或物料已被删除,请先调用上传接口.!)");
- }
- Message message;
- try {
- String projectName = bmlProjectService.getProjectNameByResourceId(resourceId);
- if (!bmlProjectService.checkEditPriv(projectName, username)) {
- LOGGER.error(
- "{} does not have edit permission on project {}. Upload resource failed ({} 对工程 {} 没有编辑权限, 上传资源失败)",
- username,
- projectName,
- username,
- projectName);
- throw new BmlProjectNoEditException(
- username
- + "does not have edit permission on project: "
- + projectName
- + ". Upload resource failed ("
- + username
- + " 对工程 { "
- + projectName
- + " }没有编辑权限,上传资源失败");
- }
- LOGGER.info(
- "User {} starts updating resources {}, using proxy user Hadoop (用户 {} 开始更新资源 {},使用代理用户hadoop)",
- username,
- resourceId,
- username,
- resourceId);
- String clientIp = HttpRequestHelper.getIp(request);
- Map<String, Object> properties = new HashMap<>();
- properties.put("clientIp", clientIp);
- ResourceTask resourceTask = null;
- synchronized (resourceId.intern()) {
- resourceTask =
- taskService.createUpdateTask(
- resourceId, DEFAULT_PROXY_USER, file, properties);
- }
- message = Message.ok("The update resource task was submitted successfully(提交更新资源任务成功)");
- message.data("resourceId", resourceId)
- .data("version", resourceTask.getVersion())
- .data("taskId", resourceTask.getId());
- } catch (final ErrorException e) {
- LOGGER.error(
- "{} update resource failed, resourceId is {}, reason:",
- username,
- resourceId,
- e);
- throw e;
- } catch (final Exception e) {
- LOGGER.error(
- "{} update resource failed, resourceId is {}, reason:",
- username,
- resourceId,
- e);
- ErrorException exception =
- new ErrorException(
- 50073,
- "The commit upload resource task failed(提交上传资源任务失败):" + e.getMessage());
- exception.initCause(e);
- throw exception;
- }
- LOGGER.info(
- "User {} ends updating resources {} (用户 {} 结束更新资源 {} )",
- username,
- resourceId,
- username,
- resourceId);
- return message;
- }
+ return Message.ok("success to create project(创建工程ok)");
+ }
- @ApiOperation(value = "downloadShareResource", notes = "download share resource", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = false, dataType = "String", value = "resource id"),
- @ApiImplicitParam(name = "version", required = false, dataType = "String", value = "version")
- })
- @RequestMapping(path = "downloadShareResource", method = RequestMethod.GET)
- public void downloadShareResource(
- @RequestParam(value = "resourceId", required = false) String resourceId,
- @RequestParam(value = "version", required = false) String version,
- HttpServletResponse resp,
- HttpServletRequest request)
- throws IOException, ErrorException {
- String user = RestfulUtils.getUserName(request);
- Message message = null;
- resp.setContentType("application/x-msdownload");
- resp.setHeader("Content-Disposition", "attachment");
- String ip = HttpRequestHelper.getIp(request);
- DownloadModel downloadModel = new DownloadModel(resourceId, version, user, ip);
- try {
- String projectName = bmlProjectService.getProjectNameByResourceId(resourceId);
- if (!bmlProjectService.checkAccessPriv(projectName, user)) {
- LOGGER.error(
- "{} does not have view privileges on project {}. Download resource failed({} 对工程 {} 没有查看权限, 下载资源失败)",
- user,
- projectName,
- user,
- projectName);
- throw new BmlProjectNoEditException(
- user
- + " does not have view privileges on project "
- + projectName
- + ". Download resource failed"
- + user
- + " 对工程 { "
- + projectName
- + " }没有编辑权限,上传资源失败");
- }
- LOGGER.info(
- "user {} begin to downLoad resource resourceId is {}, version is {} ,ip is {}, 并代理成hadoop ",
- user,
- resourceId,
- version,
- ip);
- Map<String, Object> properties = new HashMap<>();
- boolean downloadResult =
- versionService.downloadResource(
- DEFAULT_PROXY_USER,
- resourceId,
- version,
- resp.getOutputStream(),
- properties);
- downloadModel.setEndTime(new Date(System.currentTimeMillis()));
- downloadModel.setState(0);
- if (!downloadResult) {
- LOGGER.warn(
- "ResourceId :{}, version:{} has a problem when user {} downloads the resource. The copied size is less than 0 (用户 {} 下载资源 resourceId: {}, version:{} 出现问题,复制的size小于0)",
- user,
- resourceId,
- version,
- user,
- resourceId,
- version);
- downloadModel.setState(1);
- throw new BmlQueryFailException(FAILED_DOWNLOAD_RESOURCE.getErrorDesc());
- }
- downloadService.addDownloadRecord(downloadModel);
- LOGGER.info(
- "User {} ends downloading the resource {} (用户 {} 结束下载资源 {}) ",
- user,
- resourceId,
- user,
- resourceId);
- } catch (IOException e) {
- LOGGER.error(
- "IO Exception: ResourceId :{}, version:{} (用户 {} 下载资源 resourceId: {}, version:{} 出现IO异常)",
- resourceId,
- version,
- user,
- resourceId,
- version,
- e);
- downloadModel.setEndTime(new Date());
- downloadModel.setState(1);
- downloadService.addDownloadRecord(downloadModel);
- throw new ErrorException(
- 73562,
- "Sorry, the background IO error caused you to download the resources failed(抱歉,后台IO错误造成您本次下载资源失败)");
- } catch (final Throwable t) {
- LOGGER.error(
- "ResourceId :{}, version:{} abnormal when user {} downloads resource (用户 {} 下载资源 resourceId: {}, version:{} 出现异常)",
- resourceId,
- version,
- user,
- user,
- resourceId,
- version);
- downloadModel.setEndTime(new Date());
- downloadModel.setState(1);
- downloadService.addDownloadRecord(downloadModel);
- throw new ErrorException(
- 73561,
- "Sorry, the background service error caused you to download the resources failed (抱歉,后台服务出错导致您本次下载资源失败)");
- } finally {
- IOUtils.closeQuietly(resp.getOutputStream());
- }
- LOGGER.info(
- "{} Download resource {} successfully ({} 下载资源 {} 成功)",
- user,
- resourceId,
- user,
- resourceId);
+ @ApiOperation(
+ value = "uploadShareResource",
+ notes = "upload share resource",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "system", required = false, dataType = "String", value = "system"),
+ @ApiImplicitParam(name = "resourceHeader", dataType = "String", value = "resource header"),
+ @ApiImplicitParam(name = "isExpire", dataType = "String", value = "is expire"),
+ @ApiImplicitParam(name = "expireType", dataType = "String", value = "expire type"),
+ @ApiImplicitParam(name = "expireTime", dataType = "String", value = "expire time"),
+ @ApiImplicitParam(name = "maxVersion", dataType = "Integer", value = "max version"),
+ @ApiImplicitParam(name = "projectName", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "file", required = true, dataType = "List<MultipartFile>")
+ })
+ @RequestMapping(path = "uploadShareResource", method = RequestMethod.POST)
+ public Message uploadShareResource(
+ HttpServletRequest request,
+ @RequestParam(name = "system", required = false) String system,
+ @RequestParam(name = "resourceHeader", required = false) String resourceHeader,
+ @RequestParam(name = "isExpire", required = false) String isExpire,
+ @RequestParam(name = "expireType", required = false) String expireType,
+ @RequestParam(name = "expireTime", required = false) String expireTime,
+ @RequestParam(name = "maxVersion", required = false) Integer maxVersion,
+ @RequestParam(name = "projectName") String projectName,
+ @RequestParam(name = "file") List<MultipartFile> files)
+ throws ErrorException {
+ String username = ModuleUserUtils.getOperationUser(request, "uploadShareResource");
+ Message message;
+ try {
+ LOGGER.info(
+ "User {} starts uploading shared resources and is proxied as a Hadoop user for uploading(用户 {} 开始上传共享资源,会被代理成hadoop用户进行上传)",
+ username,
+ username);
+ if (!bmlProjectService.checkEditPriv(projectName, username)) {
+ LOGGER.error(
+ "{} does not have edit permission on project {}. Upload resource failed ({} 对工程 {} 没有编辑权限, 上传资源失败)",
+ username,
+ projectName,
+ username,
+ projectName);
+ throw new BmlProjectNoEditException(
+ username
+ + "does not have edit permission on project "
+ + projectName
+ + ". Upload resource failed"
+ + username
+ + " 对工程 { "
+ + projectName
+ + " }没有编辑权限,上传资源失败");
+ }
+ Map<String, Object> properties = new HashMap<>();
+ properties.put("system", system);
+ properties.put("resourceHeader", resourceHeader);
+ properties.put("isExpire", isExpire);
+ properties.put("expireType", expireType);
+ properties.put("expireTime", expireTime);
+ properties.put("maxVersion", maxVersion);
+ String clientIp = HttpRequestHelper.getIp(request);
+ properties.put("clientIp", clientIp);
+ ResourceTask resourceTask =
+ taskService.createUploadTask(files, DEFAULT_PROXY_USER, properties);
+ bmlProjectService.addProjectResource(resourceTask.getResourceId(), projectName);
+ message =
+ Message.ok("The task of submitting and uploading resources was successful(提交上传资源任务成功)");
+ message.data("resourceId", resourceTask.getResourceId());
+ message.data("version", resourceTask.getVersion());
+ message.data("taskId", resourceTask.getId());
+ LOGGER.info(
+ "The task of submitting and uploading resources was successful (用户 {} 提交上传资源任务成功), resourceId is {}",
+ username,
+ resourceTask.getResourceId());
+ } catch (final Exception e) {
+ LOGGER.error("upload resource for user : {} failed, reason:", username, e);
+ ErrorException exception =
+ new ErrorException(
+ 50073, "The commit upload resource task failed: (提交上传资源任务失败)" + e.getMessage());
+ exception.initCause(e);
+ throw exception;
}
+ return message;
+ }
- @ApiOperation(value = "getProjectInfo", notes = "get project info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "projectName", required = false, dataType = "String", value = "project name")
- })
- @RequestMapping(path = "getProjectInfo", method = RequestMethod.GET)
- public Message getProjectInfo(
- HttpServletRequest request,
- @RequestParam(value = "projectName", required = false) String projectName) {
- return Message.ok("Obtain project information successfully (获取工程信息成功)");
+ @ApiOperation(
+ value = "updateShareResource",
+ notes = "update share resource",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "resourceId", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "file", required = true, dataType = "MultipartFile", value = "file")
+ })
+ @RequestMapping(path = "updateShareResource", method = RequestMethod.POST)
+ public Message updateShareResource(
+ HttpServletRequest request,
+ @RequestParam("resourceId") String resourceId,
+ @RequestParam("file") MultipartFile file)
+ throws ErrorException {
+ String username =
+ ModuleUserUtils.getOperationUser(request, "updateShareResource:" + resourceId);
+ if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
+ LOGGER.error("the error resourceId is {} ", resourceId);
+ throw new BmlServerParaErrorException(
+ "the resourceId: "
+ + resourceId
+ + " is Null, illegal, or deleted (resourceId: "
+ + resourceId
+ + " 为空,非法或者已被删除!)");
+ }
+ if (StringUtils.isEmpty(versionService.getNewestVersion(resourceId))) {
+ LOGGER.error(
+ "If the material has not been uploaded or has been deleted, please call the upload interface first(resourceId:{} 之前未上传物料,或物料已被删除,请先调用上传接口.)",
+ resourceId);
+ throw new BmlServerParaErrorException(
+ "If the material has not been uploaded or has been deleted, please call the upload interface first (resourceId: "
+ + resourceId
+ + " 之前未上传物料,或物料已被删除,请先调用上传接口.!)");
+ }
+ Message message;
+ try {
+ String projectName = bmlProjectService.getProjectNameByResourceId(resourceId);
+ if (!bmlProjectService.checkEditPriv(projectName, username)) {
+ LOGGER.error(
+ "{} does not have edit permission on project {}. Upload resource failed ({} 对工程 {} 没有编辑权限, 上传资源失败)",
+ username,
+ projectName,
+ username,
+ projectName);
+ throw new BmlProjectNoEditException(
+ username
+ + "does not have edit permission on project: "
+ + projectName
+ + ". Upload resource failed ("
+ + username
+ + " 对工程 { "
+ + projectName
+ + " }没有编辑权限,上传资源失败");
+ }
+ LOGGER.info(
+ "User {} starts updating resources {}, using proxy user Hadoop (用户 {} 开始更新资源 {},使用代理用户hadoop)",
+ username,
+ resourceId,
+ username,
+ resourceId);
+ String clientIp = HttpRequestHelper.getIp(request);
+ Map<String, Object> properties = new HashMap<>();
+ properties.put("clientIp", clientIp);
+ ResourceTask resourceTask = null;
+ synchronized (resourceId.intern()) {
+ resourceTask =
+ taskService.createUpdateTask(resourceId, DEFAULT_PROXY_USER, file, properties);
+ }
+ message = Message.ok("The update resource task was submitted successfully(提交更新资源任务成功)");
+ message
+ .data("resourceId", resourceId)
+ .data("version", resourceTask.getVersion())
+ .data("taskId", resourceTask.getId());
+ } catch (final ErrorException e) {
+ LOGGER.error("{} update resource failed, resourceId is {}, reason:", username, resourceId, e);
+ throw e;
+ } catch (final Exception e) {
+ LOGGER.error("{} update resource failed, resourceId is {}, reason:", username, resourceId, e);
+ ErrorException exception =
+ new ErrorException(
+ 50073, "The commit upload resource task failed(提交上传资源任务失败):" + e.getMessage());
+ exception.initCause(e);
+ throw exception;
}
+ LOGGER.info(
+ "User {} ends updating resources {} (用户 {} 结束更新资源 {} )",
+ username,
+ resourceId,
+ username,
+ resourceId);
+ return message;
+ }
- @ApiOperation(value = "attachResourceAndProject", notes = "attach Resource and project", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "projectName", required = true, dataType = "String", value = "project name"),
- @ApiImplicitParam(name = "resourceId", required = true, dataType = "String", value = "resource id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "attachResourceAndProject", method = RequestMethod.POST)
- public Message attachResourceAndProject(
- HttpServletRequest request, @RequestBody JsonNode jsonNode) throws ErrorException {
- String username = ModuleUserUtils.getOperationUser(request, "attachResourceAndProject");
- String projectName = jsonNode.get(PROJECT_NAME_STR).textValue();
- String resourceId = jsonNode.get("resourceId").textValue();
- LOGGER.info("begin to attach {} and {}", projectName, username);
- bmlProjectService.attach(projectName, resourceId);
- return Message.ok("attach resource and project ok");
+ @ApiOperation(
+ value = "downloadShareResource",
+ notes = "download share resource",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "resourceId", dataType = "String"),
+ @ApiImplicitParam(name = "version", dataType = "String")
+ })
+ @RequestMapping(path = "downloadShareResource", method = RequestMethod.GET)
+ public void downloadShareResource(
+ @RequestParam(value = "resourceId", required = false) String resourceId,
+ @RequestParam(value = "version", required = false) String version,
+ HttpServletResponse resp,
+ HttpServletRequest request)
+ throws IOException, ErrorException {
+ String user = RestfulUtils.getUserName(request);
+ Message message = null;
+ resp.setContentType("application/x-msdownload");
+ resp.setHeader("Content-Disposition", "attachment");
+ String ip = HttpRequestHelper.getIp(request);
+ DownloadModel downloadModel = new DownloadModel(resourceId, version, user, ip);
+ try {
+ String projectName = bmlProjectService.getProjectNameByResourceId(resourceId);
+ if (!bmlProjectService.checkAccessPriv(projectName, user)) {
+ LOGGER.error(
+ "{} does not have view privileges on project {}. Download resource failed({} 对工程 {} 没有查看权限, 下载资源失败)",
+ user,
+ projectName,
+ user,
+ projectName);
+ throw new BmlProjectNoEditException(
+ user
+ + " does not have view privileges on project "
+ + projectName
+ + ". Download resource failed"
+ + user
+ + " 对工程 { "
+ + projectName
+ + " }没有编辑权限,上传资源失败");
+ }
+ LOGGER.info(
+ "user {} begin to downLoad resource resourceId is {}, version is {} ,ip is {}, 并代理成hadoop ",
+ user,
+ resourceId,
+ version,
+ ip);
+ Map<String, Object> properties = new HashMap<>();
+ boolean downloadResult =
+ versionService.downloadResource(
+ DEFAULT_PROXY_USER, resourceId, version, resp.getOutputStream(), properties);
+ downloadModel.setEndTime(new Date(System.currentTimeMillis()));
+ downloadModel.setState(0);
+ if (!downloadResult) {
+ LOGGER.warn(
+ "ResourceId :{}, version:{} has a problem when user {} downloads the resource. The copied size is less than 0 (用户 {} 下载资源 resourceId: {}, version:{} 出现问题,复制的size小于0)",
+ user,
+ resourceId,
+ version,
+ user,
+ resourceId,
+ version);
+ downloadModel.setState(1);
+ throw new BmlQueryFailException(FAILED_DOWNLOAD_RESOURCE.getErrorDesc());
+ }
+ downloadService.addDownloadRecord(downloadModel);
+ LOGGER.info(
+ "User {} ends downloading the resource {} (用户 {} 结束下载资源 {}) ",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ } catch (IOException e) {
+ LOGGER.error(
+ "IO Exception: ResourceId :{}, version:{} (用户 {} 下载资源 resourceId: {}, version:{} 出现IO异常)",
+ resourceId,
+ version,
+ user,
+ resourceId,
+ version,
+ e);
+ downloadModel.setEndTime(new Date());
+ downloadModel.setState(1);
+ downloadService.addDownloadRecord(downloadModel);
+ throw new ErrorException(
+ 73562,
+ "Sorry, the background IO error caused you to download the resources failed(抱歉,后台IO错误造成您本次下载资源失败)");
+ } catch (final Throwable t) {
+ LOGGER.error(
+ "ResourceId :{}, version:{} abnormal when user {} downloads resource (用户 {} 下载资源 resourceId: {}, version:{} 出现异常)",
+ resourceId,
+ version,
+ user,
+ user,
+ resourceId,
+ version);
+ downloadModel.setEndTime(new Date());
+ downloadModel.setState(1);
+ downloadService.addDownloadRecord(downloadModel);
+ throw new ErrorException(
+ 73561,
+ "Sorry, the background service error caused you to download the resources failed (抱歉,后台服务出错导致您本次下载资源失败)");
+ } finally {
+ IOUtils.closeQuietly(resp.getOutputStream());
}
+ LOGGER.info(
+ "{} Download resource {} successfully ({} 下载资源 {} 成功)", user, resourceId, user, resourceId);
+ }
- @ApiOperation(value = "updateProjectUsers", notes = "update project users info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "projectName", required = true, dataType = "String", value = "project name"),
- @ApiImplicitParam(name = "editUsers", required = true, dataType = "String", value = "edit users"),
- @ApiImplicitParam(name = "accessUsers", required = true, dataType = "String", value = "access users")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "updateProjectUsers", method = RequestMethod.POST)
- public Message updateProjectUsers(HttpServletRequest request, @RequestBody JsonNode jsonNode)
- throws ErrorException {
- String username = ModuleUserUtils.getOperationUser(request, "updateProjectUsers");
- String projectName = jsonNode.get("projectName").textValue();
- LOGGER.info("{} begins to update project users for {}", username, projectName);
- List<String> editUsers = new ArrayList<>();
- List<String> accessUsers = new ArrayList<>();
- JsonNode editUsersNode = jsonNode.get("editUsers");
- if (editUsersNode.isArray()) {
- editUsersNode.forEach(node -> editUsers.add(node.textValue()));
- }
- JsonNode accessUsersNode = jsonNode.get("accessUsers");
- if (accessUsersNode.isArray()) {
- accessUsersNode.forEach(node -> accessUsers.add(node.textValue()));
- }
- bmlProjectService.updateProjectUsers(username, projectName, editUsers, accessUsers);
- return Message.ok("Updated project related user success(更新工程的相关用户成功)");
+ @ApiOperation(value = "getProjectInfo", notes = "get project info", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "projectName", dataType = "String", value = "project name")
+ })
+ @RequestMapping(path = "getProjectInfo", method = RequestMethod.GET)
+ public Message getProjectInfo(
+ HttpServletRequest request,
+ @RequestParam(value = "projectName", required = false) String projectName) {
+ return Message.ok("Obtain project information successfully (获取工程信息成功)");
+ }
+
+ @ApiOperation(
+ value = "attachResourceAndProject",
+ notes = "attach Resource and project",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "projectName", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "resourceId", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "attachResourceAndProject", method = RequestMethod.POST)
+ public Message attachResourceAndProject(
+ HttpServletRequest request, @RequestBody JsonNode jsonNode) throws ErrorException {
+ String username = ModuleUserUtils.getOperationUser(request, "attachResourceAndProject");
+ String projectName = jsonNode.get(PROJECT_NAME_STR).textValue();
+ String resourceId = jsonNode.get("resourceId").textValue();
+ LOGGER.info("begin to attach {} and {}", projectName, username);
+ bmlProjectService.attach(projectName, resourceId);
+ return Message.ok("attach resource and project ok");
+ }
+
+ @ApiOperation(
+ value = "updateProjectUsers",
+ notes = "update project users info",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "projectName", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "editUsers", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "accessUsers", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "updateProjectUsers", method = RequestMethod.POST)
+ public Message updateProjectUsers(HttpServletRequest request, @RequestBody JsonNode jsonNode)
+ throws ErrorException {
+ String username = ModuleUserUtils.getOperationUser(request, "updateProjectUsers");
+ String projectName = jsonNode.get("projectName").textValue();
+ LOGGER.info("{} begins to update project users for {}", username, projectName);
+ List<String> editUsers = new ArrayList<>();
+ List<String> accessUsers = new ArrayList<>();
+ JsonNode editUsersNode = jsonNode.get("editUsers");
+ if (editUsersNode.isArray()) {
+ editUsersNode.forEach(node -> editUsers.add(node.textValue()));
+ }
+ JsonNode accessUsersNode = jsonNode.get("accessUsers");
+ if (accessUsersNode.isArray()) {
+ accessUsersNode.forEach(node -> accessUsers.add(node.textValue()));
}
+ bmlProjectService.updateProjectUsers(username, projectName, editUsers, accessUsers);
+ return Message.ok("Updated project related user success(更新工程的相关用户成功)");
+ }
}
diff --git a/linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/restful/BmlRestfulApi.java b/linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/restful/BmlRestfulApi.java
index fd5ec266c..99682d293 100644
--- a/linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/restful/BmlRestfulApi.java
+++ b/linkis-public-enhancements/linkis-bml/linkis-bml-server/src/main/java/org/apache/linkis/bml/restful/BmlRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -52,15 +52,6 @@ import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
@@ -70,6 +61,15 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import static org.apache.linkis.bml.errorcode.BmlServerErrorCodeSummary.*;
@Api(tags = "bml(bigdata material library) opreation")
@@ -77,891 +77,860 @@ import static org.apache.linkis.bml.errorcode.BmlServerErrorCodeSummary.*;
@RestController
public class BmlRestfulApi {
- @Autowired private BmlService bmlService;
-
- @Autowired private VersionService versionService;
-
- @Autowired private ResourceService resourceService;
-
- @Autowired private DownloadService downloadService;
-
- @Autowired private TaskService taskService;
-
- private Logger logger = LoggerFactory.getLogger(getClass());
-
- public static final String URL_PREFIX = "/bml/";
-
- @ApiOperation(value = "getVersions", notes = "get resource versions info list", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = false, dataType = "String", value = "resource Id"),
- @ApiImplicitParam(name = "currentPage", required = false, dataType = "String", value = "current page"),
- @ApiImplicitParam(name = "pageSize", required = false, dataType = "String", value = "page size")
- })
- @RequestMapping(path = "getVersions", method = RequestMethod.GET)
- public Message getVersions(
- @RequestParam(value = "resourceId", required = false) String resourceId,
- @RequestParam(value = "currentPage", required = false) String currentPage,
- @RequestParam(value = "pageSize", required = false) String pageSize,
- HttpServletRequest request)
- throws ErrorException {
-
- String user = RestfulUtils.getUserName(request);
- if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
- logger.error(
- "ResourceId {} provided by user {} is illegal (用户{} 提供的resourceId {} is illegal)",
- resourceId,
- user,
- user,
- resourceId);
- throw new BmlServerParaErrorException(
- SUBMITTED_INVALID.getErrorDesc());
- }
-
- Integer current = 0;
- Integer size = 0;
- if (StringUtils.isEmpty(currentPage) || !StringUtils.isNumeric(currentPage)) {
- current = 1;
- } else {
- current = Integer.valueOf(currentPage);
- }
- if (StringUtils.isEmpty(pageSize) || !StringUtils.isNumeric(pageSize)) {
- size = 10;
- } else {
- size = Integer.valueOf(pageSize);
- }
-
- Message message = null;
-
- try {
- logger.info(
- "User {} starts getting information about all versions of {} (用户 {} 开始获取 {} 的所有版本信息)",
- user,
- resourceId,
- user,
- resourceId);
- List<Version> versionList =
- versionService.selectVersionByPage(current, size, resourceId);
- if (versionList.size() > 0) {
- message = Message.ok("Version information obtained successfully (成功获取版本信息)");
- message.setMethod(URL_PREFIX + "getVersions");
- message.setStatus(0);
- ResourceVersionsVO resourceVersionsVO = new ResourceVersionsVO();
- resourceVersionsVO.setVersions(versionList);
- resourceVersionsVO.setResourceId(resourceId);
- resourceVersionsVO.setUser(user);
- message.data("ResourceVersions", resourceVersionsVO);
- } else {
- logger.warn(
- "User {} fetch resource {} no error, but fetch version length 0 (user {} 获取资源{}未报错,但是获取到的version长度为0)",
- user,
- resourceId,
- user,
- resourceId);
- message = Message.error("Failed to get version information correctly(未能正确获取到版本信息)");
- message.setMethod(URL_PREFIX + "getVersions");
- message.setStatus(2);
- }
- logger.info(
- "User {} ends getting all version information for {} (用户 {} 结束获取 {} 的所有版本信息)",
- user,
- resourceId,
- user,
- resourceId);
- } catch (final Exception e) {
- logger.error(
- "User {} Failed to get version information of the ResourceId {} resource(user {} 获取resourceId {} 资源的版本信息失败)",
- user,
- resourceId,
- user,
- resourceId,
- e);
- throw new BmlQueryFailException(
- QUERY_VERSION_FAILED.getErrorDesc());
- }
+ @Autowired private BmlService bmlService;
+
+ @Autowired private VersionService versionService;
+
+ @Autowired private ResourceService resourceService;
+
+ @Autowired private DownloadService downloadService;
+
+ @Autowired private TaskService taskService;
+
+ private Logger logger = LoggerFactory.getLogger(getClass());
+
+ public static final String URL_PREFIX = "/bml/";
+
+ @ApiOperation(
+ value = "getVersions",
+ notes = "get resource versions info list",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "resourceId", dataType = "String"),
+ @ApiImplicitParam(name = "currentPage", dataType = "String"),
+ @ApiImplicitParam(name = "pageSize", required = false, dataType = "String", value = "page size")
+ })
+ @RequestMapping(path = "getVersions", method = RequestMethod.GET)
+ public Message getVersions(
+ @RequestParam(value = "resourceId", required = false) String resourceId,
+ @RequestParam(value = "currentPage", required = false) String currentPage,
+ @RequestParam(value = "pageSize", required = false) String pageSize,
+ HttpServletRequest request)
+ throws ErrorException {
+
+ String user = RestfulUtils.getUserName(request);
+ if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
+ logger.error(
+ "ResourceId {} provided by user {} is illegal (用户{} 提供的resourceId {} is illegal)",
+ resourceId,
+ user,
+ user,
+ resourceId);
+ throw new BmlServerParaErrorException(SUBMITTED_INVALID.getErrorDesc());
+ }
- return message;
- }
-
- @ApiOperation(value = "getResources", notes = "get resources info list", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "system", required = false, dataType = "String", value = "system"),
- @ApiImplicitParam(name = "currentPage", required = false, dataType = "String", value = "current page"),
- @ApiImplicitParam(name = "pageSize", required = false, dataType = "String", value = "page size")
- })
- @RequestMapping(path = "getResources", method = RequestMethod.GET)
- public Message getResources(
- @RequestParam(value = "system", required = false) String system,
- @RequestParam(value = "currentPage", required = false) String currentPage,
- @RequestParam(value = "pageSize", required = false) String pageSize,
- HttpServletRequest request,
- HttpServletResponse response)
- throws ErrorException {
-
- String user = RestfulUtils.getUserName(request);
-
- if (StringUtils.isEmpty(system)) {
- // 默认系统是wtss
- system = Constant.DEFAULT_SYSTEM;
- }
+ Integer current = 0;
+ Integer size = 0;
+ if (StringUtils.isEmpty(currentPage) || !StringUtils.isNumeric(currentPage)) {
+ current = 1;
+ } else {
+ current = Integer.valueOf(currentPage);
+ }
+ if (StringUtils.isEmpty(pageSize) || !StringUtils.isNumeric(pageSize)) {
+ size = 10;
+ } else {
+ size = Integer.valueOf(pageSize);
+ }
- Integer current = 0;
- Integer size = 0;
- if (StringUtils.isEmpty(currentPage) || !StringUtils.isNumeric(currentPage)) {
- current = 1;
- } else {
- current = Integer.valueOf(currentPage);
- }
- if (StringUtils.isEmpty(pageSize) || !StringUtils.isNumeric(pageSize)) {
- size = 10;
- } else {
- size = Integer.valueOf(pageSize);
- }
- Message message = null;
- try {
- logger.info(
- "User {} starts fetching all the resources of the system {}(用户 {} 开始获取系统 {} 的所有资源)",
- user,
- system,
- user,
- system);
- List<ResourceVersion> resourceVersionPageInfoList =
- versionService.selectResourcesViaSystemByPage(current, size, system, user);
- if (resourceVersionPageInfoList.size() > 0) {
- message =
- Message.ok(
- "Get all your resources in system "
- + system
- + " successfully(获取您在系统"
- + system
- + "中所有资源成功)");
- message.setStatus(0);
- message.setMethod(URL_PREFIX + "getResources");
- List<ResourceVO> resourceVOList = new ArrayList<>();
- for (ResourceVersion resourceVersion : resourceVersionPageInfoList) {
- ResourceVO resourceVO = new ResourceVO();
- resourceVO.setResource(resourceVersion.getResource());
- resourceVO.setUser(user);
- resourceVO.setResourceId(resourceVersion.getResourceId());
- resourceVO.setVersion(resourceVersion.getVersion());
- resourceVOList.add(resourceVO);
- }
- message.data("Resources", resourceVOList);
- } else {
- logger.warn(
- "User {} gets system {} resource size of 0(用户 {} 获取系统 {} 资源的size为0)",
- user,
- system,
- user,
- system);
- message = Message.error("Failed to obtain all resource information(未能成功获取到所有资源信息)");
- message.setStatus(2);
- message.setMethod(URL_PREFIX + "getResources");
- }
- logger.info(
- "User {} ends fetching all resources for system {}(用户 {} 结束获取系统 {} 的所有资源)",
- user,
- system,
- user,
- system);
- } catch (final Exception e) {
- logger.error(
- "User {} failed to obtain all resources of the system {}(用户 {} 获取系统 {} 所有资源失败).",
- user,
- system,
- user,
- system,
- e);
- throw new BmlQueryFailException(
- FAILED_ALL_INFORMATION.getErrorDesc());
- }
+ Message message = null;
+
+ try {
+ logger.info(
+ "User {} starts getting information about all versions of {} (用户 {} 开始获取 {} 的所有版本信息)",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ List<Version> versionList = versionService.selectVersionByPage(current, size, resourceId);
+ if (versionList.size() > 0) {
+ message = Message.ok("Version information obtained successfully (成功获取版本信息)");
+ message.setMethod(URL_PREFIX + "getVersions");
+ message.setStatus(0);
+ ResourceVersionsVO resourceVersionsVO = new ResourceVersionsVO();
+ resourceVersionsVO.setVersions(versionList);
+ resourceVersionsVO.setResourceId(resourceId);
+ resourceVersionsVO.setUser(user);
+ message.data("ResourceVersions", resourceVersionsVO);
+ } else {
+ logger.warn(
+ "User {} fetch resource {} no error, but fetch version length 0 (user {} 获取资源{}未报错,但是获取到的version长度为0)",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ message = Message.error("Failed to get version information correctly(未能正确获取到版本信息)");
+ message.setMethod(URL_PREFIX + "getVersions");
+ message.setStatus(2);
+ }
+ logger.info(
+ "User {} ends getting all version information for {} (用户 {} 结束获取 {} 的所有版本信息)",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ } catch (final Exception e) {
+ logger.error(
+ "User {} Failed to get version information of the ResourceId {} resource(user {} 获取resourceId {} 资源的版本信息失败)",
+ user,
+ resourceId,
+ user,
+ resourceId,
+ e);
+ throw new BmlQueryFailException(QUERY_VERSION_FAILED.getErrorDesc());
+ }
- return message;
- }
-
- @ApiOperation(value = "deleteVersion", notes = "delete version", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = true, dataType = "String", value = "resource id"),
- @ApiImplicitParam(name = "version", required = true, dataType = "String", value = "version")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "deleteVersion", method = RequestMethod.POST)
- public Message deleteVersion(HttpServletRequest request, @RequestBody JsonNode jsonNode)
- throws IOException, ErrorException {
- String user = RestfulUtils.getUserName(request);
- if (null == jsonNode.get("resourceId")
- || null == jsonNode.get("version")
- || StringUtils.isEmpty(jsonNode.get("resourceId").textValue())
- || StringUtils.isEmpty(jsonNode.get("version").textValue())) {
- throw new BmlServerParaErrorException(
- DELETE_SPECIFIED_VERSION.getErrorDesc());
- }
+ return message;
+ }
+
+ @ApiOperation(value = "getResources", notes = "get resources info list", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "system", required = false, dataType = "String", value = "system"),
+ @ApiImplicitParam(name = "currentPage", dataType = "String"),
+ @ApiImplicitParam(name = "pageSize", required = false, dataType = "String", value = "page size")
+ })
+ @RequestMapping(path = "getResources", method = RequestMethod.GET)
+ public Message getResources(
+ @RequestParam(value = "system", required = false) String system,
+ @RequestParam(value = "currentPage", required = false) String currentPage,
+ @RequestParam(value = "pageSize", required = false) String pageSize,
+ HttpServletRequest request,
+ HttpServletResponse response)
+ throws ErrorException {
+
+ String user = RestfulUtils.getUserName(request);
+
+ if (StringUtils.isEmpty(system)) {
+ // 默认系统是wtss
+ system = Constant.DEFAULT_SYSTEM;
+ }
- String resourceId = jsonNode.get("resourceId").textValue();
- String version = jsonNode.get("version").textValue();
- // 检查资源和版本是否存在
- if (!resourceService.checkResourceId(resourceId)
- || !versionService.checkVersion(resourceId, version)
- || !versionService.canAccess(resourceId, version)) {
- throw new BmlServerParaErrorException(
- ILLEGAL_OR_DELETED.getErrorDesc());
- }
- Message message = null;
- ResourceTask resourceTask =
- taskService.createDeleteVersionTask(
- resourceId, version, user, HttpRequestHelper.getIp(request));
- try {
- logger.info(
- "User {} starts to delete resource of ResourceID: {} version: {}(用户 {} 开始删除 resourceId: {} version: {} 的资源)",
- user,
- resourceId,
- version,
- user,
- resourceId,
- version);
- versionService.deleteResourceVersion(resourceId, version);
- message = Message.ok("Deleted version successfully(删除版本成功)");
- message.setMethod(URL_PREFIX + "deleteVersion");
- message.setStatus(0);
- logger.info(
- "User {} ends deleting the resourceID: {} version: {} resource(用户 {} 结束删除 resourceId: {} version: {} 的资源)",
- user,
- resourceId,
- version,
- user,
- resourceId,
- version);
- taskService.updateState(resourceTask.getId(), TaskState.SUCCESS.getValue(), new Date());
- logger.info(
- "Update task tasKid :{} -ResourceId :{} with {} state(删除版本成功.更新任务 taskId:{}-resourceId:{} 为 {} 状态).",
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.SUCCESS.getValue(),
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.SUCCESS.getValue());
- } catch (final Exception e) {
- logger.error(
- "User {} failed to delete resource {}, version {}(用户{}删除resource {}, version {} 失败)",
- user,
- resourceId,
- version,
- user,
- resourceId,
- version,
- e);
- taskService.updateState2Failed(
- resourceTask.getId(), TaskState.FAILED.getValue(), new Date(), e.getMessage());
- logger.info(
- "Update task tasKid :{} -ResourceId :{} with {} state(删除版本成功.更新任务 taskId:{}-resourceId:{} 为 {} 状态).",
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.SUCCESS.getValue(),
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.SUCCESS.getValue());
- throw new BmlQueryFailException(DELETE_VERSION_FAILED.getErrorDesc());
- }
- return message;
+ Integer current = 0;
+ Integer size = 0;
+ if (StringUtils.isEmpty(currentPage) || !StringUtils.isNumeric(currentPage)) {
+ current = 1;
+ } else {
+ current = Integer.valueOf(currentPage);
+ }
+ if (StringUtils.isEmpty(pageSize) || !StringUtils.isNumeric(pageSize)) {
+ size = 10;
+ } else {
+ size = Integer.valueOf(pageSize);
+ }
+ Message message = null;
+ try {
+ logger.info(
+ "User {} starts fetching all the resources of the system {}(用户 {} 开始获取系统 {} 的所有资源)",
+ user,
+ system,
+ user,
+ system);
+ List<ResourceVersion> resourceVersionPageInfoList =
+ versionService.selectResourcesViaSystemByPage(current, size, system, user);
+ if (resourceVersionPageInfoList.size() > 0) {
+ message =
+ Message.ok(
+ "Get all your resources in system "
+ + system
+ + " successfully(获取您在系统"
+ + system
+ + "中所有资源成功)");
+ message.setStatus(0);
+ message.setMethod(URL_PREFIX + "getResources");
+ List<ResourceVO> resourceVOList = new ArrayList<>();
+ for (ResourceVersion resourceVersion : resourceVersionPageInfoList) {
+ ResourceVO resourceVO = new ResourceVO();
+ resourceVO.setResource(resourceVersion.getResource());
+ resourceVO.setUser(user);
+ resourceVO.setResourceId(resourceVersion.getResourceId());
+ resourceVO.setVersion(resourceVersion.getVersion());
+ resourceVOList.add(resourceVO);
+ }
+ message.data("Resources", resourceVOList);
+ } else {
+ logger.warn(
+ "User {} gets system {} resource size of 0(用户 {} 获取系统 {} 资源的size为0)",
+ user,
+ system,
+ user,
+ system);
+ message = Message.error("Failed to obtain all resource information(未能成功获取到所有资源信息)");
+ message.setStatus(2);
+ message.setMethod(URL_PREFIX + "getResources");
+ }
+ logger.info(
+ "User {} ends fetching all resources for system {}(用户 {} 结束获取系统 {} 的所有资源)",
+ user,
+ system,
+ user,
+ system);
+ } catch (final Exception e) {
+ logger.error(
+ "User {} failed to obtain all resources of the system {}(用户 {} 获取系统 {} 所有资源失败).",
+ user,
+ system,
+ user,
+ system,
+ e);
+ throw new BmlQueryFailException(FAILED_ALL_INFORMATION.getErrorDesc());
}
- @ApiOperation(value = "deleteResource", notes = "delete Resource", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = true, dataType = "String", value = "resource id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "deleteResource", method = RequestMethod.POST)
- public Message deleteResource(HttpServletRequest request, @RequestBody JsonNode jsonNode)
- throws IOException, ErrorException {
+ return message;
+ }
+
+ @ApiOperation(value = "deleteVersion", notes = "delete version", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "resourceId", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "version", required = true, dataType = "String", value = "version")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "deleteVersion", method = RequestMethod.POST)
+ public Message deleteVersion(HttpServletRequest request, @RequestBody JsonNode jsonNode)
+ throws IOException, ErrorException {
+ String user = RestfulUtils.getUserName(request);
+ if (null == jsonNode.get("resourceId")
+ || null == jsonNode.get("version")
+ || StringUtils.isEmpty(jsonNode.get("resourceId").textValue())
+ || StringUtils.isEmpty(jsonNode.get("version").textValue())) {
+ throw new BmlServerParaErrorException(DELETE_SPECIFIED_VERSION.getErrorDesc());
+ }
- String user = RestfulUtils.getUserName(request);
+ String resourceId = jsonNode.get("resourceId").textValue();
+ String version = jsonNode.get("version").textValue();
+ // 检查资源和版本是否存在
+ if (!resourceService.checkResourceId(resourceId)
+ || !versionService.checkVersion(resourceId, version)
+ || !versionService.canAccess(resourceId, version)) {
+ throw new BmlServerParaErrorException(ILLEGAL_OR_DELETED.getErrorDesc());
+ }
+ Message message = null;
+ ResourceTask resourceTask =
+ taskService.createDeleteVersionTask(
+ resourceId, version, user, HttpRequestHelper.getIp(request));
+ try {
+ logger.info(
+ "User {} starts to delete resource of ResourceID: {} version: {}(用户 {} 开始删除 resourceId: {} version: {} 的资源)",
+ user,
+ resourceId,
+ version,
+ user,
+ resourceId,
+ version);
+ versionService.deleteResourceVersion(resourceId, version);
+ message = Message.ok("Deleted version successfully(删除版本成功)");
+ message.setMethod(URL_PREFIX + "deleteVersion");
+ message.setStatus(0);
+ logger.info(
+ "User {} ends deleting the resourceID: {} version: {} resource(用户 {} 结束删除 resourceId: {} version: {} 的资源)",
+ user,
+ resourceId,
+ version,
+ user,
+ resourceId,
+ version);
+ taskService.updateState(resourceTask.getId(), TaskState.SUCCESS.getValue(), new Date());
+ logger.info(
+ "Update task tasKid :{} -ResourceId :{} with {} state(删除版本成功.更新任务 taskId:{}-resourceId:{} 为 {} 状态).",
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.SUCCESS.getValue(),
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.SUCCESS.getValue());
+ } catch (final Exception e) {
+ logger.error(
+ "User {} failed to delete resource {}, version {}(用户{}删除resource {}, version {} 失败)",
+ user,
+ resourceId,
+ version,
+ user,
+ resourceId,
+ version,
+ e);
+ taskService.updateState2Failed(
+ resourceTask.getId(), TaskState.FAILED.getValue(), new Date(), e.getMessage());
+ logger.info(
+ "Update task tasKid :{} -ResourceId :{} with {} state(删除版本成功.更新任务 taskId:{}-resourceId:{} 为 {} 状态).",
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.SUCCESS.getValue(),
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.SUCCESS.getValue());
+ throw new BmlQueryFailException(DELETE_VERSION_FAILED.getErrorDesc());
+ }
+ return message;
+ }
- if (null == jsonNode.get("resourceId")) {
- throw new BmlServerParaErrorException(
- NOT_BALID_RESOURCEID.getErrorDesc());
- }
+ @ApiOperation(value = "deleteResource", notes = "delete Resource", response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "resourceId", required = true, dataType = "String")})
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "deleteResource", method = RequestMethod.POST)
+ public Message deleteResource(HttpServletRequest request, @RequestBody JsonNode jsonNode)
+ throws IOException, ErrorException {
- String resourceId = jsonNode.get("resourceId").textValue();
- if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
- logger.error("the error resourceId is {} ", resourceId);
- throw new BmlServerParaErrorException(
- "the resourceId"
- + resourceId
- + " is null ,Illegal or deleted (resourceId:"
- + resourceId
- + "为空,非法或者已被删除!)");
- }
+ String user = RestfulUtils.getUserName(request);
- Message message = null;
- ResourceTask resourceTask =
- taskService.createDeleteResourceTask(
- resourceId, user, HttpRequestHelper.getIp(request));
- try {
- logger.info(
- "User {} starts to delete all resources corresponding to ResourceId: {}(用户 {} 开始删除 resourceId: {} 对应的所有资源)",
- user,
- resourceId,
- user,
- resourceId);
- resourceService.deleteResource(resourceId);
- message = Message.ok("Resource deleted successfully(删除资源成功)");
- message.setMethod(URL_PREFIX + "deleteResource");
- message.setStatus(0);
- logger.info(
- "User {} ends deleting all resources corresponding to ResourceId: {}(用户 {} 结束删除 resourceId: {} 对应的所有资源)",
- user,
- resourceId,
- user,
- resourceId);
- taskService.updateState(resourceTask.getId(), TaskState.SUCCESS.getValue(), new Date());
- logger.info(
- "Resource deleted successfully. Update task tasKid :{} -ResourceId :{} with {} state (删除资源成功.更新任务 taskId:{}-resourceId:{} 为 {} 状态).",
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.SUCCESS.getValue(),
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.SUCCESS.getValue());
- } catch (final Exception e) {
- logger.error(
- "User {} failed to delete resource {}(用户 {} 删除资源 {} 失败)",
- user,
- resourceId,
- user,
- resourceId);
- taskService.updateState2Failed(
- resourceTask.getId(), TaskState.FAILED.getValue(), new Date(), e.getMessage());
- logger.info(
- "Failed to delete resource. Update task tasKid :{} -ResourceId :{} is in {} state(删除资源失败.更新任务 taskId:{}-resourceId:{} 为 {} 状态.)",
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.FAILED.getValue(),
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.FAILED.getValue());
- throw new BmlQueryFailException(DELETE_OPERATION_FAILED.getErrorDesc());
- }
+ if (null == jsonNode.get("resourceId")) {
+ throw new BmlServerParaErrorException(NOT_BALID_RESOURCEID.getErrorDesc());
+ }
- return message;
+ String resourceId = jsonNode.get("resourceId").textValue();
+ if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
+ logger.error("the error resourceId is {} ", resourceId);
+ throw new BmlServerParaErrorException(
+ "the resourceId"
+ + resourceId
+ + " is null ,Illegal or deleted (resourceId:"
+ + resourceId
+ + "为空,非法或者已被删除!)");
}
- @ApiOperation(value = "deleteResources", notes = "batch delete resource", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceIds", required = true, dataType = "List", value = "collection of resource id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "deleteResources", method = RequestMethod.POST)
- public Message deleteResources(HttpServletRequest request, @RequestBody JsonNode jsonNode)
- throws IOException, ErrorException {
- String user = RestfulUtils.getUserName(request);
- List<String> resourceIds = new ArrayList<>();
+ Message message = null;
+ ResourceTask resourceTask =
+ taskService.createDeleteResourceTask(resourceId, user, HttpRequestHelper.getIp(request));
+ try {
+ logger.info(
+ "User {} starts to delete all resources corresponding to ResourceId: {}(用户 {} 开始删除 resourceId: {} 对应的所有资源)",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ resourceService.deleteResource(resourceId);
+ message = Message.ok("Resource deleted successfully(删除资源成功)");
+ message.setMethod(URL_PREFIX + "deleteResource");
+ message.setStatus(0);
+ logger.info(
+ "User {} ends deleting all resources corresponding to ResourceId: {}(用户 {} 结束删除 resourceId: {} 对应的所有资源)",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ taskService.updateState(resourceTask.getId(), TaskState.SUCCESS.getValue(), new Date());
+ logger.info(
+ "Resource deleted successfully. Update task tasKid :{} -ResourceId :{} with {} state (删除资源成功.更新任务 taskId:{}-resourceId:{} 为 {} 状态).",
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.SUCCESS.getValue(),
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.SUCCESS.getValue());
+ } catch (final Exception e) {
+ logger.error(
+ "User {} failed to delete resource {}(用户 {} 删除资源 {} 失败)",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ taskService.updateState2Failed(
+ resourceTask.getId(), TaskState.FAILED.getValue(), new Date(), e.getMessage());
+ logger.info(
+ "Failed to delete resource. Update task tasKid :{} -ResourceId :{} is in {} state(删除资源失败.更新任务 taskId:{}-resourceId:{} 为 {} 状态.)",
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.FAILED.getValue(),
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.FAILED.getValue());
+ throw new BmlQueryFailException(DELETE_OPERATION_FAILED.getErrorDesc());
+ }
- if (null == jsonNode.get("resourceIds")) {
- throw new BmlServerParaErrorException(
- BULK_DELETION_PARAMETERS.getErrorDesc());
- }
+ return message;
+ }
+
+ @ApiOperation(
+ value = "deleteResources",
+ notes = "batch delete resource",
+ response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "resourceIds", required = true, dataType = "List")})
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "deleteResources", method = RequestMethod.POST)
+ public Message deleteResources(HttpServletRequest request, @RequestBody JsonNode jsonNode)
+ throws IOException, ErrorException {
+ String user = RestfulUtils.getUserName(request);
+ List<String> resourceIds = new ArrayList<>();
+
+ if (null == jsonNode.get("resourceIds")) {
+ throw new BmlServerParaErrorException(BULK_DELETION_PARAMETERS.getErrorDesc());
+ }
- Iterator<JsonNode> jsonNodeIter = jsonNode.get("resourceIds").elements();
- while (jsonNodeIter.hasNext()) {
- resourceIds.add(jsonNodeIter.next().asText());
- }
+ Iterator<JsonNode> jsonNodeIter = jsonNode.get("resourceIds").elements();
+ while (jsonNodeIter.hasNext()) {
+ resourceIds.add(jsonNodeIter.next().asText());
+ }
- if (0 == resourceIds.size()) {
- throw new BmlServerParaErrorException(
- PARAMETERS_IS_NULL.getErrorDesc());
- } else {
- for (String resourceId : resourceIds) {
- if (StringUtils.isBlank(resourceId)
- || !resourceService.checkResourceId(resourceId)) {
- Message message =
- Message.error(MessageFormat.format(RESOURCEID_BEEN_DELETED.getErrorDesc(),resourceId));
- message.setMethod(URL_PREFIX + "deleteResources");
- message.setStatus(1);
- return message;
- }
- }
- }
+ if (0 == resourceIds.size()) {
+ throw new BmlServerParaErrorException(PARAMETERS_IS_NULL.getErrorDesc());
+ } else {
+ for (String resourceId : resourceIds) {
+ if (StringUtils.isBlank(resourceId) || !resourceService.checkResourceId(resourceId)) {
+ Message message =
+ Message.error(
+ MessageFormat.format(RESOURCEID_BEEN_DELETED.getErrorDesc(), resourceId));
+ message.setMethod(URL_PREFIX + "deleteResources");
+ message.setStatus(1);
+ return message;
+ }
+ }
+ }
- ResourceTask resourceTask =
- taskService.createDeleteResourcesTask(
- resourceIds, user, HttpRequestHelper.getIp(request));
- Message message = null;
- try {
- logger.info("User {} begins to batch delete resources (用户 {} 开始批删除资源) ", user, user);
- resourceService.batchDeleteResources(resourceIds);
- message = Message.ok("Batch deletion of resource was successful(批量删除资源成功)");
- message.setMethod(URL_PREFIX + "deleteResources");
- message.setStatus(0);
- logger.info("User {} ends the bulk deletion of resources (用户 {} 结束批量删除资源)", user, user);
- taskService.updateState(resourceTask.getId(), TaskState.SUCCESS.getValue(), new Date());
- logger.info(
- "Batch deletion of resource was successful. Update task tasKid :{} -ResourceId :{} is in the {} state (批量删除资源成功.更新任务 taskId:{}-resourceId:{} 为 {} 状态.)",
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.SUCCESS.getValue(),
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.SUCCESS.getValue());
- } catch (final Exception e) {
- logger.error(
- "\"User {} failed to delete resources in bulk (用户 {} 批量删除资源失败)", user, user, e);
- taskService.updateState2Failed(
- resourceTask.getId(), TaskState.FAILED.getValue(), new Date(), e.getMessage());
- logger.info(
- "Failed to delete resources in bulk. Update task tasKid :{} -ResourceId :{} is in the {} state (批量删除资源失败.更新任务 taskId:{}-resourceId:{} 为 {} 状态.)",
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.FAILED.getValue(),
- resourceTask.getId(),
- resourceTask.getResourceId(),
- TaskState.FAILED.getValue());
- throw new BmlQueryFailException(
- BULK_DELETE_FAILED.getErrorDesc());
- }
- return message;
- }
-
- /**
- * 通过resourceId 和 version两个参数获取下载对应的资源
- *
- * @param resourceId 资源Id
- * @param version 资源版本,如果不指定,默认为最新
- * @param resp httpServletResponse
- * @param request httpServletRequest
- * @return void
- * @throws IOException
- * @throws ErrorException
- */
- @ApiOperation(value = "download", notes = "download resource", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = false, dataType = "String", value = "resource Id"),
- @ApiImplicitParam(name = "version", required = false, dataType = "String", value = "resource version")
- })
- @RequestMapping(path = "download", method = RequestMethod.GET)
- public void download(
- @RequestParam(value = "resourceId", required = false) String resourceId,
- @RequestParam(value = "version", required = false) String version,
- HttpServletResponse resp,
- HttpServletRequest request)
- throws IOException, ErrorException {
- String user = RestfulUtils.getUserName(request);
+ ResourceTask resourceTask =
+ taskService.createDeleteResourcesTask(resourceIds, user, HttpRequestHelper.getIp(request));
+ Message message = null;
+ try {
+ logger.info("User {} begins to batch delete resources (用户 {} 开始批删除资源) ", user, user);
+ resourceService.batchDeleteResources(resourceIds);
+ message = Message.ok("Batch deletion of resource was successful(批量删除资源成功)");
+ message.setMethod(URL_PREFIX + "deleteResources");
+ message.setStatus(0);
+ logger.info("User {} ends the bulk deletion of resources (用户 {} 结束批量删除资源)", user, user);
+ taskService.updateState(resourceTask.getId(), TaskState.SUCCESS.getValue(), new Date());
+ logger.info(
+ "Batch deletion of resource was successful. Update task tasKid :{} -ResourceId :{} is in the {} state (批量删除资源成功.更新任务 taskId:{}-resourceId:{} 为 {} 状态.)",
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.SUCCESS.getValue(),
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.SUCCESS.getValue());
+ } catch (final Exception e) {
+ logger.error("\"User {} failed to delete resources in bulk (用户 {} 批量删除资源失败)", user, user, e);
+ taskService.updateState2Failed(
+ resourceTask.getId(), TaskState.FAILED.getValue(), new Date(), e.getMessage());
+ logger.info(
+ "Failed to delete resources in bulk. Update task tasKid :{} -ResourceId :{} is in the {} state (批量删除资源失败.更新任务 taskId:{}-resourceId:{} 为 {} 状态.)",
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.FAILED.getValue(),
+ resourceTask.getId(),
+ resourceTask.getResourceId(),
+ TaskState.FAILED.getValue());
+ throw new BmlQueryFailException(BULK_DELETE_FAILED.getErrorDesc());
+ }
+ return message;
+ }
+
+ /**
+ * 通过resourceId 和 version两个参数获取下载对应的资源
+ *
+ * @param resourceId 资源Id
+ * @param version 资源版本,如果不指定,默认为最新
+ * @param resp httpServletResponse
+ * @param request httpServletRequest
+ * @return void
+ * @throws IOException
+ * @throws ErrorException
+ */
+ @ApiOperation(value = "download", notes = "download resource", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "resourceId", dataType = "String"),
+ @ApiImplicitParam(name = "version", dataType = "String")
+ })
+ @RequestMapping(path = "download", method = RequestMethod.GET)
+ public void download(
+ @RequestParam(value = "resourceId", required = false) String resourceId,
+ @RequestParam(value = "version", required = false) String version,
+ HttpServletResponse resp,
+ HttpServletRequest request)
+ throws IOException, ErrorException {
+ String user = RestfulUtils.getUserName(request);
+
+ if (StringUtils.isBlank(resourceId) || !resourceService.checkResourceId(resourceId)) {
+ throw new BmlQueryFailException(
+ "ResourceID :"
+ + resourceId
+ + " is empty, illegal or has been deleted (resourceId:"
+ + resourceId
+ + "为空,非法或者已被删除!)");
+ }
- if (StringUtils.isBlank(resourceId) || !resourceService.checkResourceId(resourceId)) {
- throw new BmlQueryFailException(
- "ResourceID :"
- + resourceId
- + " is empty, illegal or has been deleted (resourceId:"
- + resourceId
- + "为空,非法或者已被删除!)");
- }
+ if (!resourceService.checkAuthority(user, resourceId)) {
+ throw new BmlPermissionDeniedException(NOT_HAVE_PERMISSION.getErrorDesc());
+ }
+ // version is null get NewestVersion
+ if (StringUtils.isBlank(version)) {
+ version = versionService.getNewestVersion(resourceId);
+ }
+ // check version
+ if (!versionService.checkVersion(resourceId, version)) {
+ throw new BmlQueryFailException(
+ MessageFormat.format(VERSION_BEEN_DELETED.getErrorDesc(), version));
+ }
+ // checkExpire
+ if (!resourceService.checkExpire(resourceId, version)) {
+ throw new BmlResourceExpiredException(resourceId);
+ }
- if (!resourceService.checkAuthority(user, resourceId)) {
- throw new BmlPermissionDeniedException(
- NOT_HAVE_PERMISSION.getErrorDesc());
- }
- // version is null get NewestVersion
- if (StringUtils.isBlank(version)) {
- version = versionService.getNewestVersion(resourceId);
- }
- // check version
- if (!versionService.checkVersion(resourceId, version)) {
- throw new BmlQueryFailException(
- MessageFormat.format(VERSION_BEEN_DELETED.getErrorDesc(),version));
- }
- // checkExpire
- if (!resourceService.checkExpire(resourceId, version)) {
- throw new BmlResourceExpiredException(resourceId);
- }
+ Message message = null;
+ resp.setContentType("application/x-msdownload");
+ resp.setHeader("Content-Disposition", "attachment");
+ String ip = HttpRequestHelper.getIp(request);
+ DownloadModel downloadModel = new DownloadModel(resourceId, version, user, ip);
+ try {
+ logger.info(
+ "user {} downLoad resource resourceId is {}, version is {} ,ip is {} ",
+ user,
+ resourceId,
+ version,
+ ip);
+ Map<String, Object> properties = new HashMap<>();
+ boolean downloadResult =
+ versionService.downloadResource(
+ user, resourceId, version, resp.getOutputStream(), properties);
+ downloadModel.setEndTime(new Date(System.currentTimeMillis()));
+ downloadModel.setState(0);
+ if (!downloadResult) {
+ logger.warn(
+ "ResourceId :{}, version:{} has a problem when user {} downloads the resource. The copied size is less than 0(用户 {} 下载资源 resourceId: {}, version:{} 出现问题,复制的size小于0)",
+ resourceId,
+ version,
+ user,
+ user,
+ resourceId,
+ version);
+ downloadModel.setState(1);
+ throw new BmlQueryFailException(FAILED_DOWNLOAD_RESOURCE.getErrorDesc());
+ }
+ downloadService.addDownloadRecord(downloadModel);
+ logger.info(
+ "User {} ends downloading the resource {}(用户 {} 结束下载资源 {}) ",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ } catch (IOException e) {
+ logger.error(
+ "IO Exception: ResourceId :{}, version:{} (用户 {} 下载资源 resourceId: {}, version:{} 出现IO异常)",
+ resourceId,
+ version,
+ user,
+ resourceId,
+ version,
+ e);
+ downloadModel.setEndTime(new Date());
+ downloadModel.setState(1);
+ downloadService.addDownloadRecord(downloadModel);
+ throw new ErrorException(
+ 73562,
+ "Sorry, the background IO error caused you to download the resources failed(抱歉,后台IO错误造成您本次下载资源失败)");
+ } catch (final Throwable t) {
+ logger.error(
+ "ResourceId :{}, version:{} abnormal when user {} downloads resource (用户 {} 下载资源 resourceId: {}, version:{} 出现异常)",
+ resourceId,
+ version,
+ user,
+ user,
+ resourceId,
+ version,
+ t);
+ downloadModel.setEndTime(new Date());
+ downloadModel.setState(1);
+ downloadService.addDownloadRecord(downloadModel);
+ throw new ErrorException(
+ 73561,
+ "Sorry, the background service error caused you to download the resources failed(抱歉,后台服务出错导致您本次下载资源失败)");
+ } finally {
+ IOUtils.closeQuietly(resp.getOutputStream());
+ }
+ logger.info(
+ "{} Download resource {} successfully {} 下载资源 {} 成功", user, resourceId, user, resourceId);
+ }
+
+ @ApiOperation(value = "upload", notes = "upload resource", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "system", required = false, dataType = "String", value = "system"),
+ @ApiImplicitParam(name = "resourceHeader", dataType = "String"),
+ @ApiImplicitParam(name = "isExpire", dataType = "String"),
+ @ApiImplicitParam(name = "expireType", dataType = "String"),
+ @ApiImplicitParam(name = "expireTime", dataType = "String"),
+ @ApiImplicitParam(name = "maxVersion", dataType = "String"),
+ @ApiImplicitParam(name = "file", required = true, dataType = "List<MultipartFile>")
+ })
+ @RequestMapping(path = "upload", method = RequestMethod.POST)
+ public Message uploadResource(
+ HttpServletRequest req,
+ @RequestParam(name = "system", required = false) String system,
+ @RequestParam(name = "resourceHeader", required = false) String resourceHeader,
+ @RequestParam(name = "isExpire", required = false) String isExpire,
+ @RequestParam(name = "expireType", required = false) String expireType,
+ @RequestParam(name = "expireTime", required = false) String expireTime,
+ @RequestParam(name = "maxVersion", required = false) Integer maxVersion,
+ @RequestParam(name = "file") List<MultipartFile> files)
+ throws ErrorException {
+ String user = RestfulUtils.getUserName(req);
+ Message message;
+ try {
+ logger.info("User {} starts uploading resources (用户 {} 开始上传资源)", user, user);
+ Map<String, Object> properties = new HashMap<>();
+ properties.put("system", system);
+ properties.put("resourceHeader", resourceHeader);
+ properties.put("isExpire", isExpire);
+ properties.put("expireType", expireType);
+ properties.put("expireTime", expireTime);
+ properties.put("maxVersion", maxVersion);
+ String clientIp = HttpRequestHelper.getIp(req);
+ properties.put("clientIp", clientIp);
+ ResourceTask resourceTask = taskService.createUploadTask(files, user, properties);
+ message =
+ Message.ok("The task of submitting and uploading resources was successful(提交上传资源任务成功)");
+ message.setMethod(URL_PREFIX + "upload");
+ message.setStatus(0);
+ message.data("resourceId", resourceTask.getResourceId());
+ message.data("version", resourceTask.getVersion());
+ message.data("taskId", resourceTask.getId());
+ logger.info(
+ "User {} submitted upload resource task successfully(用户 {} 提交上传资源任务成功, resourceId is {})",
+ user,
+ user,
+ resourceTask.getResourceId());
+ } catch (final Exception e) {
+ logger.error("upload resource for user : {} failed, reason:", user, e);
+ ErrorException exception =
+ new ErrorException(
+ 50073, "The commit upload resource task failed(提交上传资源任务失败):" + e.getMessage());
+ exception.initCause(e);
+ throw exception;
+ }
+ return message;
+ }
+
+ /**
+ * 用户通过http的方式更新资源文件
+ *
+ * @param request httpServletRequest
+ * @param resourceId 用户希望更新资源的resourceId
+ * @param file file文件
+ * @return resourceId 以及 新的版本号
+ */
+ @ApiOperation(
+ value = "updateVersion",
+ notes = "update resource version",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "resourceId", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "file", required = true, dataType = "MultipartFile", value = "file")
+ })
+ @RequestMapping(path = "updateVersion", method = RequestMethod.POST)
+ public Message updateVersion(
+ HttpServletRequest request,
+ @RequestParam("resourceId") String resourceId,
+ @RequestParam("file") MultipartFile file)
+ throws Exception {
+ String user = RestfulUtils.getUserName(request);
+ if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
+ logger.error("error resourceId is {} ", resourceId);
+ throw new BmlServerParaErrorException(
+ "resourceId: " + resourceId + " is Null, illegal, or deleted!");
+ }
+ if (StringUtils.isEmpty(versionService.getNewestVersion(resourceId))) {
+ logger.error(
+ "If the material has not been uploaded or has been deleted, please call the upload interface first .(resourceId:{} 之前未上传物料,或物料已被删除,请先调用上传接口.)",
+ resourceId);
+ throw new BmlServerParaErrorException(
+ "If the material has not been uploaded or has been deleted, please call the upload interface first( resourceId: "
+ + resourceId
+ + " 之前未上传物料,或物料已被删除,请先调用上传接口.!)");
+ }
+ Message message;
+ try {
+ logger.info(
+ "User {} starts updating resources {}(用户 {} 开始更新资源 {}) ",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ String clientIp = HttpRequestHelper.getIp(request);
+ Map<String, Object> properties = new HashMap<>();
+ properties.put("clientIp", clientIp);
+ ResourceTask resourceTask = null;
+ synchronized (resourceId.intern()) {
+ resourceTask = taskService.createUpdateTask(resourceId, user, file, properties);
+ }
+ message = Message.ok("The update resource task was submitted successfully(提交更新资源任务成功)");
+ message
+ .data("resourceId", resourceId)
+ .data("version", resourceTask.getVersion())
+ .data("taskId", resourceTask.getId());
+ } catch (final ErrorException e) {
+ logger.error("{} update resource failed, resourceId is {}, reason:", user, resourceId, e);
+ throw e;
+ } catch (final Exception e) {
+ logger.error("{} update resource failed, resourceId is {}, reason:", user, resourceId, e);
+ ErrorException exception =
+ new ErrorException(
+ 50073, "The commit upload resource task failed(提交上传资源任务失败):" + e.getMessage());
+ exception.initCause(e);
+ throw exception;
+ }
+ logger.info(
+ "User {} ends updating resources {}(用户 {} 结束更新资源 {}) ", user, resourceId, user, resourceId);
+ return message;
+ }
+
+ @ApiOperation(value = "getBasic", notes = "get resource basic info", response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "resourceId", required = true, dataType = "String")})
+ @RequestMapping(path = "getBasic", method = RequestMethod.GET)
+ public Message getBasic(
+ @RequestParam(value = "resourceId", required = false) String resourceId,
+ HttpServletRequest request)
+ throws ErrorException {
+ String user = RestfulUtils.getUserName(request);
+
+ if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
+ throw new BmlServerParaErrorException(PARAMETER_IS_ILLEGAL.getErrorDesc());
+ }
- Message message = null;
- resp.setContentType("application/x-msdownload");
- resp.setHeader("Content-Disposition", "attachment");
- String ip = HttpRequestHelper.getIp(request);
- DownloadModel downloadModel = new DownloadModel(resourceId, version, user, ip);
- try {
- logger.info(
- "user {} downLoad resource resourceId is {}, version is {} ,ip is {} ",
- user,
- resourceId,
- version,
- ip);
- Map<String, Object> properties = new HashMap<>();
- boolean downloadResult =
- versionService.downloadResource(
- user, resourceId, version, resp.getOutputStream(), properties);
- downloadModel.setEndTime(new Date(System.currentTimeMillis()));
- downloadModel.setState(0);
- if (!downloadResult) {
- logger.warn(
- "ResourceId :{}, version:{} has a problem when user {} downloads the resource. The copied size is less than 0(用户 {} 下载资源 resourceId: {}, version:{} 出现问题,复制的size小于0)",
- resourceId,
- version,
- user,
- user,
- resourceId,
- version);
- downloadModel.setState(1);
- throw new BmlQueryFailException(FAILED_DOWNLOAD_RESOURCE.getErrorDesc());
- }
- downloadService.addDownloadRecord(downloadModel);
- logger.info(
- "User {} ends downloading the resource {}(用户 {} 结束下载资源 {}) ",
- user,
- resourceId,
- user,
- resourceId);
- } catch (IOException e) {
- logger.error(
- "IO Exception: ResourceId :{}, version:{} (用户 {} 下载资源 resourceId: {}, version:{} 出现IO异常)",
- resourceId,
- version,
- user,
- resourceId,
- version,
- e);
- downloadModel.setEndTime(new Date());
- downloadModel.setState(1);
- downloadService.addDownloadRecord(downloadModel);
- throw new ErrorException(
- 73562,
- "Sorry, the background IO error caused you to download the resources failed(抱歉,后台IO错误造成您本次下载资源失败)");
- } catch (final Throwable t) {
- logger.error(
- "ResourceId :{}, version:{} abnormal when user {} downloads resource (用户 {} 下载资源 resourceId: {}, version:{} 出现异常)",
- resourceId,
- version,
- user,
- user,
- resourceId,
- version,
- t);
- downloadModel.setEndTime(new Date());
- downloadModel.setState(1);
- downloadService.addDownloadRecord(downloadModel);
- throw new ErrorException(
- 73561,
- "Sorry, the background service error caused you to download the resources failed(抱歉,后台服务出错导致您本次下载资源失败)");
- } finally {
- IOUtils.closeQuietly(resp.getOutputStream());
- }
+ Message message = null;
+ try {
+ Resource resource = resourceService.getResource(resourceId);
+ // int numberOfVersions = versionService.getNumOfVersions(resourceId);
+ if (!resource.isEnableFlag()) {
+ logger.warn(
+ "The resource {} that user {} wants to query has been deleted (用户 {} 想要查询的资源 {} 已经被删除)",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ message = Message.error("The resource has been deleted(资源已经被删除)");
+ } else {
logger.info(
- "{} Download resource {} successfully {} 下载资源 {} 成功",
- user,
- resourceId,
- user,
- resourceId);
- }
-
- @ApiOperation(value = "upload", notes = "upload resource", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "system", required = false, dataType = "String", value = "system"),
- @ApiImplicitParam(name = "resourceHeader", required = false, dataType = "String", value = "resource header"),
- @ApiImplicitParam(name = "isExpire", required = false, dataType = "String", value = "is expire"),
- @ApiImplicitParam(name = "expireType", required = false, dataType = "String", value = "expire type"),
- @ApiImplicitParam(name = "expireTime", required = false, dataType = "String", value = "expire time"),
- @ApiImplicitParam(name = "maxVersion", required = false, dataType = "String", value = "max version"),
- @ApiImplicitParam(name = "file", required = true, dataType = "List<MultipartFile>", value = "file")
- })
- @RequestMapping(path = "upload", method = RequestMethod.POST)
- public Message uploadResource(
- HttpServletRequest req,
- @RequestParam(name = "system", required = false) String system,
- @RequestParam(name = "resourceHeader", required = false) String resourceHeader,
- @RequestParam(name = "isExpire", required = false) String isExpire,
- @RequestParam(name = "expireType", required = false) String expireType,
- @RequestParam(name = "expireTime", required = false) String expireTime,
- @RequestParam(name = "maxVersion", required = false) Integer maxVersion,
- @RequestParam(name = "file") List<MultipartFile> files)
- throws ErrorException {
- String user = RestfulUtils.getUserName(req);
- Message message;
- try {
- logger.info("User {} starts uploading resources (用户 {} 开始上传资源)", user, user);
- Map<String, Object> properties = new HashMap<>();
- properties.put("system", system);
- properties.put("resourceHeader", resourceHeader);
- properties.put("isExpire", isExpire);
- properties.put("expireType", expireType);
- properties.put("expireTime", expireTime);
- properties.put("maxVersion", maxVersion);
- String clientIp = HttpRequestHelper.getIp(req);
- properties.put("clientIp", clientIp);
- ResourceTask resourceTask = taskService.createUploadTask(files, user, properties);
- message =
- Message.ok(
- "The task of submitting and uploading resources was successful(提交上传资源任务成功)");
- message.setMethod(URL_PREFIX + "upload");
- message.setStatus(0);
- message.data("resourceId", resourceTask.getResourceId());
- message.data("version", resourceTask.getVersion());
- message.data("taskId", resourceTask.getId());
- logger.info(
- "User {} submitted upload resource task successfully(用户 {} 提交上传资源任务成功, resourceId is {})",
- user,
- user,
- resourceTask.getResourceId());
- } catch (final Exception e) {
- logger.error("upload resource for user : {} failed, reason:", user, e);
- ErrorException exception =
- new ErrorException(
- 50073,
- "The commit upload resource task failed(提交上传资源任务失败):" + e.getMessage());
- exception.initCause(e);
- throw exception;
- }
- return message;
- }
-
- /**
- * 用户通过http的方式更新资源文件
- *
- * @param request httpServletRequest
- * @param resourceId 用户希望更新资源的resourceId
- * @param file file文件
- * @return resourceId 以及 新的版本号
- */
- @ApiOperation(value = "updateVersion", notes = "update resource version", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId",required = true, dataType = "String", value = "resource Id"),
- @ApiImplicitParam(name = "file", required = true, dataType = "MultipartFile", value = "file")
- })
- @RequestMapping(path = "updateVersion", method = RequestMethod.POST)
- public Message updateVersion(
- HttpServletRequest request,
- @RequestParam("resourceId") String resourceId,
- @RequestParam("file") MultipartFile file)
- throws Exception {
- String user = RestfulUtils.getUserName(request);
- if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
- logger.error("error resourceId is {} ", resourceId);
- throw new BmlServerParaErrorException(
- "resourceId: " + resourceId + " is Null, illegal, or deleted!");
- }
- if (StringUtils.isEmpty(versionService.getNewestVersion(resourceId))) {
- logger.error(
- "If the material has not been uploaded or has been deleted, please call the upload interface first .(resourceId:{} 之前未上传物料,或物料已被删除,请先调用上传接口.)",
- resourceId);
- throw new BmlServerParaErrorException(
- "If the material has not been uploaded or has been deleted, please call the upload interface first( resourceId: "
- + resourceId
- + " 之前未上传物料,或物料已被删除,请先调用上传接口.!)");
- }
- Message message;
- try {
- logger.info(
- "User {} starts updating resources {}(用户 {} 开始更新资源 {}) ",
- user,
- resourceId,
- user,
- resourceId);
- String clientIp = HttpRequestHelper.getIp(request);
- Map<String, Object> properties = new HashMap<>();
- properties.put("clientIp", clientIp);
- ResourceTask resourceTask = null;
- synchronized (resourceId.intern()) {
- resourceTask = taskService.createUpdateTask(resourceId, user, file, properties);
- }
- message = Message.ok("The update resource task was submitted successfully(提交更新资源任务成功)");
- message.data("resourceId", resourceId)
- .data("version", resourceTask.getVersion())
- .data("taskId", resourceTask.getId());
- } catch (final ErrorException e) {
- logger.error(
- "{} update resource failed, resourceId is {}, reason:", user, resourceId, e);
- throw e;
- } catch (final Exception e) {
- logger.error(
- "{} update resource failed, resourceId is {}, reason:", user, resourceId, e);
- ErrorException exception =
- new ErrorException(
- 50073,
- "The commit upload resource task failed(提交上传资源任务失败):" + e.getMessage());
- exception.initCause(e);
- throw exception;
+ "User {} starts getting basic information about {}(用户 {} 开始获取 {} 的基本信息)",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ ResourceBasicVO basic = new ResourceBasicVO();
+ basic.setResourceId(resourceId);
+ basic.setCreateTime(resource.getCreateTime());
+ basic.setDownloadedFileName(resource.getDownloadedFileName());
+ basic.setOwner(resource.getUser());
+ // todo 正确的版本信息
+ basic.setNumberOfVerions(10);
+ if (resource.isExpire()) {
+ basic.setExpireTime(
+ RestfulUtils.getExpireTime(
+ resource.getCreateTime(), resource.getExpireType(), resource.getExpireTime()));
+ } else {
+ basic.setExpireTime("Resource not expired(资源不过期)");
}
+ message = Message.ok("Acquisition of resource basic information successfully(获取资源基本信息成功)");
+ message.setStatus(0);
+ message.setMethod(URL_PREFIX + "getBasic");
+ message.data("basic", basic);
logger.info(
- "User {} ends updating resources {}(用户 {} 结束更新资源 {}) ",
- user,
- resourceId,
- user,
- resourceId);
- return message;
- }
-
- @ApiOperation(value = "getBasic", notes = "get resource basic info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = true, dataType = "String", value = "resource Id")
- })
- @RequestMapping(path = "getBasic", method = RequestMethod.GET)
- public Message getBasic(
- @RequestParam(value = "resourceId", required = false) String resourceId,
- HttpServletRequest request)
- throws ErrorException {
- String user = RestfulUtils.getUserName(request);
-
- if (StringUtils.isEmpty(resourceId) || !resourceService.checkResourceId(resourceId)) {
- throw new BmlServerParaErrorException(
- PARAMETER_IS_ILLEGAL.getErrorDesc());
- }
-
- Message message = null;
- try {
- Resource resource = resourceService.getResource(resourceId);
- // int numberOfVersions = versionService.getNumOfVersions(resourceId);
- if (!resource.isEnableFlag()) {
- logger.warn(
- "The resource {} that user {} wants to query has been deleted (用户 {} 想要查询的资源 {} 已经被删除)",
- user,
- resourceId,
- user,
- resourceId);
- message = Message.error("The resource has been deleted(资源已经被删除)");
- } else {
- logger.info(
- "User {} starts getting basic information about {}(用户 {} 开始获取 {} 的基本信息)",
- user,
- resourceId,
- user,
- resourceId);
- ResourceBasicVO basic = new ResourceBasicVO();
- basic.setResourceId(resourceId);
- basic.setCreateTime(resource.getCreateTime());
- basic.setDownloadedFileName(resource.getDownloadedFileName());
- basic.setOwner(resource.getUser());
- // todo 正确的版本信息
- basic.setNumberOfVerions(10);
- if (resource.isExpire()) {
- basic.setExpireTime(
- RestfulUtils.getExpireTime(
- resource.getCreateTime(),
- resource.getExpireType(),
- resource.getExpireTime()));
- } else {
- basic.setExpireTime("Resource not expired(资源不过期)");
- }
- message =
- Message.ok(
- "Acquisition of resource basic information successfully(获取资源基本信息成功)");
- message.setStatus(0);
- message.setMethod(URL_PREFIX + "getBasic");
- message.data("basic", basic);
- logger.info(
- "User {} ends fetching basic information for {}(用户 {} 结束获取 {} 的基本信息)",
- user,
- resourceId,
- user,
- resourceId);
- }
- } catch (final Exception e) {
- logger.error("用户 {} 获取 {} 资源信息失败", user, resourceId, e);
- throw new BmlQueryFailException(
- FAILED_RESOURCE_BASIC.getErrorDesc());
- }
+ "User {} ends fetching basic information for {}(用户 {} 结束获取 {} 的基本信息)",
+ user,
+ resourceId,
+ user,
+ resourceId);
+ }
+ } catch (final Exception e) {
+ logger.error("用户 {} 获取 {} 资源信息失败", user, resourceId, e);
+ throw new BmlQueryFailException(FAILED_RESOURCE_BASIC.getErrorDesc());
+ }
- return message;
- }
-
- @ApiOperation(value = "getResourceInfo", notes = "get resource info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = true, dataType = "String", value = "resource Id")
- })
- @RequestMapping(path = "getResourceInfo", method = RequestMethod.GET)
- public Message getResourceInfo(
- HttpServletRequest request,
- @RequestParam(value = "resourceId", required = false) String resourceId) {
- return Message.ok("Obtained information successfully(获取信息成功)");
- }
-
- @ApiOperation(value = "changeOwner", notes = "change resource owner", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = true, dataType = "String", value = "resourceId"),
- @ApiImplicitParam(name = "oldOwner", required = true, dataType = "String", value = "old Owner"),
- @ApiImplicitParam(name = "newOwner", required = true, dataType = "String", value = "new Owner")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "changeOwner", method = RequestMethod.POST)
- public Message changeOwnerByResourceId(
- HttpServletRequest request, @RequestBody JsonNode jsonNode) throws ErrorException {
- String resourceId = jsonNode.get("resourceId").textValue();
- String oldOwner = jsonNode.get("oldOwner").textValue();
- String newOwner = jsonNode.get("newOwner").textValue();
- resourceService.changeOwnerByResourceId(resourceId, oldOwner, newOwner);
- return Message.ok("更新owner成功!");
- }
-
- @ApiOperation(value = "copyResourceToAnotherUser", notes = "copy resource to another user", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = true, dataType = "String", value = "resourceId"),
- @ApiImplicitParam(name = "anotherUser", required = true, dataType = "String", value = "another user")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "copyResourceToAnotherUser", method = RequestMethod.POST)
- public Message copyResourceToAnotherUser(
- HttpServletRequest request, @RequestBody JsonNode jsonNode) {
- String username = ModuleUserUtils.getOperationUser(request, "copyResourceToAnotherUser");
- String resourceId = jsonNode.get("resourceId").textValue();
- String anotherUser = jsonNode.get("anotherUser").textValue();
- Message message = null;
- try {
- logger.info("用户 {} 开始 copy bml resource: {}", username, resourceId);
- String clientIp = HttpRequestHelper.getIp(request);
- Map<String, Object> properties = new HashMap<>();
- properties.put("clientIp", clientIp);
- properties.put("maxVersion", 0);
- properties.put("system", "dss");
- ResourceTask resourceTask = null;
- synchronized (resourceId.intern()) {
- resourceTask =
- taskService.createCopyResourceTask(resourceId, anotherUser, properties);
- }
- message = Message.ok();
- message.data("resourceId", resourceTask.getResourceId());
- } catch (Exception e) {
- logger.error("failed to copy bml resource:", e);
- message = Message.error(e.getMessage());
- }
- logger.info("用户 {} 结束 copy bml resource: {}", username, resourceId);
- return message;
- }
-
- @ApiOperation(value = "RollbackVersion", notes = "rollback resource version", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "resourceId", required = true, dataType = "String", value = "resource id"),
- @ApiImplicitParam(name = "version", required = true, dataType = "String", value = "version")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "rollbackVersion", method = RequestMethod.POST)
- public Message rollbackVersion(HttpServletRequest request, @RequestBody JsonNode jsonNode) {
- String username = ModuleUserUtils.getOperationUser(request, "rollbackVersion");
- String resourceId = jsonNode.get("resourceId").textValue();
- String rollbackVersion = jsonNode.get("version").textValue();
- Message message = null;
- try {
- logger.info(
- "用户 {} 开始rollback bml resource: {}, version:{} ",
- username,
- resourceId,
- rollbackVersion);
- String clientIp = HttpRequestHelper.getIp(request);
- Map<String, Object> properties = new HashMap<>();
- properties.put("clientIp", clientIp);
- ResourceTask resourceTask = null;
- synchronized (resourceId.intern()) {
- resourceTask =
- taskService.createRollbackVersionTask(
- resourceId, rollbackVersion, username, properties);
- }
- message = Message.ok();
- message.data("resourceId", resourceTask.getResourceId())
- .data("version", resourceTask.getVersion());
- } catch (Exception e) {
- logger.error("failed to rollback version:", e);
- message = Message.error(e.getMessage());
- }
- logger.info(
- "用户 {} 结束rollback bml resource: {}, version:{} ",
- username,
- resourceId,
- rollbackVersion);
- return message;
+ return message;
+ }
+
+ @ApiOperation(value = "getResourceInfo", notes = "get resource info", response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "resourceId", required = true, dataType = "String")})
+ @RequestMapping(path = "getResourceInfo", method = RequestMethod.GET)
+ public Message getResourceInfo(
+ HttpServletRequest request,
+ @RequestParam(value = "resourceId", required = false) String resourceId) {
+ return Message.ok("Obtained information successfully(获取信息成功)");
+ }
+
+ @ApiOperation(value = "changeOwner", notes = "change resource owner", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "resourceId", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "oldOwner", required = true, dataType = "String", value = "old Owner"),
+ @ApiImplicitParam(name = "newOwner", required = true, dataType = "String", value = "new Owner")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "changeOwner", method = RequestMethod.POST)
+ public Message changeOwnerByResourceId(HttpServletRequest request, @RequestBody JsonNode jsonNode)
+ throws ErrorException {
+ String resourceId = jsonNode.get("resourceId").textValue();
+ String oldOwner = jsonNode.get("oldOwner").textValue();
+ String newOwner = jsonNode.get("newOwner").textValue();
+ resourceService.changeOwnerByResourceId(resourceId, oldOwner, newOwner);
+ return Message.ok("更新owner成功!");
+ }
+
+ @ApiOperation(
+ value = "copyResourceToAnotherUser",
+ notes = "copy resource to another user",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "resourceId", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "anotherUser", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "copyResourceToAnotherUser", method = RequestMethod.POST)
+ public Message copyResourceToAnotherUser(
+ HttpServletRequest request, @RequestBody JsonNode jsonNode) {
+ String username = ModuleUserUtils.getOperationUser(request, "copyResourceToAnotherUser");
+ String resourceId = jsonNode.get("resourceId").textValue();
+ String anotherUser = jsonNode.get("anotherUser").textValue();
+ Message message = null;
+ try {
+ logger.info("用户 {} 开始 copy bml resource: {}", username, resourceId);
+ String clientIp = HttpRequestHelper.getIp(request);
+ Map<String, Object> properties = new HashMap<>();
+ properties.put("clientIp", clientIp);
+ properties.put("maxVersion", 0);
+ properties.put("system", "dss");
+ ResourceTask resourceTask = null;
+ synchronized (resourceId.intern()) {
+ resourceTask = taskService.createCopyResourceTask(resourceId, anotherUser, properties);
+ }
+ message = Message.ok();
+ message.data("resourceId", resourceTask.getResourceId());
+ } catch (Exception e) {
+ logger.error("failed to copy bml resource:", e);
+ message = Message.error(e.getMessage());
+ }
+ logger.info("用户 {} 结束 copy bml resource: {}", username, resourceId);
+ return message;
+ }
+
+ @ApiOperation(
+ value = "RollbackVersion",
+ notes = "rollback resource version",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "resourceId", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "version", required = true, dataType = "String", value = "version")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "rollbackVersion", method = RequestMethod.POST)
+ public Message rollbackVersion(HttpServletRequest request, @RequestBody JsonNode jsonNode) {
+ String username = ModuleUserUtils.getOperationUser(request, "rollbackVersion");
+ String resourceId = jsonNode.get("resourceId").textValue();
+ String rollbackVersion = jsonNode.get("version").textValue();
+ Message message = null;
+ try {
+ logger.info(
+ "用户 {} 开始rollback bml resource: {}, version:{} ", username, resourceId, rollbackVersion);
+ String clientIp = HttpRequestHelper.getIp(request);
+ Map<String, Object> properties = new HashMap<>();
+ properties.put("clientIp", clientIp);
+ ResourceTask resourceTask = null;
+ synchronized (resourceId.intern()) {
+ resourceTask =
+ taskService.createRollbackVersionTask(
+ resourceId, rollbackVersion, username, properties);
+ }
+ message = Message.ok();
+ message
+ .data("resourceId", resourceTask.getResourceId())
+ .data("version", resourceTask.getVersion());
+ } catch (Exception e) {
+ logger.error("failed to rollback version:", e);
+ message = Message.error(e.getMessage());
}
+ logger.info(
+ "用户 {} 结束rollback bml resource: {}, version:{} ", username, resourceId, rollbackVersion);
+ return message;
+ }
}
diff --git a/linkis-public-enhancements/linkis-configuration/src/main/java/org/apache/linkis/configuration/restful/api/ConfigurationRestfulApi.java b/linkis-public-enhancements/linkis-configuration/src/main/java/org/apache/linkis/configuration/restful/api/ConfigurationRestfulApi.java
index c2106a8ac..f1ac09fba 100644
--- a/linkis-public-enhancements/linkis-configuration/src/main/java/org/apache/linkis/configuration/restful/api/ConfigurationRestfulApi.java
+++ b/linkis-public-enhancements/linkis-configuration/src/main/java/org/apache/linkis/configuration/restful/api/ConfigurationRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -40,6 +40,11 @@ import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
@@ -50,11 +55,6 @@ import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
import static org.apache.linkis.configuration.errorcode.LinkisConfigurationErrorCodeSummary.*;
@Api(tags = "parameter configuration")
@@ -62,363 +62,372 @@ import static org.apache.linkis.configuration.errorcode.LinkisConfigurationError
@RequestMapping(path = "/configuration")
public class ConfigurationRestfulApi {
- private static final Logger logger = LoggerFactory.getLogger(ConfigurationRestfulApi.class);
-
- @Autowired private ConfigurationService configurationService;
-
- @Autowired private CategoryService categoryService;
-
- @Autowired private ConfigKeyService configKeyService;
-
- ObjectMapper mapper = new ObjectMapper();
-
- private static final String NULL = "null";
-
- @ApiOperation(value = "addKeyForEngine", notes = "add key for engine", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "engineType", required = false, dataType = "String", value = "engine type"),
- @ApiImplicitParam(name = "version", required = false, dataType = "String", value = "version"),
- @ApiImplicitParam(name = "token, required = false", dataType = "String", value = "token"),
- @ApiImplicitParam(name = "keyJson", required = false, dataType = "String", value = "key json")
- })
- @RequestMapping(path = "/addKeyForEngine", method = RequestMethod.GET)
- public Message addKeyForEngine(
- HttpServletRequest req,
- @RequestParam(value = "engineType", required = false) String engineType,
- @RequestParam(value = "version", required = false) String version,
- @RequestParam(value = "token", required = false) String token,
- @RequestParam(value = "keyJson", required = false) String keyJson)
- throws ConfigurationException {
- if (StringUtils.isBlank(engineType)
- || StringUtils.isBlank(version)
- || StringUtils.isBlank(token)) {
- throw new ConfigurationException(PARAMS_CANNOT_BE_EMPTY.getErrorDesc());
- }
- // todo 检验token
- if (!token.equals(ConfigurationConfiguration.COPYKEYTOKEN)) {
- throw new ConfigurationException(TOKEN_IS_ERROR.getErrorDesc());
- }
- ConfigKey configKey = BDPJettyServerHelper.gson().fromJson(keyJson, ConfigKey.class);
- configurationService.addKeyForEngine(engineType, version, configKey);
- // TODO: 2019/12/30 configKey参数校验
- return Message.ok();
+ private static final Logger logger = LoggerFactory.getLogger(ConfigurationRestfulApi.class);
+
+ @Autowired private ConfigurationService configurationService;
+
+ @Autowired private CategoryService categoryService;
+
+ @Autowired private ConfigKeyService configKeyService;
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ private static final String NULL = "null";
+
+ @ApiOperation(value = "addKeyForEngine", notes = "add key for engine", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "engineType", dataType = "String"),
+ @ApiImplicitParam(name = "version", required = false, dataType = "String", value = "version"),
+ @ApiImplicitParam(name = "token, required = false", dataType = "String", value = "token"),
+ @ApiImplicitParam(name = "keyJson", required = false, dataType = "String", value = "key json")
+ })
+ @RequestMapping(path = "/addKeyForEngine", method = RequestMethod.GET)
+ public Message addKeyForEngine(
+ HttpServletRequest req,
+ @RequestParam(value = "engineType", required = false) String engineType,
+ @RequestParam(value = "version", required = false) String version,
+ @RequestParam(value = "token", required = false) String token,
+ @RequestParam(value = "keyJson", required = false) String keyJson)
+ throws ConfigurationException {
+ if (StringUtils.isBlank(engineType)
+ || StringUtils.isBlank(version)
+ || StringUtils.isBlank(token)) {
+ throw new ConfigurationException(PARAMS_CANNOT_BE_EMPTY.getErrorDesc());
}
-
- @ApiOperation(value = "getFullTreesByAppName", notes = "get full trees by app name", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "engineType", required = false, dataType = "String", value = "engine type"),
- @ApiImplicitParam(name = "version", required = false, dataType = "String", value = "version"),
- @ApiImplicitParam(name = "creator", required = false, dataType = "String", value = "creator")
- })
- @RequestMapping(path = "/getFullTreesByAppName", method = RequestMethod.GET)
- public Message getFullTreesByAppName(
- HttpServletRequest req,
- @RequestParam(value = "engineType", required = false) String engineType,
- @RequestParam(value = "version", required = false) String version,
- @RequestParam(value = "creator", required = false) String creator)
- throws ConfigurationException {
- String username = ModuleUserUtils.getOperationUser(req, "getFullTreesByAppName");
- if (creator != null && (creator.equals("通用设置") || creator.equals("全局设置"))) {
- engineType = "*";
- version = "*";
- creator = "*";
- }
- List labelList =
- LabelEntityParser.generateUserCreatorEngineTypeLabelList(
- username, creator, engineType, version);
- ArrayList<ConfigTree> configTrees =
- configurationService.getFullTreeByLabelList(labelList, true);
- return Message.ok().data("fullTree", configTrees);
+ // todo 检验token
+ if (!token.equals(ConfigurationConfiguration.COPYKEYTOKEN)) {
+ throw new ConfigurationException(TOKEN_IS_ERROR.getErrorDesc());
}
-
- @ApiOperation(value = "getCategory", notes = "get category", response = Message.class)
- @RequestMapping(path = "/getCategory", method = RequestMethod.GET)
- public Message getCategory(HttpServletRequest req) {
- List<CategoryLabelVo> categoryLabelList = categoryService.getAllCategory();
- return Message.ok().data("Category", categoryLabelList);
+ ConfigKey configKey = BDPJettyServerHelper.gson().fromJson(keyJson, ConfigKey.class);
+ configurationService.addKeyForEngine(engineType, version, configKey);
+ // TODO: 2019/12/30 configKey参数校验
+ return Message.ok();
+ }
+
+ @ApiOperation(
+ value = "getFullTreesByAppName",
+ notes = "get full trees by app name",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "engineType", dataType = "String"),
+ @ApiImplicitParam(name = "version", dataType = "String", value = "version"),
+ @ApiImplicitParam(name = "creator", dataType = "String", value = "creator")
+ })
+ @RequestMapping(path = "/getFullTreesByAppName", method = RequestMethod.GET)
+ public Message getFullTreesByAppName(
+ HttpServletRequest req,
+ @RequestParam(value = "engineType", required = false) String engineType,
+ @RequestParam(value = "version", required = false) String version,
+ @RequestParam(value = "creator", required = false) String creator)
+ throws ConfigurationException {
+ String username = ModuleUserUtils.getOperationUser(req, "getFullTreesByAppName");
+ if (creator != null && (creator.equals("通用设置") || creator.equals("全局设置"))) {
+ engineType = "*";
+ version = "*";
+ creator = "*";
}
-
- @ApiOperation(value = "createFirstCategory", notes = "create first category", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "categoryName", required = true,dataType = "String", value = "category name", example = "name"),
- @ApiImplicitParam(name = "description", required = true, dataType = "STring", value = "description", example = "description"),
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/createFirstCategory", method = RequestMethod.POST)
- public Message createFirstCategory(HttpServletRequest request, @RequestBody JsonNode jsonNode)
- throws ConfigurationException {
- String username = ModuleUserUtils.getOperationUser(request, "createFirstCategory");
- checkAdmin(username);
- String categoryName = jsonNode.get("categoryName").asText();
- String description = jsonNode.get("description").asText();
- if (StringUtils.isEmpty(categoryName) || categoryName.equals(NULL)) {
- throw new ConfigurationException(IS_NULL_CANNOT_BE_ADDED.getErrorDesc());
- }
- if (StringUtils.isEmpty(categoryName) || categoryName.contains("-")) {
- throw new ConfigurationException(CANNOT_BE_INCLUDED.getErrorDesc());
- }
- categoryService.createFirstCategory(categoryName, description);
- return Message.ok();
+ List labelList =
+ LabelEntityParser.generateUserCreatorEngineTypeLabelList(
+ username, creator, engineType, version);
+ ArrayList<ConfigTree> configTrees =
+ configurationService.getFullTreeByLabelList(labelList, true);
+ return Message.ok().data("fullTree", configTrees);
+ }
+
+ @ApiOperation(value = "getCategory", notes = "get category", response = Message.class)
+ @RequestMapping(path = "/getCategory", method = RequestMethod.GET)
+ public Message getCategory(HttpServletRequest req) {
+ List<CategoryLabelVo> categoryLabelList = categoryService.getAllCategory();
+ return Message.ok().data("Category", categoryLabelList);
+ }
+
+ @ApiOperation(
+ value = "createFirstCategory",
+ notes = "create first category",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "categoryName", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "description", required = true, dataType = "String"),
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/createFirstCategory", method = RequestMethod.POST)
+ public Message createFirstCategory(HttpServletRequest request, @RequestBody JsonNode jsonNode)
+ throws ConfigurationException {
+ String username = ModuleUserUtils.getOperationUser(request, "createFirstCategory");
+ checkAdmin(username);
+ String categoryName = jsonNode.get("categoryName").asText();
+ String description = jsonNode.get("description").asText();
+ if (StringUtils.isEmpty(categoryName) || categoryName.equals(NULL)) {
+ throw new ConfigurationException(IS_NULL_CANNOT_BE_ADDED.getErrorDesc());
}
-
- @ApiOperation(value = "deleteCategory", notes = "delete category", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "categoryId", required = true,dataType = "String", value = "category id", example = "54")
- })
- @ApiOperationSupport(ignoreParameters = "jsonNode")
- @RequestMapping(path = "/deleteCategory", method = RequestMethod.POST)
- public Message deleteCategory(HttpServletRequest request, @RequestBody JsonNode jsonNode)
- throws ConfigurationException {
- String username = ModuleUserUtils.getOperationUser(request, "deleteCategory");
- checkAdmin(username);
- Integer categoryId = jsonNode.get("categoryId").asInt();
- categoryService.deleteCategory(categoryId);
- return Message.ok();
+ if (StringUtils.isEmpty(categoryName) || categoryName.contains("-")) {
+ throw new ConfigurationException(CANNOT_BE_INCLUDED.getErrorDesc());
}
-
- @ApiOperation(value = "createSecondCategory", notes = "create second category", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "categoryId", required = true,dataType = "String", value = "category id", example = "39"),
- @ApiImplicitParam(name = "engineType",required = true, dataType = "String", value = "engine type", example = "hive"),
- @ApiImplicitParam(name = "version", required = true,dataType = "String", value = "Version", example = "1.2.0"),
- @ApiImplicitParam(name = "description", required = true,dataType = "String", value = "description"),
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/createSecondCategory", method = RequestMethod.POST)
- public Message createSecondCategory(HttpServletRequest request, @RequestBody JsonNode jsonNode)
- throws ConfigurationException {
- String username = ModuleUserUtils.getOperationUser(request, "createSecondCategory");
- checkAdmin(username);
- Integer categoryId = jsonNode.get("categoryId").asInt();
- String engineType = jsonNode.get("engineType").asText();
- String version = jsonNode.get("version").asText();
- String description = jsonNode.get("description").asText();
- if (categoryId <= 0) {
- throw new ConfigurationException(CREATOR_IS_NULL_CANNOT_BE_ADDED.getErrorDesc());
- }
- if (StringUtils.isEmpty(engineType) || engineType.toLowerCase().equals(NULL)) {
- throw new ConfigurationException(ENGINE_TYPE_IS_NULL.getErrorDesc());
- }
- if (StringUtils.isEmpty(version) || version.toLowerCase().equals(NULL)) {
- version = LabelUtils.COMMON_VALUE;
- }
- categoryService.createSecondCategory(categoryId, engineType, version, description);
- return Message.ok();
+ categoryService.createFirstCategory(categoryName, description);
+ return Message.ok();
+ }
+
+ @ApiOperation(value = "deleteCategory", notes = "delete category", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "categoryId", required = true, dataType = "String", example = "54")
+ })
+ @ApiOperationSupport(ignoreParameters = "jsonNode")
+ @RequestMapping(path = "/deleteCategory", method = RequestMethod.POST)
+ public Message deleteCategory(HttpServletRequest request, @RequestBody JsonNode jsonNode)
+ throws ConfigurationException {
+ String username = ModuleUserUtils.getOperationUser(request, "deleteCategory");
+ checkAdmin(username);
+ Integer categoryId = jsonNode.get("categoryId").asInt();
+ categoryService.deleteCategory(categoryId);
+ return Message.ok();
+ }
+
+ @ApiOperation(
+ value = "createSecondCategory",
+ notes = "create second category",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "categoryId", required = true, dataType = "String", example = "39"),
+ @ApiImplicitParam(name = "engineType", required = true, dataType = "String", example = "hive"),
+ @ApiImplicitParam(name = "version", required = true, dataType = "String", example = "1.2.0"),
+ @ApiImplicitParam(name = "description", required = true, dataType = "String"),
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/createSecondCategory", method = RequestMethod.POST)
+ public Message createSecondCategory(HttpServletRequest request, @RequestBody JsonNode jsonNode)
+ throws ConfigurationException {
+ String username = ModuleUserUtils.getOperationUser(request, "createSecondCategory");
+ checkAdmin(username);
+ Integer categoryId = jsonNode.get("categoryId").asInt();
+ String engineType = jsonNode.get("engineType").asText();
+ String version = jsonNode.get("version").asText();
+ String description = jsonNode.get("description").asText();
+ if (categoryId <= 0) {
+ throw new ConfigurationException(CREATOR_IS_NULL_CANNOT_BE_ADDED.getErrorDesc());
}
-
- @ApiOperation(value = "saveFullTree", notes = "save full tree", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "creator", required = true,dataType = "String", value = "creator", example = "xwzTest"),
- @ApiImplicitParam(name = "engineType",required = true, dataType = "String", value = "engine type", example = "python-ss"),
- @ApiImplicitParam(name = "fullTree", required = true,dataType = "List", value = "full tree"),
- @ApiImplicitParam(name = "name", required = true,dataType = "String", value = "name"),
- @ApiImplicitParam(name = "description",required = true, dataType = "String", value = "description"),
- @ApiImplicitParam(name = "settings", required = true,dataType = "List", value = "settings")
- })
- @ApiOperationSupport(ignoreParameters = {"json"})
- @RequestMapping(path = "/saveFullTree", method = RequestMethod.POST)
- public Message saveFullTree(HttpServletRequest req, @RequestBody JsonNode json)
- throws IOException, ConfigurationException {
- List fullTrees = mapper.treeToValue(json.get("fullTree"), List.class);
- String creator = JsonNodeUtil.getStringValue(json.get("creator"));
- String engineType = JsonNodeUtil.getStringValue(json.get("engineType"));
- if (creator != null && (creator.equals("通用设置") || creator.equals("全局设置"))) {
- creator = "*";
- }
- String username = ModuleUserUtils.getOperationUser(req, "saveFullTree");
- ArrayList<ConfigValue> createList = new ArrayList<>();
- ArrayList<ConfigValue> updateList = new ArrayList<>();
- for (Object o : fullTrees) {
- String s = BDPJettyServerHelper.gson().toJson(o);
- ConfigTree fullTree = BDPJettyServerHelper.gson().fromJson(s, ConfigTree.class);
- List<ConfigKeyValue> settings = fullTree.getSettings();
- Integer userLabelId =
- configurationService.checkAndCreateUserLabel(settings, username, creator);
- for (ConfigKeyValue setting : settings) {
- configurationService.updateUserValue(setting, userLabelId, createList, updateList);
- }
- }
- String engine = null;
- String version = null;
- if (engineType != null) {
- String[] tmpString = engineType.split("-");
- if (tmpString.length != 2) {
- throw new ConfigurationException(
- INCORRECT_FIXED_SUCH.getErrorDesc());
- }
- engine = tmpString[0];
- version = tmpString[1];
- }
- configurationService.updateUserValue(createList, updateList);
- configurationService.clearAMCacheConf(username, creator, engine, version);
- Message message = Message.ok();
- return message;
+ if (StringUtils.isEmpty(engineType) || engineType.toLowerCase().equals(NULL)) {
+ throw new ConfigurationException(ENGINE_TYPE_IS_NULL.getErrorDesc());
}
-
- @ApiOperation(value = "listAllEngineType", notes = "list all engine type", response = Message.class)
- @RequestMapping(path = "/engineType", method = RequestMethod.GET)
- public Message listAllEngineType(HttpServletRequest request) {
- String[] engineType = configurationService.listAllEngineType();
- return Message.ok().data("engineType", engineType);
+ if (StringUtils.isEmpty(version) || version.toLowerCase().equals(NULL)) {
+ version = LabelUtils.COMMON_VALUE;
}
-
- @ApiOperation(value = "updateCategoryInfo", notes = "update category info", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "description",required = true, dataType = "String", value = "description"),
- @ApiImplicitParam(name = "categoryId", required = true,dataType = "String", value = "category id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "/updateCategoryInfo", method = RequestMethod.POST)
- public Message updateCategoryInfo(HttpServletRequest request, @RequestBody JsonNode jsonNode)
- throws ConfigurationException {
- String username = ModuleUserUtils.getOperationUser(request, "updateCategoryInfo");
- checkAdmin(username);
- String description = null;
- Integer categoryId = null;
- try {
- description = jsonNode.get("description").asText();
- categoryId = jsonNode.get("categoryId").asInt();
- } catch (Exception e) {
- throw new ConfigurationException(INCOMPLETE_RECONFIRM.getErrorDesc());
- }
- if (description != null) {
- categoryService.updateCategory(categoryId, description);
- }
- return Message.ok();
+ categoryService.createSecondCategory(categoryId, engineType, version, description);
+ return Message.ok();
+ }
+
+ @ApiOperation(value = "saveFullTree", notes = "save full tree", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "creator", required = true, dataType = "String", example = "xwzTest"),
+ @ApiImplicitParam(name = "engineType", required = true, dataType = "String", example = "hive"),
+ @ApiImplicitParam(name = "fullTree", required = true, dataType = "List", value = "full tree"),
+ @ApiImplicitParam(name = "name", required = true, dataType = "String", value = "name"),
+ @ApiImplicitParam(name = "description", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "settings", required = true, dataType = "List", value = "settings")
+ })
+ @ApiOperationSupport(ignoreParameters = {"json"})
+ @RequestMapping(path = "/saveFullTree", method = RequestMethod.POST)
+ public Message saveFullTree(HttpServletRequest req, @RequestBody JsonNode json)
+ throws IOException, ConfigurationException {
+ List fullTrees = mapper.treeToValue(json.get("fullTree"), List.class);
+ String creator = JsonNodeUtil.getStringValue(json.get("creator"));
+ String engineType = JsonNodeUtil.getStringValue(json.get("engineType"));
+ if (creator != null && (creator.equals("通用设置") || creator.equals("全局设置"))) {
+ creator = "*";
}
-
- @ApiOperation(value = "rpcTest", notes = "rpc test", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "creator",required = false, dataType = "String", value = "creator"),
- @ApiImplicitParam(name = "engineType", required = false,dataType = "String", value = "engine type"),
- @ApiImplicitParam(name = "username", required = false,dataType = "String", value = "user name"),
- @ApiImplicitParam(name = "version", required = false,dataType = "String", value = "version")
- })
- @RequestMapping(path = "/rpcTest", method = RequestMethod.GET)
- public Message rpcTest(
- @RequestParam(value = "username", required = false) String username,
- @RequestParam(value = "creator", required = false) String creator,
- @RequestParam(value = "engineType", required = false) String engineType,
- @RequestParam(value = "version", required = false) String version) {
- configurationService.queryGlobalConfig(username);
- EngineTypeLabel engineTypeLabel = new EngineTypeLabel();
- engineTypeLabel.setVersion(version);
- engineTypeLabel.setEngineType(engineType);
- configurationService.queryDefaultEngineConfig(engineTypeLabel);
- UserCreatorLabel userCreatorLabel = new UserCreatorLabel();
- userCreatorLabel.setCreator(creator);
- userCreatorLabel.setUser(username);
- configurationService.queryConfig(userCreatorLabel, engineTypeLabel, "wds.linkis.rm");
- Message message = Message.ok();
- return message;
+ String username = ModuleUserUtils.getOperationUser(req, "saveFullTree");
+ ArrayList<ConfigValue> createList = new ArrayList<>();
+ ArrayList<ConfigValue> updateList = new ArrayList<>();
+ for (Object o : fullTrees) {
+ String s = BDPJettyServerHelper.gson().toJson(o);
+ ConfigTree fullTree = BDPJettyServerHelper.gson().fromJson(s, ConfigTree.class);
+ List<ConfigKeyValue> settings = fullTree.getSettings();
+ Integer userLabelId =
+ configurationService.checkAndCreateUserLabel(settings, username, creator);
+ for (ConfigKeyValue setting : settings) {
+ configurationService.updateUserValue(setting, userLabelId, createList, updateList);
+ }
}
-
- private void checkAdmin(String userName) throws ConfigurationException {
- if (!Configuration.isAdmin(userName)) {
- throw new ConfigurationException(ONLY_ADMIN_CAN_MODIFY.getErrorDesc());
- }
+ String engine = null;
+ String version = null;
+ if (engineType != null) {
+ String[] tmpString = engineType.split("-");
+ if (tmpString.length != 2) {
+ throw new ConfigurationException(INCORRECT_FIXED_SUCH.getErrorDesc());
+ }
+ engine = tmpString[0];
+ version = tmpString[1];
}
-
- @ApiOperation(value = "getKeyValue", notes = "get key value", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "creator", required = false,dataType = "String", value = "creator"),
- @ApiImplicitParam(name = "engineType", required = false,dataType = "String", value = "engine type"),
- @ApiImplicitParam(name = "configKey", required = false, dataType = "String", value = "config key"),
- @ApiImplicitParam(name = "version", required = false,dataType = "String", value = "version")
- })
- @RequestMapping(path = "/keyvalue", method = RequestMethod.GET)
- public Message getKeyValue(
- HttpServletRequest req,
- @RequestParam(value = "engineType", required = false, defaultValue = "*")
- String engineType,
- @RequestParam(value = "version", required = false, defaultValue = "*") String version,
- @RequestParam(value = "creator", required = false, defaultValue = "*") String creator,
- @RequestParam(value = "configKey") String configKey)
- throws ConfigurationException {
- String username = ModuleUserUtils.getOperationUser(req, "saveKey");
- if (engineType.equals("*") && !version.equals("*")) {
- return Message.error(
- "When engineType is any engine, the version must also be any version");
- }
- List labelList =
- LabelEntityParser.generateUserCreatorEngineTypeLabelList(
- username, creator, engineType, version);
-
- List<ConfigValue> configValues = configKeyService.getConfigValue(configKey, labelList);
- Message message = Message.ok().data("configValues", configValues);
- if (configValues.size() > 1) {
- message.data(
- "warnMessage",
- "There are multiple values for the corresponding Key: " + configKey);
- }
- return message;
+ configurationService.updateUserValue(createList, updateList);
+ configurationService.clearAMCacheConf(username, creator, engine, version);
+ Message message = Message.ok();
+ return message;
+ }
+
+ @ApiOperation(
+ value = "listAllEngineType",
+ notes = "list all engine type",
+ response = Message.class)
+ @RequestMapping(path = "/engineType", method = RequestMethod.GET)
+ public Message listAllEngineType(HttpServletRequest request) {
+ String[] engineType = configurationService.listAllEngineType();
+ return Message.ok().data("engineType", engineType);
+ }
+
+ @ApiOperation(
+ value = "updateCategoryInfo",
+ notes = "update category info",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "description", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "categoryId", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "/updateCategoryInfo", method = RequestMethod.POST)
+ public Message updateCategoryInfo(HttpServletRequest request, @RequestBody JsonNode jsonNode)
+ throws ConfigurationException {
+ String username = ModuleUserUtils.getOperationUser(request, "updateCategoryInfo");
+ checkAdmin(username);
+ String description = null;
+ Integer categoryId = null;
+ try {
+ description = jsonNode.get("description").asText();
+ categoryId = jsonNode.get("categoryId").asInt();
+ } catch (Exception e) {
+ throw new ConfigurationException(INCOMPLETE_RECONFIRM.getErrorDesc());
}
-
- @ApiOperation(value = "saveKeyValue", notes = "save key value", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "engineType", required = true, dataType = "String", value = "engine type"),
- @ApiImplicitParam(name = "version", required = true,dataType = "String", value = "version"),
- @ApiImplicitParam(name = "creator", required = true,dataType = "String", value = "creator"),
- @ApiImplicitParam(name = "configKey", required = true, dataType = "String", value = "config key"),
- @ApiImplicitParam(name = "configValue", required = true,dataType = "String", value = "config value")
- })
- @ApiOperationSupport(ignoreParameters = {"json"})
- @RequestMapping(path = "/keyvalue", method = RequestMethod.POST)
- public Message saveKeyValue(HttpServletRequest req, @RequestBody Map<String, Object> json)
- throws ConfigurationException {
- String username = ModuleUserUtils.getOperationUser(req, "saveKey");
- String engineType = (String) json.getOrDefault("engineType", "*");
- String version = (String) json.getOrDefault("version", "*");
- String creator = (String) json.getOrDefault("creator", "*");
- String configKey = (String) json.get("configKey");
- String value = (String) json.get("configValue");
- if (engineType.equals("*") && !version.equals("*")) {
- return Message.error(
- "When engineType is any engine, the version must also be any version");
- }
- if (StringUtils.isBlank(configKey) || StringUtils.isBlank(value)) {
- return Message.error("key or value cannot be empty");
- }
- List labelList =
- LabelEntityParser.generateUserCreatorEngineTypeLabelList(
- username, creator, engineType, version);
-
- ConfigKeyValue configKeyValue = new ConfigKeyValue();
- configKeyValue.setKey(configKey);
- configKeyValue.setConfigValue(value);
-
- ConfigValue configValue = configKeyService.saveConfigValue(configKeyValue, labelList);
- configurationService.clearAMCacheConf(username, creator, engineType, version);
- return Message.ok().data("configValue", configValue);
+ if (description != null) {
+ categoryService.updateCategory(categoryId, description);
}
-
- @ApiOperation(value = "deleteKeyValue", notes = "delete key value", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "engineType", required = true,dataType = "String", value = "engine type"),
- @ApiImplicitParam(name = "version", required = true, dataType = "String", value = "version"),
- @ApiImplicitParam(name = "creator", required = true, dataType = "String", value = "creator"),
- @ApiImplicitParam(name = "configKey", required = true, dataType = "String", value = "config key")
- })
- @ApiOperationSupport(ignoreParameters = {"json"})
- @RequestMapping(path = "/keyvalue", method = RequestMethod.DELETE)
- public Message deleteKeyValue(HttpServletRequest req, @RequestBody Map<String, Object> json)
- throws ConfigurationException {
- String username = ModuleUserUtils.getOperationUser(req, "saveKey");
- String engineType = (String) json.getOrDefault("engineType", "*");
- String version = (String) json.getOrDefault("version", "*");
- String creator = (String) json.getOrDefault("creator", "*");
- String configKey = (String) json.get("configKey");
- if (engineType.equals("*") && !version.equals("*")) {
- return Message.error(
- "When engineType is any engine, the version must also be any version");
- }
- if (StringUtils.isBlank(configKey)) {
- return Message.error("key cannot be empty");
- }
- List labelList =
- LabelEntityParser.generateUserCreatorEngineTypeLabelList(
- username, creator, engineType, version);
- List<ConfigValue> configValues = configKeyService.deleteConfigValue(configKey, labelList);
- return Message.ok().data("configValues", configValues);
+ return Message.ok();
+ }
+
+ @ApiOperation(value = "rpcTest", notes = "rpc test", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "creator", dataType = "String", value = "creator"),
+ @ApiImplicitParam(name = "engineType", dataType = "String"),
+ @ApiImplicitParam(name = "username", dataType = "String"),
+ @ApiImplicitParam(name = "version", required = false, dataType = "String", value = "version")
+ })
+ @RequestMapping(path = "/rpcTest", method = RequestMethod.GET)
+ public Message rpcTest(
+ @RequestParam(value = "username", required = false) String username,
+ @RequestParam(value = "creator", required = false) String creator,
+ @RequestParam(value = "engineType", required = false) String engineType,
+ @RequestParam(value = "version", required = false) String version) {
+ configurationService.queryGlobalConfig(username);
+ EngineTypeLabel engineTypeLabel = new EngineTypeLabel();
+ engineTypeLabel.setVersion(version);
+ engineTypeLabel.setEngineType(engineType);
+ configurationService.queryDefaultEngineConfig(engineTypeLabel);
+ UserCreatorLabel userCreatorLabel = new UserCreatorLabel();
+ userCreatorLabel.setCreator(creator);
+ userCreatorLabel.setUser(username);
+ configurationService.queryConfig(userCreatorLabel, engineTypeLabel, "wds.linkis.rm");
+ Message message = Message.ok();
+ return message;
+ }
+
+ private void checkAdmin(String userName) throws ConfigurationException {
+ if (!Configuration.isAdmin(userName)) {
+ throw new ConfigurationException(ONLY_ADMIN_CAN_MODIFY.getErrorDesc());
+ }
+ }
+
+ @ApiOperation(value = "getKeyValue", notes = "get key value", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "creator", required = false, dataType = "String", value = "creator"),
+ @ApiImplicitParam(name = "engineType", dataType = "String"),
+ @ApiImplicitParam(name = "configKey", dataType = "String"),
+ @ApiImplicitParam(name = "version", required = false, dataType = "String", value = "version")
+ })
+ @RequestMapping(path = "/keyvalue", method = RequestMethod.GET)
+ public Message getKeyValue(
+ HttpServletRequest req,
+ @RequestParam(value = "engineType", required = false, defaultValue = "*") String engineType,
+ @RequestParam(value = "version", required = false, defaultValue = "*") String version,
+ @RequestParam(value = "creator", required = false, defaultValue = "*") String creator,
+ @RequestParam(value = "configKey") String configKey)
+ throws ConfigurationException {
+ String username = ModuleUserUtils.getOperationUser(req, "saveKey");
+ if (engineType.equals("*") && !version.equals("*")) {
+ return Message.error("When engineType is any engine, the version must also be any version");
+ }
+ List labelList =
+ LabelEntityParser.generateUserCreatorEngineTypeLabelList(
+ username, creator, engineType, version);
+
+ List<ConfigValue> configValues = configKeyService.getConfigValue(configKey, labelList);
+ Message message = Message.ok().data("configValues", configValues);
+ if (configValues.size() > 1) {
+ message.data(
+ "warnMessage", "There are multiple values for the corresponding Key: " + configKey);
+ }
+ return message;
+ }
+
+ @ApiOperation(value = "saveKeyValue", notes = "save key value", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "engineType", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "version", required = true, dataType = "String", value = "version"),
+ @ApiImplicitParam(name = "creator", required = true, dataType = "String", value = "creator"),
+ @ApiImplicitParam(name = "configKey", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "configValue", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"json"})
+ @RequestMapping(path = "/keyvalue", method = RequestMethod.POST)
+ public Message saveKeyValue(HttpServletRequest req, @RequestBody Map<String, Object> json)
+ throws ConfigurationException {
+ String username = ModuleUserUtils.getOperationUser(req, "saveKey");
+ String engineType = (String) json.getOrDefault("engineType", "*");
+ String version = (String) json.getOrDefault("version", "*");
+ String creator = (String) json.getOrDefault("creator", "*");
+ String configKey = (String) json.get("configKey");
+ String value = (String) json.get("configValue");
+ if (engineType.equals("*") && !version.equals("*")) {
+ return Message.error("When engineType is any engine, the version must also be any version");
+ }
+ if (StringUtils.isBlank(configKey) || StringUtils.isBlank(value)) {
+ return Message.error("key or value cannot be empty");
+ }
+ List labelList =
+ LabelEntityParser.generateUserCreatorEngineTypeLabelList(
+ username, creator, engineType, version);
+
+ ConfigKeyValue configKeyValue = new ConfigKeyValue();
+ configKeyValue.setKey(configKey);
+ configKeyValue.setConfigValue(value);
+
+ ConfigValue configValue = configKeyService.saveConfigValue(configKeyValue, labelList);
+ configurationService.clearAMCacheConf(username, creator, engineType, version);
+ return Message.ok().data("configValue", configValue);
+ }
+
+ @ApiOperation(value = "deleteKeyValue", notes = "delete key value", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "engineType", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "version", required = true, dataType = "String", value = "version"),
+ @ApiImplicitParam(name = "creator", required = true, dataType = "String", value = "creator"),
+ @ApiImplicitParam(name = "configKey", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"json"})
+ @RequestMapping(path = "/keyvalue", method = RequestMethod.DELETE)
+ public Message deleteKeyValue(HttpServletRequest req, @RequestBody Map<String, Object> json)
+ throws ConfigurationException {
+ String username = ModuleUserUtils.getOperationUser(req, "saveKey");
+ String engineType = (String) json.getOrDefault("engineType", "*");
+ String version = (String) json.getOrDefault("version", "*");
+ String creator = (String) json.getOrDefault("creator", "*");
+ String configKey = (String) json.get("configKey");
+ if (engineType.equals("*") && !version.equals("*")) {
+ return Message.error("When engineType is any engine, the version must also be any version");
+ }
+ if (StringUtils.isBlank(configKey)) {
+ return Message.error("key cannot be empty");
}
+ List labelList =
+ LabelEntityParser.generateUserCreatorEngineTypeLabelList(
+ username, creator, engineType, version);
+ List<ConfigValue> configValues = configKeyService.deleteConfigValue(configKey, labelList);
+ return Message.ok().data("configValues", configValues);
+ }
}
diff --git a/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextHistoryRestfulApi.java b/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextHistoryRestfulApi.java
index 3f6a1fede..a61c0a3f4 100644
--- a/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextHistoryRestfulApi.java
+++ b/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextHistoryRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -35,6 +35,8 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
@@ -43,129 +45,128 @@ import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
-import java.io.IOException;
-
@Api(tags = "cs(contextservice) history operation")
@RestController
@RequestMapping(path = "/contextservice")
public class ContextHistoryRestfulApi implements CsRestfulParent {
- @Autowired private CsScheduler csScheduler;
-
- private ObjectMapper objectMapper = new ObjectMapper();
-
- @ApiOperation(value = "createHistory", notes = "create context history", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextHistory", required = true, dataType = "String", value = "context history"),
- @ApiImplicitParam(name = "contextID", required = true, dataType = "String", value = "context Id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "createHistory", method = RequestMethod.POST)
- public Message createHistory(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextHistory history = getContextHistoryFromJsonNode(jsonNode);
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- // source and contextid cannot be empty
- if (StringUtils.isEmpty(history.getSource())) {
- throw new CSErrorException(97000, "history source cannot be empty");
- }
- if (StringUtils.isEmpty(contextID.getContextId())) {
- throw new CSErrorException(97000, "contxtId cannot be empty");
- }
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.CREATE, contextID, history);
- return generateResponse(answerJob, "");
+ @Autowired private CsScheduler csScheduler;
+
+ private ObjectMapper objectMapper = new ObjectMapper();
+
+ @ApiOperation(value = "createHistory", notes = "create context history", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextHistory", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "createHistory", method = RequestMethod.POST)
+ public Message createHistory(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextHistory history = getContextHistoryFromJsonNode(jsonNode);
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ // source and contextid cannot be empty
+ if (StringUtils.isEmpty(history.getSource())) {
+ throw new CSErrorException(97000, "history source cannot be empty");
}
-
- @ApiOperation(value = "removeHistory", notes = "remove context history", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextHistory", required = false, dataType = "String", value = "context history"),
- @ApiImplicitParam(name = "contextID", required = false, dataType = "String", value = "context Id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "removeHistory", method = RequestMethod.POST)
- public Message removeHistory(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextHistory history = getContextHistoryFromJsonNode(jsonNode);
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- // source and contextid cannot be empty
- if (StringUtils.isEmpty(history.getSource())) {
- throw new CSErrorException(97000, "history source cannot be empty");
- }
- if (StringUtils.isEmpty(contextID.getContextId())) {
- throw new CSErrorException(97000, "contxtId cannot be empty");
- }
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVE, contextID, history);
- return generateResponse(answerJob, "");
+ if (StringUtils.isEmpty(contextID.getContextId())) {
+ throw new CSErrorException(97000, "contxtId cannot be empty");
}
-
- @ApiOperation(value = "getHistories", notes = "get content history list", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextID", required = false, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "getHistories", method = RequestMethod.POST)
- public Message getHistories(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- if (StringUtils.isEmpty(contextID.getContextId())) {
- throw new CSErrorException(97000, "contxtId cannot be empty");
- }
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, contextID);
- Message message = generateResponse(answerJob, "contextHistory");
- return message;
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.CREATE, contextID, history);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(value = "removeHistory", notes = "remove context history", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextHistory", dataType = "String"),
+ @ApiImplicitParam(name = "contextID", dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "removeHistory", method = RequestMethod.POST)
+ public Message removeHistory(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextHistory history = getContextHistoryFromJsonNode(jsonNode);
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ // source and contextid cannot be empty
+ if (StringUtils.isEmpty(history.getSource())) {
+ throw new CSErrorException(97000, "history source cannot be empty");
}
-
- @ApiOperation(value = "GetHistory", notes = "get context history", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextID", required = true, dataType = "String", value = "context id"),
- @ApiImplicitParam(name = "source", required = false,dataType = "String", value = "source")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "getHistory", method = RequestMethod.POST)
- public Message getHistory(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- // ContextID contextID, String source
- String source = jsonNode.get("source").textValue();
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- // source and contextid cannot be empty
- if (StringUtils.isEmpty(source)) {
- throw new CSErrorException(97000, "history source cannot be empty");
- }
- if (StringUtils.isEmpty(contextID.getContextId())) {
- throw new CSErrorException(97000, "contxtId cannot be empty");
- }
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, contextID, source);
- Message message = generateResponse(answerJob, "contextHistory");
- return message;
+ if (StringUtils.isEmpty(contextID.getContextId())) {
+ throw new CSErrorException(97000, "contxtId cannot be empty");
}
-
- @ApiOperation(value = "searchHistory", notes = "search history", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextID", required = true, dataType = "String", value = "context id"),
- @ApiImplicitParam(name = "keywords", required = false, dataType = "String", value = "key words")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "searchHistory", method = RequestMethod.POST)
- public Message searchHistory(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- // ContextID contextID, String[] keywords
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- String[] keywords = objectMapper.treeToValue(jsonNode.get("keywords"), String[].class);
- if (StringUtils.isEmpty(contextID.getContextId())) {
- throw new CSErrorException(97000, "contxtId cannot be empty");
- }
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SEARCH, contextID, keywords);
- Message message = generateResponse(answerJob, "contextHistory");
- return message;
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVE, contextID, history);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(
+ value = "getHistories",
+ notes = "get content history list",
+ response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "contextID", dataType = "String")})
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "getHistories", method = RequestMethod.POST)
+ public Message getHistories(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ if (StringUtils.isEmpty(contextID.getContextId())) {
+ throw new CSErrorException(97000, "contxtId cannot be empty");
}
-
- @Override
- public ServiceType getServiceType() {
- return ServiceType.CONTEXT_HISTORY;
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, contextID);
+ Message message = generateResponse(answerJob, "contextHistory");
+ return message;
+ }
+
+ @ApiOperation(value = "GetHistory", notes = "get context history", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "source", required = false, dataType = "String", value = "source")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "getHistory", method = RequestMethod.POST)
+ public Message getHistory(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ // ContextID contextID, String source
+ String source = jsonNode.get("source").textValue();
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ // source and contextid cannot be empty
+ if (StringUtils.isEmpty(source)) {
+ throw new CSErrorException(97000, "history source cannot be empty");
}
-
- @Override
- public CsScheduler getScheduler() {
- return this.csScheduler;
+ if (StringUtils.isEmpty(contextID.getContextId())) {
+ throw new CSErrorException(97000, "contxtId cannot be empty");
+ }
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, contextID, source);
+ Message message = generateResponse(answerJob, "contextHistory");
+ return message;
+ }
+
+ @ApiOperation(value = "searchHistory", notes = "search history", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "keywords", dataType = "String", value = "key words")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "searchHistory", method = RequestMethod.POST)
+ public Message searchHistory(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ // ContextID contextID, String[] keywords
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ String[] keywords = objectMapper.treeToValue(jsonNode.get("keywords"), String[].class);
+ if (StringUtils.isEmpty(contextID.getContextId())) {
+ throw new CSErrorException(97000, "contxtId cannot be empty");
}
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SEARCH, contextID, keywords);
+ Message message = generateResponse(answerJob, "contextHistory");
+ return message;
+ }
+
+ @Override
+ public ServiceType getServiceType() {
+ return ServiceType.CONTEXT_HISTORY;
+ }
+
+ @Override
+ public CsScheduler getScheduler() {
+ return this.csScheduler;
+ }
}
diff --git a/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextIDRestfulApi.java b/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextIDRestfulApi.java
index 7a749e691..64fb4979a 100644
--- a/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextIDRestfulApi.java
+++ b/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextIDRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -40,6 +40,11 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Date;
+
import com.fasterxml.jackson.databind.JsonNode;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
@@ -49,11 +54,6 @@ import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.Date;
-
import static org.apache.linkis.cs.common.utils.CSCommonUtils.localDatetimeToDate;
@Api(tags = "cs(contextservice) recording operation")
@@ -61,195 +61,187 @@ import static org.apache.linkis.cs.common.utils.CSCommonUtils.localDatetimeToDat
@RequestMapping(path = "/contextservice")
public class ContextIDRestfulApi implements CsRestfulParent {
- private static final Logger logger = LoggerFactory.getLogger(ContextIDRestfulApi.class);
-
- @Autowired private CsScheduler csScheduler;
-
- @ApiOperation(value = "createContextID", notes = "create context Id", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextID", required = false, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "createContextID", method = RequestMethod.POST)
- public Message createContextID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, ClassNotFoundException, IOException, CSErrorException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.CREATE, contextID);
- return generateResponse(answerJob, "contextId");
+ private static final Logger logger = LoggerFactory.getLogger(ContextIDRestfulApi.class);
+
+ @Autowired private CsScheduler csScheduler;
+
+ @ApiOperation(value = "createContextID", notes = "create context Id", response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "contextID", dataType = "String")})
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "createContextID", method = RequestMethod.POST)
+ public Message createContextID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, ClassNotFoundException, IOException, CSErrorException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.CREATE, contextID);
+ return generateResponse(answerJob, "contextId");
+ }
+
+ @ApiOperation(value = "GetContextID", notes = "Get_Context_Id", response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "contextId", required = false, dataType = "String")})
+ @RequestMapping(path = "getContextID", method = RequestMethod.GET)
+ public Message getContextID(
+ HttpServletRequest req, @RequestParam(value = "contextId", required = false) String id)
+ throws InterruptedException, CSErrorException {
+ if (StringUtils.isEmpty(id)) {
+ throw new CSErrorException(97000, "contxtId cannot be empty");
}
-
- @ApiOperation(value = "GetContextID", notes = "Get_Context_Id", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextId", required = false, dataType = "String", value = "context id")
- })
- @RequestMapping(path = "getContextID", method = RequestMethod.GET)
- public Message getContextID(
- HttpServletRequest req, @RequestParam(value = "contextId", required = false) String id)
- throws InterruptedException, CSErrorException {
- if (StringUtils.isEmpty(id)) {
- throw new CSErrorException(97000, "contxtId cannot be empty");
- }
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, id);
- Message message = generateResponse(answerJob, "contextID");
- return message;
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, id);
+ Message message = generateResponse(answerJob, "contextID");
+ return message;
+ }
+
+ @ApiOperation(value = "updateContextID", notes = "update content id", response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "contextId", dataType = "String")})
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "updateContextID", method = RequestMethod.POST)
+ public Message updateContextID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ if (StringUtils.isEmpty(contextID.getContextId())) {
+ throw new CSErrorException(97000, "contxtId cannot be empty");
}
-
- @ApiOperation(value = "updateContextID", notes = "update content id", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextId", required = false, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "updateContextID", method = RequestMethod.POST)
- public Message updateContextID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- if (StringUtils.isEmpty(contextID.getContextId())) {
- throw new CSErrorException(97000, "contxtId cannot be empty");
- }
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.UPDATE, contextID);
- return generateResponse(answerJob, "");
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.UPDATE, contextID);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(value = "resetContextID", notes = "reset context Id", response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "contextId", dataType = "String")})
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "resetContextID", method = RequestMethod.POST)
+ public Message resetContextID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException {
+ if (!jsonNode.has(ContextHTTPConstant.CONTEXT_ID_STR)) {
+ throw new CSErrorException(97000, ContextHTTPConstant.CONTEXT_ID_STR + " cannot be empty");
}
-
- @ApiOperation(value = "resetContextID", notes = "reset context Id", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextId", required = false, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "resetContextID", method = RequestMethod.POST)
- public Message resetContextID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException {
- if (!jsonNode.has(ContextHTTPConstant.CONTEXT_ID_STR)) {
- throw new CSErrorException(
- 97000, ContextHTTPConstant.CONTEXT_ID_STR + " cannot be empty");
- }
- String id = jsonNode.get(ContextHTTPConstant.CONTEXT_ID_STR).textValue();
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.RESET, id);
- return generateResponse(answerJob, "");
+ String id = jsonNode.get(ContextHTTPConstant.CONTEXT_ID_STR).textValue();
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.RESET, id);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(value = "removeContextID", notes = "remove context ID", response = Message.class)
+ @ApiImplicitParams({@ApiImplicitParam(name = "contextId", dataType = "String")})
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "removeContextID", method = RequestMethod.POST)
+ public Message removeContextID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException {
+ String id = jsonNode.get("contextId").textValue();
+ if (StringUtils.isEmpty(id)) {
+ throw new CSErrorException(97000, "contxtId cannot be empty");
}
-
- @ApiOperation(value = "removeContextID", notes = "remove context ID", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextId", required = false, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "removeContextID", method = RequestMethod.POST)
- public Message removeContextID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException {
- String id = jsonNode.get("contextId").textValue();
- if (StringUtils.isEmpty(id)) {
- throw new CSErrorException(97000, "contxtId cannot be empty");
- }
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVE, id);
- return generateResponse(answerJob, "");
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVE, id);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(
+ value = "searchContextIDByTime",
+ notes = "search contextId by time",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "createTimeStart", dataType = "String"),
+ @ApiImplicitParam(name = "createTimeEnd", dataType = "String"),
+ @ApiImplicitParam(name = "updateTimeStart", dataType = "String"),
+ @ApiImplicitParam(name = "updateTimeEnd", dataType = "String"),
+ @ApiImplicitParam(name = "accessTimeStart", dataType = "String"),
+ @ApiImplicitParam(name = "accessTimeEnd", dataType = "String"),
+ @ApiImplicitParam(name = "pageNow", dataType = "String", value = "page now"),
+ @ApiImplicitParam(name = "pageSize", dataType = "String", value = "page size")
+ })
+ @RequestMapping(path = "searchContextIDByTime", method = RequestMethod.GET)
+ public Message searchContextIDByTime(
+ HttpServletRequest req,
+ @RequestParam(value = "createTimeStart", required = false) String createTimeStart,
+ @RequestParam(value = "createTimeEnd", required = false) String createTimeEnd,
+ @RequestParam(value = "updateTimeStart", required = false) String updateTimeStart,
+ @RequestParam(value = "updateTimeEnd", required = false) String updateTimeEnd,
+ @RequestParam(value = "accessTimeStart", required = false) String accessTimeStart,
+ @RequestParam(value = "accessTimeEnd", required = false) String accessTimeEnd,
+ @RequestParam(value = "pageNow", required = false) Integer paramPageNow,
+ @RequestParam(value = "pageSize", required = false) Integer paramPageSize)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ String username = ModuleUserUtils.getOperationUser(req);
+ if (!Configuration.isAdmin(username)) {
+ throw new CSErrorException(97018, "Only station admins are allowed.");
}
-
- @ApiOperation(value = "searchContextIDByTime", notes = "search contextId by time", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "createTimeStart",required = false, dataType = "String", value = "create time start"),
- @ApiImplicitParam(name = "createTimeEnd",required = false, dataType = "String", value = "create time end"),
- @ApiImplicitParam(name = "updateTimeStart",required = false, dataType = "String",value = "update time start"),
- @ApiImplicitParam(name = "updateTimeEnd", required = false, dataType = "String", value = "update time end"),
- @ApiImplicitParam(name = "accessTimeStart", required = false, dataType = "String", value = "access time start"),
- @ApiImplicitParam(name = "accessTimeEnd", required = false, dataType = "String", value = "access time end"),
- @ApiImplicitParam(name = "pageNow", required = false, dataType = "String", value = "page now"),
- @ApiImplicitParam(name = "pageSize", required = false, dataType = "String", value = "page size")
- })
- @RequestMapping(path = "searchContextIDByTime", method = RequestMethod.GET)
- public Message searchContextIDByTime(
- HttpServletRequest req,
- @RequestParam(value = "createTimeStart", required = false) String createTimeStart,
- @RequestParam(value = "createTimeEnd", required = false) String createTimeEnd,
- @RequestParam(value = "updateTimeStart", required = false) String updateTimeStart,
- @RequestParam(value = "updateTimeEnd", required = false) String updateTimeEnd,
- @RequestParam(value = "accessTimeStart", required = false) String accessTimeStart,
- @RequestParam(value = "accessTimeEnd", required = false) String accessTimeEnd,
- @RequestParam(value = "pageNow", required = false) Integer paramPageNow,
- @RequestParam(value = "pageSize", required = false) Integer paramPageSize)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- String username = ModuleUserUtils.getOperationUser(req);
- if (!Configuration.isAdmin(username)) {
- throw new CSErrorException(97018, "Only station admins are allowed.");
- }
- logger.info(
- "user: {}, searchContextIDByTime : createTimeStart : {}, createTimeEnd : {}, updateTimeStart : {}, updateTimeEnd : {}, accessTimeStart : {}, accessTimeEnd : {}, pageNow : {}, pageSize : {}.",
- username,
- createTimeStart,
- createTimeEnd,
- updateTimeStart,
- updateTimeEnd,
- accessTimeStart,
- accessTimeEnd,
- paramPageNow,
- paramPageSize);
-
- if (null == createTimeStart
- && null == createTimeEnd
- && null == updateTimeStart
- && null == createTimeEnd
- && null == accessTimeStart
- && null == accessTimeEnd) {
- throw new CSErrorException(
- 97000,
- "createTimeStart, createTimeEnd, updateTimeStart, updateTimeEnd, accessTimeStart, accessTimeEnd cannot be all null.");
- }
- int pageStart = 0;
- if (null == paramPageNow || paramPageNow <= 0) {
- pageStart = 1;
- } else {
- pageStart = paramPageNow;
- }
- int pageSize = 0;
- if (null == paramPageSize
- || paramPageSize <= 0
- || paramPageSize > CSCommonUtils.CONTEXT_MAX_PAGE_SIZE) {
- pageSize = CSCommonUtils.CONTEXT_MAX_PAGE_SIZE;
- } else {
- pageSize = paramPageSize;
- }
- Date createTimeStartDate = null;
- Date createTimeEndDate = null;
- Date updateTimeStartDate = null;
- Date updateTimeEndDate = null;
- Date accessTimeStartDate = null;
- Date accessTimeEndDate = null;
-
- DateTimeFormatter dtf = DateTimeFormatter.ofPattern(CSCommonUtils.DEFAULT_TIME_FORMAT);
- if (StringUtils.isNotBlank(createTimeStart))
- createTimeStartDate = localDatetimeToDate(LocalDateTime.parse(createTimeStart, dtf));
- if (StringUtils.isNotBlank(createTimeEnd))
- createTimeEndDate = localDatetimeToDate(LocalDateTime.parse(createTimeEnd, dtf));
- if (StringUtils.isNotBlank(updateTimeStart))
- updateTimeStartDate = localDatetimeToDate(LocalDateTime.parse(updateTimeStart, dtf));
- if (StringUtils.isNotBlank(updateTimeEnd))
- updateTimeEndDate = localDatetimeToDate(LocalDateTime.parse(updateTimeEnd, dtf));
- if (StringUtils.isNotBlank(accessTimeStart))
- accessTimeStartDate = localDatetimeToDate(LocalDateTime.parse(accessTimeStart, dtf));
- if (StringUtils.isNotBlank(accessTimeEnd))
- accessTimeEndDate = localDatetimeToDate(LocalDateTime.parse(accessTimeEnd, dtf));
- HttpAnswerJob answerJob =
- submitRestJob(
- req,
- ServiceMethod.SEARCH,
- createTimeStartDate,
- createTimeEndDate,
- updateTimeStartDate,
- updateTimeEndDate,
- accessTimeStartDate,
- accessTimeEndDate,
- pageStart,
- pageSize);
- Message resp = generateResponse(answerJob, "contextIDs");
- resp.setMethod("/api/contextservice/searchContextIDByTime");
- return resp;
+ logger.info(
+ "user: {}, searchContextIDByTime : createTimeStart : {}, createTimeEnd : {}, updateTimeStart : {}, updateTimeEnd : {}, accessTimeStart : {}, accessTimeEnd : {}, pageNow : {}, pageSize : {}.",
+ username,
+ createTimeStart,
+ createTimeEnd,
+ updateTimeStart,
+ updateTimeEnd,
+ accessTimeStart,
+ accessTimeEnd,
+ paramPageNow,
+ paramPageSize);
+
+ if (null == createTimeStart
+ && null == createTimeEnd
+ && null == updateTimeStart
+ && null == createTimeEnd
+ && null == accessTimeStart
+ && null == accessTimeEnd) {
+ throw new CSErrorException(
+ 97000,
+ "createTimeStart, createTimeEnd, updateTimeStart, updateTimeEnd, accessTimeStart, accessTimeEnd cannot be all null.");
}
-
- @Override
- public ServiceType getServiceType() {
- return ServiceType.CONTEXT_ID;
+ int pageStart = 0;
+ if (null == paramPageNow || paramPageNow <= 0) {
+ pageStart = 1;
+ } else {
+ pageStart = paramPageNow;
}
-
- @Override
- public CsScheduler getScheduler() {
- return this.csScheduler;
+ int pageSize = 0;
+ if (null == paramPageSize
+ || paramPageSize <= 0
+ || paramPageSize > CSCommonUtils.CONTEXT_MAX_PAGE_SIZE) {
+ pageSize = CSCommonUtils.CONTEXT_MAX_PAGE_SIZE;
+ } else {
+ pageSize = paramPageSize;
}
+ Date createTimeStartDate = null;
+ Date createTimeEndDate = null;
+ Date updateTimeStartDate = null;
+ Date updateTimeEndDate = null;
+ Date accessTimeStartDate = null;
+ Date accessTimeEndDate = null;
+
+ DateTimeFormatter dtf = DateTimeFormatter.ofPattern(CSCommonUtils.DEFAULT_TIME_FORMAT);
+ if (StringUtils.isNotBlank(createTimeStart))
+ createTimeStartDate = localDatetimeToDate(LocalDateTime.parse(createTimeStart, dtf));
+ if (StringUtils.isNotBlank(createTimeEnd))
+ createTimeEndDate = localDatetimeToDate(LocalDateTime.parse(createTimeEnd, dtf));
+ if (StringUtils.isNotBlank(updateTimeStart))
+ updateTimeStartDate = localDatetimeToDate(LocalDateTime.parse(updateTimeStart, dtf));
+ if (StringUtils.isNotBlank(updateTimeEnd))
+ updateTimeEndDate = localDatetimeToDate(LocalDateTime.parse(updateTimeEnd, dtf));
+ if (StringUtils.isNotBlank(accessTimeStart))
+ accessTimeStartDate = localDatetimeToDate(LocalDateTime.parse(accessTimeStart, dtf));
+ if (StringUtils.isNotBlank(accessTimeEnd))
+ accessTimeEndDate = localDatetimeToDate(LocalDateTime.parse(accessTimeEnd, dtf));
+ HttpAnswerJob answerJob =
+ submitRestJob(
+ req,
+ ServiceMethod.SEARCH,
+ createTimeStartDate,
+ createTimeEndDate,
+ updateTimeStartDate,
+ updateTimeEndDate,
+ accessTimeStartDate,
+ accessTimeEndDate,
+ pageStart,
+ pageSize);
+ Message resp = generateResponse(answerJob, "contextIDs");
+ resp.setMethod("/api/contextservice/searchContextIDByTime");
+ return resp;
+ }
+
+ @Override
+ public ServiceType getServiceType() {
+ return ServiceType.CONTEXT_ID;
+ }
+
+ @Override
+ public CsScheduler getScheduler() {
+ return this.csScheduler;
+ }
}
diff --git a/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextListenerRestfulApi.java b/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextListenerRestfulApi.java
index d37b44ef5..2546083c3 100644
--- a/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextListenerRestfulApi.java
+++ b/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextListenerRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -37,68 +37,71 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
-import java.io.IOException;
-
@Api(tags = "cs(contextservice) listener operation")
@RestController
@RequestMapping(path = "/contextservice")
public class ContextListenerRestfulApi implements CsRestfulParent {
- @Autowired private CsScheduler csScheduler;
+ @Autowired private CsScheduler csScheduler;
- private ObjectMapper objectMapper = new ObjectMapper();
+ private ObjectMapper objectMapper = new ObjectMapper();
- @ApiOperation(value = "onBindIDListener", notes = "on bind id listener", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "onBindIDListener", method = RequestMethod.POST)
- public Message onBindIDListener(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- String source = jsonNode.get("source").textValue();
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- ContextIDListenerDomain listener = new CommonContextIDListenerDomain();
- listener.setSource(source);
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.BIND, contextID, listener);
- return generateResponse(answerJob, "");
- }
+ @ApiOperation(value = "onBindIDListener", notes = "on bind id listener", response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "onBindIDListener", method = RequestMethod.POST)
+ public Message onBindIDListener(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ String source = jsonNode.get("source").textValue();
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ ContextIDListenerDomain listener = new CommonContextIDListenerDomain();
+ listener.setSource(source);
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.BIND, contextID, listener);
+ return generateResponse(answerJob, "");
+ }
- @ApiOperation(value = "onBindKeyListener", notes = "on bind key listener", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "onBindKeyListener", method = RequestMethod.POST)
- public Message onBindKeyListener(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- String source = jsonNode.get("source").textValue();
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
- CommonContextKeyListenerDomain listener = new CommonContextKeyListenerDomain();
- listener.setSource(source);
- HttpAnswerJob answerJob =
- submitRestJob(req, ServiceMethod.BIND, contextID, contextKey, listener);
- return generateResponse(answerJob, "");
- }
+ @ApiOperation(
+ value = "onBindKeyListener",
+ notes = "on bind key listener",
+ response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "onBindKeyListener", method = RequestMethod.POST)
+ public Message onBindKeyListener(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ String source = jsonNode.get("source").textValue();
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
+ CommonContextKeyListenerDomain listener = new CommonContextKeyListenerDomain();
+ listener.setSource(source);
+ HttpAnswerJob answerJob =
+ submitRestJob(req, ServiceMethod.BIND, contextID, contextKey, listener);
+ return generateResponse(answerJob, "");
+ }
- @ApiOperation(value = "heartbeat", notes = "heart beat", response = Message.class)
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "heartbeat", method = RequestMethod.POST)
- public Message heartbeat(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, IOException, CSErrorException {
- String source = jsonNode.get("source").textValue();
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.HEARTBEAT, source);
- return generateResponse(answerJob, "ContextKeyValueBean");
- }
+ @ApiOperation(value = "heartbeat", notes = "heart beat", response = Message.class)
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "heartbeat", method = RequestMethod.POST)
+ public Message heartbeat(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, IOException, CSErrorException {
+ String source = jsonNode.get("source").textValue();
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.HEARTBEAT, source);
+ return generateResponse(answerJob, "ContextKeyValueBean");
+ }
- @Override
- public ServiceType getServiceType() {
- return ServiceType.CONTEXT_LISTENER;
- }
+ @Override
+ public ServiceType getServiceType() {
+ return ServiceType.CONTEXT_LISTENER;
+ }
- @Override
- public CsScheduler getScheduler() {
- return this.csScheduler;
- }
+ @Override
+ public CsScheduler getScheduler() {
+ return this.csScheduler;
+ }
}
diff --git a/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextRestfulApi.java b/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextRestfulApi.java
index 87460cd96..9399e5592 100644
--- a/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextRestfulApi.java
+++ b/linkis-public-enhancements/linkis-context-service/linkis-cs-server/src/main/java/org/apache/linkis/cs/server/restful/ContextRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -41,6 +41,14 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -53,14 +61,6 @@ import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
import static org.apache.linkis.cs.common.utils.CSCommonUtils.localDatetimeToDate;
@Api(tags = "cs(contextservice) operation")
@@ -68,284 +68,280 @@ import static org.apache.linkis.cs.common.utils.CSCommonUtils.localDatetimeToDat
@RequestMapping(path = "/contextservice")
public class ContextRestfulApi implements CsRestfulParent {
- private static final Logger logger = LoggerFactory.getLogger(ContextRestfulApi.class);
-
- @Autowired private CsScheduler csScheduler;
-
- private ObjectMapper objectMapper = new ObjectMapper();
-
-
- @ApiOperation(value = "getContextValue", notes = "get context value", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextKey", required = true, dataType = "String", value = "context key"),
- @ApiImplicitParam(name = "contextID", required = true, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "getContextValue", method = RequestMethod.POST)
- public Message getContextValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, contextID, contextKey);
- Message message = generateResponse(answerJob, "contextValue");
- return message;
- }
-
-
- @ApiOperation(value = "searchContextValue", notes = "search context value", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "condition", required = true, dataType = "String", value = "condition"),
- @ApiImplicitParam(name = "contextID", required = true, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "searchContextValue", method = RequestMethod.POST)
- public Message searchContextValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- JsonNode condition = jsonNode.get("condition");
- Map<Object, Object> conditionMap =
- objectMapper.convertValue(condition, new TypeReference<Map<Object, Object>>() {});
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SEARCH, contextID, conditionMap);
- Message message = generateResponse(answerJob, "contextKeyValue");
- return message;
- }
-
-
- @ApiOperation(value = "setValueByKey", notes = "set value by key", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextKey", required = true, dataType = "String", value = "context key"),
- @ApiImplicitParam(name = "contextID", required = true, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "setValueByKey", method = RequestMethod.POST)
- public Message setValueByKey(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws CSErrorException, IOException, ClassNotFoundException, InterruptedException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
- ContextValue contextValue = getContextValueFromJsonNode(jsonNode);
- HttpAnswerJob answerJob =
- submitRestJob(req, ServiceMethod.SET, contextID, contextKey, contextValue);
- return generateResponse(answerJob, "");
- }
-
-
- @ApiOperation(value = "setValue", notes = "set value", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextKeyValue", required = true, dataType = "String", value = "context key value"),
- @ApiImplicitParam(name = "contextID", required = true, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "setValue", method = RequestMethod.POST)
- public Message setValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- ContextKeyValue contextKeyValue = getContextKeyValueFromJsonNode(jsonNode);
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SET, contextID, contextKeyValue);
- return generateResponse(answerJob, "");
- }
-
-
- @ApiOperation(value = "resetValue", notes = "reset value", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextKey", required = true, dataType = "String", value = "context key"),
- @ApiImplicitParam(name = "contextID", required = true, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "resetValue", method = RequestMethod.POST)
- public Message resetValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.RESET, contextID, contextKey);
- return generateResponse(answerJob, "");
- }
-
-
- @ApiOperation(value = "removeValue", notes = "remove value", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextKey", required = true, dataType = "String", value = "context key"),
- @ApiImplicitParam(name = "contextID", required = true, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "removeValue", method = RequestMethod.POST)
- public Message removeValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVE, contextID, contextKey);
- return generateResponse(answerJob, "");
- }
-
-
- @ApiOperation(value = "removeAllValue", notes = "remove all value", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextKey",required = true, dataType = "String", value = "context key"),
- @ApiImplicitParam(name = "contextID",required = true, dataType = "String", value = "context id")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "removeAllValue", method = RequestMethod.POST)
- public Message removeAllValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVEALL, contextID);
- return generateResponse(answerJob, "");
- }
-
-
- @ApiOperation(value = "removeAllValueByKeyPrefixAndContextType", notes = "remove all value by key prefix and context type", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextKeyType",required = true, dataType = "String", value = "context key type"),
- @ApiImplicitParam(name = "keyPrefix",required = true, dataType = "String", value = "key prefix")
- })
- @ApiOperationSupport(ignoreParameters = {"jsonNode"})
- @RequestMapping(path = "removeAllValueByKeyPrefixAndContextType", method = RequestMethod.POST)
- public Message removeAllValueByKeyPrefixAndContextType(
- HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- String contextType = jsonNode.get(ContextHTTPConstant.CONTEXT_KEY_TYPE_STR).textValue();
- String keyPrefix = jsonNode.get(ContextHTTPConstant.CONTEXT_KEY_PREFIX_STR).textValue();
- HttpAnswerJob answerJob =
- submitRestJob(
- req,
- ServiceMethod.REMOVEALL,
- contextID,
- ContextType.valueOf(contextType),
- keyPrefix);
- return generateResponse(answerJob, "");
- }
-
- @ApiOperation(value = "removeAllValueByKeyPrefix", notes = "remove all value by key prefix", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "contextID", required = false, dataType = "String", value = "context iD"),
- @ApiImplicitParam(name = "keyPrefix", required = false, dataType = "String", value = "key prefix")
- })
- @RequestMapping(path = "removeAllValueByKeyPrefix", method = RequestMethod.POST)
- public Message removeAllValueByKeyPrefix(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- ContextID contextID = getContextIDFromJsonNode(jsonNode);
- String keyPrefix = jsonNode.get(ContextHTTPConstant.CONTEXT_KEY_PREFIX_STR).textValue();
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVEALL, contextID, keyPrefix);
- return generateResponse(answerJob, "");
+ private static final Logger logger = LoggerFactory.getLogger(ContextRestfulApi.class);
+
+ @Autowired private CsScheduler csScheduler;
+
+ private ObjectMapper objectMapper = new ObjectMapper();
+
+ @ApiOperation(value = "getContextValue", notes = "get context value", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextKey", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "getContextValue", method = RequestMethod.POST)
+ public Message getContextValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.GET, contextID, contextKey);
+ Message message = generateResponse(answerJob, "contextValue");
+ return message;
+ }
+
+ @ApiOperation(
+ value = "searchContextValue",
+ notes = "search context value",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "condition", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "searchContextValue", method = RequestMethod.POST)
+ public Message searchContextValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ JsonNode condition = jsonNode.get("condition");
+ Map<Object, Object> conditionMap =
+ objectMapper.convertValue(condition, new TypeReference<Map<Object, Object>>() {});
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SEARCH, contextID, conditionMap);
+ Message message = generateResponse(answerJob, "contextKeyValue");
+ return message;
+ }
+
+ @ApiOperation(value = "setValueByKey", notes = "set value by key", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextKey", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "setValueByKey", method = RequestMethod.POST)
+ public Message setValueByKey(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws CSErrorException, IOException, ClassNotFoundException, InterruptedException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
+ ContextValue contextValue = getContextValueFromJsonNode(jsonNode);
+ HttpAnswerJob answerJob =
+ submitRestJob(req, ServiceMethod.SET, contextID, contextKey, contextValue);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(value = "setValue", notes = "set value", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextKeyValue", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "setValue", method = RequestMethod.POST)
+ public Message setValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ ContextKeyValue contextKeyValue = getContextKeyValueFromJsonNode(jsonNode);
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.SET, contextID, contextKeyValue);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(value = "resetValue", notes = "reset value", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextKey", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "resetValue", method = RequestMethod.POST)
+ public Message resetValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.RESET, contextID, contextKey);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(value = "removeValue", notes = "remove value", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextKey", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "removeValue", method = RequestMethod.POST)
+ public Message removeValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ ContextKey contextKey = getContextKeyFromJsonNode(jsonNode);
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVE, contextID, contextKey);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(value = "removeAllValue", notes = "remove all value", response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextKey", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "contextID", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "removeAllValue", method = RequestMethod.POST)
+ public Message removeAllValue(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVEALL, contextID);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(
+ value = "removeAllValueByKeyPrefixAndContextType",
+ notes = "remove all value by key prefix and context type",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextKeyType", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "keyPrefix", required = true, dataType = "String")
+ })
+ @ApiOperationSupport(ignoreParameters = {"jsonNode"})
+ @RequestMapping(path = "removeAllValueByKeyPrefixAndContextType", method = RequestMethod.POST)
+ public Message removeAllValueByKeyPrefixAndContextType(
+ HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ String contextType = jsonNode.get(ContextHTTPConstant.CONTEXT_KEY_TYPE_STR).textValue();
+ String keyPrefix = jsonNode.get(ContextHTTPConstant.CONTEXT_KEY_PREFIX_STR).textValue();
+ HttpAnswerJob answerJob =
+ submitRestJob(
+ req, ServiceMethod.REMOVEALL, contextID, ContextType.valueOf(contextType), keyPrefix);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(
+ value = "removeAllValueByKeyPrefix",
+ notes = "remove all value by key prefix",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "contextID", dataType = "String"),
+ @ApiImplicitParam(name = "keyPrefix", dataType = "String")
+ })
+ @RequestMapping(path = "removeAllValueByKeyPrefix", method = RequestMethod.POST)
+ public Message removeAllValueByKeyPrefix(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ ContextID contextID = getContextIDFromJsonNode(jsonNode);
+ String keyPrefix = jsonNode.get(ContextHTTPConstant.CONTEXT_KEY_PREFIX_STR).textValue();
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.REMOVEALL, contextID, keyPrefix);
+ return generateResponse(answerJob, "");
+ }
+
+ @ApiOperation(
+ value = "clearAllContextByID",
+ notes = "clear all context by id",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "idList", required = true, dataType = "String", value = "id list"),
+ })
+ @RequestMapping(path = "clearAllContextByID", method = RequestMethod.POST)
+ public Message clearAllContextByID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ if (null == jsonNode
+ || !jsonNode.has("idList")
+ || !jsonNode.get("idList").isArray()
+ || (jsonNode.get("idList").isArray() && ((ArrayNode) jsonNode.get("idList")).size() == 0)) {
+ throw new CSErrorException(97000, "idList cannot be empty.");
}
-
- @ApiOperation(value = "clearAllContextByID", notes = "clear all context by id", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "idList", required = true,dataType = "String", value = "id list"),
- })
- @RequestMapping(path = "clearAllContextByID", method = RequestMethod.POST)
- public Message clearAllContextByID(HttpServletRequest req, @RequestBody JsonNode jsonNode)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- if (null == jsonNode
- || !jsonNode.has("idList")
- || !jsonNode.get("idList").isArray()
- || (jsonNode.get("idList").isArray()
- && ((ArrayNode) jsonNode.get("idList")).size() == 0)) {
- throw new CSErrorException(97000, "idList cannot be empty.");
- }
- ArrayNode idArray = (ArrayNode) jsonNode.get("idList");
- logger.info("clearAllContextByID idList size : {}", idArray.size());
- List<String> idList = new ArrayList<>(idArray.size());
- for (int i = 0; i < idArray.size(); i++) {
- idList.add(idArray.get(i).asText());
- }
- HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.CLEAR, idList);
- Message resp = generateResponse(answerJob, "num");
- resp.setMethod("/api/contextservice/clearAllContextByID");
- return resp;
+ ArrayNode idArray = (ArrayNode) jsonNode.get("idList");
+ logger.info("clearAllContextByID idList size : {}", idArray.size());
+ List<String> idList = new ArrayList<>(idArray.size());
+ for (int i = 0; i < idArray.size(); i++) {
+ idList.add(idArray.get(i).asText());
}
-
- @ApiOperation(value = "clearAllContextByID(time)", notes = "clear all context by id(time)", response = Message.class)
- @ApiImplicitParams({
- @ApiImplicitParam(name = "createTimeStart", required = true,dataType = "String", value = "create time start"),
- @ApiImplicitParam(name = "createTimeEnd", required = true,dataType = "String", value = "create time end"),
- @ApiImplicitParam(name = "updateTimeStart",required = true, dataType = "String", value = "update time start"),
- @ApiImplicitParam(name = "createTimeEnd",required = true, dataType = "String", value = "update time end"),
- @ApiImplicitParam(name = "accessTimeStart",required = true, dataType = "String", value = "access time start"),
- @ApiImplicitParam(name = "accessTimeEnd", required = true,dataType = "String", value = "access time end")
- })
- @RequestMapping(path = "clearAllContextByTime", method = RequestMethod.POST)
- public Message clearAllContextByID(
- HttpServletRequest req, @RequestBody Map<String, Object> bodyMap)
- throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
- String username = ModuleUserUtils.getOperationUser(req);
- if (!Configuration.isAdmin(username)) {
- throw new CSErrorException(97018, "Only station admins are allowed.");
- }
- if (null == bodyMap || bodyMap.isEmpty()) {
- throw new CSErrorException(97000, "idList cannot be empty.");
- }
- Date createTimeStart = null;
- Date createTimeEnd = null;
- Date updateTimeStart = null;
- Date updateTimeEnd = null;
- Date accessTimeStart = null;
- Date accessTimeEnd = null;
-
- DateTimeFormatter dtf = DateTimeFormatter.ofPattern(CSCommonUtils.DEFAULT_TIME_FORMAT);
- if (bodyMap.containsKey("createTimeStart") && null != bodyMap.get("createTimeStart"))
- createTimeStart =
- localDatetimeToDate(
- LocalDateTime.parse((String) bodyMap.get("createTimeStart"), dtf));
- if (bodyMap.containsKey("createTimeEnd") && null != bodyMap.get("createTimeEnd"))
- createTimeEnd =
- localDatetimeToDate(
- LocalDateTime.parse((String) bodyMap.get("createTimeEnd"), dtf));
- if (bodyMap.containsKey("updateTimeStart") && null != bodyMap.get("updateTimeStart"))
- updateTimeStart =
- localDatetimeToDate(
- LocalDateTime.parse((String) bodyMap.get("updateTimeStart"), dtf));
- if (bodyMap.containsKey("updateTimeEnd") && null != bodyMap.get("updateTimeEnd"))
- updateTimeEnd =
- localDatetimeToDate(
- LocalDateTime.parse((String) bodyMap.get("updateTimeEnd"), dtf));
- if (bodyMap.containsKey("accessTimeStart") && null != bodyMap.get("accessTimeStart"))
- updateTimeStart =
- localDatetimeToDate(
- LocalDateTime.parse((String) bodyMap.get("accessTimeStart"), dtf));
- if (bodyMap.containsKey("accessTimeEnd") && null != bodyMap.get("accessTimeEnd"))
- updateTimeEnd =
- localDatetimeToDate(
- LocalDateTime.parse((String) bodyMap.get("accessTimeEnd"), dtf));
- if (null == createTimeStart
- && null == createTimeEnd
- && null == updateTimeStart
- && null == createTimeEnd) {
- throw new CSErrorException(
- 97000,
- "createTimeStart, createTimeEnd, updateTimeStart, updateTimeEnd cannot be all null.");
- }
- logger.info(
- "clearAllContextByTime: user : {}, createTimeStart : {}, createTimeEnd : {}, updateTimeStart : {}, updateTimeEnd : {}, accessTimeStart : {}, accessTimeEnd : {}, pageNow : {}, pageSize : {}.",
- username,
- createTimeStart,
- createTimeEnd,
- updateTimeStart,
- updateTimeEnd,
- accessTimeStart,
- accessTimeEnd);
- HttpAnswerJob answerJob =
- submitRestJob(
- req,
- ServiceMethod.CLEAR,
- createTimeStart,
- createTimeEnd,
- updateTimeStart,
- updateTimeEnd,
- accessTimeStart,
- accessTimeEnd);
- Message resp = generateResponse(answerJob, "num");
- resp.setMethod("/api/contextservice/clearAllContextByTime");
- return resp;
+ HttpAnswerJob answerJob = submitRestJob(req, ServiceMethod.CLEAR, idList);
+ Message resp = generateResponse(answerJob, "num");
+ resp.setMethod("/api/contextservice/clearAllContextByID");
+ return resp;
+ }
+
+ @ApiOperation(
+ value = "clearAllContextByID(time)",
+ notes = "clear all context by id(time)",
+ response = Message.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "createTimeStart", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "createTimeEnd", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "updateTimeStart", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "createTimeEnd", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "accessTimeStart", required = true, dataType = "String"),
+ @ApiImplicitParam(name = "accessTimeEnd", required = true, dataType = "String")
+ })
+ @RequestMapping(path = "clearAllContextByTime", method = RequestMethod.POST)
+ public Message clearAllContextByID(
+ HttpServletRequest req, @RequestBody Map<String, Object> bodyMap)
+ throws InterruptedException, CSErrorException, IOException, ClassNotFoundException {
+ String username = ModuleUserUtils.getOperationUser(req);
+ if (!Configuration.isAdmin(username)) {
+ throw new CSErrorException(97018, "Only station admins are allowed.");
}
-
- @Override
- public ServiceType getServiceType() {
- return ServiceType.CONTEXT;
+ if (null == bodyMap || bodyMap.isEmpty()) {
+ throw new CSErrorException(97000, "idList cannot be empty.");
}
-
- @Override
- public CsScheduler getScheduler() {
- return this.csScheduler;
+ Date createTimeStart = null;
+ Date createTimeEnd = null;
+ Date updateTimeStart = null;
+ Date updateTimeEnd = null;
+ Date accessTimeStart = null;
+ Date accessTimeEnd = null;
+
+ DateTimeFormatter dtf = DateTimeFormatter.ofPattern(CSCommonUtils.DEFAULT_TIME_FORMAT);
+ if (bodyMap.containsKey("createTimeStart") && null != bodyMap.get("createTimeStart"))
+ createTimeStart =
+ localDatetimeToDate(LocalDateTime.parse((String) bodyMap.get("createTimeStart"), dtf));
+ if (bodyMap.containsKey("createTimeEnd") && null != bodyMap.get("createTimeEnd"))
+ createTimeEnd =
+ localDatetimeToDate(LocalDateTime.parse((String) bodyMap.get("createTimeEnd"), dtf));
+ if (bodyMap.containsKey("updateTimeStart") && null != bodyMap.get("updateTimeStart"))
+ updateTimeStart =
+ localDatetimeToDate(LocalDateTime.parse((String) bodyMap.get("updateTimeStart"), dtf));
+ if (bodyMap.containsKey("updateTimeEnd") && null != bodyMap.get("updateTimeEnd"))
+ updateTimeEnd =
+ localDatetimeToDate(LocalDateTime.parse((String) bodyMap.get("updateTimeEnd"), dtf));
+ if (bodyMap.containsKey("accessTimeStart") && null != bodyMap.get("accessTimeStart"))
+ updateTimeStart =
+ localDatetimeToDate(LocalDateTime.parse((String) bodyMap.get("accessTimeStart"), dtf));
+ if (bodyMap.containsKey("accessTimeEnd") && null != bodyMap.get("accessTimeEnd"))
+ updateTimeEnd =
+ localDatetimeToDate(LocalDateTime.parse((String) bodyMap.get("accessTimeEnd"), dtf));
+ if (null == createTimeStart
+ && null == createTimeEnd
+ && null == updateTimeStart
+ && null == createTimeEnd) {
+ throw new CSErrorException(
+ 97000,
+ "createTimeStart, createTimeEnd, updateTimeStart, updateTimeEnd cannot be all null.");
}
+ logger.info(
+ "clearAllContextByTime: user : {}, createTimeStart : {}, createTimeEnd : {}, updateTimeStart : {}, updateTimeEnd : {}, accessTimeStart : {}, accessTimeEnd : {}, pageNow : {}, pageSize : {}.",
+ username,
+ createTimeStart,
+ createTimeEnd,
+ updateTimeStart,
+ updateTimeEnd,
+ accessTimeStart,
+ accessTimeEnd);
+ HttpAnswerJob answerJob =
+ submitRestJob(
+ req,
+ ServiceMethod.CLEAR,
+ createTimeStart,
+ createTimeEnd,
+ updateTimeStart,
+ updateTimeEnd,
+ accessTimeStart,
+ accessTimeEnd);
+ Message resp = generateResponse(answerJob, "num");
+ resp.setMethod("/api/contextservice/clearAllContextByTime");
+ return resp;
+ }
+
+ @Override
+ public ServiceType getServiceType() {
+ return ServiceType.CONTEXT;
+ }
+
+ @Override
+ public CsScheduler getScheduler() {
+ return this.csScheduler;
+ }
}
diff --git a/linkis-public-enhancements/linkis-datasource/linkis-datasource-manager/server/src/main/java/org/apache/linkis/datasourcemanager/core/restful/DataSourceAdminRestfulApi.java b/linkis-public-enhancements/linkis-datasource/linkis-datasource-manager/server/src/main/java/org/apache/linkis/datasourcemanager/core/restful/DataSourceAdminRestfulApi.java
index 36b679145..5c2f7b273 100644
--- a/linkis-public-enhancements/linkis-datasource/linkis-datasource-manager/server/src/main/java/org/apache/linkis/datasourcemanager/core/restful/DataSourceAdminRestfulApi.java
+++ b/linkis-public-enhancements/linkis-datasource/linkis-datasource-manager/server/src/main/java/org/apache/linkis/datasourcemanager/core/restful/DataSourceAdminRestfulApi.java
@@ -6,7 +6,7 @@
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,11 +17,6 @@
package org.apache.linkis.datasourcemanager.core.restful;
-import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiImplicitParam;
-import io.swagger.annotations.ApiImplicitParams;
-import io.swagger.annotations.ApiOperation;
import org.apache.linkis.common.exception.ErrorException;
import org.apache.linkis.datasourcemanager.common.domain.DataSourceEnv;
import org.apache.linkis.datasourcemanager.common.domain.DataSourceParamKeyDefinition;
@@ -33,6 +28,7 @@ import org.apache.linkis.datasourcemanager.core.validate.ParameterValidator;
import org.apache.linkis.datasourcemanager.core.vo.DataSourceEnvVo;
import org.apache.linkis.server.Message;
import org.apache.linkis.server.utils.ModuleUserUtils;
+
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -42,334 +38,348 @@ import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import javax.validation.groups.Default;
+
import java.util.*;
+import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+
@Api(tags = "data source admin restful api")
@RestController
@RequestMapping(
- value = "/data-source-manager",
- produces = {"application/json"})
+ value = "/data-source-manager",
+ produces = {"application/json"})
public class DataSourceAdminRestfulApi {
- private final List<String> permitSystemList = Arrays.asList("Qualitis");
- @Autowired private DataSourceInfoService dataSourceInfoService;
+ private final List<String> permitSystemList = Arrays.asList("Qualitis");
+ @Autowired private DataSourceInfoService dataSourceInfoService;
- @Autowired private DataSourceRelateService dataSourceRelateService;
+ @Autowired private DataSourceRelateService dataSourceRelateService;
- @Autowired private ParameterValidator parameterValidator;
+ @Autowired private ParameterValidator parameterValidator;
- @Autowired private Validator beanValidator;
+ @Autowired private Validator beanValidator;
- private MultiPartFormDataTransformer formDataTransformer;
+ private MultiPartFormDataTransformer formDataTransformer;
- @PostConstruct
- public void initRestful() {
- this.formDataTransformer = FormDataTransformerFactory.buildCustom();
- }
+ @PostConstruct
+ public void initRestful() {
... 7678 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@linkis.apache.org
For additional commands, e-mail: commits-help@linkis.apache.org