From 67e7c6b8c4559b1c76257212a80dba078c913fe3 Mon Sep 17 00:00:00 2001 From: Shaeny <417298932@qq.com> Date: Tue, 27 Dec 2022 10:09:21 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=E5=8D=87=E7=BA=A7springBoot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 18 +- .../webase/front/abi/AbiController.java | 4 +- .../webank/webase/front/abi/AbiService.java | 2 +- .../front/base/config/TomcatConfig.java | 51 +- .../front/contract/ContractService.java | 33 +- .../contractStore/PresetDataService.java | 19 +- .../event/ContractEventInfoRepository.java | 2 - .../webase/front/event/EventController.java | 8 +- .../webase/front/event/EventService.java | 8 +- .../event/NewBlockEventInfoRepository.java | 2 - .../front/keystore/KeyStoreService.java | 4 +- .../front/logparse/LogParseService.java | 10 +- .../webase/front/method/MethodService.java | 2 +- .../webase/front/monitor/MonitorService.java | 10 +- .../front/performance/PerformanceService.java | 10 +- .../precompiledapi/PrecompiledController.java | 1420 ++++++++--------- .../precompiledapi/PrecompiledService.java | 458 +++--- .../precompiledapi/crud/CRUDParseUtils.java | 1244 +++++++-------- .../webank/webase/front/solc/SolcService.java | 6 +- .../front/transaction/TransService.java | 77 +- src/main/resources/application.yml | 8 +- 21 files changed, 1697 insertions(+), 1699 deletions(-) diff --git a/build.gradle b/build.gradle index 18cf2dfcb..01a330ca8 100644 --- a/build.gradle +++ b/build.gradle @@ -23,7 +23,7 @@ repositories { } -def spring_version="4.3.29.RELEASE" +def spring_version="5.2.22.RELEASE" List spring =[ "org.springframework:spring-core:$spring_version", "org.springframework:spring-beans:$spring_version", @@ -40,13 +40,14 @@ List spring =[ ] -def spring_boot_version="1.5.22.RELEASE" +def spring_boot_version="2.7.0" List spring_boot =[ "org.springframework.boot:spring-boot-starter-web:$spring_boot_version", "org.springframework.boot:spring-boot-autoconfigure:$spring_boot_version", "org.springframework.boot:spring-boot-configuration-processor:$spring_boot_version", "org.springframework.boot:spring-boot-starter-data-jpa:$spring_boot_version", - "org.springframework.boot:spring-boot-starter-amqp:$spring_boot_version" + "org.springframework.boot:spring-boot-starter-amqp:$spring_boot_version", + "org.springframework.boot:spring-boot-starter-validation:$spring_boot_version" ] @@ -56,7 +57,7 @@ List swagger = [ ] -def log4j_version="2.15.0" +def log4j_version="2.18.0" List logger = [ "org.apache.logging.log4j:log4j-api:$log4j_version", "org.apache.logging.log4j:log4j-core:$log4j_version", @@ -71,12 +72,13 @@ List jaxb = [ "javax.activation:activation:1.1.1" ] -def jackson_version = "2.11.4" +def jackson_version = "2.14.1" List jackson = [ "com.fasterxml.jackson.core:jackson-annotations:$jackson_version", "com.fasterxml.jackson.core:jackson-core:$jackson_version", "com.fasterxml.jackson.core:jackson-databind:$jackson_version", - "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version", + "com.fasterxml.jackson.core:jackson-databind:$jackson_version" ] // cover old version @@ -96,7 +98,7 @@ List scaffold = [ ] dependencies { - compile spring,spring_boot,swagger,logger,jaxb,jackson,tomcat,scaffold + compile spring_boot,swagger,logger,jaxb,jackson,tomcat,scaffold compile 'org.fisco-bcos.java-sdk:fisco-bcos-java-sdk:2.7.2' // support guomi/ecdsa same time, support solcJ-0.5.2 compile 'org.fisco-bcos:solcJ:0.4.25-rc1' @@ -104,9 +106,9 @@ dependencies { compile 'org.fusesource:sigar:1.6.4' annotationProcessor 'org.projectlombok:lombok:1.18.6' compile 'org.projectlombok:lombok:1.18.6' - compile 'com.github.jsqlparser:jsqlparser:2.0' compile 'org.apache.commons:commons-lang3:3.8.1' compile 'org.slf4j:jcl-over-slf4j:1.7.30' + compile 'org.apache.httpcomponents:httpclient:4.5.14' // cover low version guava compile 'com.google.guava:guava:29.0-jre' testCompile('org.springframework.boot:spring-boot-starter-test') { diff --git a/src/main/java/com/webank/webase/front/abi/AbiController.java b/src/main/java/com/webank/webase/front/abi/AbiController.java index 2ac762c4a..c03ca63d7 100644 --- a/src/main/java/com/webank/webase/front/abi/AbiController.java +++ b/src/main/java/com/webank/webase/front/abi/AbiController.java @@ -61,8 +61,8 @@ public BasePageResponse getAbiListByGroupId(@PathVariable("groupId") Integer gro if (pageNumber < 1) { throw new FrontException(ConstantCode.PARAM_ERROR); } - Pageable pageable = new PageRequest(pageNumber - 1, pageSize, - new Sort(Sort.Direction.DESC, "createTime")); + Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, + Sort.by(Sort.Direction.DESC, "createTime")); resList = abiService.getListByGroupId(groupId, pageable); log.debug("end getAbiListByGroupId resList count. {}", resList.size()); diff --git a/src/main/java/com/webank/webase/front/abi/AbiService.java b/src/main/java/com/webank/webase/front/abi/AbiService.java index 4140a9989..bf18227bd 100644 --- a/src/main/java/com/webank/webase/front/abi/AbiService.java +++ b/src/main/java/com/webank/webase/front/abi/AbiService.java @@ -130,7 +130,7 @@ public void updateAbiInfo(ReqImportAbi param) { public void delete(Long id) { checkAbiIdExist(id); - abiRepository.delete(id); + abiRepository.deleteById(id); } public AbiInfo getAbiById(Long abiId) { diff --git a/src/main/java/com/webank/webase/front/base/config/TomcatConfig.java b/src/main/java/com/webank/webase/front/base/config/TomcatConfig.java index d34c78941..18eafbf49 100644 --- a/src/main/java/com/webank/webase/front/base/config/TomcatConfig.java +++ b/src/main/java/com/webank/webase/front/base/config/TomcatConfig.java @@ -1,26 +1,25 @@ -package com.webank.webase.front.base.config; - -import com.webank.webase.front.base.properties.Constants; -import org.apache.coyote.http11.Http11NioProtocol; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; -import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class TomcatConfig { - - @Autowired - Constants constantProperties; - @Bean - public EmbeddedServletContainerFactory createEmbeddedServletContainerFactory() { - TomcatEmbeddedServletContainerFactory tomcatFactory = new TomcatEmbeddedServletContainerFactory(); - tomcatFactory.addConnectorCustomizers(connector -> { - Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler(); - protocol.setKeepAliveTimeout(constantProperties.getKeepAliveTimeout()* 1000); - protocol.setMaxKeepAliveRequests(constantProperties.getKeepAliveRequests()); - }); - return tomcatFactory; - } -} +//package com.webank.webase.front.base.config; +// +//import com.webank.webase.front.base.properties.Constants; +//import org.apache.coyote.http11.Http11NioProtocol; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +// +//@Configuration +//public class TomcatConfig { +// +// @Autowired +// Constants constantProperties; +// @Bean +// public TomcatServletWebServerFactory createEmbeddedServletContainerFactory() { +// TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory(); +// tomcatFactory.addConnectorCustomizers(connector -> { +// Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler(); +// protocol.setKeepAliveTimeout(constantProperties.getKeepAliveTimeout()* 1000); +// protocol.setMaxKeepAliveRequests(constantProperties.getKeepAliveRequests()); +// }); +// return tomcatFactory; +// } +//} diff --git a/src/main/java/com/webank/webase/front/contract/ContractService.java b/src/main/java/com/webank/webase/front/contract/ContractService.java index da0c5d87d..9fb7262f1 100644 --- a/src/main/java/com/webank/webase/front/contract/ContractService.java +++ b/src/main/java/com/webank/webase/front/contract/ContractService.java @@ -43,7 +43,6 @@ import com.webank.webase.front.contract.entity.RspContractNoAbi; import com.webank.webase.front.contract.entity.RspMultiContractCompile; import com.webank.webase.front.keystore.KeyStoreService; -import com.webank.webase.front.precompiledapi.PrecompiledService; import com.webank.webase.front.precompiledapi.PrecompiledWithSignService; import com.webank.webase.front.precompiledapi.permission.PermissionManageService; import com.webank.webase.front.transaction.TransService; @@ -133,8 +132,8 @@ public class ContractService { private PermissionManageService permissionManageService; @Autowired private PrecompiledWithSignService precompiledWithSignService; - @Autowired - private PrecompiledService precompiledService; +// @Autowired +// private PrecompiledService precompiledService; @Autowired @Qualifier(value = "common") private CryptoSuite cryptoSuite; @@ -328,12 +327,12 @@ public void registerCns(ReqRegisterCns req) throws Exception { String version = req.getVersion(); String contractAddress = req.getContractAddress(); String abiInfo = JsonUtils.toJSONString(req.getAbiInfo()); - List cnsList = - precompiledService.queryCnsByNameAndVersion(groupId, cnsName, version); - if (!CollectionUtils.isEmpty(cnsList)) { - log.error("registerCns. cnsName:{} version:{} exists", cnsName, version); - throw new FrontException(ErrorCodeHandleUtils.PRECOMPILED_CONTRACT_NAME_VERSION_EXIST); - } +// List cnsList = +// precompiledService.queryCnsByNameAndVersion(groupId, cnsName, version); +// if (!CollectionUtils.isEmpty(cnsList)) { +// log.error("registerCns. cnsName:{} version:{} exists", cnsName, version); +// throw new FrontException(ErrorCodeHandleUtils.PRECOMPILED_CONTRACT_NAME_VERSION_EXIST); +// } // locally if (req.isSaveEnabled()) { if (StringUtils.isBlank(req.getContractPath())) { @@ -516,7 +515,7 @@ public void deleteContract(Long contractId, int groupId) { // check contract id verifyContractIdExist(contractId, groupId); // remove - contractRepository.delete(contractId); + contractRepository.deleteById(contractId); log.debug("end deleteContract"); } @@ -619,7 +618,7 @@ public Page findContractByPage(ReqPageContract param) throws IOExcepti // page start from index 1 instead of 0 int pageNumber = param.getPageNumber() - 1; Pageable pageable = - new PageRequest(pageNumber, param.getPageSize(), Direction.DESC, "modifyTime"); + PageRequest.of(pageNumber, param.getPageSize(), Direction.DESC, "modifyTime"); Page contractPage = contractRepository.findAll( (Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) -> { // v1.4.2, param add contractPath to filter @@ -867,7 +866,7 @@ public boolean accept(File dir, String fileName) { */ public ContractPath addContractPath(ReqContractPath req) { ContractPathKey pathKey = new ContractPathKey(req.getGroupId(), req.getContractPath()); - ContractPath check = contractPathRepository.findOne(pathKey); + ContractPath check = contractPathRepository.findById(pathKey).orElse(null); if (check != null) { log.error("addContractPath fail, path exists check:{}", check); throw new FrontException(ConstantCode.CONTRACT_PATH_IS_EXISTS); @@ -888,7 +887,7 @@ public List findPathList(Integer groupId) throws IOException { // init default contracts and dir initDefaultContract(groupId); // get from database - Sort sort = new Sort(Sort.Direction.DESC, "modifyTime"); + Sort sort = Sort.by(Sort.Direction.DESC, "modifyTime"); List contractPaths = contractPathRepository.findAll((Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) -> { Predicate predicate = criteriaBuilder.equal(root.get("groupId"), groupId); @@ -904,7 +903,7 @@ public void deletePath(Integer groupId, String contractPath) { ContractPathKey contractPathKey = new ContractPathKey(); contractPathKey.setGroupId(groupId); contractPathKey.setContractPath(contractPath); - contractPathRepository.delete(contractPathKey); + contractPathRepository.deleteById(contractPathKey); } /** @@ -943,14 +942,14 @@ public void batchDeleteByPath(int groupId, String contractPath) { List contractList = contractRepository.findByGroupIdAndContractPath(groupId, contractPath); log.debug("batchDeleteByPath delete contracts"); - contractList.forEach(c -> contractRepository.delete(c.getId())); + contractList.forEach(c -> contractRepository.deleteById(c.getId())); log.debug("batchDeleteByPath delete contracts"); - contractPathRepository.delete(new ContractPathKey(groupId, contractPath)); + contractPathRepository.deleteById(new ContractPathKey(groupId, contractPath)); log.debug("batchDeleteByPath delete contract path"); } public Contract findById(Long contractId) { - Contract contract = contractRepository.findOne(contractId); + Contract contract = contractRepository.findById(contractId).orElse(null); if (Objects.isNull(contract)) { throw new FrontException(ConstantCode.INVALID_CONTRACT_ID); } diff --git a/src/main/java/com/webank/webase/front/contractStore/PresetDataService.java b/src/main/java/com/webank/webase/front/contractStore/PresetDataService.java index ea807920f..10eb7ffee 100644 --- a/src/main/java/com/webank/webase/front/contractStore/PresetDataService.java +++ b/src/main/java/com/webank/webase/front/contractStore/PresetDataService.java @@ -17,6 +17,7 @@ import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; +import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import java.time.LocalDateTime; @@ -84,7 +85,7 @@ public void insertStoreItem(long storeId, String storeName, String StoreName_en, String StoreDetail_en) { log.info("insert storeItem id:{},storeName:{}", storeId, storeName); - if (contractStoreRepository.exists(storeId)) { + if (contractStoreRepository.existsById(storeId)) { log.info("insertStoreItem skip storeId:{} already exist", storeId); return; } @@ -155,7 +156,7 @@ public void insertContractFolderItem(long contractFolderId, long storeId, String String contractFolderDesc_en, String contractFolderDetail_en) { log.info("insert contractFolderItem id:{},contractFolderName:{} ", contractFolderId, contractFolderName); - if (contractFolderRepository.exists(contractFolderId)) { + if (contractFolderRepository.existsById(contractFolderId)) { log.info("insertContractFolderItem skip contractFolderId:{} already exist", contractFolderId); return; } @@ -289,7 +290,7 @@ public void insertContractItem(long contractId, long contractFolderId, String co String contractDesc, String contractDesc_en) { log.info("insert contractItem id:{},contractName:{}", contractId, contractName); - if (contractItemRepository.exists(contractId)) { + if (contractItemRepository.existsById(contractId)) { log.info("insertContractItem skip contractId:{} already exist", contractId); return; } @@ -327,13 +328,13 @@ public void readAndInitStoreItem() { } List item2Save = new ArrayList<>(); for (StoreItem item : storeItems) { - if (!contractStoreRepository.exists(item.getStoreId())) { + if (!contractStoreRepository.existsById(item.getStoreId())) { item.setCreateTime(LocalDateTime.now()); item.setModifyTime(item.getCreateTime()); item2Save.add(item); } } - contractStoreRepository.save(item2Save); + contractStoreRepository.saveAll(item2Save); log.info("readAndInitStoreItem save {} items", storeItems.size()); } @@ -346,13 +347,13 @@ public void readAndInitFolderItem() { } List item2Save = new ArrayList<>(); for (ContractFolderItem item : folderItems) { - if (!contractFolderRepository.exists(item.getContractFolderId())) { + if (!contractFolderRepository.existsById(item.getContractFolderId())) { item.setCreateTime(LocalDateTime.now()); item.setModifyTime(item.getCreateTime()); item2Save.add(item); } } - contractFolderRepository.save(item2Save); + contractFolderRepository.saveAll(item2Save); log.info("readAndInitFolderItem save {} items", folderItems.size()); } @@ -365,13 +366,13 @@ public void readAndInitContractItem() { } List item2Save = new ArrayList<>(); for (ContractItem item : contractItems) { - if (!contractItemRepository.exists(item.getContractId())) { + if (!contractItemRepository.existsById(item.getContractId())) { item.setCreateTime(LocalDateTime.now()); item.setModifyTime(item.getCreateTime()); item2Save.add(item); } } - contractItemRepository.save(item2Save); + contractItemRepository.exists((Specification) item2Save); log.info("readAndInitContractItem save {} items", contractItems.size()); } diff --git a/src/main/java/com/webank/webase/front/event/ContractEventInfoRepository.java b/src/main/java/com/webank/webase/front/event/ContractEventInfoRepository.java index e229115a8..8c61654bf 100644 --- a/src/main/java/com/webank/webase/front/event/ContractEventInfoRepository.java +++ b/src/main/java/com/webank/webase/front/event/ContractEventInfoRepository.java @@ -14,8 +14,6 @@ public interface ContractEventInfoRepository extends CrudRepository, JpaSpecificationExecutor { - ContractEventInfo findById(String id); - List findByAppId(String appId); List findByGroupId(int groupId); diff --git a/src/main/java/com/webank/webase/front/event/EventController.java b/src/main/java/com/webank/webase/front/event/EventController.java index 33aa65e5b..0a0056087 100644 --- a/src/main/java/com/webank/webase/front/event/EventController.java +++ b/src/main/java/com/webank/webase/front/event/EventController.java @@ -168,8 +168,8 @@ public BasePageResponse getNewBlockEventInfo(@PathVariable("groupId") Integer gr if (pageNumber < 1) { return new BasePageResponse(ConstantCode.PARAM_ERROR, null, 0); } - Pageable pageable = new PageRequest(pageNumber - 1, pageSize, - new Sort(Sort.Direction.DESC, "createTime")); + Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, + Sort.by(Sort.Direction.DESC, "createTime")); resList = eventService.getNewBlockInfoList(groupId, pageable); } log.debug("end getNewBlockEventInfo resList count. {}", resList.size()); @@ -227,8 +227,8 @@ public BasePageResponse getContractEventInfo(@PathVariable("groupId") Integer gr if (pageNumber < 1) { return new BasePageResponse(ConstantCode.PARAM_ERROR, null, 0); } - Pageable pageable = new PageRequest(pageNumber - 1, pageSize, - new Sort(Sort.Direction.DESC, "createTime")); + Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, + Sort.by(Sort.Direction.DESC, "createTime")); resList = eventService.getContractEventInfoList(groupId, pageable); } log.debug("end getContractEventInfo resList count. {}", resList.size()); diff --git a/src/main/java/com/webank/webase/front/event/EventService.java b/src/main/java/com/webank/webase/front/event/EventService.java index b1c30b1b7..c78214cba 100644 --- a/src/main/java/com/webank/webase/front/event/EventService.java +++ b/src/main/java/com/webank/webase/front/event/EventService.java @@ -295,7 +295,7 @@ public List unregisterNewBlock(String infoId, String appId, i String queueName) { log.debug("unregisterNewBlock appId:{},groupId:{},exchangeName:{},queueName:{}", appId, groupId, exchangeName, queueName); - NewBlockEventInfo eventInfo = newBlockEventInfoRepository.findById(infoId); + NewBlockEventInfo eventInfo = newBlockEventInfoRepository.findById(infoId).orElse(null);; if (Objects.isNull(eventInfo)) { throw new FrontException(ConstantCode.DATA_NOT_EXIST_ERROR); } @@ -310,7 +310,7 @@ public List unregisterNewBlock(String infoId, String appId, i throw new FrontException(ConstantCode.UNREGISTER_FAILED_ERROR); } // remove from db - newBlockEventInfoRepository.delete(infoId); + newBlockEventInfoRepository.deleteById(infoId); return newBlockEventInfoRepository.findByAppId(appId); } @@ -347,7 +347,7 @@ public List unregisterContractEvent(String infoId, String app String queueName) { log.debug("unregisterContractEvent infoId:{},appId:{},groupId:{},exchangeName:{},queueName:{}", infoId, appId, groupId, exchangeName, queueName); - ContractEventInfo eventInfo = contractEventInfoRepository.findById(infoId); + ContractEventInfo eventInfo = contractEventInfoRepository.findById(infoId).orElse(null);; if (Objects.isNull(eventInfo)) { throw new FrontException(ConstantCode.DATA_NOT_EXIST_ERROR); } @@ -367,7 +367,7 @@ public List unregisterContractEvent(String infoId, String app throw new FrontException(ConstantCode.UNREGISTER_FAILED_ERROR); } // remove from db - contractEventInfoRepository.delete(infoId); + contractEventInfoRepository.deleteById(infoId); return contractEventInfoRepository.findByAppId(appId); } diff --git a/src/main/java/com/webank/webase/front/event/NewBlockEventInfoRepository.java b/src/main/java/com/webank/webase/front/event/NewBlockEventInfoRepository.java index c73e8e502..354fe93a6 100644 --- a/src/main/java/com/webank/webase/front/event/NewBlockEventInfoRepository.java +++ b/src/main/java/com/webank/webase/front/event/NewBlockEventInfoRepository.java @@ -27,8 +27,6 @@ public interface NewBlockEventInfoRepository extends CrudRepository, JpaSpecificationExecutor { - NewBlockEventInfo findById(String id); - List findByGroupIdAndAppId(int groupId, String appId); List findByAppId(String appId); diff --git a/src/main/java/com/webank/webase/front/keystore/KeyStoreService.java b/src/main/java/com/webank/webase/front/keystore/KeyStoreService.java index 0d6ec2b6c..54c9ef4ca 100644 --- a/src/main/java/com/webank/webase/front/keystore/KeyStoreService.java +++ b/src/main/java/com/webank/webase/front/keystore/KeyStoreService.java @@ -100,7 +100,7 @@ public class KeyStoreService { * without external user */ public List getLocalKeyStoreList() { - Sort sort = new Sort(Sort.Direction.ASC, "userName"); + Sort sort = Sort.by(Sort.Direction.ASC, "userName"); List keyStores = keystoreRepository.findAll( (Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) -> { Predicate predicate = criteriaBuilder.equal(root.get("type"), KeyTypes.LOCALUSER.getValue()); @@ -179,7 +179,7 @@ private KeyStoreInfo saveSignKeyStore(RspUserInfo rspUserInfo) { * deleteKeyStore. */ public void deleteKeyStore(String address) { - keystoreRepository.delete(address); + keystoreRepository.deleteById(address); } /** diff --git a/src/main/java/com/webank/webase/front/logparse/LogParseService.java b/src/main/java/com/webank/webase/front/logparse/LogParseService.java index 20b84048c..a867c5a54 100644 --- a/src/main/java/com/webank/webase/front/logparse/LogParseService.java +++ b/src/main/java/com/webank/webase/front/logparse/LogParseService.java @@ -158,8 +158,8 @@ public synchronized void syncLogData() { public Page getNetWorkData(Integer groupId, Integer pageNumber, Integer pageSize, LocalDateTime beginDate, LocalDateTime endDate) { - Sort sort = new Sort(Sort.Direction.ASC, "id"); - Pageable pageable = new PageRequest(pageNumber - 1, pageSize, sort); + Sort sort = Sort.by(Sort.Direction.ASC, "id"); + Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort); Specification queryParam = new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, @@ -182,8 +182,8 @@ public Predicate toPredicate(Root root, CriteriaQuery criteriaQu public Page getTxGasData(int groupId, Integer pageNumber, Integer pageSize, LocalDateTime beginDate, LocalDateTime endDate, String transHash) { - Sort sort = new Sort(Sort.Direction.ASC, "id"); - Pageable pageable = new PageRequest(pageNumber - 1, pageSize, sort); + Sort sort = Sort.by(Sort.Direction.ASC, "id"); + Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort); Specification queryParam = new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, @@ -221,7 +221,7 @@ public int deleteData(int groupId, int type, LocalDateTime keepEndDate) { } private CurrentState getCurrentState() { - CurrentState currentState = currentStateRepository.findOne(1); + CurrentState currentState = currentStateRepository.findById(1).orElse(null); return currentState; } diff --git a/src/main/java/com/webank/webase/front/method/MethodService.java b/src/main/java/com/webank/webase/front/method/MethodService.java index 1909d266a..5e82d2011 100644 --- a/src/main/java/com/webank/webase/front/method/MethodService.java +++ b/src/main/java/com/webank/webase/front/method/MethodService.java @@ -54,6 +54,6 @@ public Method getByMethodId(String methodId, int groupId) { MethodKey pram = new MethodKey(); pram.setMethodId(methodId); pram.setGroupId(groupId); - return methodRepository.findOne(pram); + return methodRepository.findById(pram).orElse(null); } } diff --git a/src/main/java/com/webank/webase/front/monitor/MonitorService.java b/src/main/java/com/webank/webase/front/monitor/MonitorService.java index bb6ae015f..1fbf09e2a 100644 --- a/src/main/java/com/webank/webase/front/monitor/MonitorService.java +++ b/src/main/java/com/webank/webase/front/monitor/MonitorService.java @@ -93,7 +93,7 @@ public List findContrastDataByTime(int groupId, LocalDateTime s public Page pagingQuery(int groupId, Integer pageNumber, Integer pageSize, LocalDateTime beginDate, LocalDateTime endDate) { - Pageable pageable = new PageRequest(pageNumber - 1, pageSize); + Pageable pageable = PageRequest.of(pageNumber - 1, pageSize); Specification queryParam = (root, criteriaQuery, criteriaBuilder) -> { List predicates = new ArrayList<>(); predicates.add(criteriaBuilder.equal(root.get("groupId"), groupId)); @@ -269,8 +269,8 @@ public List getGroupSizeInfos() { public BasePageResponse pagingQueryStat(int groupId, Integer pageNumber, Integer pageSize, LocalDateTime beginDate, LocalDateTime endDate) { // get larger than endDate - Pageable pageableEnd = new PageRequest(pageNumber - 1, pageSize / 2, - new Sort(Direction.ASC, "id")); + Pageable pageableEnd = PageRequest.of(pageNumber - 1, pageSize / 2, + Sort.by(Direction.ASC, "id")); Specification queryEndParam = (root, criteriaQuery, criteriaBuilder) -> { List predicates = new ArrayList<>(); predicates.add(criteriaBuilder.equal(root.get("groupId"), groupId)); @@ -282,8 +282,8 @@ public BasePageResponse pagingQueryStat(int groupId, Integer pageNumber, Integer return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); }; // get less than beginDate - Pageable pageableBegin = new PageRequest(pageNumber - 1, pageSize / 2, - new Sort(Direction.DESC, "id")); + Pageable pageableBegin = PageRequest.of(pageNumber - 1, pageSize / 2, + Sort.by(Direction.DESC, "id")); Specification queryBeginParam = (root, criteriaQuery, criteriaBuilder) -> { List predicates = new ArrayList<>(); predicates.add(criteriaBuilder.equal(root.get("groupId"), groupId)); diff --git a/src/main/java/com/webank/webase/front/performance/PerformanceService.java b/src/main/java/com/webank/webase/front/performance/PerformanceService.java index ae8fd0d8a..52409bcb9 100644 --- a/src/main/java/com/webank/webase/front/performance/PerformanceService.java +++ b/src/main/java/com/webank/webase/front/performance/PerformanceService.java @@ -122,7 +122,7 @@ public List findContrastDataByTime(LocalDateTime startTime, public Page pagingQuery(Integer pageNumber, Integer pageSize, LocalDateTime beginDate, LocalDateTime endDate) { - Pageable pageable = new PageRequest(pageNumber - 1, pageSize); + Pageable pageable = PageRequest.of(pageNumber - 1, pageSize); Specification queryParam = new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, @@ -155,8 +155,8 @@ public Predicate toPredicate(Root root, CriteriaQuery criteriaQu public BasePageResponse pagingQueryStat(Integer pageNumber, Integer pageSize, LocalDateTime beginDate, LocalDateTime endDate) { // get larger than endDate - Pageable pageableEnd = new PageRequest(pageNumber - 1, - pageSize / 2, new Sort(Direction.ASC, "id")); + Pageable pageableEnd = PageRequest.of(pageNumber - 1, + pageSize / 2, Sort.by(Direction.ASC, "id")); Specification queryEndParam = (root, criteriaQuery, criteriaBuilder) -> { List predicates = new ArrayList<>(); if (endDate != null) { @@ -168,8 +168,8 @@ public BasePageResponse pagingQueryStat(Integer pageNumber, Integer pageSize, return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); }; // get less than beginDate - Pageable pageableBegin = new PageRequest(pageNumber - 1, - pageSize / 2, new Sort(Direction.DESC, "id")); + Pageable pageableBegin = PageRequest.of(pageNumber - 1, + pageSize / 2, Sort.by(Direction.DESC, "id")); Specification queryBeginParam = (root, criteriaQuery, criteriaBuilder) -> { List predicates = new ArrayList<>(); if (beginDate != null) { diff --git a/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledController.java b/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledController.java index 63496dab4..70aa6b1f3 100644 --- a/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledController.java +++ b/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledController.java @@ -1,734 +1,734 @@ -/* - * Copyright 2014-2020 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (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 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.webank.webase.front.precompiledapi; - -import com.webank.webase.front.base.code.ConstantCode; -import com.webank.webase.front.base.exception.FrontException; -import com.webank.webase.front.base.response.BasePageResponse; -import com.webank.webase.front.base.response.BaseResponse; -import com.webank.webase.front.precompiledapi.crud.CRUDParseUtils; -import com.webank.webase.front.precompiledapi.crud.Table; -import com.webank.webase.front.precompiledapi.entity.ConsensusHandle; -import com.webank.webase.front.precompiledapi.entity.ContractManageResult; -import com.webank.webase.front.precompiledapi.entity.ContractStatusHandle; -import com.webank.webase.front.precompiledapi.entity.CrudHandle; -import com.webank.webase.front.precompiledapi.entity.NodeInfo; -import com.webank.webase.front.util.JsonUtils; -import com.webank.webase.front.util.PrecompiledUtils; -import com.webank.webase.front.util.pageutils.List2Page; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiOperation; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import javax.validation.Valid; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.fisco.bcos.sdk.contract.precompiled.cns.CnsInfo; -import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; -import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; -import org.fisco.bcos.sdk.model.PrecompiledConstant; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * Precompiled common controller including management of CNS, node consensus status, CRUD - */ -@Api(value = "/precompiled", tags = "precompiled manage interface") -@Slf4j -@RestController -@RequestMapping(value = "precompiled") -public class PrecompiledController { - @Autowired - private PrecompiledService precompiledService; - - /** - * Cns manage - */ - @GetMapping("cns/list") - public Object queryCns(@RequestParam(defaultValue = "1") int groupId, - @RequestParam String contractNameAndVersion, - @RequestParam(defaultValue = "10") int pageSize, - @RequestParam(defaultValue = "1") int pageNumber) throws Exception { - Instant startTime = Instant.now(); - log.info("start queryCns. startTime:{}, groupId:{}, contractNameAndVersion:{}", - startTime.toEpochMilli(), groupId, contractNameAndVersion); - List resList = new ArrayList<>(); - // get "name:version" - String[] params = contractNameAndVersion.split(":"); - if (params.length == 1) { - String name = params[0]; - resList = precompiledService.queryCnsByName(groupId, name); - log.info("end queryCns useTime:{} resList:{}", - Duration.between(startTime, Instant.now()).toMillis(), resList); - if (resList.size() != 0) { - List2Page list2Page = - new List2Page(resList, pageSize, pageNumber); - List finalList = list2Page.getPagedList(); - long totalCount = (long) resList.size(); - log.debug("end queryCns. Contract Name finalList:{}", finalList); - return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); - } else { - return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); - } - } else if (params.length == 2) { - String name = params[0]; - String version = params[1]; - if (!PrecompiledUtils.checkVersion(version)) { - return ConstantCode.INVALID_VERSION; - } - // check return list size - resList = precompiledService.queryCnsByNameAndVersion(groupId, name, version); - log.info("end queryCns useTime:{} resList:{}", - Duration.between(startTime, Instant.now()).toMillis(), resList); - if (resList.size() != 0) { - List2Page list2Page = - new List2Page(resList, pageSize, pageNumber); - List finalList = list2Page.getPagedList(); - long totalCount = (long) resList.size(); - log.debug("in queryCns case: Contract Name And Version. finalList:{}", finalList); - return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); - } else { - return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); - } - } else { - return ConstantCode.PARAM_ERROR; - } - } - - - - /** - * Node manage (Consensus control) - */ - - @GetMapping("consensus/list") - public Object getNodeList(@RequestParam(defaultValue = "1") int groupId, - @RequestParam(defaultValue = "10") int pageSize, - @RequestParam(defaultValue = "1") int pageNumber) throws Exception { - Instant startTime = Instant.now(); - log.info("start getNodeList startTime:{}, groupId:{}", startTime.toEpochMilli(), groupId); - List resList = precompiledService.getNodeList(groupId); - log.info("end getNodeList useTime:{} resList:{}", - Duration.between(startTime, Instant.now()).toMillis(), resList); - if (resList.size() != 0) { - List2Page list2Page = new List2Page(resList, pageSize, pageNumber); - List finalList = list2Page.getPagedList(); - long totalCount = resList.size(); - log.debug("end getNodeList. finalList:{}", finalList); - return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); - } else { - return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); - } - } - - @ApiOperation(value = "nodeManageControl", notes = "set system config value by key") - @ApiImplicitParam(name = "consensusHandle", value = "node consensus status control", - required = true, dataType = "ConsensusHandle") - @PostMapping("consensus") - public Object nodeManageControl(@Valid @RequestBody ConsensusHandle consensusHandle) - throws Exception { - log.info("start nodeManageControl. consensusHandle:{}", consensusHandle); - String nodeType = consensusHandle.getNodeType(); - int groupId = consensusHandle.getGroupId(); - String from = consensusHandle.getSignUserId(); - String nodeId = consensusHandle.getNodeId(); - if (!PrecompiledUtils.checkNodeId(nodeId)) { - return ConstantCode.INVALID_NODE_ID; - } - switch (nodeType) { - case PrecompiledUtils.NODE_TYPE_SEALER: - return addSealer(groupId, from, nodeId); - case PrecompiledUtils.NODE_TYPE_OBSERVER: - return addObserver(groupId, from, nodeId); - case PrecompiledUtils.NODE_TYPE_REMOVE: - return removeNode(groupId, from, nodeId); - default: - log.debug("end nodeManageControl invalid node type"); - return ConstantCode.INVALID_NODE_TYPE; - } - } - - public Object addSealer(int groupId, String fromAddress, String nodeId) throws Exception { - Instant startTime = Instant.now(); - log.info("start addSealer startTime:{}, groupId:{},fromAddress:{},nodeId:{}", - startTime.toEpochMilli(), groupId, fromAddress, nodeId); - try { - Object res = precompiledService.addSealer(groupId, fromAddress, nodeId); - log.info("end addSealer useTime:{} res:{}", - Duration.between(startTime, Instant.now()).toMillis(), res); - return res; - } catch (Exception e) { - log.error("addSealer exception:[]", e); - return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); - } - } - - public Object addObserver(int groupId, String fromAddress, String nodeId) throws Exception { - Instant startTime = Instant.now(); - log.info("start addObserver startTime:{}, groupId:{},fromAddress:{},nodeId:{}", - startTime.toEpochMilli(), groupId, fromAddress, nodeId); - try { - Object res = precompiledService.addObserver(groupId, fromAddress, nodeId); - log.info("end addObserver useTime:{} res:{}", - Duration.between(startTime, Instant.now()).toMillis(), res); - return res; - } catch (Exception e) { - log.error("addObserver exception:[]", e); - return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); - } - } - - public Object removeNode(int groupId, String fromAddress, String nodeId) throws Exception { - Instant startTime = Instant.now(); - log.info("start addSealer startTime:{}, groupId:{},fromAddress:{},nodeId:{}", - startTime.toEpochMilli(), groupId, fromAddress, nodeId); - try { - Object res = precompiledService.removeNode(groupId, fromAddress, nodeId); - log.info("end addSealer useTime:{} res:{}", - Duration.between(startTime, Instant.now()).toMillis(), res); - return res; - } catch (Exception e) { // e.getCause - log.error("removeNode exception:[]", e); - return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); - } - } - - /** - * CRUD operation checkVersionForCRUD(); - * "bcos's version above of 2.0.0-rc3 support crud operation" - */ - @ApiOperation(value = "crudManage", notes = "operate table by crud") - @ApiImplicitParam(name = "crudHandle", value = "crud operation info", required = true, - dataType = "CrudHandle") - @PostMapping("crud") - public Object crudManageControl(@Valid @RequestBody CrudHandle crudHandle) throws Exception { - log.info("start crudManageControl. crudHandle:{}", crudHandle); - int groupId = crudHandle.getGroupId(); - String from = crudHandle.getSignUserId(); - String sql = crudHandle.getSql(); - // to lower case - String[] sqlParams = sql.trim().split(" "); - switch (sqlParams[0].toLowerCase()) { - case "create": - return createTable(groupId, from, sql); - case "desc": - return desc(groupId, sql); - case "select": - return select(groupId, sql); - case "insert": - return insert(groupId, from, sql); - case "update": - return update(groupId, from, sql); - case "delete": - return remove(groupId, from, sql); - default: - log.debug("end crudManageControl no such crud operation"); - return new BaseResponse(ConstantCode.PARAM_FAIL_SQL_ERROR, - "no such crud operation"); - } - } - - - public Object createTable(int groupId, String fromAddress, String sql) { - Instant startTime = Instant.now(); - log.info("start createTable startTime:{}, groupId:{},fromAddress:{},sql:{}", - startTime.toEpochMilli(), groupId, fromAddress, sql); - Table table = new Table(); - try { - log.debug("start parseCreateTable."); - CRUDParseUtils.parseCreateTable(sql, table); - log.debug("end parseCreateTable. table:{}, key:{}, keyField:{}, values:{}", - table.getTableName(), table.getKey(), table.getKeyFieldName(), table.getValueFields()); - } catch (Exception e) { - log.error("parseCreateTable. table:{},exception:{}", table, e); - CRUDParseUtils.invalidSymbol(sql); - return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, - "Could not parse SQL statement."); - } - // CRUDParseUtils.checkTableParams(table); - String result = precompiledService.createTable(groupId, fromAddress, table); - log.info("end createTable useTime:{} res:{}", - Duration.between(startTime, Instant.now()).toMillis(), result); - return result; - - } - - // check table name exist by desc(tableName) - public Object desc(int groupId, String sql) { - Instant startTime = Instant.now(); - log.info("start descTable startTime:{}, groupId:{},sql:{}", startTime.toEpochMilli(), - groupId, sql); - String[] sqlParams = sql.split(" "); - // "desc t_demo" - String tableName = sqlParams[1]; - - if (tableName.length() > PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH) { - return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, - "The table name length is greater than " - + PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH + ".", - "The table name length is greater than " - + PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH + "."); - } - CRUDParseUtils.invalidSymbol(tableName); - if (tableName.endsWith(";")) { - tableName = tableName.substring(0, tableName.length() - 1); - } - try { - List> table = precompiledService.desc(groupId, tableName); - log.info("end descTable useTime:{} res:{}", - Duration.between(startTime, Instant.now()).toMillis(), table); - return new BaseResponse(ConstantCode.RET_SUCCESS, table); - } catch (Exception e) { - log.error("descTable.exception:[] ", e); - return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, e.getMessage()); - } - } - - public Object select(int groupId, String sql) throws Exception { - Instant startTime = Instant.now(); - log.info("start select startTime:{}, groupId:{},sql:{}", startTime.toEpochMilli(), groupId, - sql); - Table table = new Table(); - Condition conditions = new Condition(); - List selectColumns = new ArrayList<>(); - - try { // 转化select语句 - log.debug("start parseSelect. sql:{}", sql); - CRUDParseUtils.parseSelect(sql, table, conditions, selectColumns); - log.debug("end parseSelect. table:{}, conditions:{}, selectColumns:{}", table, - conditions, selectColumns); - } catch (Exception e) { - log.error("parseSelect Error exception:[]", e); - CRUDParseUtils.invalidSymbol(sql); - return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); - } - - List> descTable = null; - try { - descTable = precompiledService.desc(groupId, table.getTableName()); - } catch (Exception e) { - log.error("select in descTable Error exception:[]", e); - return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists "); - } - String keyField = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); - table.setKey(keyField); - CRUDParseUtils.handleKey(table, conditions); -// String fields = descTable.getKey() + "," + descTable.getValueFields(); -// List fieldsList = Arrays.asList(fields.split(",")); -// for (String column : selectColumns) { -// if (!fieldsList.contains(column) && !"*".equals(column)) { -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -// "Unknown field '" + column + "' in field list.", -// "Unknown field '" + column + "' in field list."); +///* +// * Copyright 2014-2020 the original author or authors. +// * +// * Licensed under the Apache License, Version 2.0 (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 +// * +// * Unless required by applicable law or agreed to in writing, software distributed under the License +// * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +// * or implied. See the License for the specific language governing permissions and limitations under +// * the License. +// */ +//package com.webank.webase.front.precompiledapi; +// +//import com.webank.webase.front.base.code.ConstantCode; +//import com.webank.webase.front.base.exception.FrontException; +//import com.webank.webase.front.base.response.BasePageResponse; +//import com.webank.webase.front.base.response.BaseResponse; +//import com.webank.webase.front.precompiledapi.crud.CRUDParseUtils; +//import com.webank.webase.front.precompiledapi.crud.Table; +//import com.webank.webase.front.precompiledapi.entity.ConsensusHandle; +//import com.webank.webase.front.precompiledapi.entity.ContractManageResult; +//import com.webank.webase.front.precompiledapi.entity.ContractStatusHandle; +//import com.webank.webase.front.precompiledapi.entity.CrudHandle; +//import com.webank.webase.front.precompiledapi.entity.NodeInfo; +//import com.webank.webase.front.util.JsonUtils; +//import com.webank.webase.front.util.PrecompiledUtils; +//import com.webank.webase.front.util.pageutils.List2Page; +//import io.swagger.annotations.Api; +//import io.swagger.annotations.ApiImplicitParam; +//import io.swagger.annotations.ApiOperation; +//import java.time.Duration; +//import java.time.Instant; +//import java.util.ArrayList; +//import java.util.Arrays; +//import java.util.List; +//import java.util.Map; +//import javax.validation.Valid; +//import lombok.extern.slf4j.Slf4j; +//import org.apache.commons.lang3.StringUtils; +//import org.fisco.bcos.sdk.contract.precompiled.cns.CnsInfo; +//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; +//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; +//import org.fisco.bcos.sdk.model.PrecompiledConstant; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.web.bind.annotation.GetMapping; +//import org.springframework.web.bind.annotation.PostMapping; +//import org.springframework.web.bind.annotation.RequestBody; +//import org.springframework.web.bind.annotation.RequestMapping; +//import org.springframework.web.bind.annotation.RequestParam; +//import org.springframework.web.bind.annotation.RestController; +// +///** +// * Precompiled common controller including management of CNS, node consensus status, CRUD +// */ +//@Api(value = "/precompiled", tags = "precompiled manage interface") +//@Slf4j +//@RestController +//@RequestMapping(value = "precompiled") +//public class PrecompiledController { +// @Autowired +// private PrecompiledService precompiledService; +// +// /** +// * Cns manage +// */ +// @GetMapping("cns/list") +// public Object queryCns(@RequestParam(defaultValue = "1") int groupId, +// @RequestParam String contractNameAndVersion, +// @RequestParam(defaultValue = "10") int pageSize, +// @RequestParam(defaultValue = "1") int pageNumber) throws Exception { +// Instant startTime = Instant.now(); +// log.info("start queryCns. startTime:{}, groupId:{}, contractNameAndVersion:{}", +// startTime.toEpochMilli(), groupId, contractNameAndVersion); +// List resList = new ArrayList<>(); +// // get "name:version" +// String[] params = contractNameAndVersion.split(":"); +// if (params.length == 1) { +// String name = params[0]; +// resList = precompiledService.queryCnsByName(groupId, name); +// log.info("end queryCns useTime:{} resList:{}", +// Duration.between(startTime, Instant.now()).toMillis(), resList); +// if (resList.size() != 0) { +// List2Page list2Page = +// new List2Page(resList, pageSize, pageNumber); +// List finalList = list2Page.getPagedList(); +// long totalCount = (long) resList.size(); +// log.debug("end queryCns. Contract Name finalList:{}", finalList); +// return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); +// } else { +// return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); +// } +// } else if (params.length == 2) { +// String name = params[0]; +// String version = params[1]; +// if (!PrecompiledUtils.checkVersion(version)) { +// return ConstantCode.INVALID_VERSION; +// } +// // check return list size +// resList = precompiledService.queryCnsByNameAndVersion(groupId, name, version); +// log.info("end queryCns useTime:{} resList:{}", +// Duration.between(startTime, Instant.now()).toMillis(), resList); +// if (resList.size() != 0) { +// List2Page list2Page = +// new List2Page(resList, pageSize, pageNumber); +// List finalList = list2Page.getPagedList(); +// long totalCount = (long) resList.size(); +// log.debug("in queryCns case: Contract Name And Version. finalList:{}", finalList); +// return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); +// } else { +// return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); // } +// } else { +// return ConstantCode.PARAM_ERROR; +// } +// } +// +// +// +// /** +// * Node manage (Consensus control) +// */ +// +// @GetMapping("consensus/list") +// public Object getNodeList(@RequestParam(defaultValue = "1") int groupId, +// @RequestParam(defaultValue = "10") int pageSize, +// @RequestParam(defaultValue = "1") int pageNumber) throws Exception { +// Instant startTime = Instant.now(); +// log.info("start getNodeList startTime:{}, groupId:{}", startTime.toEpochMilli(), groupId); +// List resList = precompiledService.getNodeList(groupId); +// log.info("end getNodeList useTime:{} resList:{}", +// Duration.between(startTime, Instant.now()).toMillis(), resList); +// if (resList.size() != 0) { +// List2Page list2Page = new List2Page(resList, pageSize, pageNumber); +// List finalList = list2Page.getPagedList(); +// long totalCount = resList.size(); +// log.debug("end getNodeList. finalList:{}", finalList); +// return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); +// } else { +// return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); +// } +// } +// +// @ApiOperation(value = "nodeManageControl", notes = "set system config value by key") +// @ApiImplicitParam(name = "consensusHandle", value = "node consensus status control", +// required = true, dataType = "ConsensusHandle") +// @PostMapping("consensus") +// public Object nodeManageControl(@Valid @RequestBody ConsensusHandle consensusHandle) +// throws Exception { +// log.info("start nodeManageControl. consensusHandle:{}", consensusHandle); +// String nodeType = consensusHandle.getNodeType(); +// int groupId = consensusHandle.getGroupId(); +// String from = consensusHandle.getSignUserId(); +// String nodeId = consensusHandle.getNodeId(); +// if (!PrecompiledUtils.checkNodeId(nodeId)) { +// return ConstantCode.INVALID_NODE_ID; +// } +// switch (nodeType) { +// case PrecompiledUtils.NODE_TYPE_SEALER: +// return addSealer(groupId, from, nodeId); +// case PrecompiledUtils.NODE_TYPE_OBSERVER: +// return addObserver(groupId, from, nodeId); +// case PrecompiledUtils.NODE_TYPE_REMOVE: +// return removeNode(groupId, from, nodeId); +// default: +// log.debug("end nodeManageControl invalid node type"); +// return ConstantCode.INVALID_NODE_TYPE; +// } +// } +// +// public Object addSealer(int groupId, String fromAddress, String nodeId) throws Exception { +// Instant startTime = Instant.now(); +// log.info("start addSealer startTime:{}, groupId:{},fromAddress:{},nodeId:{}", +// startTime.toEpochMilli(), groupId, fromAddress, nodeId); +// try { +// Object res = precompiledService.addSealer(groupId, fromAddress, nodeId); +// log.info("end addSealer useTime:{} res:{}", +// Duration.between(startTime, Instant.now()).toMillis(), res); +// return res; +// } catch (Exception e) { +// log.error("addSealer exception:[]", e); +// return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); +// } +// } +// +// public Object addObserver(int groupId, String fromAddress, String nodeId) throws Exception { +// Instant startTime = Instant.now(); +// log.info("start addObserver startTime:{}, groupId:{},fromAddress:{},nodeId:{}", +// startTime.toEpochMilli(), groupId, fromAddress, nodeId); +// try { +// Object res = precompiledService.addObserver(groupId, fromAddress, nodeId); +// log.info("end addObserver useTime:{} res:{}", +// Duration.between(startTime, Instant.now()).toMillis(), res); +// return res; +// } catch (Exception e) { +// log.error("addObserver exception:[]", e); +// return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); +// } +// } +// +// public Object removeNode(int groupId, String fromAddress, String nodeId) throws Exception { +// Instant startTime = Instant.now(); +// log.info("start addSealer startTime:{}, groupId:{},fromAddress:{},nodeId:{}", +// startTime.toEpochMilli(), groupId, fromAddress, nodeId); +// try { +// Object res = precompiledService.removeNode(groupId, fromAddress, nodeId); +// log.info("end addSealer useTime:{} res:{}", +// Duration.between(startTime, Instant.now()).toMillis(), res); +// return res; +// } catch (Exception e) { // e.getCause +// log.error("removeNode exception:[]", e); +// return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); +// } +// } +// +// /** +// * CRUD operation checkVersionForCRUD(); +// * "bcos's version above of 2.0.0-rc3 support crud operation" +// */ +// @ApiOperation(value = "crudManage", notes = "operate table by crud") +// @ApiImplicitParam(name = "crudHandle", value = "crud operation info", required = true, +// dataType = "CrudHandle") +// @PostMapping("crud") +// public Object crudManageControl(@Valid @RequestBody CrudHandle crudHandle) throws Exception { +// log.info("start crudManageControl. crudHandle:{}", crudHandle); +// int groupId = crudHandle.getGroupId(); +// String from = crudHandle.getSignUserId(); +// String sql = crudHandle.getSql(); +// // to lower case +// String[] sqlParams = sql.trim().split(" "); +// switch (sqlParams[0].toLowerCase()) { +// case "create": +// return createTable(groupId, from, sql); +// case "desc": +// return desc(groupId, sql); +// case "select": +// return select(groupId, sql); +// case "insert": +// return insert(groupId, from, sql); +// case "update": +// return update(groupId, from, sql); +// case "delete": +// return remove(groupId, from, sql); +// default: +// log.debug("end crudManageControl no such crud operation"); +// return new BaseResponse(ConstantCode.PARAM_FAIL_SQL_ERROR, +// "no such crud operation"); +// } +// } +// +// +// public Object createTable(int groupId, String fromAddress, String sql) { +// Instant startTime = Instant.now(); +// log.info("start createTable startTime:{}, groupId:{},fromAddress:{},sql:{}", +// startTime.toEpochMilli(), groupId, fromAddress, sql); +// Table table = new Table(); +// try { +// log.debug("start parseCreateTable."); +// CRUDParseUtils.parseCreateTable(sql, table); +// log.debug("end parseCreateTable. table:{}, key:{}, keyField:{}, values:{}", +// table.getTableName(), table.getKey(), table.getKeyFieldName(), table.getValueFields()); +// } catch (Exception e) { +// log.error("parseCreateTable. table:{},exception:{}", table, e); +// CRUDParseUtils.invalidSymbol(sql); +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +// "Could not parse SQL statement."); +// } +// // CRUDParseUtils.checkTableParams(table); +// String result = precompiledService.createTable(groupId, fromAddress, table); +// log.info("end createTable useTime:{} res:{}", +// Duration.between(startTime, Instant.now()).toMillis(), result); +// return result; +// +// } +// +// // check table name exist by desc(tableName) +// public Object desc(int groupId, String sql) { +// Instant startTime = Instant.now(); +// log.info("start descTable startTime:{}, groupId:{},sql:{}", startTime.toEpochMilli(), +// groupId, sql); +// String[] sqlParams = sql.split(" "); +// // "desc t_demo" +// String tableName = sqlParams[1]; +// +// if (tableName.length() > PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH) { +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +// "The table name length is greater than " +// + PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH + ".", +// "The table name length is greater than " +// + PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH + "."); +// } +// CRUDParseUtils.invalidSymbol(tableName); +// if (tableName.endsWith(";")) { +// tableName = tableName.substring(0, tableName.length() - 1); +// } +// try { +// List> table = precompiledService.desc(groupId, tableName); +// log.info("end descTable useTime:{} res:{}", +// Duration.between(startTime, Instant.now()).toMillis(), table); +// return new BaseResponse(ConstantCode.RET_SUCCESS, table); +// } catch (Exception e) { +// log.error("descTable.exception:[] ", e); +// return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, e.getMessage()); +// } +// } +// +// public Object select(int groupId, String sql) throws Exception { +// Instant startTime = Instant.now(); +// log.info("start select startTime:{}, groupId:{},sql:{}", startTime.toEpochMilli(), groupId, +// sql); +// Table table = new Table(); +// Condition conditions = new Condition(); +// List selectColumns = new ArrayList<>(); +// +// try { // 转化select语句 +// log.debug("start parseSelect. sql:{}", sql); +// CRUDParseUtils.parseSelect(sql, table, conditions, selectColumns); +// log.debug("end parseSelect. table:{}, conditions:{}, selectColumns:{}", table, +// conditions, selectColumns); +// } catch (Exception e) { +// log.error("parseSelect Error exception:[]", e); +// CRUDParseUtils.invalidSymbol(sql); +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); +// } +// +// List> descTable = null; +// try { +// descTable = precompiledService.desc(groupId, table.getTableName()); +// } catch (Exception e) { +// log.error("select in descTable Error exception:[]", e); +// return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists "); // } - - List> result = precompiledService.select(groupId, table, conditions); - log.info("end select useTime:{} res:{}", - Duration.between(startTime, Instant.now()).toMillis(), result); - if (result.size() == 0) { - return new BaseResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, - ConstantCode.CRUD_EMPTY_SET); - } - result = CRUDParseUtils.filterSystemColum(result); - if ("*".equals(selectColumns.get(0))) { - selectColumns.clear(); - selectColumns.add(keyField); - String[] valueArr = descTable.get(0).get(PrecompiledConstant.VALUE_FIELD_NAME).split(","); - selectColumns.addAll(Arrays.asList(valueArr)); - result = CRUDParseUtils.getSelectedColumn(selectColumns, result); - log.info("end select. result:{}", result); - return new BaseResponse(ConstantCode.RET_SUCCESS, result); - } else { - List> selectedResult = - CRUDParseUtils.getSelectedColumn(selectColumns, result); - log.info("end select. selectedResult:{}", selectedResult); - return new BaseResponse(ConstantCode.RET_SUCCESS, selectedResult); - } - - } - - public Object insert(int groupId, String fromAddress, String sql) throws Exception { - Instant startTime = Instant.now(); - log.info("start insert startTime:{}, groupId:{},fromAddress:{},sql:{}", - startTime.toEpochMilli(), groupId, fromAddress, sql); - Table table = new Table(); - Entry entry = new Entry(); - List> descTable = null; - - String tableName = CRUDParseUtils.parseInsertedTableName(sql); - descTable = precompiledService.desc(groupId, tableName); - log.debug( - "insert, tableName: {}, descTable: {}", tableName, descTable.get(0).toString()); - CRUDParseUtils.parseInsert(sql, table, entry, descTable.get(0)); - String keyName = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); - String keyValue = entry.getFieldNameToValue().get(keyName); - log.debug( - "fieldNameToValue: {}, keyName: {}, keyValue: {}", entry.getFieldNameToValue(), keyName, keyValue); - if (keyValue == null) { - log.error("Please insert the key field '" + keyName + "'."); - throw new FrontException("Please insert the key field '" + keyName + "'."); - } - // table primary key - table.setKey(keyValue); - String insertResult = - precompiledService.insert(groupId, fromAddress, table, entry); - return insertResult; -// if (insertResult >= 0) { -// log.info("Insert OK: {}", insertResult); -// return new BaseResponse(insertResult, insertResult + " row affected."); +// String keyField = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); +// table.setKey(keyField); +// CRUDParseUtils.handleKey(table, conditions); +//// String fields = descTable.getKey() + "," + descTable.getValueFields(); +//// List fieldsList = Arrays.asList(fields.split(",")); +//// for (String column : selectColumns) { +//// if (!fieldsList.contains(column) && !"*".equals(column)) { +//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +//// "Unknown field '" + column + "' in field list.", +//// "Unknown field '" + column + "' in field list."); +//// } +//// } +// +// List> result = precompiledService.select(groupId, table, conditions); +// log.info("end select useTime:{} res:{}", +// Duration.between(startTime, Instant.now()).toMillis(), result); +// if (result.size() == 0) { +// return new BaseResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, +// ConstantCode.CRUD_EMPTY_SET); +// } +// result = CRUDParseUtils.filterSystemColum(result); +// if ("*".equals(selectColumns.get(0))) { +// selectColumns.clear(); +// selectColumns.add(keyField); +// String[] valueArr = descTable.get(0).get(PrecompiledConstant.VALUE_FIELD_NAME).split(","); +// selectColumns.addAll(Arrays.asList(valueArr)); +// result = CRUDParseUtils.getSelectedColumn(selectColumns, result); +// log.info("end select. result:{}", result); +// return new BaseResponse(ConstantCode.RET_SUCCESS, result); // } else { -// log.info("Result of insert for " + table.getTableName() + ":"); -// return new BaseResponse(insertResult, "insert failed!"); +// List> selectedResult = +// CRUDParseUtils.getSelectedColumn(selectColumns, result); +// log.info("end select. selectedResult:{}", selectedResult); +// return new BaseResponse(ConstantCode.RET_SUCCESS, selectedResult); +// } +// +// } +// +// public Object insert(int groupId, String fromAddress, String sql) throws Exception { +// Instant startTime = Instant.now(); +// log.info("start insert startTime:{}, groupId:{},fromAddress:{},sql:{}", +// startTime.toEpochMilli(), groupId, fromAddress, sql); +// Table table = new Table(); +// Entry entry = new Entry(); +// List> descTable = null; +// +// String tableName = CRUDParseUtils.parseInsertedTableName(sql); +// descTable = precompiledService.desc(groupId, tableName); +// log.debug( +// "insert, tableName: {}, descTable: {}", tableName, descTable.get(0).toString()); +// CRUDParseUtils.parseInsert(sql, table, entry, descTable.get(0)); +// String keyName = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); +// String keyValue = entry.getFieldNameToValue().get(keyName); +// log.debug( +// "fieldNameToValue: {}, keyName: {}, keyValue: {}", entry.getFieldNameToValue(), keyName, keyValue); +// if (keyValue == null) { +// log.error("Please insert the key field '" + keyName + "'."); +// throw new FrontException("Please insert the key field '" + keyName + "'."); // } - } +// // table primary key +// table.setKey(keyValue); +// String insertResult = +// precompiledService.insert(groupId, fromAddress, table, entry); +// return insertResult; +//// if (insertResult >= 0) { +//// log.info("Insert OK: {}", insertResult); +//// return new BaseResponse(insertResult, insertResult + " row affected."); +//// } else { +//// log.info("Result of insert for " + table.getTableName() + ":"); +//// return new BaseResponse(insertResult, "insert failed!"); +//// } +// } +//// Table table = new Table(); +//// Entry entry = new Entry(); +//// +//// // insert sql use "values" or not +//// boolean useValues = false; +//// try { +//// log.debug("start parseInsert. sql:{}", sql); +//// useValues = CRUDParseUtils.parseInsert(sql, table, entry); +//// log.debug("end parseInsert. table:{}, entry:{}", table, entry); +//// } catch (Exception e) { +//// log.error("parseInsert Error exception:[]", e); +//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +//// "Could not parse SQL statement." + CRUDParseUtils.invalidSymbol(sql), +//// "Could not parse SQL statement." + CRUDParseUtils.invalidSymbol(sql)); +//// } +//// +//// String tableName = table.getTableName(); +//// Table descTable; +//// try { +//// descTable = precompiledService.desc(groupId, tableName); +//// } catch (Exception e) { +//// log.error("insertTable Error exception:[]", e); +//// return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); +//// } +//// String keyName = descTable.getKey(); +//// String fields = keyName + "," + descTable.getValueFields(); +//// +//// List fieldsList = Arrays.asList(fields.split(",")); +//// Set entryFields = entry.getFieldNameToValue().keySet(); +//// +//// // ex: insert into t_test values (fruit, 1, apple) +//// if (useValues) { +//// if (entry.getFieldNameToValue().size() != fieldsList.size()) { +//// log.error("field value size not equal to field size"); +//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +//// "Column count doesn't match value count.", +//// "Column count doesn't match value count."); +//// } else { +//// Entry entryValue = table.getEntry(); +//// for (int i = 0; i < entry.getFieldNameToValue().size(); i++) { +//// for (String entryField : entryFields) { +//// if ((i + "").equals(entryField)) { +//// Map map = new HashMap<>(); +//// map.put(fieldsList.get(i), entry.getFieldNameToValue().get(i + "")); +//// entryValue.setFieldNameToValue(map); +//// if (keyName.equals(fieldsList.get(i))) { +//// table.setKey(entry.getFieldNameToValue().get(i + "")); +//// } +//// } +//// } +//// } +//// entry = entryValue; +//// } +//// } +//// // ex: insert into t_test (name, item_id, item_name) values (fruit, 1, apple) +//// else { +//// for (String entryField : entryFields) { +//// if (!fieldsList.contains(entryField)) { +//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +//// "Unknown field '" + entryField + "' in field list.", +//// "Unknown field '" + entryField + "' in field list."); +//// } +//// if (fieldsList.size() != entryFields.size()) { +//// List listString = new ArrayList(fieldsList); +//// for (String entryItem : entryFields) { +//// listString.remove(entryItem); +//// } +//// StringBuilder strBuilder = new StringBuilder("Please provide field '"); +//// for (int i = 0; i < listString.size(); i++) { +//// if (i == listString.size() - 1) { +//// strBuilder.append(listString.get(i)).append("' "); +//// } else { +//// strBuilder.append(listString.get(i)).append("', '"); +//// } +//// } +//// strBuilder.append("in field list."); +//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, strBuilder.toString(), +//// strBuilder.toString()); +//// } +//// } +//// String keyValue = entry.getFieldNameToValue().get(keyName); +//// if (keyValue == null) { +//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +//// "Column count doesn't match value count.", +//// "Column count doesn't match value count."); +//// } +//// table.setKey(keyValue); +//// } +//// CRUDParseUtils.checkUserTableParam(entry, descTable); +//// int insertResult = precompiledService.insert(groupId, fromAddress, table, entry); +//// log.info("end insert useTime:{} insertResult:{}", +//// Duration.between(startTime, Instant.now()).toMillis(), insertResult); +//// if (insertResult >= 0) { +//// return new BaseResponse(ConstantCode.RET_SUCCESS, +//// "Insert OK, " + insertResult + " row(s) affected."); +//// } else { +//// return new BaseResponse(insertResult, "Insert failed."); +//// } +// +// public Object update(int groupId, String fromAddress, String sql) throws Exception { +// Instant startTime = Instant.now(); +// log.info("start update startTime:{}, groupId:{},fromAddress:{},sql:{}", +// startTime.toEpochMilli(), groupId, fromAddress, sql); // Table table = new Table(); // Entry entry = new Entry(); +// Condition conditions = new Condition(); // -// // insert sql use "values" or not -// boolean useValues = false; // try { -// log.debug("start parseInsert. sql:{}", sql); -// useValues = CRUDParseUtils.parseInsert(sql, table, entry); -// log.debug("end parseInsert. table:{}, entry:{}", table, entry); +// log.debug("start parseUpdate. sql:{}", sql); +// CRUDParseUtils.parseUpdate(sql, table, entry, conditions); +// log.debug("end parseUpdate. table:{}, entry:{}, conditions:{}", table, entry, +// conditions); // } catch (Exception e) { -// log.error("parseInsert Error exception:[]", e); -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -// "Could not parse SQL statement." + CRUDParseUtils.invalidSymbol(sql), -// "Could not parse SQL statement." + CRUDParseUtils.invalidSymbol(sql)); +// log.error("parseUpdate error exception:[]", e); +// CRUDParseUtils.invalidSymbol(sql); +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); // } // // String tableName = table.getTableName(); -// Table descTable; +// List> descTable = null; // try { // descTable = precompiledService.desc(groupId, tableName); // } catch (Exception e) { -// log.error("insertTable Error exception:[]", e); +// log.error("updateTable Error exception:[]", e); +// return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); +// } +// +// String keyName = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); +// if (entry.getFieldNameToValue().containsKey(keyName)) { +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +// "Please don't set the key field '" + keyName + "'.", +// "Please don't set the key field '" + keyName + "'."); +// } +// table.setKey(keyName); +// CRUDParseUtils.handleKey(table, conditions); +// String updateResult = precompiledService.update(groupId, fromAddress, table, entry, conditions); +// log.info("end update useTime:{} updateResult:{}", +// Duration.between(startTime, Instant.now()).toMillis(), updateResult); +// return updateResult; +// } +// +// public Object remove(int groupId, String fromAddress, String sql) { +// Instant startTime = Instant.now(); +// log.info("start remove startTime:{}, groupId:{},fromAddress:{},sql:{}", +// startTime.toEpochMilli(), groupId, fromAddress, sql); +// Table table = new Table(); +// Condition conditions = new Condition(); +// +// try { +// log.debug("start parseRemove. sql:{}", sql); +// CRUDParseUtils.parseRemove(sql, table, conditions); +// log.debug("end parseRemove. table:{}, conditions:{}", table, conditions); +// } catch (Exception e) { +// log.error("parseRemove Error exception:[]", e); +// CRUDParseUtils.invalidSymbol(sql); +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); +// } +// +// List> descTable = null; +// try { +// descTable = precompiledService.desc(groupId, table.getTableName()); +// } catch (Exception e) { +// log.error("removeTable Error exception:[]", e); // return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); // } -// String keyName = descTable.getKey(); -// String fields = keyName + "," + descTable.getValueFields(); -// -// List fieldsList = Arrays.asList(fields.split(",")); -// Set entryFields = entry.getFieldNameToValue().keySet(); -// -// // ex: insert into t_test values (fruit, 1, apple) -// if (useValues) { -// if (entry.getFieldNameToValue().size() != fieldsList.size()) { -// log.error("field value size not equal to field size"); -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -// "Column count doesn't match value count.", -// "Column count doesn't match value count."); +// table.setKey(descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME)); +// CRUDParseUtils.handleKey(table, conditions); +// String removeResult = precompiledService.remove(groupId, fromAddress, table, conditions); +// log.info("end remove useTime:{} removeResult:{}", +// Duration.between(startTime, Instant.now()).toMillis(), removeResult); +// return removeResult; +// +// } +// +// @ApiOperation(value = "contractStatusManage", notes = "contract status manage") +// @PostMapping("contractStatusManage") +// public Object contractStatusManage( +// @Valid @RequestBody ContractStatusHandle contractStatusHandle) throws Exception { +// log.debug("start contractStatusManage. contractStatusHandle:{}", contractStatusHandle); +// switch (contractStatusHandle.getHandleType()) { +// case PrecompiledUtils.CONTRACT_MANAGE_FREEZE: +// return contractFreeze(contractStatusHandle); +// case PrecompiledUtils.CONTRACT_MANAGE_UNFREEZE: +// return contractUnfreeze(contractStatusHandle); +// case PrecompiledUtils.CONTRACT_MANAGE_GRANTMANAGER: +// return contractGrantManager(contractStatusHandle); +// case PrecompiledUtils.CONTRACT_MANAGE_GETSTATUS: +// return contractStatus(contractStatusHandle); +// case PrecompiledUtils.CONTRACT_MANAGE_LISTMANAGER: +// return contractManagerList(contractStatusHandle); +// default: +// log.error("end contractStatusManage. invalid contract handle type"); +// throw new FrontException(ConstantCode.INVALID_CONTRACT_HANDLE_TYPE); +// } +// } +// +// private Object contractFreeze(ContractStatusHandle contractStatusHandle) { +// Instant startTime = Instant.now(); +// log.info("start contractFreeze startTime:{}", startTime.toEpochMilli()); +// try { +// if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { +// log.error("signUserId is empty"); +// throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); +// } +// String res = precompiledService.contractFreeze(contractStatusHandle.getGroupId(), +// contractStatusHandle.getSignUserId(), +// contractStatusHandle.getContractAddress()); +// ContractManageResult contractManageResult = +// JsonUtils.toJavaObject(res, ContractManageResult.class); +// if (contractManageResult == null) { +// return new FrontException(ConstantCode.FAIL_PARSE_JSON); +// } +// if (contractManageResult.getCode() == 0) { +// log.info("end contractFreeze useTime:{} contractManageResult:{}", +// Duration.between(startTime, Instant.now()).toMillis(), +// contractManageResult); +// return new BaseResponse(ConstantCode.RET_SUCCEED); // } else { -// Entry entryValue = table.getEntry(); -// for (int i = 0; i < entry.getFieldNameToValue().size(); i++) { -// for (String entryField : entryFields) { -// if ((i + "").equals(entryField)) { -// Map map = new HashMap<>(); -// map.put(fieldsList.get(i), entry.getFieldNameToValue().get(i + "")); -// entryValue.setFieldNameToValue(map); -// if (keyName.equals(fieldsList.get(i))) { -// table.setKey(entry.getFieldNameToValue().get(i + "")); -// } -// } -// } -// } -// entry = entryValue; +// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), +// contractManageResult.getMsg()); // } +// } catch (Exception e) { +// log.error("contractFreeze exception:", e); +// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); // } -// // ex: insert into t_test (name, item_id, item_name) values (fruit, 1, apple) -// else { -// for (String entryField : entryFields) { -// if (!fieldsList.contains(entryField)) { -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -// "Unknown field '" + entryField + "' in field list.", -// "Unknown field '" + entryField + "' in field list."); -// } -// if (fieldsList.size() != entryFields.size()) { -// List listString = new ArrayList(fieldsList); -// for (String entryItem : entryFields) { -// listString.remove(entryItem); -// } -// StringBuilder strBuilder = new StringBuilder("Please provide field '"); -// for (int i = 0; i < listString.size(); i++) { -// if (i == listString.size() - 1) { -// strBuilder.append(listString.get(i)).append("' "); -// } else { -// strBuilder.append(listString.get(i)).append("', '"); -// } -// } -// strBuilder.append("in field list."); -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, strBuilder.toString(), -// strBuilder.toString()); -// } +// } +// +// private Object contractUnfreeze(ContractStatusHandle contractStatusHandle) throws Exception { +// Instant startTime = Instant.now(); +// log.info("start contractUnfreeze startTime:{}", startTime.toEpochMilli()); +// try { +// if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { +// log.error("signUserId is empty"); +// throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); // } -// String keyValue = entry.getFieldNameToValue().get(keyName); -// if (keyValue == null) { -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -// "Column count doesn't match value count.", -// "Column count doesn't match value count."); +// String res = precompiledService.contractUnfreeze(contractStatusHandle.getGroupId(), +// contractStatusHandle.getSignUserId(), +// contractStatusHandle.getContractAddress()); +// ContractManageResult contractManageResult = +// JsonUtils.toJavaObject(res, ContractManageResult.class); +// if (contractManageResult.getCode() == 0) { +// log.info("end contractUnfreeze useTime:{} contractManageResult:{}", +// Duration.between(startTime, Instant.now()).toMillis(), +// contractManageResult); +// return new BaseResponse(ConstantCode.RET_SUCCEED); +// } else { +// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), +// contractManageResult.getMsg()); // } -// table.setKey(keyValue); +// } catch (Exception e) { +// log.error("contractUnfreeze exception:", e); +// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); // } -// CRUDParseUtils.checkUserTableParam(entry, descTable); -// int insertResult = precompiledService.insert(groupId, fromAddress, table, entry); -// log.info("end insert useTime:{} insertResult:{}", -// Duration.between(startTime, Instant.now()).toMillis(), insertResult); -// if (insertResult >= 0) { -// return new BaseResponse(ConstantCode.RET_SUCCESS, -// "Insert OK, " + insertResult + " row(s) affected."); -// } else { -// return new BaseResponse(insertResult, "Insert failed."); +// } +// +// private Object contractGrantManager(ContractStatusHandle contractStatusHandle) { +// Instant startTime = Instant.now(); +// log.info("start contractGrantManager startTime:{}", startTime.toEpochMilli()); +// try { +// if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { +// log.error("signUserId is empty"); +// throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); +// } +// if (StringUtils.isBlank(contractStatusHandle.getGrantAddress())) { +// log.error("grantAddress cannot be empty"); +// throw new FrontException(ConstantCode.PARAM_FAIL_GRANT_ADDRESS_EMPTY); +// } +// String res = precompiledService.contractGrantManager(contractStatusHandle.getGroupId(), +// contractStatusHandle.getSignUserId(), contractStatusHandle.getContractAddress(), +// contractStatusHandle.getGrantAddress()); +// ContractManageResult contractManageResult = +// JsonUtils.toJavaObject(res, ContractManageResult.class); +// if (contractManageResult.getCode() == 0) { +// log.info("end contractGrantManager useTime:{} contractManageResult:{}", +// Duration.between(startTime, Instant.now()).toMillis(), +// contractManageResult); +// return new BaseResponse(ConstantCode.RET_SUCCEED); +// } else { +// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), +// contractManageResult.getMsg()); +// } +// } catch (Exception e) { +// log.error("contractGrantManager exception:", e); +// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); // } - - public Object update(int groupId, String fromAddress, String sql) throws Exception { - Instant startTime = Instant.now(); - log.info("start update startTime:{}, groupId:{},fromAddress:{},sql:{}", - startTime.toEpochMilli(), groupId, fromAddress, sql); - Table table = new Table(); - Entry entry = new Entry(); - Condition conditions = new Condition(); - - try { - log.debug("start parseUpdate. sql:{}", sql); - CRUDParseUtils.parseUpdate(sql, table, entry, conditions); - log.debug("end parseUpdate. table:{}, entry:{}, conditions:{}", table, entry, - conditions); - } catch (Exception e) { - log.error("parseUpdate error exception:[]", e); - CRUDParseUtils.invalidSymbol(sql); - return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); - } - - String tableName = table.getTableName(); - List> descTable = null; - try { - descTable = precompiledService.desc(groupId, tableName); - } catch (Exception e) { - log.error("updateTable Error exception:[]", e); - return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); - } - - String keyName = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); - if (entry.getFieldNameToValue().containsKey(keyName)) { - return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, - "Please don't set the key field '" + keyName + "'.", - "Please don't set the key field '" + keyName + "'."); - } - table.setKey(keyName); - CRUDParseUtils.handleKey(table, conditions); - String updateResult = precompiledService.update(groupId, fromAddress, table, entry, conditions); - log.info("end update useTime:{} updateResult:{}", - Duration.between(startTime, Instant.now()).toMillis(), updateResult); - return updateResult; - } - - public Object remove(int groupId, String fromAddress, String sql) { - Instant startTime = Instant.now(); - log.info("start remove startTime:{}, groupId:{},fromAddress:{},sql:{}", - startTime.toEpochMilli(), groupId, fromAddress, sql); - Table table = new Table(); - Condition conditions = new Condition(); - - try { - log.debug("start parseRemove. sql:{}", sql); - CRUDParseUtils.parseRemove(sql, table, conditions); - log.debug("end parseRemove. table:{}, conditions:{}", table, conditions); - } catch (Exception e) { - log.error("parseRemove Error exception:[]", e); - CRUDParseUtils.invalidSymbol(sql); - return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); - } - - List> descTable = null; - try { - descTable = precompiledService.desc(groupId, table.getTableName()); - } catch (Exception e) { - log.error("removeTable Error exception:[]", e); - return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); - } - table.setKey(descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME)); - CRUDParseUtils.handleKey(table, conditions); - String removeResult = precompiledService.remove(groupId, fromAddress, table, conditions); - log.info("end remove useTime:{} removeResult:{}", - Duration.between(startTime, Instant.now()).toMillis(), removeResult); - return removeResult; - - } - - @ApiOperation(value = "contractStatusManage", notes = "contract status manage") - @PostMapping("contractStatusManage") - public Object contractStatusManage( - @Valid @RequestBody ContractStatusHandle contractStatusHandle) throws Exception { - log.debug("start contractStatusManage. contractStatusHandle:{}", contractStatusHandle); - switch (contractStatusHandle.getHandleType()) { - case PrecompiledUtils.CONTRACT_MANAGE_FREEZE: - return contractFreeze(contractStatusHandle); - case PrecompiledUtils.CONTRACT_MANAGE_UNFREEZE: - return contractUnfreeze(contractStatusHandle); - case PrecompiledUtils.CONTRACT_MANAGE_GRANTMANAGER: - return contractGrantManager(contractStatusHandle); - case PrecompiledUtils.CONTRACT_MANAGE_GETSTATUS: - return contractStatus(contractStatusHandle); - case PrecompiledUtils.CONTRACT_MANAGE_LISTMANAGER: - return contractManagerList(contractStatusHandle); - default: - log.error("end contractStatusManage. invalid contract handle type"); - throw new FrontException(ConstantCode.INVALID_CONTRACT_HANDLE_TYPE); - } - } - - private Object contractFreeze(ContractStatusHandle contractStatusHandle) { - Instant startTime = Instant.now(); - log.info("start contractFreeze startTime:{}", startTime.toEpochMilli()); - try { - if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { - log.error("signUserId is empty"); - throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); - } - String res = precompiledService.contractFreeze(contractStatusHandle.getGroupId(), - contractStatusHandle.getSignUserId(), - contractStatusHandle.getContractAddress()); - ContractManageResult contractManageResult = - JsonUtils.toJavaObject(res, ContractManageResult.class); - if (contractManageResult == null) { - return new FrontException(ConstantCode.FAIL_PARSE_JSON); - } - if (contractManageResult.getCode() == 0) { - log.info("end contractFreeze useTime:{} contractManageResult:{}", - Duration.between(startTime, Instant.now()).toMillis(), - contractManageResult); - return new BaseResponse(ConstantCode.RET_SUCCEED); - } else { - throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), - contractManageResult.getMsg()); - } - } catch (Exception e) { - log.error("contractFreeze exception:", e); - throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); - } - } - - private Object contractUnfreeze(ContractStatusHandle contractStatusHandle) throws Exception { - Instant startTime = Instant.now(); - log.info("start contractUnfreeze startTime:{}", startTime.toEpochMilli()); - try { - if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { - log.error("signUserId is empty"); - throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); - } - String res = precompiledService.contractUnfreeze(contractStatusHandle.getGroupId(), - contractStatusHandle.getSignUserId(), - contractStatusHandle.getContractAddress()); - ContractManageResult contractManageResult = - JsonUtils.toJavaObject(res, ContractManageResult.class); - if (contractManageResult.getCode() == 0) { - log.info("end contractUnfreeze useTime:{} contractManageResult:{}", - Duration.between(startTime, Instant.now()).toMillis(), - contractManageResult); - return new BaseResponse(ConstantCode.RET_SUCCEED); - } else { - throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), - contractManageResult.getMsg()); - } - } catch (Exception e) { - log.error("contractUnfreeze exception:", e); - throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); - } - } - - private Object contractGrantManager(ContractStatusHandle contractStatusHandle) { - Instant startTime = Instant.now(); - log.info("start contractGrantManager startTime:{}", startTime.toEpochMilli()); - try { - if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { - log.error("signUserId is empty"); - throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); - } - if (StringUtils.isBlank(contractStatusHandle.getGrantAddress())) { - log.error("grantAddress cannot be empty"); - throw new FrontException(ConstantCode.PARAM_FAIL_GRANT_ADDRESS_EMPTY); - } - String res = precompiledService.contractGrantManager(contractStatusHandle.getGroupId(), - contractStatusHandle.getSignUserId(), contractStatusHandle.getContractAddress(), - contractStatusHandle.getGrantAddress()); - ContractManageResult contractManageResult = - JsonUtils.toJavaObject(res, ContractManageResult.class); - if (contractManageResult.getCode() == 0) { - log.info("end contractGrantManager useTime:{} contractManageResult:{}", - Duration.between(startTime, Instant.now()).toMillis(), - contractManageResult); - return new BaseResponse(ConstantCode.RET_SUCCEED); - } else { - throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), - contractManageResult.getMsg()); - } - } catch (Exception e) { - log.error("contractGrantManager exception:", e); - throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); - } - } - - private Object contractStatus(ContractStatusHandle contractStatusHandle) { - Instant startTime = Instant.now(); - log.info("start contractStatus startTime:{}", startTime.toEpochMilli()); - try { - String res = precompiledService.contractStatus(contractStatusHandle.getGroupId(), - contractStatusHandle.getContractAddress()); - if (res.contains("code")) { - ContractManageResult contractManageResult = - JsonUtils.toJavaObject(res, ContractManageResult.class); - throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), - contractManageResult.getMsg()); - } else { - BaseResponse response = new BaseResponse(ConstantCode.RET_SUCCEED); - response.setData(res); - log.info("end contractStatus useTime:{} response:{}", - Duration.between(startTime, Instant.now()).toMillis(), response); - return response; - } - } catch (Exception e) { - log.error("contractStatus exception:", e); - throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); - } - } - - private Object contractManagerList(ContractStatusHandle contractStatusHandle) { - Instant startTime = Instant.now(); - log.info("start contractManagerList startTime:{}", startTime.toEpochMilli()); - try { - List res = precompiledService.contractManagerList(contractStatusHandle.getGroupId(), - contractStatusHandle.getContractAddress()); - BaseResponse response = new BaseResponse(ConstantCode.RET_SUCCEED); - response.setData(res); - log.info("end contractManagerList useTime:{} response:{}", - Duration.between(startTime, Instant.now()).toMillis(), response); - return response; - } catch (Exception e) { - log.error("contractManagerList exception:", e); - throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); - } - } - -} +// } +// +// private Object contractStatus(ContractStatusHandle contractStatusHandle) { +// Instant startTime = Instant.now(); +// log.info("start contractStatus startTime:{}", startTime.toEpochMilli()); +// try { +// String res = precompiledService.contractStatus(contractStatusHandle.getGroupId(), +// contractStatusHandle.getContractAddress()); +// if (res.contains("code")) { +// ContractManageResult contractManageResult = +// JsonUtils.toJavaObject(res, ContractManageResult.class); +// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), +// contractManageResult.getMsg()); +// } else { +// BaseResponse response = new BaseResponse(ConstantCode.RET_SUCCEED); +// response.setData(res); +// log.info("end contractStatus useTime:{} response:{}", +// Duration.between(startTime, Instant.now()).toMillis(), response); +// return response; +// } +// } catch (Exception e) { +// log.error("contractStatus exception:", e); +// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); +// } +// } +// +// private Object contractManagerList(ContractStatusHandle contractStatusHandle) { +// Instant startTime = Instant.now(); +// log.info("start contractManagerList startTime:{}", startTime.toEpochMilli()); +// try { +// List res = precompiledService.contractManagerList(contractStatusHandle.getGroupId(), +// contractStatusHandle.getContractAddress()); +// BaseResponse response = new BaseResponse(ConstantCode.RET_SUCCEED); +// response.setData(res); +// log.info("end contractManagerList useTime:{} response:{}", +// Duration.between(startTime, Instant.now()).toMillis(), response); +// return response; +// } catch (Exception e) { +// log.error("contractManagerList exception:", e); +// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); +// } +// } +// +//} diff --git a/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledService.java b/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledService.java index bb8f97665..0b05a5c81 100644 --- a/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledService.java +++ b/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledService.java @@ -1,229 +1,229 @@ -/* - * Copyright 2014-2020 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (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 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package com.webank.webase.front.precompiledapi; - -import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_OBSERVER; -import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_REMOVE; -import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_SEALER; - -import com.webank.webase.front.base.code.ConstantCode; -import com.webank.webase.front.base.exception.FrontException; -import com.webank.webase.front.keystore.KeyStoreService; -import com.webank.webase.front.precompiledapi.crud.CRUDParseUtils; -import com.webank.webase.front.precompiledapi.crud.Table; -import com.webank.webase.front.precompiledapi.entity.NodeInfo; -import com.webank.webase.front.util.JsonUtils; -import com.webank.webase.front.web3api.Web3ApiService; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import org.fisco.bcos.sdk.contract.precompiled.cns.CnsInfo; -import org.fisco.bcos.sdk.contract.precompiled.cns.CnsService; -import org.fisco.bcos.sdk.contract.precompiled.contractmgr.ContractLifeCycleService; -import org.fisco.bcos.sdk.contract.precompiled.crud.TableCRUDService; -import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; -import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; -import org.fisco.bcos.sdk.model.PrecompiledConstant; -import org.fisco.bcos.sdk.transaction.model.exception.ContractException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - - -/** - * Precompiled common service including management of CNS, node consensus status, CRUD based on - * PrecompiledWithSignService - */ -@Service -public class PrecompiledService { - - @Autowired - private Web3ApiService web3ApiService; - @Autowired - private KeyStoreService keyStoreService; - @Autowired - private PrecompiledWithSignService precompiledWithSignService; - - /** - * CNS config related - */ - public List queryCnsByName(int groupId, String contractName) throws ContractException { - CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), - keyStoreService.getCredentialsForQuery()); - return cnsService.selectByName(contractName); - } - - public List queryCnsByNameAndVersion(int groupId, String contractName, - String version) throws ContractException { - CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), - keyStoreService.getCredentialsForQuery()); - return cnsService.selectByNameAndVersion(contractName, version); - } - - public String getAddressByContractNameAndVersion(int groupId, String contractName, - String version) throws ContractException { - CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), - keyStoreService.getCredentialsForQuery()); - return cnsService.getContractAddress(contractName, version); - } - - /** - * Consensus config related - */ - public String addSealer(int groupId, String signUserId, String nodeId) { - String res = precompiledWithSignService.addSealer(groupId, signUserId, nodeId); - return res; - } - - public String addObserver(int groupId, String signUserId, String nodeId) { - String res = precompiledWithSignService.addObserver(groupId, signUserId, nodeId); - return res; - } - - public String removeNode(int groupId, String signUserId, String nodeId) { - String res = precompiledWithSignService.removeNode(groupId, signUserId, nodeId); - return res; - } - - public List getNodeList(int groupId) throws IOException { - // nodeListWithType 组合多个带有类型的nodeid list - List sealerList = - web3ApiService.getWeb3j(groupId).getSealerList().getSealerList(); - List observerList = - web3ApiService.getWeb3j(groupId).getObserverList().getObserverList(); - List peerList = web3ApiService.getWeb3j(groupId).getNodeIDList().getNodeIDList(); - // process nodeList - List nodeListWithType = new ArrayList<>(); - - // add all sealer and observer in List - sealerList.forEach(sealer -> nodeListWithType.add(new NodeInfo(sealer, NODE_TYPE_SEALER))); - observerList.forEach( - observer -> nodeListWithType.add(new NodeInfo(observer, NODE_TYPE_OBSERVER))); - // peer not in sealer/observer but connected is remove node(游离节点) - peerList.stream().filter(peer -> !sealerList.contains(peer) && !observerList.contains(peer)) - .forEach(peerToAdd -> nodeListWithType - .add(new NodeInfo(peerToAdd, NODE_TYPE_REMOVE))); - - return nodeListWithType; - } - - /** - * CRUD related Table table - validation in controller - */ - public String createTable(int groupId, String signUserId, Table table) { - String res = precompiledWithSignService.createTable(groupId, signUserId, table); - return res; - } - - /** - * insert 校验tableName等操作放在controller - */ - public String insert(int groupId, String signUserId, Table table, Entry entry) { - String res = precompiledWithSignService.insert(groupId, signUserId, table, entry); - return res; - } - - /** - * update - */ - public String update(int groupId, String signUserId, Table table, Entry entry, Condition condition) - { - String res = precompiledWithSignService.update(groupId, signUserId, table, entry, condition); - return res; - } - - /** - * remove - */ - public String remove(int groupId, String signUserId, Table table, Condition condition) { - String res = precompiledWithSignService.remove(groupId, signUserId, table, condition); - return res; - } - - /** - * desc - */ - public List> desc(int groupId, String tableName) throws Exception { - TableCRUDService crudService = new TableCRUDService(web3ApiService.getWeb3j(groupId), - keyStoreService.getCredentialsForQuery()); - List> descRes = crudService.desc(tableName); - if (!CRUDParseUtils.checkTableExistence(descRes)) { - throw new FrontException(ConstantCode.FAIL_TABLE_NOT_EXISTS); - } - return descRes; -// String tableKey = descRes.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); -// String valueFields = descRes.get(0).get(PrecompiledConstant.VALUE_FIELD_NAME); -// return new Table(tableName, tableKey, valueFields); - } - - public String descTable(int groupId, String tableName) throws Exception { - List> descRes = this.desc(groupId, tableName); - if (!CRUDParseUtils.checkTableExistence(descRes)) { - throw new FrontException(ConstantCode.FAIL_TABLE_NOT_EXISTS); - } - String tableInfo = JsonUtils.objToString(descRes); - return CRUDParseUtils.formatJson(tableInfo); - } - - /** - * select - */ - public List> select(int groupId, Table table, - Condition conditions) throws Exception { - TableCRUDService crudService = new TableCRUDService(web3ApiService.getWeb3j(groupId), - keyStoreService.getCredentialsForQuery()); - List> selectRes = crudService.select(table.getTableName(), table.getKey(), conditions); - return selectRes; - } - - public String contractFreeze(int groupId, String signUserId, String contractAddress) - { - return precompiledWithSignService.contractFreeze(groupId, signUserId, contractAddress); - } - - public String contractUnfreeze(int groupId, String signUserId, String contractAddress) - { - return precompiledWithSignService.contractUnfreeze(groupId, signUserId, contractAddress); - } - - public String contractGrantManager(int groupId, String signUserId, String contractAddress, - String grantAddress) { - return precompiledWithSignService.contractGrantManager(groupId, signUserId, contractAddress, - grantAddress); - } - - public String contractStatus(int groupId, String contractAddress) throws Exception { - ContractLifeCycleService contractStatusService = new ContractLifeCycleService( - web3ApiService.getWeb3j(groupId), keyStoreService.getCredentialsForQuery()); - String res = contractStatusService.getContractStatus(contractAddress); - if (res.contains("frozen")) { - // res: The account has been frozen. You can use this account after unfreezing it. - return "1"; - } else { - // res: The address is nonexistent. - // res: The account is available. - // res: invalid - // res: not a account address - return "0"; - } - } - - public List contractManagerList(int groupId, String contractAddress) throws Exception { - ContractLifeCycleService contractStatusService = new ContractLifeCycleService( - web3ApiService.getWeb3j(groupId), keyStoreService.getCredentialsForQuery()); - return contractStatusService.listManager(contractAddress); - } -} +///* +// * Copyright 2014-2020 the original author or authors. +// * +// * Licensed under the Apache License, Version 2.0 (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 +// * +// * Unless required by applicable law or agreed to in writing, software distributed under the License +// * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +// * or implied. See the License for the specific language governing permissions and limitations under +// * the License. +// */ +//package com.webank.webase.front.precompiledapi; +// +//import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_OBSERVER; +//import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_REMOVE; +//import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_SEALER; +// +//import com.webank.webase.front.base.code.ConstantCode; +//import com.webank.webase.front.base.exception.FrontException; +//import com.webank.webase.front.keystore.KeyStoreService; +//import com.webank.webase.front.precompiledapi.crud.CRUDParseUtils; +//import com.webank.webase.front.precompiledapi.crud.Table; +//import com.webank.webase.front.precompiledapi.entity.NodeInfo; +//import com.webank.webase.front.util.JsonUtils; +//import com.webank.webase.front.web3api.Web3ApiService; +//import java.io.IOException; +//import java.util.ArrayList; +//import java.util.Arrays; +//import java.util.Collections; +//import java.util.List; +//import java.util.Map; +//import org.fisco.bcos.sdk.contract.precompiled.cns.CnsInfo; +//import org.fisco.bcos.sdk.contract.precompiled.cns.CnsService; +//import org.fisco.bcos.sdk.contract.precompiled.contractmgr.ContractLifeCycleService; +//import org.fisco.bcos.sdk.contract.precompiled.crud.TableCRUDService; +//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; +//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; +//import org.fisco.bcos.sdk.model.PrecompiledConstant; +//import org.fisco.bcos.sdk.transaction.model.exception.ContractException; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.stereotype.Service; +// +// +///** +// * Precompiled common service including management of CNS, node consensus status, CRUD based on +// * PrecompiledWithSignService +// */ +//@Service +//public class PrecompiledService { +// +// @Autowired +// private Web3ApiService web3ApiService; +// @Autowired +// private KeyStoreService keyStoreService; +// @Autowired +// private PrecompiledWithSignService precompiledWithSignService; +// +// /** +// * CNS config related +// */ +// public List queryCnsByName(int groupId, String contractName) throws ContractException { +// CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), +// keyStoreService.getCredentialsForQuery()); +// return cnsService.selectByName(contractName); +// } +// +// public List queryCnsByNameAndVersion(int groupId, String contractName, +// String version) throws ContractException { +// CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), +// keyStoreService.getCredentialsForQuery()); +// return cnsService.selectByNameAndVersion(contractName, version); +// } +// +// public String getAddressByContractNameAndVersion(int groupId, String contractName, +// String version) throws ContractException { +// CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), +// keyStoreService.getCredentialsForQuery()); +// return cnsService.getContractAddress(contractName, version); +// } +// +// /** +// * Consensus config related +// */ +// public String addSealer(int groupId, String signUserId, String nodeId) { +// String res = precompiledWithSignService.addSealer(groupId, signUserId, nodeId); +// return res; +// } +// +// public String addObserver(int groupId, String signUserId, String nodeId) { +// String res = precompiledWithSignService.addObserver(groupId, signUserId, nodeId); +// return res; +// } +// +// public String removeNode(int groupId, String signUserId, String nodeId) { +// String res = precompiledWithSignService.removeNode(groupId, signUserId, nodeId); +// return res; +// } +// +// public List getNodeList(int groupId) throws IOException { +// // nodeListWithType 组合多个带有类型的nodeid list +// List sealerList = +// web3ApiService.getWeb3j(groupId).getSealerList().getSealerList(); +// List observerList = +// web3ApiService.getWeb3j(groupId).getObserverList().getObserverList(); +// List peerList = web3ApiService.getWeb3j(groupId).getNodeIDList().getNodeIDList(); +// // process nodeList +// List nodeListWithType = new ArrayList<>(); +// +// // add all sealer and observer in List +// sealerList.forEach(sealer -> nodeListWithType.add(new NodeInfo(sealer, NODE_TYPE_SEALER))); +// observerList.forEach( +// observer -> nodeListWithType.add(new NodeInfo(observer, NODE_TYPE_OBSERVER))); +// // peer not in sealer/observer but connected is remove node(游离节点) +// peerList.stream().filter(peer -> !sealerList.contains(peer) && !observerList.contains(peer)) +// .forEach(peerToAdd -> nodeListWithType +// .add(new NodeInfo(peerToAdd, NODE_TYPE_REMOVE))); +// +// return nodeListWithType; +// } +// +// /** +// * CRUD related Table table - validation in controller +// */ +// public String createTable(int groupId, String signUserId, Table table) { +// String res = precompiledWithSignService.createTable(groupId, signUserId, table); +// return res; +// } +// +// /** +// * insert 校验tableName等操作放在controller +// */ +// public String insert(int groupId, String signUserId, Table table, Entry entry) { +// String res = precompiledWithSignService.insert(groupId, signUserId, table, entry); +// return res; +// } +// +// /** +// * update +// */ +// public String update(int groupId, String signUserId, Table table, Entry entry, Condition condition) +// { +// String res = precompiledWithSignService.update(groupId, signUserId, table, entry, condition); +// return res; +// } +// +// /** +// * remove +// */ +// public String remove(int groupId, String signUserId, Table table, Condition condition) { +// String res = precompiledWithSignService.remove(groupId, signUserId, table, condition); +// return res; +// } +// +// /** +// * desc +// */ +// public List> desc(int groupId, String tableName) throws Exception { +// TableCRUDService crudService = new TableCRUDService(web3ApiService.getWeb3j(groupId), +// keyStoreService.getCredentialsForQuery()); +// List> descRes = crudService.desc(tableName); +// if (!CRUDParseUtils.checkTableExistence(descRes)) { +// throw new FrontException(ConstantCode.FAIL_TABLE_NOT_EXISTS); +// } +// return descRes; +//// String tableKey = descRes.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); +//// String valueFields = descRes.get(0).get(PrecompiledConstant.VALUE_FIELD_NAME); +//// return new Table(tableName, tableKey, valueFields); +// } +// +// public String descTable(int groupId, String tableName) throws Exception { +// List> descRes = this.desc(groupId, tableName); +// if (!CRUDParseUtils.checkTableExistence(descRes)) { +// throw new FrontException(ConstantCode.FAIL_TABLE_NOT_EXISTS); +// } +// String tableInfo = JsonUtils.objToString(descRes); +// return CRUDParseUtils.formatJson(tableInfo); +// } +// +// /** +// * select +// */ +// public List> select(int groupId, Table table, +// Condition conditions) throws Exception { +// TableCRUDService crudService = new TableCRUDService(web3ApiService.getWeb3j(groupId), +// keyStoreService.getCredentialsForQuery()); +// List> selectRes = crudService.select(table.getTableName(), table.getKey(), conditions); +// return selectRes; +// } +// +// public String contractFreeze(int groupId, String signUserId, String contractAddress) +// { +// return precompiledWithSignService.contractFreeze(groupId, signUserId, contractAddress); +// } +// +// public String contractUnfreeze(int groupId, String signUserId, String contractAddress) +// { +// return precompiledWithSignService.contractUnfreeze(groupId, signUserId, contractAddress); +// } +// +// public String contractGrantManager(int groupId, String signUserId, String contractAddress, +// String grantAddress) { +// return precompiledWithSignService.contractGrantManager(groupId, signUserId, contractAddress, +// grantAddress); +// } +// +// public String contractStatus(int groupId, String contractAddress) throws Exception { +// ContractLifeCycleService contractStatusService = new ContractLifeCycleService( +// web3ApiService.getWeb3j(groupId), keyStoreService.getCredentialsForQuery()); +// String res = contractStatusService.getContractStatus(contractAddress); +// if (res.contains("frozen")) { +// // res: The account has been frozen. You can use this account after unfreezing it. +// return "1"; +// } else { +// // res: The address is nonexistent. +// // res: The account is available. +// // res: invalid +// // res: not a account address +// return "0"; +// } +// } +// +// public List contractManagerList(int groupId, String contractAddress) throws Exception { +// ContractLifeCycleService contractStatusService = new ContractLifeCycleService( +// web3ApiService.getWeb3j(groupId), keyStoreService.getCredentialsForQuery()); +// return contractStatusService.listManager(contractAddress); +// } +//} diff --git a/src/main/java/com/webank/webase/front/precompiledapi/crud/CRUDParseUtils.java b/src/main/java/com/webank/webase/front/precompiledapi/crud/CRUDParseUtils.java index 748b8c227..76ceb831b 100644 --- a/src/main/java/com/webank/webase/front/precompiledapi/crud/CRUDParseUtils.java +++ b/src/main/java/com/webank/webase/front/precompiledapi/crud/CRUDParseUtils.java @@ -1,622 +1,622 @@ -package com.webank.webase.front.precompiledapi.crud; - -import com.webank.webase.front.base.code.ConstantCode; -import com.webank.webase.front.base.exception.FrontException; -import com.webank.webase.front.util.PrecompiledUtils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import net.sf.jsqlparser.JSQLParserException; -import net.sf.jsqlparser.expression.BinaryExpression; -import net.sf.jsqlparser.expression.Expression; -import net.sf.jsqlparser.expression.ExpressionVisitorAdapter; -import net.sf.jsqlparser.expression.Function; -import net.sf.jsqlparser.expression.NotExpression; -import net.sf.jsqlparser.expression.operators.conditional.OrExpression; -import net.sf.jsqlparser.expression.operators.relational.ComparisonOperator; -import net.sf.jsqlparser.expression.operators.relational.ExpressionList; -import net.sf.jsqlparser.expression.operators.relational.InExpression; -import net.sf.jsqlparser.expression.operators.relational.IsNullExpression; -import net.sf.jsqlparser.expression.operators.relational.ItemsList; -import net.sf.jsqlparser.expression.operators.relational.LikeExpression; -import net.sf.jsqlparser.parser.CCJSqlParserUtil; -import net.sf.jsqlparser.schema.Column; -import net.sf.jsqlparser.statement.Statement; -import net.sf.jsqlparser.statement.create.table.ColumnDefinition; -import net.sf.jsqlparser.statement.create.table.CreateTable; -import net.sf.jsqlparser.statement.create.table.Index; -import net.sf.jsqlparser.statement.delete.Delete; -import net.sf.jsqlparser.statement.insert.Insert; -import net.sf.jsqlparser.statement.select.Limit; -import net.sf.jsqlparser.statement.select.PlainSelect; -import net.sf.jsqlparser.statement.select.Select; -import net.sf.jsqlparser.statement.select.SelectExpressionItem; -import net.sf.jsqlparser.statement.select.SelectItem; -import net.sf.jsqlparser.statement.select.SubSelect; -import net.sf.jsqlparser.statement.update.Update; -import net.sf.jsqlparser.util.TablesNamesFinder; -import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; -import org.fisco.bcos.sdk.contract.precompiled.crud.common.ConditionOperator; -import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; -import org.fisco.bcos.sdk.model.PrecompiledConstant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CRUDParseUtils { - private static final Logger logger = LoggerFactory.getLogger(CRUDParseUtils.class); - public static final String PRIMARY_KEY = "primary key"; - - public static void parseCreateTable(String sql, Table table) - throws JSQLParserException, FrontException { - Statement statement = CCJSqlParserUtil.parse(sql); - CreateTable createTable = (CreateTable) statement; - - // parse table name - String tableName = createTable.getTable().getName(); - table.setTableName(tableName); - - // parse key from index - boolean keyFlag = false; - List indexes = createTable.getIndexes(); - if (indexes != null) { - if (indexes.size() > 1) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Please provide only one primary key for the table."); - } - keyFlag = true; - Index index = indexes.get(0); - String type = index.getType().toLowerCase(); - if (PRIMARY_KEY.equals(type)) { - table.setKey(index.getColumnsNames().get(0)); - table.setKeyFieldName(index.getColumnsNames().get(0)); - } else { - throw new FrontException(ConstantCode.SQL_ERROR, - "Please provide only one primary key for the table."); - } - } - List columnDefinitions = createTable.getColumnDefinitions(); - // parse key from ColumnDefinition - for (int i = 0; i < columnDefinitions.size(); i++) { - List columnSpecStrings = columnDefinitions.get(i).getColumnSpecStrings(); - if (columnSpecStrings == null) { - continue; - } else { - if (columnSpecStrings.size() == 2 - && "primary".equals(columnSpecStrings.get(0)) - && "key".equals(columnSpecStrings.get(1))) { - String key = columnDefinitions.get(i).getColumnName(); - if (keyFlag) { - if (!table.getKey().equals(key)) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Please provide only one primary key for the table."); - } - } else { - keyFlag = true; - table.setKey(key); - } - break; - } - } - } - if (!keyFlag) { - throw new FrontException(ConstantCode.SQL_ERROR, "Please provide a primary key for the table."); - } - // parse value field - List fieldsList = new ArrayList<>(); - for (int i = 0; i < columnDefinitions.size(); i++) { - String columnName = columnDefinitions.get(i).getColumnName(); - if (fieldsList.contains(columnName)) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Please provide the field '" + columnName + "' only once."); - } else { - fieldsList.add(columnName); - } - } - if (!fieldsList.contains(table.getKey())) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Please provide the field '" + table.getKey() + "' in column definition."); - } else { - fieldsList.remove(table.getKey()); - } - table.setValueFields(fieldsList); - } - - public static String parseInsertedTableName(String sql) - throws JSQLParserException, FrontException { - Statement statement = CCJSqlParserUtil.parse(sql); - Insert insert = (Insert) statement; - - if (insert.getSelect() != null) { - throw new FrontException(ConstantCode.SQL_ERROR, "The insert select clause is not supported."); - } - // parse table name - return insert.getTable().getName(); - } - - public static boolean parseInsert( - String sql, Table table, Entry entry, Map tableDesc) - throws JSQLParserException, FrontException { - Statement statement = CCJSqlParserUtil.parse(sql); - Insert insert = (Insert) statement; - String valueFieldString = tableDesc.get(PrecompiledConstant.VALUE_FIELD_NAME); - String[] valueFields = valueFieldString.split(","); - String expectedValueField = - tableDesc.get(PrecompiledConstant.KEY_FIELD_NAME) + ", " + valueFieldString; - int expectedValueNum = valueFields.length + 1; - - if (insert.getSelect() != null) { - throw new FrontException(ConstantCode.SQL_ERROR, "The insert select clause is not supported."); - } - // parse table name - String tableName = insert.getTable().getName(); - table.setTableName(tableName); - - // parse columns - List columns = insert.getColumns(); - ItemsList itemsList = insert.getItemsList(); - - ExpressionList expressionList = (ExpressionList) itemsList; - List expressions = expressionList.getExpressions(); - - String[] itemArr = new String[expressions.size()]; - for (int i = 0; i < expressions.size(); i++) { - itemArr[i] = expressions.get(i).toString().trim(); - } - if (columns != null) { - if (columns.size() != itemArr.length) { - throw new FrontException(ConstantCode.SQL_ERROR, "Column count doesn't match value count."); - } - if (expectedValueNum != columns.size()) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Column count doesn't match value count, fields size: " - + valueFields.length - + ", provided field value size: " - + columns.size() - + ", expected field list: " - + expectedValueField); - } - List columnNames = new ArrayList<>(); - for (Column column : columns) { - String columnName = trimQuotes(column.toString()); - if (columnNames.contains(columnName)) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Please provide the field '" + columnName + "' only once."); - } else { - columnNames.add(columnName); - } - } - for (int i = 0; i < columnNames.size(); i++) { - entry.getFieldNameToValue().put(columnNames.get(i), trimQuotes(itemArr[i])); - } - return false; - } else { - String keyField = tableDesc.get(PrecompiledConstant.KEY_FIELD_NAME); - if (expectedValueNum != itemArr.length) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Column count doesn't match value count, fields size: " - + valueFields.length - + ", provided field value size: " - + itemArr.length - + ", expected field list: " - + expectedValueField); - } - String[] allFields = new String[itemArr.length]; - allFields[0] = keyField; - System.arraycopy(valueFields, 0, allFields, 1, valueFields.length); - for (int i = 0; i < itemArr.length; i++) { - entry.getFieldNameToValue().put(allFields[i], trimQuotes(itemArr[i])); - } - return true; - } - } - - public static void parseSelect( - String sql, Table table, Condition condition, List selectColumns) - throws JSQLParserException, FrontException { - Statement statement; - statement = CCJSqlParserUtil.parse(sql); - Select selectStatement = (Select) statement; - - // parse table name - TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); - List tableList = tablesNamesFinder.getTableList(selectStatement); - if (tableList.size() != 1) { - throw new FrontException(ConstantCode.SQL_ERROR, "Please provide only one table name."); - } - table.setTableName(tableList.get(0)); - - // parse where clause - PlainSelect selectBody = (PlainSelect) selectStatement.getSelectBody(); - if (selectBody.getOrderByElements() != null) { - throw new FrontException(ConstantCode.SQL_ERROR, "The order clause is not supported."); - } - if (selectBody.getGroupBy() != null) { - throw new FrontException(ConstantCode.SQL_ERROR, "The group clause is not supported."); - } - if (selectBody.getHaving() != null) { - throw new FrontException(ConstantCode.SQL_ERROR, "The having clause is not supported."); - } - if (selectBody.getJoins() != null) { - throw new FrontException(ConstantCode.SQL_ERROR, "The join clause is not supported."); - } - if (selectBody.getTop() != null) { - throw new FrontException(ConstantCode.SQL_ERROR, "The top clause is not supported."); - } - if (selectBody.getDistinct() != null) { - throw new FrontException(ConstantCode.SQL_ERROR, "The distinct clause is not supported."); - } - Expression expr = selectBody.getWhere(); - condition = handleExpression(condition, expr); - - Limit limit = selectBody.getLimit(); - if (limit != null) { - parseLimit(condition, limit); - } - - // parse select item - List selectItems = selectBody.getSelectItems(); - for (SelectItem item : selectItems) { - if (item instanceof SelectExpressionItem) { - SelectExpressionItem selectExpressionItem = (SelectExpressionItem) item; - Expression expression = selectExpressionItem.getExpression(); - if (expression instanceof Function) { - Function func = (Function) expression; - throw new FrontException(ConstantCode.SQL_ERROR, - "The " + func.getName() + " function is not supported."); - } - } - selectColumns.add(item.toString()); - } - } - - private static void checkExpression(Expression expression) throws FrontException { - if (expression instanceof OrExpression) { - throw new FrontException(ConstantCode.SQL_ERROR, "The OrExpression is not supported."); - } - if (expression instanceof NotExpression) { - throw new FrontException(ConstantCode.SQL_ERROR, "The NotExpression is not supported."); - } - if (expression instanceof InExpression) { - throw new FrontException(ConstantCode.SQL_ERROR, "The InExpression is not supported."); - } - if (expression instanceof LikeExpression) { - logger.debug("The LikeExpression is not supported."); - throw new FrontException(ConstantCode.SQL_ERROR, "The LikeExpression is not supported."); - } - if (expression instanceof SubSelect) { - throw new FrontException(ConstantCode.SQL_ERROR, "The SubSelect is not supported."); - } - if (expression instanceof IsNullExpression) { - throw new FrontException(ConstantCode.SQL_ERROR, "The IsNullExpression is not supported."); - } - } - - private static Condition handleExpression(Condition condition, Expression expr) - throws FrontException { - if (expr instanceof BinaryExpression) { - condition = getWhereClause((BinaryExpression) (expr), condition); - } - checkExpression(expr); - Map> conditions = condition.getConditions(); - Set keys = conditions.keySet(); - for (String key : keys) { - Map value = conditions.get(key); - ConditionOperator operation = value.keySet().iterator().next(); - String itemValue = value.values().iterator().next(); - String newValue = trimQuotes(itemValue); - value.put(operation, newValue); - conditions.put(key, value); - } - condition.setConditions(conditions); - return condition; - } - - public static String trimQuotes(String str) { - char[] value = str.toCharArray(); - int len = value.length; - int st = 1; - char[] val = value; /* avoid getfield opcode */ - - while ((st < len) && (val[st] == '"' || val[st] == '\'')) { - st++; - } - while ((st < len) && (val[len - 1] == '"' || val[len - 1] == '\'')) { - len--; - } - String string = ((st > 1) || (len < value.length)) ? str.substring(st, len) : str; - return string; - } - - public static void parseUpdate(String sql, Table table, Entry entry, Condition condition) - throws JSQLParserException, FrontException { - Statement statement = CCJSqlParserUtil.parse(sql); - Update update = (Update) statement; - - // parse table name - List tables = update.getTables(); - String tableName = tables.get(0).getName(); - table.setTableName(tableName); - - // parse columns - List columns = update.getColumns(); - List expressions = update.getExpressions(); - int size = expressions.size(); - String[] values = new String[size]; - for (int i = 0; i < size; i++) { - values[i] = expressions.get(i).toString(); - } - for (int i = 0; i < columns.size(); i++) { - entry.getFieldNameToValue() - .put(trimQuotes(columns.get(i).toString()), trimQuotes(values[i])); - } - - // parse where clause - Expression where = update.getWhere(); - if (where != null) { - BinaryExpression expr2 = (BinaryExpression) (where); - handleExpression(condition, expr2); - } - Limit limit = update.getLimit(); - parseLimit(condition, limit); - } - - public static void parseRemove(String sql, Table table, Condition condition) - throws JSQLParserException, FrontException { - Statement statement = CCJSqlParserUtil.parse(sql); - Delete delete = (Delete) statement; - - // parse table name - net.sf.jsqlparser.schema.Table sqlTable = delete.getTable(); - table.setTableName(sqlTable.getName()); - - // parse where clause - Expression where = delete.getWhere(); - if (where != null) { - BinaryExpression expr = (BinaryExpression) (where); - handleExpression(condition, expr); - } - Limit limit = delete.getLimit(); - parseLimit(condition, limit); - } - - private static void parseLimit(Condition condition, Limit limit) - throws FrontException { - if (limit != null) { - Expression offset = limit.getOffset(); - Expression count = limit.getRowCount(); - try { - if (offset != null) { - condition.Limit( - Integer.parseInt(offset.toString()), - Integer.parseInt(count.toString())); - } else { - condition.Limit(Integer.parseInt(count.toString())); - } - } catch (NumberFormatException e) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Please provide limit parameters by non-negative integer mode, " - + PrecompiledUtils.NonNegativeIntegerRange - + "."); - } - } - } - - private static Condition getWhereClause(Expression expr, Condition condition) - throws FrontException { - Set keySet = new HashSet<>(); - Set conflictKeys = new HashSet<>(); - Set unsupportedConditions = new HashSet<>(); - expr.accept( - new ExpressionVisitorAdapter() { - @Override - protected void visitBinaryExpression(BinaryExpression expr) { - if (expr instanceof ComparisonOperator) { - String key = trimQuotes(expr.getLeftExpression().toString()); - if (keySet.contains(key)) { - conflictKeys.add(key); - } - keySet.add(key); - String operation = expr.getStringExpression(); - String value = trimQuotes(expr.getRightExpression().toString()); - switch (operation) { - case "=": - condition.EQ(key, value); - break; - case "!=": - condition.NE(key, value); - break; - case ">": - condition.GT(key, value); - break; - case ">=": - condition.GE(key, value); - break; - case "<": - condition.LT(key, value); - break; - case "<=": - condition.LE(key, value); - break; - default: - break; - } - } else { - try { - checkExpression(expr); - } catch (FrontException e) { - unsupportedConditions.add(e.getMessage()); - } - } - super.visitBinaryExpression(expr); - } - }); - if (conflictKeys.size() > 0) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Wrong condition! There cannot be the same field in the same condition! The conflicting field is: " - + conflictKeys.toString()); - } - if (unsupportedConditions.size() > 0) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Wrong condition! Find unsupported conditions! message: " - + unsupportedConditions.toString()); - } - return condition; - } - - public static void invalidSymbol(String sql) throws FrontException { - if (sql.contains(";")) { - throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese semicolon."); - } else if (sql.contains("“") - || sql.contains("”") - || sql.contains("‘") - || sql.contains("’")) { - throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese quotes."); - } else if (sql.contains(",")) { - throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese comma."); - } - } - - public static boolean checkTableExistence(List> descTable) { - if (descTable.size() == 0 - || descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME).equals("")) { -// System.out.println("The table \"" + tableName + "\" doesn't exist!"); - return false; - } - return true; - } - - - public static String formatJson(String jsonStr) { - if (null == jsonStr || "".equals(jsonStr)) return ""; - jsonStr = jsonStr.replace("\\n", ""); - StringBuilder sb = new StringBuilder(); - char last = '\0'; - char current = '\0'; - int indent = 0; - boolean isInQuotationMarks = false; - for (int i = 0; i < jsonStr.length(); i++) { - last = current; - current = jsonStr.charAt(i); - switch (current) { - case '"': - if (last != '\\') { - isInQuotationMarks = !isInQuotationMarks; - } - sb.append(current); - break; - case '{': - case '[': - sb.append(current); - if (!isInQuotationMarks) { - sb.append('\n'); - indent++; - addIndentBlank(sb, indent); - } - break; - case '}': - case ']': - if (!isInQuotationMarks) { - sb.append('\n'); - indent--; - addIndentBlank(sb, indent); - } - sb.append(current); - break; - case ',': - sb.append(current); - if (last != '\\' && !isInQuotationMarks) { - sb.append('\n'); - addIndentBlank(sb, indent); - } - break; - case ' ': - if (',' != jsonStr.charAt(i - 1)) { - sb.append(current); - } - break; - case '\\': - sb.append("\\"); - break; - default: - if (!(current == " ".charAt(0))) sb.append(current); - } - } - - return sb.toString(); - } - - private static void addIndentBlank(StringBuilder sb, int indent) { - for (int i = 0; i < indent; i++) { - sb.append(" "); - } - } - - - public static void handleKey(Table table, Condition condition) { - - String keyName = table.getKey(); - String keyValue = ""; - Map keyMap = condition.getConditions().get(keyName); - if (keyMap == null) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Please provide a equal condition for the key field '" - + keyName - + "' in where clause."); - } else { - Set keySet = keyMap.keySet(); - for (ConditionOperator enumOP : keySet) { - if (enumOP != ConditionOperator.eq) { - throw new FrontException(ConstantCode.SQL_ERROR, - "Please provide a equal condition for the key field '" - + keyName - + "' in where clause."); - } else { - keyValue = keyMap.get(enumOP); - } - } - } - table.setKey(keyValue); - } - - public static List> filterSystemColum(List> result) { - - List filteredColumns = Arrays.asList("_id_", "_hash_", "_status_", "_num_"); - List> filteredResult = new ArrayList<>(result.size()); - Map filteredRecords; - for (Map records : result) { - filteredRecords = new LinkedHashMap<>(); - Set recordKeys = records.keySet(); - for (String recordKey : recordKeys) { - if (!filteredColumns.contains(recordKey)) { - filteredRecords.put(recordKey, records.get(recordKey)); - } - } - filteredResult.add(filteredRecords); - } - return filteredResult; - } - - public static List> getSelectedColumn( - List selectColumns, List> result) { - List> selectedResult = new ArrayList<>(result.size()); - Map selectedRecords; - for (Map records : result) { - selectedRecords = new LinkedHashMap<>(); - for (String column : selectColumns) { - Set recordKeys = records.keySet(); - for (String recordKey : recordKeys) { - if (recordKey.equals(column)) { - selectedRecords.put(recordKey, records.get(recordKey)); - } - } - } - selectedResult.add(selectedRecords); - } - selectedResult.forEach(System.out::println); - return selectedResult; - } -} +//package com.webank.webase.front.precompiledapi.crud; +// +//import com.webank.webase.front.base.code.ConstantCode; +//import com.webank.webase.front.base.exception.FrontException; +//import com.webank.webase.front.util.PrecompiledUtils; +//import java.util.ArrayList; +//import java.util.Arrays; +//import java.util.HashSet; +//import java.util.LinkedHashMap; +//import java.util.List; +//import java.util.Map; +//import java.util.Set; +//import net.sf.jsqlparser.JSQLParserException; +//import net.sf.jsqlparser.expression.BinaryExpression; +//import net.sf.jsqlparser.expression.Expression; +//import net.sf.jsqlparser.expression.ExpressionVisitorAdapter; +//import net.sf.jsqlparser.expression.Function; +//import net.sf.jsqlparser.expression.NotExpression; +//import net.sf.jsqlparser.expression.operators.conditional.OrExpression; +//import net.sf.jsqlparser.expression.operators.relational.ComparisonOperator; +//import net.sf.jsqlparser.expression.operators.relational.ExpressionList; +//import net.sf.jsqlparser.expression.operators.relational.InExpression; +//import net.sf.jsqlparser.expression.operators.relational.IsNullExpression; +//import net.sf.jsqlparser.expression.operators.relational.ItemsList; +//import net.sf.jsqlparser.expression.operators.relational.LikeExpression; +//import net.sf.jsqlparser.parser.CCJSqlParserUtil; +//import net.sf.jsqlparser.schema.Column; +//import net.sf.jsqlparser.statement.Statement; +//import net.sf.jsqlparser.statement.create.table.ColumnDefinition; +//import net.sf.jsqlparser.statement.create.table.CreateTable; +//import net.sf.jsqlparser.statement.create.table.Index; +//import net.sf.jsqlparser.statement.delete.Delete; +//import net.sf.jsqlparser.statement.insert.Insert; +//import net.sf.jsqlparser.statement.select.Limit; +//import net.sf.jsqlparser.statement.select.PlainSelect; +//import net.sf.jsqlparser.statement.select.Select; +//import net.sf.jsqlparser.statement.select.SelectExpressionItem; +//import net.sf.jsqlparser.statement.select.SelectItem; +//import net.sf.jsqlparser.statement.select.SubSelect; +//import net.sf.jsqlparser.statement.update.Update; +//import net.sf.jsqlparser.util.TablesNamesFinder; +//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; +//import org.fisco.bcos.sdk.contract.precompiled.crud.common.ConditionOperator; +//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; +//import org.fisco.bcos.sdk.model.PrecompiledConstant; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +//public class CRUDParseUtils { +// private static final Logger logger = LoggerFactory.getLogger(CRUDParseUtils.class); +// public static final String PRIMARY_KEY = "primary key"; +// +// public static void parseCreateTable(String sql, Table table) +// throws JSQLParserException, FrontException { +// Statement statement = CCJSqlParserUtil.parse(sql); +// CreateTable createTable = (CreateTable) statement; +// +// // parse table name +// String tableName = createTable.getTable().getName(); +// table.setTableName(tableName); +// +// // parse key from index +// boolean keyFlag = false; +// List indexes = createTable.getIndexes(); +// if (indexes != null) { +// if (indexes.size() > 1) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Please provide only one primary key for the table."); +// } +// keyFlag = true; +// Index index = indexes.get(0); +// String type = index.getType().toLowerCase(); +// if (PRIMARY_KEY.equals(type)) { +// table.setKey(index.getColumnsNames().get(0)); +// table.setKeyFieldName(index.getColumnsNames().get(0)); +// } else { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Please provide only one primary key for the table."); +// } +// } +// List columnDefinitions = createTable.getColumnDefinitions(); +// // parse key from ColumnDefinition +// for (int i = 0; i < columnDefinitions.size(); i++) { +// List columnSpecStrings = columnDefinitions.get(i).getColumnSpecStrings(); +// if (columnSpecStrings == null) { +// continue; +// } else { +// if (columnSpecStrings.size() == 2 +// && "primary".equals(columnSpecStrings.get(0)) +// && "key".equals(columnSpecStrings.get(1))) { +// String key = columnDefinitions.get(i).getColumnName(); +// if (keyFlag) { +// if (!table.getKey().equals(key)) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Please provide only one primary key for the table."); +// } +// } else { +// keyFlag = true; +// table.setKey(key); +// } +// break; +// } +// } +// } +// if (!keyFlag) { +// throw new FrontException(ConstantCode.SQL_ERROR, "Please provide a primary key for the table."); +// } +// // parse value field +// List fieldsList = new ArrayList<>(); +// for (int i = 0; i < columnDefinitions.size(); i++) { +// String columnName = columnDefinitions.get(i).getColumnName(); +// if (fieldsList.contains(columnName)) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Please provide the field '" + columnName + "' only once."); +// } else { +// fieldsList.add(columnName); +// } +// } +// if (!fieldsList.contains(table.getKey())) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Please provide the field '" + table.getKey() + "' in column definition."); +// } else { +// fieldsList.remove(table.getKey()); +// } +// table.setValueFields(fieldsList); +// } +// +// public static String parseInsertedTableName(String sql) +// throws JSQLParserException, FrontException { +// Statement statement = CCJSqlParserUtil.parse(sql); +// Insert insert = (Insert) statement; +// +// if (insert.getSelect() != null) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The insert select clause is not supported."); +// } +// // parse table name +// return insert.getTable().getName(); +// } +// +// public static boolean parseInsert( +// String sql, Table table, Entry entry, Map tableDesc) +// throws JSQLParserException, FrontException { +// Statement statement = CCJSqlParserUtil.parse(sql); +// Insert insert = (Insert) statement; +// String valueFieldString = tableDesc.get(PrecompiledConstant.VALUE_FIELD_NAME); +// String[] valueFields = valueFieldString.split(","); +// String expectedValueField = +// tableDesc.get(PrecompiledConstant.KEY_FIELD_NAME) + ", " + valueFieldString; +// int expectedValueNum = valueFields.length + 1; +// +// if (insert.getSelect() != null) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The insert select clause is not supported."); +// } +// // parse table name +// String tableName = insert.getTable().getName(); +// table.setTableName(tableName); +// +// // parse columns +// List columns = insert.getColumns(); +// ItemsList itemsList = insert.getItemsList(); +// +// ExpressionList expressionList = (ExpressionList) itemsList; +// List expressions = expressionList.getExpressions(); +// +// String[] itemArr = new String[expressions.size()]; +// for (int i = 0; i < expressions.size(); i++) { +// itemArr[i] = expressions.get(i).toString().trim(); +// } +// if (columns != null) { +// if (columns.size() != itemArr.length) { +// throw new FrontException(ConstantCode.SQL_ERROR, "Column count doesn't match value count."); +// } +// if (expectedValueNum != columns.size()) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Column count doesn't match value count, fields size: " +// + valueFields.length +// + ", provided field value size: " +// + columns.size() +// + ", expected field list: " +// + expectedValueField); +// } +// List columnNames = new ArrayList<>(); +// for (Column column : columns) { +// String columnName = trimQuotes(column.toString()); +// if (columnNames.contains(columnName)) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Please provide the field '" + columnName + "' only once."); +// } else { +// columnNames.add(columnName); +// } +// } +// for (int i = 0; i < columnNames.size(); i++) { +// entry.getFieldNameToValue().put(columnNames.get(i), trimQuotes(itemArr[i])); +// } +// return false; +// } else { +// String keyField = tableDesc.get(PrecompiledConstant.KEY_FIELD_NAME); +// if (expectedValueNum != itemArr.length) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Column count doesn't match value count, fields size: " +// + valueFields.length +// + ", provided field value size: " +// + itemArr.length +// + ", expected field list: " +// + expectedValueField); +// } +// String[] allFields = new String[itemArr.length]; +// allFields[0] = keyField; +// System.arraycopy(valueFields, 0, allFields, 1, valueFields.length); +// for (int i = 0; i < itemArr.length; i++) { +// entry.getFieldNameToValue().put(allFields[i], trimQuotes(itemArr[i])); +// } +// return true; +// } +// } +// +// public static void parseSelect( +// String sql, Table table, Condition condition, List selectColumns) +// throws JSQLParserException, FrontException { +// Statement statement; +// statement = CCJSqlParserUtil.parse(sql); +// Select selectStatement = (Select) statement; +// +// // parse table name +// TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); +// List tableList = tablesNamesFinder.getTableList(selectStatement); +// if (tableList.size() != 1) { +// throw new FrontException(ConstantCode.SQL_ERROR, "Please provide only one table name."); +// } +// table.setTableName(tableList.get(0)); +// +// // parse where clause +// PlainSelect selectBody = (PlainSelect) selectStatement.getSelectBody(); +// if (selectBody.getOrderByElements() != null) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The order clause is not supported."); +// } +// if (selectBody.getGroupBy() != null) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The group clause is not supported."); +// } +// if (selectBody.getHaving() != null) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The having clause is not supported."); +// } +// if (selectBody.getJoins() != null) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The join clause is not supported."); +// } +// if (selectBody.getTop() != null) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The top clause is not supported."); +// } +// if (selectBody.getDistinct() != null) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The distinct clause is not supported."); +// } +// Expression expr = selectBody.getWhere(); +// condition = handleExpression(condition, expr); +// +// Limit limit = selectBody.getLimit(); +// if (limit != null) { +// parseLimit(condition, limit); +// } +// +// // parse select item +// List selectItems = selectBody.getSelectItems(); +// for (SelectItem item : selectItems) { +// if (item instanceof SelectExpressionItem) { +// SelectExpressionItem selectExpressionItem = (SelectExpressionItem) item; +// Expression expression = selectExpressionItem.getExpression(); +// if (expression instanceof Function) { +// Function func = (Function) expression; +// throw new FrontException(ConstantCode.SQL_ERROR, +// "The " + func.getName() + " function is not supported."); +// } +// } +// selectColumns.add(item.toString()); +// } +// } +// +// private static void checkExpression(Expression expression) throws FrontException { +// if (expression instanceof OrExpression) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The OrExpression is not supported."); +// } +// if (expression instanceof NotExpression) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The NotExpression is not supported."); +// } +// if (expression instanceof InExpression) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The InExpression is not supported."); +// } +// if (expression instanceof LikeExpression) { +// logger.debug("The LikeExpression is not supported."); +// throw new FrontException(ConstantCode.SQL_ERROR, "The LikeExpression is not supported."); +// } +// if (expression instanceof SubSelect) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The SubSelect is not supported."); +// } +// if (expression instanceof IsNullExpression) { +// throw new FrontException(ConstantCode.SQL_ERROR, "The IsNullExpression is not supported."); +// } +// } +// +// private static Condition handleExpression(Condition condition, Expression expr) +// throws FrontException { +// if (expr instanceof BinaryExpression) { +// condition = getWhereClause((BinaryExpression) (expr), condition); +// } +// checkExpression(expr); +// Map> conditions = condition.getConditions(); +// Set keys = conditions.keySet(); +// for (String key : keys) { +// Map value = conditions.get(key); +// ConditionOperator operation = value.keySet().iterator().next(); +// String itemValue = value.values().iterator().next(); +// String newValue = trimQuotes(itemValue); +// value.put(operation, newValue); +// conditions.put(key, value); +// } +// condition.setConditions(conditions); +// return condition; +// } +// +// public static String trimQuotes(String str) { +// char[] value = str.toCharArray(); +// int len = value.length; +// int st = 1; +// char[] val = value; /* avoid getfield opcode */ +// +// while ((st < len) && (val[st] == '"' || val[st] == '\'')) { +// st++; +// } +// while ((st < len) && (val[len - 1] == '"' || val[len - 1] == '\'')) { +// len--; +// } +// String string = ((st > 1) || (len < value.length)) ? str.substring(st, len) : str; +// return string; +// } +// +// public static void parseUpdate(String sql, Table table, Entry entry, Condition condition) +// throws JSQLParserException, FrontException { +// Statement statement = CCJSqlParserUtil.parse(sql); +// Update update = (Update) statement; +// +// // parse table name +// List tables = update.getTables(); +// String tableName = tables.get(0).getName(); +// table.setTableName(tableName); +// +// // parse columns +// List columns = update.getColumns(); +// List expressions = update.getExpressions(); +// int size = expressions.size(); +// String[] values = new String[size]; +// for (int i = 0; i < size; i++) { +// values[i] = expressions.get(i).toString(); +// } +// for (int i = 0; i < columns.size(); i++) { +// entry.getFieldNameToValue() +// .put(trimQuotes(columns.get(i).toString()), trimQuotes(values[i])); +// } +// +// // parse where clause +// Expression where = update.getWhere(); +// if (where != null) { +// BinaryExpression expr2 = (BinaryExpression) (where); +// handleExpression(condition, expr2); +// } +// Limit limit = update.getLimit(); +// parseLimit(condition, limit); +// } +// +// public static void parseRemove(String sql, Table table, Condition condition) +// throws JSQLParserException, FrontException { +// Statement statement = CCJSqlParserUtil.parse(sql); +// Delete delete = (Delete) statement; +// +// // parse table name +// net.sf.jsqlparser.schema.Table sqlTable = delete.getTable(); +// table.setTableName(sqlTable.getName()); +// +// // parse where clause +// Expression where = delete.getWhere(); +// if (where != null) { +// BinaryExpression expr = (BinaryExpression) (where); +// handleExpression(condition, expr); +// } +// Limit limit = delete.getLimit(); +// parseLimit(condition, limit); +// } +// +// private static void parseLimit(Condition condition, Limit limit) +// throws FrontException { +// if (limit != null) { +// Expression offset = limit.getOffset(); +// Expression count = limit.getRowCount(); +// try { +// if (offset != null) { +// condition.Limit( +// Integer.parseInt(offset.toString()), +// Integer.parseInt(count.toString())); +// } else { +// condition.Limit(Integer.parseInt(count.toString())); +// } +// } catch (NumberFormatException e) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Please provide limit parameters by non-negative integer mode, " +// + PrecompiledUtils.NonNegativeIntegerRange +// + "."); +// } +// } +// } +// +// private static Condition getWhereClause(Expression expr, Condition condition) +// throws FrontException { +// Set keySet = new HashSet<>(); +// Set conflictKeys = new HashSet<>(); +// Set unsupportedConditions = new HashSet<>(); +// expr.accept( +// new ExpressionVisitorAdapter() { +// @Override +// protected void visitBinaryExpression(BinaryExpression expr) { +// if (expr instanceof ComparisonOperator) { +// String key = trimQuotes(expr.getLeftExpression().toString()); +// if (keySet.contains(key)) { +// conflictKeys.add(key); +// } +// keySet.add(key); +// String operation = expr.getStringExpression(); +// String value = trimQuotes(expr.getRightExpression().toString()); +// switch (operation) { +// case "=": +// condition.EQ(key, value); +// break; +// case "!=": +// condition.NE(key, value); +// break; +// case ">": +// condition.GT(key, value); +// break; +// case ">=": +// condition.GE(key, value); +// break; +// case "<": +// condition.LT(key, value); +// break; +// case "<=": +// condition.LE(key, value); +// break; +// default: +// break; +// } +// } else { +// try { +// checkExpression(expr); +// } catch (FrontException e) { +// unsupportedConditions.add(e.getMessage()); +// } +// } +// super.visitBinaryExpression(expr); +// } +// }); +// if (conflictKeys.size() > 0) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Wrong condition! There cannot be the same field in the same condition! The conflicting field is: " +// + conflictKeys.toString()); +// } +// if (unsupportedConditions.size() > 0) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Wrong condition! Find unsupported conditions! message: " +// + unsupportedConditions.toString()); +// } +// return condition; +// } +// +// public static void invalidSymbol(String sql) throws FrontException { +// if (sql.contains(";")) { +// throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese semicolon."); +// } else if (sql.contains("“") +// || sql.contains("”") +// || sql.contains("‘") +// || sql.contains("’")) { +// throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese quotes."); +// } else if (sql.contains(",")) { +// throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese comma."); +// } +// } +// +// public static boolean checkTableExistence(List> descTable) { +// if (descTable.size() == 0 +// || descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME).equals("")) { +//// System.out.println("The table \"" + tableName + "\" doesn't exist!"); +// return false; +// } +// return true; +// } +// +// +// public static String formatJson(String jsonStr) { +// if (null == jsonStr || "".equals(jsonStr)) return ""; +// jsonStr = jsonStr.replace("\\n", ""); +// StringBuilder sb = new StringBuilder(); +// char last = '\0'; +// char current = '\0'; +// int indent = 0; +// boolean isInQuotationMarks = false; +// for (int i = 0; i < jsonStr.length(); i++) { +// last = current; +// current = jsonStr.charAt(i); +// switch (current) { +// case '"': +// if (last != '\\') { +// isInQuotationMarks = !isInQuotationMarks; +// } +// sb.append(current); +// break; +// case '{': +// case '[': +// sb.append(current); +// if (!isInQuotationMarks) { +// sb.append('\n'); +// indent++; +// addIndentBlank(sb, indent); +// } +// break; +// case '}': +// case ']': +// if (!isInQuotationMarks) { +// sb.append('\n'); +// indent--; +// addIndentBlank(sb, indent); +// } +// sb.append(current); +// break; +// case ',': +// sb.append(current); +// if (last != '\\' && !isInQuotationMarks) { +// sb.append('\n'); +// addIndentBlank(sb, indent); +// } +// break; +// case ' ': +// if (',' != jsonStr.charAt(i - 1)) { +// sb.append(current); +// } +// break; +// case '\\': +// sb.append("\\"); +// break; +// default: +// if (!(current == " ".charAt(0))) sb.append(current); +// } +// } +// +// return sb.toString(); +// } +// +// private static void addIndentBlank(StringBuilder sb, int indent) { +// for (int i = 0; i < indent; i++) { +// sb.append(" "); +// } +// } +// +// +// public static void handleKey(Table table, Condition condition) { +// +// String keyName = table.getKey(); +// String keyValue = ""; +// Map keyMap = condition.getConditions().get(keyName); +// if (keyMap == null) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Please provide a equal condition for the key field '" +// + keyName +// + "' in where clause."); +// } else { +// Set keySet = keyMap.keySet(); +// for (ConditionOperator enumOP : keySet) { +// if (enumOP != ConditionOperator.eq) { +// throw new FrontException(ConstantCode.SQL_ERROR, +// "Please provide a equal condition for the key field '" +// + keyName +// + "' in where clause."); +// } else { +// keyValue = keyMap.get(enumOP); +// } +// } +// } +// table.setKey(keyValue); +// } +// +// public static List> filterSystemColum(List> result) { +// +// List filteredColumns = Arrays.asList("_id_", "_hash_", "_status_", "_num_"); +// List> filteredResult = new ArrayList<>(result.size()); +// Map filteredRecords; +// for (Map records : result) { +// filteredRecords = new LinkedHashMap<>(); +// Set recordKeys = records.keySet(); +// for (String recordKey : recordKeys) { +// if (!filteredColumns.contains(recordKey)) { +// filteredRecords.put(recordKey, records.get(recordKey)); +// } +// } +// filteredResult.add(filteredRecords); +// } +// return filteredResult; +// } +// +// public static List> getSelectedColumn( +// List selectColumns, List> result) { +// List> selectedResult = new ArrayList<>(result.size()); +// Map selectedRecords; +// for (Map records : result) { +// selectedRecords = new LinkedHashMap<>(); +// for (String column : selectColumns) { +// Set recordKeys = records.keySet(); +// for (String recordKey : recordKeys) { +// if (recordKey.equals(column)) { +// selectedRecords.put(recordKey, records.get(recordKey)); +// } +// } +// } +// selectedResult.add(selectedRecords); +// } +// selectedResult.forEach(System.out::println); +// return selectedResult; +// } +//} diff --git a/src/main/java/com/webank/webase/front/solc/SolcService.java b/src/main/java/com/webank/webase/front/solc/SolcService.java index f1c26c00c..e79d0423d 100644 --- a/src/main/java/com/webank/webase/front/solc/SolcService.java +++ b/src/main/java/com/webank/webase/front/solc/SolcService.java @@ -199,7 +199,7 @@ public List getAllSolcInfo() { @Transactional public boolean deleteFile(Integer solcId) { - SolcInfo solcInfo = solcRepository.findOne(solcId); + SolcInfo solcInfo = solcRepository.findById(solcId).orElse(null); String fileName = solcInfo.getSolcName(); File solcDir = getSolcDir(); String solcLocate = solcDir.getAbsolutePath() + File.separator + fileName; @@ -212,10 +212,10 @@ public boolean deleteFile(Integer solcId) { } private void removeSolcInfo(Integer solcId) { - SolcInfo checkExist = solcRepository.findOne(solcId); + SolcInfo checkExist = solcRepository.findById(solcId).orElse(null); if (Objects.isNull(checkExist)) { throw new FrontException(ConstantCode.FILE_IS_NOT_EXIST); } - solcRepository.delete(solcId); + solcRepository.deleteById(solcId); } } diff --git a/src/main/java/com/webank/webase/front/transaction/TransService.java b/src/main/java/com/webank/webase/front/transaction/TransService.java index 9c99908ea..f442c48c7 100644 --- a/src/main/java/com/webank/webase/front/transaction/TransService.java +++ b/src/main/java/com/webank/webase/front/transaction/TransService.java @@ -34,7 +34,6 @@ import com.webank.webase.front.keystore.entity.KeyStoreInfo; import com.webank.webase.front.keystore.entity.RspMessageHashSignature; import com.webank.webase.front.keystore.entity.RspUserInfo; -import com.webank.webase.front.precompiledapi.PrecompiledService; import com.webank.webase.front.transaction.entity.ContractFunction; import com.webank.webase.front.transaction.entity.ReqSignMessageHash; import com.webank.webase.front.transaction.entity.ReqTransHandle; @@ -122,8 +121,8 @@ public class TransService { @Autowired @Qualifier(value = "common") private CryptoSuite cryptoSuite; - @Autowired - private PrecompiledService precompiledService; +// @Autowired +// private PrecompiledService precompiledService; @Autowired private BcosSDK bcosSDK; /** @@ -145,20 +144,20 @@ public Object transHandleWithSign(ReqTransHandleWithSign req) throws FrontExcept List funcParam = req.getFuncParam() == null ? new ArrayList<>() : req.getFuncParam(); String contractAddress = req.getContractAddress(); // handle cns - if (req.isUseCns()) { - try { - List cnsList = precompiledService.queryCnsByNameAndVersion(req.getGroupId(), - req.getCnsName(), req.getVersion()); - if (CollectionUtils.isEmpty(cnsList)) { - throw new FrontException(VERSION_NOT_EXISTS); - } - contractAddress = cnsList.iterator().next().getAddress(); - log.info("transHandleWithSign cns contractAddress:{}", contractAddress); - } catch (ContractException e) { - log.error("queryCnsByNameAndVersion ContractException fail:[]", e); - throw new FrontException(ConstantCode.CNS_QUERY_FAIL); - } - } +// if (req.isUseCns()) { +// try { +// List cnsList = precompiledService.queryCnsByNameAndVersion(req.getGroupId(), +// req.getCnsName(), req.getVersion()); +// if (CollectionUtils.isEmpty(cnsList)) { +// throw new FrontException(VERSION_NOT_EXISTS); +// } +// contractAddress = cnsList.iterator().next().getAddress(); +// log.info("transHandleWithSign cns contractAddress:{}", contractAddress); +// } catch (ContractException e) { +// log.error("queryCnsByNameAndVersion ContractException fail:[]", e); +// throw new FrontException(ConstantCode.CNS_QUERY_FAIL); +// } +// } return this.transHandleWithSign(groupId, signUserId, contractAddress, abiStr, funcName, funcParam); } @@ -477,20 +476,20 @@ public Object transHandleLocal(ReqTransHandle req) { String userAddress = req.getUser(); String contractAddress = req.getContractAddress(); - if (req.isUseCns()) { - try { - List cnsList = precompiledService.queryCnsByNameAndVersion(groupId, - req.getCnsName(), req.getVersion()); - if (CollectionUtils.isEmpty(cnsList)) { - throw new FrontException(VERSION_NOT_EXISTS); - } - contractAddress = cnsList.iterator().next().getAddress(); - log.info("transHandleLocal cns contractAddress:{}", contractAddress); - } catch (ContractException e) { - log.error("queryCnsByNameAndVersion ContractException fail:[]", e); - throw new FrontException(ConstantCode.CNS_QUERY_FAIL); - } - } +// if (req.isUseCns()) { +// try { +// List cnsList = precompiledService.queryCnsByNameAndVersion(groupId, +// req.getCnsName(), req.getVersion()); +// if (CollectionUtils.isEmpty(cnsList)) { +// throw new FrontException(VERSION_NOT_EXISTS); +// } +// contractAddress = cnsList.iterator().next().getAddress(); +// log.info("transHandleLocal cns contractAddress:{}", contractAddress); +// } catch (ContractException e) { +// log.error("queryCnsByNameAndVersion ContractException fail:[]", e); +// throw new FrontException(ConstantCode.CNS_QUERY_FAIL); +// } +// } String encodeFunction = this.encodeFunction2Str(abiStr, funcName, funcParam); @@ -720,14 +719,14 @@ public String createRawTxEncoded(boolean isLocal, String user, boolean isUseCns, String cnsName, String cnsVersion, String funcName, List funcParam) throws Exception { - if (isUseCns) { - List cnsList = precompiledService.queryCnsByNameAndVersion(groupId, cnsName, cnsVersion); - if (CollectionUtils.isEmpty(cnsList)) { - throw new FrontException(VERSION_NOT_EXISTS); - } - contractAddress = cnsList.iterator().next().getAddress(); - log.info("transHandleWithSign cns contractAddress:{}", contractAddress); - } +// if (isUseCns) { +// List cnsList = precompiledService.queryCnsByNameAndVersion(groupId, cnsName, cnsVersion); +// if (CollectionUtils.isEmpty(cnsList)) { +// throw new FrontException(VERSION_NOT_EXISTS); +// } +// contractAddress = cnsList.iterator().next().getAddress(); +// log.info("transHandleWithSign cns contractAddress:{}", contractAddress); +// } // encode function String encodeFunction = this.encodeFunction2Str(JsonUtils.objToString(contractAbi), funcName, funcParam); // check groupId diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 027571c24..9c2fb895c 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -44,7 +44,9 @@ spring: multipart: max-request-size: 30MB # request max size max-file-size: 20MB # single file size - + mvc: + pathmatch: + matching-strategy: ant_path_matcher server: port: 5002 @@ -58,8 +60,8 @@ sdk: corePoolSize: 50 maxPoolSize: 100 queueCapacity: 100 - ip: 127.0.0.1 - channelPort: 20200 + ip: 10.107.120.121 + channelPort: 21201 certPath: conf # cert path of relative or absolute logging: From 5ef0fc74a52545e4072cbc1cea9ad4d2861cc480 Mon Sep 17 00:00:00 2001 From: Shaeny <417298932@qq.com> Date: Tue, 27 Dec 2022 10:11:42 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/application.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 9c2fb895c..fba421c77 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -60,8 +60,8 @@ sdk: corePoolSize: 50 maxPoolSize: 100 queueCapacity: 100 - ip: 10.107.120.121 - channelPort: 21201 + ip: 127.0.0.1 + channelPort: 20200 certPath: conf # cert path of relative or absolute logging: From 9ac66097f806a22241d05248b1e65c5ad8667104 Mon Sep 17 00:00:00 2001 From: Shaeny <417298932@qq.com> Date: Tue, 27 Dec 2022 10:18:05 +0800 Subject: [PATCH 3/4] =?UTF-8?q?=E4=BF=AE=E6=94=B9gradle=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/build.gradle b/build.gradle index 01a330ca8..a372cb940 100644 --- a/build.gradle +++ b/build.gradle @@ -23,22 +23,22 @@ repositories { } -def spring_version="5.2.22.RELEASE" -List spring =[ - "org.springframework:spring-core:$spring_version", - "org.springframework:spring-beans:$spring_version", - "org.springframework:spring-context:$spring_version", - "org.springframework:spring-tx:$spring_version", - "org.springframework:spring-web:$spring_version", - "org.springframework:spring-webmvc:$spring_version", - "org.springframework:spring-jdbc:$spring_version", - // cover old version - "org.springframework:spring-aspects:$spring_version", - "org.springframework:spring-messaging:$spring_version", - "org.springframework:spring-orm:$spring_version", - "org.springframework:spring-test:$spring_version" - -] +//def spring_version="5.2.22.RELEASE" +//List spring =[ +// "org.springframework:spring-core:$spring_version", +// "org.springframework:spring-beans:$spring_version", +// "org.springframework:spring-context:$spring_version", +// "org.springframework:spring-tx:$spring_version", +// "org.springframework:spring-web:$spring_version", +// "org.springframework:spring-webmvc:$spring_version", +// "org.springframework:spring-jdbc:$spring_version", +// // cover old version +// "org.springframework:spring-aspects:$spring_version", +// "org.springframework:spring-messaging:$spring_version", +// "org.springframework:spring-orm:$spring_version", +// "org.springframework:spring-test:$spring_version" +// +//] def spring_boot_version="2.7.0" List spring_boot =[ From 6e4dfa491d38f3a96d03e48ba1ee8aa52df51e9f Mon Sep 17 00:00:00 2001 From: Shaeny <417298932@qq.com> Date: Wed, 28 Dec 2022 15:31:11 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=E4=BF=AE=E6=94=B9gradle=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 39 +- .../front/contract/ContractRepository.java | 1 - .../front/contract/ContractService.java | 17 +- .../contractStore/PresetDataService.java | 2 +- .../precompiledapi/PrecompiledController.java | 1420 ++++++++--------- .../precompiledapi/PrecompiledService.java | 458 +++--- .../precompiledapi/crud/CRUDParseUtils.java | 1244 +++++++-------- .../front/transaction/TransService.java | 77 +- 8 files changed, 1630 insertions(+), 1628 deletions(-) diff --git a/build.gradle b/build.gradle index a372cb940..4a81f58b7 100644 --- a/build.gradle +++ b/build.gradle @@ -23,24 +23,24 @@ repositories { } -//def spring_version="5.2.22.RELEASE" -//List spring =[ -// "org.springframework:spring-core:$spring_version", -// "org.springframework:spring-beans:$spring_version", -// "org.springframework:spring-context:$spring_version", -// "org.springframework:spring-tx:$spring_version", -// "org.springframework:spring-web:$spring_version", -// "org.springframework:spring-webmvc:$spring_version", -// "org.springframework:spring-jdbc:$spring_version", -// // cover old version -// "org.springframework:spring-aspects:$spring_version", -// "org.springframework:spring-messaging:$spring_version", -// "org.springframework:spring-orm:$spring_version", -// "org.springframework:spring-test:$spring_version" -// -//] - -def spring_boot_version="2.7.0" +def spring_version="5.2.22.RELEASE" +List spring =[ + "org.springframework:spring-core:$spring_version", + "org.springframework:spring-beans:$spring_version", + "org.springframework:spring-context:$spring_version", + "org.springframework:spring-tx:$spring_version", + "org.springframework:spring-web:$spring_version", + "org.springframework:spring-webmvc:$spring_version", + "org.springframework:spring-jdbc:$spring_version", + // cover old version + "org.springframework:spring-aspects:$spring_version", + "org.springframework:spring-messaging:$spring_version", + "org.springframework:spring-orm:$spring_version", + "org.springframework:spring-test:$spring_version" + +] + +def spring_boot_version="2.3.12.RELEASE" List spring_boot =[ "org.springframework.boot:spring-boot-starter-web:$spring_boot_version", "org.springframework.boot:spring-boot-autoconfigure:$spring_boot_version", @@ -98,7 +98,7 @@ List scaffold = [ ] dependencies { - compile spring_boot,swagger,logger,jaxb,jackson,tomcat,scaffold + compile spring,spring_boot,swagger,logger,jaxb,jackson,tomcat,scaffold compile 'org.fisco-bcos.java-sdk:fisco-bcos-java-sdk:2.7.2' // support guomi/ecdsa same time, support solcJ-0.5.2 compile 'org.fisco-bcos:solcJ:0.4.25-rc1' @@ -106,6 +106,7 @@ dependencies { compile 'org.fusesource:sigar:1.6.4' annotationProcessor 'org.projectlombok:lombok:1.18.6' compile 'org.projectlombok:lombok:1.18.6' + compile 'com.github.jsqlparser:jsqlparser:2.0' compile 'org.apache.commons:commons-lang3:3.8.1' compile 'org.slf4j:jcl-over-slf4j:1.7.30' compile 'org.apache.httpcomponents:httpclient:4.5.14' diff --git a/src/main/java/com/webank/webase/front/contract/ContractRepository.java b/src/main/java/com/webank/webase/front/contract/ContractRepository.java index ad3cadc15..ffe23f379 100644 --- a/src/main/java/com/webank/webase/front/contract/ContractRepository.java +++ b/src/main/java/com/webank/webase/front/contract/ContractRepository.java @@ -17,7 +17,6 @@ import java.util.List; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import com.webank.webase.front.contract.entity.Contract; diff --git a/src/main/java/com/webank/webase/front/contract/ContractService.java b/src/main/java/com/webank/webase/front/contract/ContractService.java index 9fb7262f1..7c8e474c6 100644 --- a/src/main/java/com/webank/webase/front/contract/ContractService.java +++ b/src/main/java/com/webank/webase/front/contract/ContractService.java @@ -43,6 +43,7 @@ import com.webank.webase.front.contract.entity.RspContractNoAbi; import com.webank.webase.front.contract.entity.RspMultiContractCompile; import com.webank.webase.front.keystore.KeyStoreService; +import com.webank.webase.front.precompiledapi.PrecompiledService; import com.webank.webase.front.precompiledapi.PrecompiledWithSignService; import com.webank.webase.front.precompiledapi.permission.PermissionManageService; import com.webank.webase.front.transaction.TransService; @@ -132,8 +133,8 @@ public class ContractService { private PermissionManageService permissionManageService; @Autowired private PrecompiledWithSignService precompiledWithSignService; -// @Autowired -// private PrecompiledService precompiledService; + @Autowired + private PrecompiledService precompiledService; @Autowired @Qualifier(value = "common") private CryptoSuite cryptoSuite; @@ -327,12 +328,12 @@ public void registerCns(ReqRegisterCns req) throws Exception { String version = req.getVersion(); String contractAddress = req.getContractAddress(); String abiInfo = JsonUtils.toJSONString(req.getAbiInfo()); -// List cnsList = -// precompiledService.queryCnsByNameAndVersion(groupId, cnsName, version); -// if (!CollectionUtils.isEmpty(cnsList)) { -// log.error("registerCns. cnsName:{} version:{} exists", cnsName, version); -// throw new FrontException(ErrorCodeHandleUtils.PRECOMPILED_CONTRACT_NAME_VERSION_EXIST); -// } + List cnsList = + precompiledService.queryCnsByNameAndVersion(groupId, cnsName, version); + if (!CollectionUtils.isEmpty(cnsList)) { + log.error("registerCns. cnsName:{} version:{} exists", cnsName, version); + throw new FrontException(ErrorCodeHandleUtils.PRECOMPILED_CONTRACT_NAME_VERSION_EXIST); + } // locally if (req.isSaveEnabled()) { if (StringUtils.isBlank(req.getContractPath())) { diff --git a/src/main/java/com/webank/webase/front/contractStore/PresetDataService.java b/src/main/java/com/webank/webase/front/contractStore/PresetDataService.java index 10eb7ffee..c5f2528ef 100644 --- a/src/main/java/com/webank/webase/front/contractStore/PresetDataService.java +++ b/src/main/java/com/webank/webase/front/contractStore/PresetDataService.java @@ -372,7 +372,7 @@ public void readAndInitContractItem() { item2Save.add(item); } } - contractItemRepository.exists((Specification) item2Save); + contractItemRepository.saveAll(item2Save); log.info("readAndInitContractItem save {} items", contractItems.size()); } diff --git a/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledController.java b/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledController.java index 70aa6b1f3..63496dab4 100644 --- a/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledController.java +++ b/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledController.java @@ -1,734 +1,734 @@ -///* -// * Copyright 2014-2020 the original author or authors. -// * -// * Licensed under the Apache License, Version 2.0 (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 -// * -// * Unless required by applicable law or agreed to in writing, software distributed under the License -// * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express -// * or implied. See the License for the specific language governing permissions and limitations under -// * the License. -// */ -//package com.webank.webase.front.precompiledapi; -// -//import com.webank.webase.front.base.code.ConstantCode; -//import com.webank.webase.front.base.exception.FrontException; -//import com.webank.webase.front.base.response.BasePageResponse; -//import com.webank.webase.front.base.response.BaseResponse; -//import com.webank.webase.front.precompiledapi.crud.CRUDParseUtils; -//import com.webank.webase.front.precompiledapi.crud.Table; -//import com.webank.webase.front.precompiledapi.entity.ConsensusHandle; -//import com.webank.webase.front.precompiledapi.entity.ContractManageResult; -//import com.webank.webase.front.precompiledapi.entity.ContractStatusHandle; -//import com.webank.webase.front.precompiledapi.entity.CrudHandle; -//import com.webank.webase.front.precompiledapi.entity.NodeInfo; -//import com.webank.webase.front.util.JsonUtils; -//import com.webank.webase.front.util.PrecompiledUtils; -//import com.webank.webase.front.util.pageutils.List2Page; -//import io.swagger.annotations.Api; -//import io.swagger.annotations.ApiImplicitParam; -//import io.swagger.annotations.ApiOperation; -//import java.time.Duration; -//import java.time.Instant; -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.List; -//import java.util.Map; -//import javax.validation.Valid; -//import lombok.extern.slf4j.Slf4j; -//import org.apache.commons.lang3.StringUtils; -//import org.fisco.bcos.sdk.contract.precompiled.cns.CnsInfo; -//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; -//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; -//import org.fisco.bcos.sdk.model.PrecompiledConstant; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.web.bind.annotation.GetMapping; -//import org.springframework.web.bind.annotation.PostMapping; -//import org.springframework.web.bind.annotation.RequestBody; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.RequestParam; -//import org.springframework.web.bind.annotation.RestController; -// -///** -// * Precompiled common controller including management of CNS, node consensus status, CRUD -// */ -//@Api(value = "/precompiled", tags = "precompiled manage interface") -//@Slf4j -//@RestController -//@RequestMapping(value = "precompiled") -//public class PrecompiledController { -// @Autowired -// private PrecompiledService precompiledService; -// -// /** -// * Cns manage -// */ -// @GetMapping("cns/list") -// public Object queryCns(@RequestParam(defaultValue = "1") int groupId, -// @RequestParam String contractNameAndVersion, -// @RequestParam(defaultValue = "10") int pageSize, -// @RequestParam(defaultValue = "1") int pageNumber) throws Exception { -// Instant startTime = Instant.now(); -// log.info("start queryCns. startTime:{}, groupId:{}, contractNameAndVersion:{}", -// startTime.toEpochMilli(), groupId, contractNameAndVersion); -// List resList = new ArrayList<>(); -// // get "name:version" -// String[] params = contractNameAndVersion.split(":"); -// if (params.length == 1) { -// String name = params[0]; -// resList = precompiledService.queryCnsByName(groupId, name); -// log.info("end queryCns useTime:{} resList:{}", -// Duration.between(startTime, Instant.now()).toMillis(), resList); -// if (resList.size() != 0) { -// List2Page list2Page = -// new List2Page(resList, pageSize, pageNumber); -// List finalList = list2Page.getPagedList(); -// long totalCount = (long) resList.size(); -// log.debug("end queryCns. Contract Name finalList:{}", finalList); -// return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); -// } else { -// return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); -// } -// } else if (params.length == 2) { -// String name = params[0]; -// String version = params[1]; -// if (!PrecompiledUtils.checkVersion(version)) { -// return ConstantCode.INVALID_VERSION; -// } -// // check return list size -// resList = precompiledService.queryCnsByNameAndVersion(groupId, name, version); -// log.info("end queryCns useTime:{} resList:{}", -// Duration.between(startTime, Instant.now()).toMillis(), resList); -// if (resList.size() != 0) { -// List2Page list2Page = -// new List2Page(resList, pageSize, pageNumber); -// List finalList = list2Page.getPagedList(); -// long totalCount = (long) resList.size(); -// log.debug("in queryCns case: Contract Name And Version. finalList:{}", finalList); -// return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); -// } else { -// return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); +/* + * Copyright 2014-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (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 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.webank.webase.front.precompiledapi; + +import com.webank.webase.front.base.code.ConstantCode; +import com.webank.webase.front.base.exception.FrontException; +import com.webank.webase.front.base.response.BasePageResponse; +import com.webank.webase.front.base.response.BaseResponse; +import com.webank.webase.front.precompiledapi.crud.CRUDParseUtils; +import com.webank.webase.front.precompiledapi.crud.Table; +import com.webank.webase.front.precompiledapi.entity.ConsensusHandle; +import com.webank.webase.front.precompiledapi.entity.ContractManageResult; +import com.webank.webase.front.precompiledapi.entity.ContractStatusHandle; +import com.webank.webase.front.precompiledapi.entity.CrudHandle; +import com.webank.webase.front.precompiledapi.entity.NodeInfo; +import com.webank.webase.front.util.JsonUtils; +import com.webank.webase.front.util.PrecompiledUtils; +import com.webank.webase.front.util.pageutils.List2Page; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiOperation; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import javax.validation.Valid; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.fisco.bcos.sdk.contract.precompiled.cns.CnsInfo; +import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; +import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; +import org.fisco.bcos.sdk.model.PrecompiledConstant; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * Precompiled common controller including management of CNS, node consensus status, CRUD + */ +@Api(value = "/precompiled", tags = "precompiled manage interface") +@Slf4j +@RestController +@RequestMapping(value = "precompiled") +public class PrecompiledController { + @Autowired + private PrecompiledService precompiledService; + + /** + * Cns manage + */ + @GetMapping("cns/list") + public Object queryCns(@RequestParam(defaultValue = "1") int groupId, + @RequestParam String contractNameAndVersion, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "1") int pageNumber) throws Exception { + Instant startTime = Instant.now(); + log.info("start queryCns. startTime:{}, groupId:{}, contractNameAndVersion:{}", + startTime.toEpochMilli(), groupId, contractNameAndVersion); + List resList = new ArrayList<>(); + // get "name:version" + String[] params = contractNameAndVersion.split(":"); + if (params.length == 1) { + String name = params[0]; + resList = precompiledService.queryCnsByName(groupId, name); + log.info("end queryCns useTime:{} resList:{}", + Duration.between(startTime, Instant.now()).toMillis(), resList); + if (resList.size() != 0) { + List2Page list2Page = + new List2Page(resList, pageSize, pageNumber); + List finalList = list2Page.getPagedList(); + long totalCount = (long) resList.size(); + log.debug("end queryCns. Contract Name finalList:{}", finalList); + return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); + } else { + return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); + } + } else if (params.length == 2) { + String name = params[0]; + String version = params[1]; + if (!PrecompiledUtils.checkVersion(version)) { + return ConstantCode.INVALID_VERSION; + } + // check return list size + resList = precompiledService.queryCnsByNameAndVersion(groupId, name, version); + log.info("end queryCns useTime:{} resList:{}", + Duration.between(startTime, Instant.now()).toMillis(), resList); + if (resList.size() != 0) { + List2Page list2Page = + new List2Page(resList, pageSize, pageNumber); + List finalList = list2Page.getPagedList(); + long totalCount = (long) resList.size(); + log.debug("in queryCns case: Contract Name And Version. finalList:{}", finalList); + return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); + } else { + return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); + } + } else { + return ConstantCode.PARAM_ERROR; + } + } + + + + /** + * Node manage (Consensus control) + */ + + @GetMapping("consensus/list") + public Object getNodeList(@RequestParam(defaultValue = "1") int groupId, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "1") int pageNumber) throws Exception { + Instant startTime = Instant.now(); + log.info("start getNodeList startTime:{}, groupId:{}", startTime.toEpochMilli(), groupId); + List resList = precompiledService.getNodeList(groupId); + log.info("end getNodeList useTime:{} resList:{}", + Duration.between(startTime, Instant.now()).toMillis(), resList); + if (resList.size() != 0) { + List2Page list2Page = new List2Page(resList, pageSize, pageNumber); + List finalList = list2Page.getPagedList(); + long totalCount = resList.size(); + log.debug("end getNodeList. finalList:{}", finalList); + return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); + } else { + return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); + } + } + + @ApiOperation(value = "nodeManageControl", notes = "set system config value by key") + @ApiImplicitParam(name = "consensusHandle", value = "node consensus status control", + required = true, dataType = "ConsensusHandle") + @PostMapping("consensus") + public Object nodeManageControl(@Valid @RequestBody ConsensusHandle consensusHandle) + throws Exception { + log.info("start nodeManageControl. consensusHandle:{}", consensusHandle); + String nodeType = consensusHandle.getNodeType(); + int groupId = consensusHandle.getGroupId(); + String from = consensusHandle.getSignUserId(); + String nodeId = consensusHandle.getNodeId(); + if (!PrecompiledUtils.checkNodeId(nodeId)) { + return ConstantCode.INVALID_NODE_ID; + } + switch (nodeType) { + case PrecompiledUtils.NODE_TYPE_SEALER: + return addSealer(groupId, from, nodeId); + case PrecompiledUtils.NODE_TYPE_OBSERVER: + return addObserver(groupId, from, nodeId); + case PrecompiledUtils.NODE_TYPE_REMOVE: + return removeNode(groupId, from, nodeId); + default: + log.debug("end nodeManageControl invalid node type"); + return ConstantCode.INVALID_NODE_TYPE; + } + } + + public Object addSealer(int groupId, String fromAddress, String nodeId) throws Exception { + Instant startTime = Instant.now(); + log.info("start addSealer startTime:{}, groupId:{},fromAddress:{},nodeId:{}", + startTime.toEpochMilli(), groupId, fromAddress, nodeId); + try { + Object res = precompiledService.addSealer(groupId, fromAddress, nodeId); + log.info("end addSealer useTime:{} res:{}", + Duration.between(startTime, Instant.now()).toMillis(), res); + return res; + } catch (Exception e) { + log.error("addSealer exception:[]", e); + return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); + } + } + + public Object addObserver(int groupId, String fromAddress, String nodeId) throws Exception { + Instant startTime = Instant.now(); + log.info("start addObserver startTime:{}, groupId:{},fromAddress:{},nodeId:{}", + startTime.toEpochMilli(), groupId, fromAddress, nodeId); + try { + Object res = precompiledService.addObserver(groupId, fromAddress, nodeId); + log.info("end addObserver useTime:{} res:{}", + Duration.between(startTime, Instant.now()).toMillis(), res); + return res; + } catch (Exception e) { + log.error("addObserver exception:[]", e); + return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); + } + } + + public Object removeNode(int groupId, String fromAddress, String nodeId) throws Exception { + Instant startTime = Instant.now(); + log.info("start addSealer startTime:{}, groupId:{},fromAddress:{},nodeId:{}", + startTime.toEpochMilli(), groupId, fromAddress, nodeId); + try { + Object res = precompiledService.removeNode(groupId, fromAddress, nodeId); + log.info("end addSealer useTime:{} res:{}", + Duration.between(startTime, Instant.now()).toMillis(), res); + return res; + } catch (Exception e) { // e.getCause + log.error("removeNode exception:[]", e); + return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); + } + } + + /** + * CRUD operation checkVersionForCRUD(); + * "bcos's version above of 2.0.0-rc3 support crud operation" + */ + @ApiOperation(value = "crudManage", notes = "operate table by crud") + @ApiImplicitParam(name = "crudHandle", value = "crud operation info", required = true, + dataType = "CrudHandle") + @PostMapping("crud") + public Object crudManageControl(@Valid @RequestBody CrudHandle crudHandle) throws Exception { + log.info("start crudManageControl. crudHandle:{}", crudHandle); + int groupId = crudHandle.getGroupId(); + String from = crudHandle.getSignUserId(); + String sql = crudHandle.getSql(); + // to lower case + String[] sqlParams = sql.trim().split(" "); + switch (sqlParams[0].toLowerCase()) { + case "create": + return createTable(groupId, from, sql); + case "desc": + return desc(groupId, sql); + case "select": + return select(groupId, sql); + case "insert": + return insert(groupId, from, sql); + case "update": + return update(groupId, from, sql); + case "delete": + return remove(groupId, from, sql); + default: + log.debug("end crudManageControl no such crud operation"); + return new BaseResponse(ConstantCode.PARAM_FAIL_SQL_ERROR, + "no such crud operation"); + } + } + + + public Object createTable(int groupId, String fromAddress, String sql) { + Instant startTime = Instant.now(); + log.info("start createTable startTime:{}, groupId:{},fromAddress:{},sql:{}", + startTime.toEpochMilli(), groupId, fromAddress, sql); + Table table = new Table(); + try { + log.debug("start parseCreateTable."); + CRUDParseUtils.parseCreateTable(sql, table); + log.debug("end parseCreateTable. table:{}, key:{}, keyField:{}, values:{}", + table.getTableName(), table.getKey(), table.getKeyFieldName(), table.getValueFields()); + } catch (Exception e) { + log.error("parseCreateTable. table:{},exception:{}", table, e); + CRUDParseUtils.invalidSymbol(sql); + return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, + "Could not parse SQL statement."); + } + // CRUDParseUtils.checkTableParams(table); + String result = precompiledService.createTable(groupId, fromAddress, table); + log.info("end createTable useTime:{} res:{}", + Duration.between(startTime, Instant.now()).toMillis(), result); + return result; + + } + + // check table name exist by desc(tableName) + public Object desc(int groupId, String sql) { + Instant startTime = Instant.now(); + log.info("start descTable startTime:{}, groupId:{},sql:{}", startTime.toEpochMilli(), + groupId, sql); + String[] sqlParams = sql.split(" "); + // "desc t_demo" + String tableName = sqlParams[1]; + + if (tableName.length() > PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH) { + return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, + "The table name length is greater than " + + PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH + ".", + "The table name length is greater than " + + PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH + "."); + } + CRUDParseUtils.invalidSymbol(tableName); + if (tableName.endsWith(";")) { + tableName = tableName.substring(0, tableName.length() - 1); + } + try { + List> table = precompiledService.desc(groupId, tableName); + log.info("end descTable useTime:{} res:{}", + Duration.between(startTime, Instant.now()).toMillis(), table); + return new BaseResponse(ConstantCode.RET_SUCCESS, table); + } catch (Exception e) { + log.error("descTable.exception:[] ", e); + return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, e.getMessage()); + } + } + + public Object select(int groupId, String sql) throws Exception { + Instant startTime = Instant.now(); + log.info("start select startTime:{}, groupId:{},sql:{}", startTime.toEpochMilli(), groupId, + sql); + Table table = new Table(); + Condition conditions = new Condition(); + List selectColumns = new ArrayList<>(); + + try { // 转化select语句 + log.debug("start parseSelect. sql:{}", sql); + CRUDParseUtils.parseSelect(sql, table, conditions, selectColumns); + log.debug("end parseSelect. table:{}, conditions:{}, selectColumns:{}", table, + conditions, selectColumns); + } catch (Exception e) { + log.error("parseSelect Error exception:[]", e); + CRUDParseUtils.invalidSymbol(sql); + return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); + } + + List> descTable = null; + try { + descTable = precompiledService.desc(groupId, table.getTableName()); + } catch (Exception e) { + log.error("select in descTable Error exception:[]", e); + return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists "); + } + String keyField = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); + table.setKey(keyField); + CRUDParseUtils.handleKey(table, conditions); +// String fields = descTable.getKey() + "," + descTable.getValueFields(); +// List fieldsList = Arrays.asList(fields.split(",")); +// for (String column : selectColumns) { +// if (!fieldsList.contains(column) && !"*".equals(column)) { +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +// "Unknown field '" + column + "' in field list.", +// "Unknown field '" + column + "' in field list."); // } -// } else { -// return ConstantCode.PARAM_ERROR; -// } -// } -// -// -// -// /** -// * Node manage (Consensus control) -// */ -// -// @GetMapping("consensus/list") -// public Object getNodeList(@RequestParam(defaultValue = "1") int groupId, -// @RequestParam(defaultValue = "10") int pageSize, -// @RequestParam(defaultValue = "1") int pageNumber) throws Exception { -// Instant startTime = Instant.now(); -// log.info("start getNodeList startTime:{}, groupId:{}", startTime.toEpochMilli(), groupId); -// List resList = precompiledService.getNodeList(groupId); -// log.info("end getNodeList useTime:{} resList:{}", -// Duration.between(startTime, Instant.now()).toMillis(), resList); -// if (resList.size() != 0) { -// List2Page list2Page = new List2Page(resList, pageSize, pageNumber); -// List finalList = list2Page.getPagedList(); -// long totalCount = resList.size(); -// log.debug("end getNodeList. finalList:{}", finalList); -// return new BasePageResponse(ConstantCode.RET_SUCCESS, finalList, totalCount); -// } else { -// return new BasePageResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, resList, 0); -// } -// } -// -// @ApiOperation(value = "nodeManageControl", notes = "set system config value by key") -// @ApiImplicitParam(name = "consensusHandle", value = "node consensus status control", -// required = true, dataType = "ConsensusHandle") -// @PostMapping("consensus") -// public Object nodeManageControl(@Valid @RequestBody ConsensusHandle consensusHandle) -// throws Exception { -// log.info("start nodeManageControl. consensusHandle:{}", consensusHandle); -// String nodeType = consensusHandle.getNodeType(); -// int groupId = consensusHandle.getGroupId(); -// String from = consensusHandle.getSignUserId(); -// String nodeId = consensusHandle.getNodeId(); -// if (!PrecompiledUtils.checkNodeId(nodeId)) { -// return ConstantCode.INVALID_NODE_ID; -// } -// switch (nodeType) { -// case PrecompiledUtils.NODE_TYPE_SEALER: -// return addSealer(groupId, from, nodeId); -// case PrecompiledUtils.NODE_TYPE_OBSERVER: -// return addObserver(groupId, from, nodeId); -// case PrecompiledUtils.NODE_TYPE_REMOVE: -// return removeNode(groupId, from, nodeId); -// default: -// log.debug("end nodeManageControl invalid node type"); -// return ConstantCode.INVALID_NODE_TYPE; -// } -// } -// -// public Object addSealer(int groupId, String fromAddress, String nodeId) throws Exception { -// Instant startTime = Instant.now(); -// log.info("start addSealer startTime:{}, groupId:{},fromAddress:{},nodeId:{}", -// startTime.toEpochMilli(), groupId, fromAddress, nodeId); -// try { -// Object res = precompiledService.addSealer(groupId, fromAddress, nodeId); -// log.info("end addSealer useTime:{} res:{}", -// Duration.between(startTime, Instant.now()).toMillis(), res); -// return res; -// } catch (Exception e) { -// log.error("addSealer exception:[]", e); -// return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); -// } -// } -// -// public Object addObserver(int groupId, String fromAddress, String nodeId) throws Exception { -// Instant startTime = Instant.now(); -// log.info("start addObserver startTime:{}, groupId:{},fromAddress:{},nodeId:{}", -// startTime.toEpochMilli(), groupId, fromAddress, nodeId); -// try { -// Object res = precompiledService.addObserver(groupId, fromAddress, nodeId); -// log.info("end addObserver useTime:{} res:{}", -// Duration.between(startTime, Instant.now()).toMillis(), res); -// return res; -// } catch (Exception e) { -// log.error("addObserver exception:[]", e); -// return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); -// } -// } -// -// public Object removeNode(int groupId, String fromAddress, String nodeId) throws Exception { -// Instant startTime = Instant.now(); -// log.info("start addSealer startTime:{}, groupId:{},fromAddress:{},nodeId:{}", -// startTime.toEpochMilli(), groupId, fromAddress, nodeId); -// try { -// Object res = precompiledService.removeNode(groupId, fromAddress, nodeId); -// log.info("end addSealer useTime:{} res:{}", -// Duration.between(startTime, Instant.now()).toMillis(), res); -// return res; -// } catch (Exception e) { // e.getCause -// log.error("removeNode exception:[]", e); -// return new BaseResponse(ConstantCode.FAIL_CHANGE_NODE_TYPE, e.getMessage()); -// } -// } -// -// /** -// * CRUD operation checkVersionForCRUD(); -// * "bcos's version above of 2.0.0-rc3 support crud operation" -// */ -// @ApiOperation(value = "crudManage", notes = "operate table by crud") -// @ApiImplicitParam(name = "crudHandle", value = "crud operation info", required = true, -// dataType = "CrudHandle") -// @PostMapping("crud") -// public Object crudManageControl(@Valid @RequestBody CrudHandle crudHandle) throws Exception { -// log.info("start crudManageControl. crudHandle:{}", crudHandle); -// int groupId = crudHandle.getGroupId(); -// String from = crudHandle.getSignUserId(); -// String sql = crudHandle.getSql(); -// // to lower case -// String[] sqlParams = sql.trim().split(" "); -// switch (sqlParams[0].toLowerCase()) { -// case "create": -// return createTable(groupId, from, sql); -// case "desc": -// return desc(groupId, sql); -// case "select": -// return select(groupId, sql); -// case "insert": -// return insert(groupId, from, sql); -// case "update": -// return update(groupId, from, sql); -// case "delete": -// return remove(groupId, from, sql); -// default: -// log.debug("end crudManageControl no such crud operation"); -// return new BaseResponse(ConstantCode.PARAM_FAIL_SQL_ERROR, -// "no such crud operation"); -// } -// } -// -// -// public Object createTable(int groupId, String fromAddress, String sql) { -// Instant startTime = Instant.now(); -// log.info("start createTable startTime:{}, groupId:{},fromAddress:{},sql:{}", -// startTime.toEpochMilli(), groupId, fromAddress, sql); -// Table table = new Table(); -// try { -// log.debug("start parseCreateTable."); -// CRUDParseUtils.parseCreateTable(sql, table); -// log.debug("end parseCreateTable. table:{}, key:{}, keyField:{}, values:{}", -// table.getTableName(), table.getKey(), table.getKeyFieldName(), table.getValueFields()); -// } catch (Exception e) { -// log.error("parseCreateTable. table:{},exception:{}", table, e); -// CRUDParseUtils.invalidSymbol(sql); -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -// "Could not parse SQL statement."); -// } -// // CRUDParseUtils.checkTableParams(table); -// String result = precompiledService.createTable(groupId, fromAddress, table); -// log.info("end createTable useTime:{} res:{}", -// Duration.between(startTime, Instant.now()).toMillis(), result); -// return result; -// -// } -// -// // check table name exist by desc(tableName) -// public Object desc(int groupId, String sql) { -// Instant startTime = Instant.now(); -// log.info("start descTable startTime:{}, groupId:{},sql:{}", startTime.toEpochMilli(), -// groupId, sql); -// String[] sqlParams = sql.split(" "); -// // "desc t_demo" -// String tableName = sqlParams[1]; -// -// if (tableName.length() > PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH) { -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -// "The table name length is greater than " -// + PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH + ".", -// "The table name length is greater than " -// + PrecompiledUtils.SYS_TABLE_KEY_MAX_LENGTH + "."); -// } -// CRUDParseUtils.invalidSymbol(tableName); -// if (tableName.endsWith(";")) { -// tableName = tableName.substring(0, tableName.length() - 1); -// } -// try { -// List> table = precompiledService.desc(groupId, tableName); -// log.info("end descTable useTime:{} res:{}", -// Duration.between(startTime, Instant.now()).toMillis(), table); -// return new BaseResponse(ConstantCode.RET_SUCCESS, table); -// } catch (Exception e) { -// log.error("descTable.exception:[] ", e); -// return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, e.getMessage()); -// } -// } -// -// public Object select(int groupId, String sql) throws Exception { -// Instant startTime = Instant.now(); -// log.info("start select startTime:{}, groupId:{},sql:{}", startTime.toEpochMilli(), groupId, -// sql); -// Table table = new Table(); -// Condition conditions = new Condition(); -// List selectColumns = new ArrayList<>(); -// -// try { // 转化select语句 -// log.debug("start parseSelect. sql:{}", sql); -// CRUDParseUtils.parseSelect(sql, table, conditions, selectColumns); -// log.debug("end parseSelect. table:{}, conditions:{}, selectColumns:{}", table, -// conditions, selectColumns); -// } catch (Exception e) { -// log.error("parseSelect Error exception:[]", e); -// CRUDParseUtils.invalidSymbol(sql); -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); -// } -// -// List> descTable = null; -// try { -// descTable = precompiledService.desc(groupId, table.getTableName()); -// } catch (Exception e) { -// log.error("select in descTable Error exception:[]", e); -// return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists "); // } -// String keyField = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); -// table.setKey(keyField); -// CRUDParseUtils.handleKey(table, conditions); -//// String fields = descTable.getKey() + "," + descTable.getValueFields(); -//// List fieldsList = Arrays.asList(fields.split(",")); -//// for (String column : selectColumns) { -//// if (!fieldsList.contains(column) && !"*".equals(column)) { -//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -//// "Unknown field '" + column + "' in field list.", -//// "Unknown field '" + column + "' in field list."); -//// } -//// } -// -// List> result = precompiledService.select(groupId, table, conditions); -// log.info("end select useTime:{} res:{}", -// Duration.between(startTime, Instant.now()).toMillis(), result); -// if (result.size() == 0) { -// return new BaseResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, -// ConstantCode.CRUD_EMPTY_SET); -// } -// result = CRUDParseUtils.filterSystemColum(result); -// if ("*".equals(selectColumns.get(0))) { -// selectColumns.clear(); -// selectColumns.add(keyField); -// String[] valueArr = descTable.get(0).get(PrecompiledConstant.VALUE_FIELD_NAME).split(","); -// selectColumns.addAll(Arrays.asList(valueArr)); -// result = CRUDParseUtils.getSelectedColumn(selectColumns, result); -// log.info("end select. result:{}", result); -// return new BaseResponse(ConstantCode.RET_SUCCESS, result); + + List> result = precompiledService.select(groupId, table, conditions); + log.info("end select useTime:{} res:{}", + Duration.between(startTime, Instant.now()).toMillis(), result); + if (result.size() == 0) { + return new BaseResponse(ConstantCode.RET_SUCCESS_EMPTY_LIST, + ConstantCode.CRUD_EMPTY_SET); + } + result = CRUDParseUtils.filterSystemColum(result); + if ("*".equals(selectColumns.get(0))) { + selectColumns.clear(); + selectColumns.add(keyField); + String[] valueArr = descTable.get(0).get(PrecompiledConstant.VALUE_FIELD_NAME).split(","); + selectColumns.addAll(Arrays.asList(valueArr)); + result = CRUDParseUtils.getSelectedColumn(selectColumns, result); + log.info("end select. result:{}", result); + return new BaseResponse(ConstantCode.RET_SUCCESS, result); + } else { + List> selectedResult = + CRUDParseUtils.getSelectedColumn(selectColumns, result); + log.info("end select. selectedResult:{}", selectedResult); + return new BaseResponse(ConstantCode.RET_SUCCESS, selectedResult); + } + + } + + public Object insert(int groupId, String fromAddress, String sql) throws Exception { + Instant startTime = Instant.now(); + log.info("start insert startTime:{}, groupId:{},fromAddress:{},sql:{}", + startTime.toEpochMilli(), groupId, fromAddress, sql); + Table table = new Table(); + Entry entry = new Entry(); + List> descTable = null; + + String tableName = CRUDParseUtils.parseInsertedTableName(sql); + descTable = precompiledService.desc(groupId, tableName); + log.debug( + "insert, tableName: {}, descTable: {}", tableName, descTable.get(0).toString()); + CRUDParseUtils.parseInsert(sql, table, entry, descTable.get(0)); + String keyName = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); + String keyValue = entry.getFieldNameToValue().get(keyName); + log.debug( + "fieldNameToValue: {}, keyName: {}, keyValue: {}", entry.getFieldNameToValue(), keyName, keyValue); + if (keyValue == null) { + log.error("Please insert the key field '" + keyName + "'."); + throw new FrontException("Please insert the key field '" + keyName + "'."); + } + // table primary key + table.setKey(keyValue); + String insertResult = + precompiledService.insert(groupId, fromAddress, table, entry); + return insertResult; +// if (insertResult >= 0) { +// log.info("Insert OK: {}", insertResult); +// return new BaseResponse(insertResult, insertResult + " row affected."); // } else { -// List> selectedResult = -// CRUDParseUtils.getSelectedColumn(selectColumns, result); -// log.info("end select. selectedResult:{}", selectedResult); -// return new BaseResponse(ConstantCode.RET_SUCCESS, selectedResult); -// } -// -// } -// -// public Object insert(int groupId, String fromAddress, String sql) throws Exception { -// Instant startTime = Instant.now(); -// log.info("start insert startTime:{}, groupId:{},fromAddress:{},sql:{}", -// startTime.toEpochMilli(), groupId, fromAddress, sql); -// Table table = new Table(); -// Entry entry = new Entry(); -// List> descTable = null; -// -// String tableName = CRUDParseUtils.parseInsertedTableName(sql); -// descTable = precompiledService.desc(groupId, tableName); -// log.debug( -// "insert, tableName: {}, descTable: {}", tableName, descTable.get(0).toString()); -// CRUDParseUtils.parseInsert(sql, table, entry, descTable.get(0)); -// String keyName = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); -// String keyValue = entry.getFieldNameToValue().get(keyName); -// log.debug( -// "fieldNameToValue: {}, keyName: {}, keyValue: {}", entry.getFieldNameToValue(), keyName, keyValue); -// if (keyValue == null) { -// log.error("Please insert the key field '" + keyName + "'."); -// throw new FrontException("Please insert the key field '" + keyName + "'."); +// log.info("Result of insert for " + table.getTableName() + ":"); +// return new BaseResponse(insertResult, "insert failed!"); // } -// // table primary key -// table.setKey(keyValue); -// String insertResult = -// precompiledService.insert(groupId, fromAddress, table, entry); -// return insertResult; -//// if (insertResult >= 0) { -//// log.info("Insert OK: {}", insertResult); -//// return new BaseResponse(insertResult, insertResult + " row affected."); -//// } else { -//// log.info("Result of insert for " + table.getTableName() + ":"); -//// return new BaseResponse(insertResult, "insert failed!"); -//// } -// } -//// Table table = new Table(); -//// Entry entry = new Entry(); -//// -//// // insert sql use "values" or not -//// boolean useValues = false; -//// try { -//// log.debug("start parseInsert. sql:{}", sql); -//// useValues = CRUDParseUtils.parseInsert(sql, table, entry); -//// log.debug("end parseInsert. table:{}, entry:{}", table, entry); -//// } catch (Exception e) { -//// log.error("parseInsert Error exception:[]", e); -//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -//// "Could not parse SQL statement." + CRUDParseUtils.invalidSymbol(sql), -//// "Could not parse SQL statement." + CRUDParseUtils.invalidSymbol(sql)); -//// } -//// -//// String tableName = table.getTableName(); -//// Table descTable; -//// try { -//// descTable = precompiledService.desc(groupId, tableName); -//// } catch (Exception e) { -//// log.error("insertTable Error exception:[]", e); -//// return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); -//// } -//// String keyName = descTable.getKey(); -//// String fields = keyName + "," + descTable.getValueFields(); -//// -//// List fieldsList = Arrays.asList(fields.split(",")); -//// Set entryFields = entry.getFieldNameToValue().keySet(); -//// -//// // ex: insert into t_test values (fruit, 1, apple) -//// if (useValues) { -//// if (entry.getFieldNameToValue().size() != fieldsList.size()) { -//// log.error("field value size not equal to field size"); -//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -//// "Column count doesn't match value count.", -//// "Column count doesn't match value count."); -//// } else { -//// Entry entryValue = table.getEntry(); -//// for (int i = 0; i < entry.getFieldNameToValue().size(); i++) { -//// for (String entryField : entryFields) { -//// if ((i + "").equals(entryField)) { -//// Map map = new HashMap<>(); -//// map.put(fieldsList.get(i), entry.getFieldNameToValue().get(i + "")); -//// entryValue.setFieldNameToValue(map); -//// if (keyName.equals(fieldsList.get(i))) { -//// table.setKey(entry.getFieldNameToValue().get(i + "")); -//// } -//// } -//// } -//// } -//// entry = entryValue; -//// } -//// } -//// // ex: insert into t_test (name, item_id, item_name) values (fruit, 1, apple) -//// else { -//// for (String entryField : entryFields) { -//// if (!fieldsList.contains(entryField)) { -//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -//// "Unknown field '" + entryField + "' in field list.", -//// "Unknown field '" + entryField + "' in field list."); -//// } -//// if (fieldsList.size() != entryFields.size()) { -//// List listString = new ArrayList(fieldsList); -//// for (String entryItem : entryFields) { -//// listString.remove(entryItem); -//// } -//// StringBuilder strBuilder = new StringBuilder("Please provide field '"); -//// for (int i = 0; i < listString.size(); i++) { -//// if (i == listString.size() - 1) { -//// strBuilder.append(listString.get(i)).append("' "); -//// } else { -//// strBuilder.append(listString.get(i)).append("', '"); -//// } -//// } -//// strBuilder.append("in field list."); -//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, strBuilder.toString(), -//// strBuilder.toString()); -//// } -//// } -//// String keyValue = entry.getFieldNameToValue().get(keyName); -//// if (keyValue == null) { -//// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -//// "Column count doesn't match value count.", -//// "Column count doesn't match value count."); -//// } -//// table.setKey(keyValue); -//// } -//// CRUDParseUtils.checkUserTableParam(entry, descTable); -//// int insertResult = precompiledService.insert(groupId, fromAddress, table, entry); -//// log.info("end insert useTime:{} insertResult:{}", -//// Duration.between(startTime, Instant.now()).toMillis(), insertResult); -//// if (insertResult >= 0) { -//// return new BaseResponse(ConstantCode.RET_SUCCESS, -//// "Insert OK, " + insertResult + " row(s) affected."); -//// } else { -//// return new BaseResponse(insertResult, "Insert failed."); -//// } -// -// public Object update(int groupId, String fromAddress, String sql) throws Exception { -// Instant startTime = Instant.now(); -// log.info("start update startTime:{}, groupId:{},fromAddress:{},sql:{}", -// startTime.toEpochMilli(), groupId, fromAddress, sql); + } // Table table = new Table(); // Entry entry = new Entry(); -// Condition conditions = new Condition(); // +// // insert sql use "values" or not +// boolean useValues = false; // try { -// log.debug("start parseUpdate. sql:{}", sql); -// CRUDParseUtils.parseUpdate(sql, table, entry, conditions); -// log.debug("end parseUpdate. table:{}, entry:{}, conditions:{}", table, entry, -// conditions); +// log.debug("start parseInsert. sql:{}", sql); +// useValues = CRUDParseUtils.parseInsert(sql, table, entry); +// log.debug("end parseInsert. table:{}, entry:{}", table, entry); // } catch (Exception e) { -// log.error("parseUpdate error exception:[]", e); -// CRUDParseUtils.invalidSymbol(sql); -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); +// log.error("parseInsert Error exception:[]", e); +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +// "Could not parse SQL statement." + CRUDParseUtils.invalidSymbol(sql), +// "Could not parse SQL statement." + CRUDParseUtils.invalidSymbol(sql)); // } // // String tableName = table.getTableName(); -// List> descTable = null; +// Table descTable; // try { // descTable = precompiledService.desc(groupId, tableName); // } catch (Exception e) { -// log.error("updateTable Error exception:[]", e); -// return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); -// } -// -// String keyName = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); -// if (entry.getFieldNameToValue().containsKey(keyName)) { -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, -// "Please don't set the key field '" + keyName + "'.", -// "Please don't set the key field '" + keyName + "'."); -// } -// table.setKey(keyName); -// CRUDParseUtils.handleKey(table, conditions); -// String updateResult = precompiledService.update(groupId, fromAddress, table, entry, conditions); -// log.info("end update useTime:{} updateResult:{}", -// Duration.between(startTime, Instant.now()).toMillis(), updateResult); -// return updateResult; -// } -// -// public Object remove(int groupId, String fromAddress, String sql) { -// Instant startTime = Instant.now(); -// log.info("start remove startTime:{}, groupId:{},fromAddress:{},sql:{}", -// startTime.toEpochMilli(), groupId, fromAddress, sql); -// Table table = new Table(); -// Condition conditions = new Condition(); -// -// try { -// log.debug("start parseRemove. sql:{}", sql); -// CRUDParseUtils.parseRemove(sql, table, conditions); -// log.debug("end parseRemove. table:{}, conditions:{}", table, conditions); -// } catch (Exception e) { -// log.error("parseRemove Error exception:[]", e); -// CRUDParseUtils.invalidSymbol(sql); -// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); -// } -// -// List> descTable = null; -// try { -// descTable = precompiledService.desc(groupId, table.getTableName()); -// } catch (Exception e) { -// log.error("removeTable Error exception:[]", e); +// log.error("insertTable Error exception:[]", e); // return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); // } -// table.setKey(descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME)); -// CRUDParseUtils.handleKey(table, conditions); -// String removeResult = precompiledService.remove(groupId, fromAddress, table, conditions); -// log.info("end remove useTime:{} removeResult:{}", -// Duration.between(startTime, Instant.now()).toMillis(), removeResult); -// return removeResult; -// -// } -// -// @ApiOperation(value = "contractStatusManage", notes = "contract status manage") -// @PostMapping("contractStatusManage") -// public Object contractStatusManage( -// @Valid @RequestBody ContractStatusHandle contractStatusHandle) throws Exception { -// log.debug("start contractStatusManage. contractStatusHandle:{}", contractStatusHandle); -// switch (contractStatusHandle.getHandleType()) { -// case PrecompiledUtils.CONTRACT_MANAGE_FREEZE: -// return contractFreeze(contractStatusHandle); -// case PrecompiledUtils.CONTRACT_MANAGE_UNFREEZE: -// return contractUnfreeze(contractStatusHandle); -// case PrecompiledUtils.CONTRACT_MANAGE_GRANTMANAGER: -// return contractGrantManager(contractStatusHandle); -// case PrecompiledUtils.CONTRACT_MANAGE_GETSTATUS: -// return contractStatus(contractStatusHandle); -// case PrecompiledUtils.CONTRACT_MANAGE_LISTMANAGER: -// return contractManagerList(contractStatusHandle); -// default: -// log.error("end contractStatusManage. invalid contract handle type"); -// throw new FrontException(ConstantCode.INVALID_CONTRACT_HANDLE_TYPE); -// } -// } -// -// private Object contractFreeze(ContractStatusHandle contractStatusHandle) { -// Instant startTime = Instant.now(); -// log.info("start contractFreeze startTime:{}", startTime.toEpochMilli()); -// try { -// if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { -// log.error("signUserId is empty"); -// throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); -// } -// String res = precompiledService.contractFreeze(contractStatusHandle.getGroupId(), -// contractStatusHandle.getSignUserId(), -// contractStatusHandle.getContractAddress()); -// ContractManageResult contractManageResult = -// JsonUtils.toJavaObject(res, ContractManageResult.class); -// if (contractManageResult == null) { -// return new FrontException(ConstantCode.FAIL_PARSE_JSON); -// } -// if (contractManageResult.getCode() == 0) { -// log.info("end contractFreeze useTime:{} contractManageResult:{}", -// Duration.between(startTime, Instant.now()).toMillis(), -// contractManageResult); -// return new BaseResponse(ConstantCode.RET_SUCCEED); +// String keyName = descTable.getKey(); +// String fields = keyName + "," + descTable.getValueFields(); +// +// List fieldsList = Arrays.asList(fields.split(",")); +// Set entryFields = entry.getFieldNameToValue().keySet(); +// +// // ex: insert into t_test values (fruit, 1, apple) +// if (useValues) { +// if (entry.getFieldNameToValue().size() != fieldsList.size()) { +// log.error("field value size not equal to field size"); +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +// "Column count doesn't match value count.", +// "Column count doesn't match value count."); // } else { -// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), -// contractManageResult.getMsg()); +// Entry entryValue = table.getEntry(); +// for (int i = 0; i < entry.getFieldNameToValue().size(); i++) { +// for (String entryField : entryFields) { +// if ((i + "").equals(entryField)) { +// Map map = new HashMap<>(); +// map.put(fieldsList.get(i), entry.getFieldNameToValue().get(i + "")); +// entryValue.setFieldNameToValue(map); +// if (keyName.equals(fieldsList.get(i))) { +// table.setKey(entry.getFieldNameToValue().get(i + "")); +// } +// } +// } +// } +// entry = entryValue; // } -// } catch (Exception e) { -// log.error("contractFreeze exception:", e); -// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); // } -// } -// -// private Object contractUnfreeze(ContractStatusHandle contractStatusHandle) throws Exception { -// Instant startTime = Instant.now(); -// log.info("start contractUnfreeze startTime:{}", startTime.toEpochMilli()); -// try { -// if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { -// log.error("signUserId is empty"); -// throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); +// // ex: insert into t_test (name, item_id, item_name) values (fruit, 1, apple) +// else { +// for (String entryField : entryFields) { +// if (!fieldsList.contains(entryField)) { +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +// "Unknown field '" + entryField + "' in field list.", +// "Unknown field '" + entryField + "' in field list."); +// } +// if (fieldsList.size() != entryFields.size()) { +// List listString = new ArrayList(fieldsList); +// for (String entryItem : entryFields) { +// listString.remove(entryItem); +// } +// StringBuilder strBuilder = new StringBuilder("Please provide field '"); +// for (int i = 0; i < listString.size(); i++) { +// if (i == listString.size() - 1) { +// strBuilder.append(listString.get(i)).append("' "); +// } else { +// strBuilder.append(listString.get(i)).append("', '"); +// } +// } +// strBuilder.append("in field list."); +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, strBuilder.toString(), +// strBuilder.toString()); +// } // } -// String res = precompiledService.contractUnfreeze(contractStatusHandle.getGroupId(), -// contractStatusHandle.getSignUserId(), -// contractStatusHandle.getContractAddress()); -// ContractManageResult contractManageResult = -// JsonUtils.toJavaObject(res, ContractManageResult.class); -// if (contractManageResult.getCode() == 0) { -// log.info("end contractUnfreeze useTime:{} contractManageResult:{}", -// Duration.between(startTime, Instant.now()).toMillis(), -// contractManageResult); -// return new BaseResponse(ConstantCode.RET_SUCCEED); -// } else { -// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), -// contractManageResult.getMsg()); +// String keyValue = entry.getFieldNameToValue().get(keyName); +// if (keyValue == null) { +// return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, +// "Column count doesn't match value count.", +// "Column count doesn't match value count."); // } -// } catch (Exception e) { -// log.error("contractUnfreeze exception:", e); -// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); +// table.setKey(keyValue); // } -// } -// -// private Object contractGrantManager(ContractStatusHandle contractStatusHandle) { -// Instant startTime = Instant.now(); -// log.info("start contractGrantManager startTime:{}", startTime.toEpochMilli()); -// try { -// if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { -// log.error("signUserId is empty"); -// throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); -// } -// if (StringUtils.isBlank(contractStatusHandle.getGrantAddress())) { -// log.error("grantAddress cannot be empty"); -// throw new FrontException(ConstantCode.PARAM_FAIL_GRANT_ADDRESS_EMPTY); -// } -// String res = precompiledService.contractGrantManager(contractStatusHandle.getGroupId(), -// contractStatusHandle.getSignUserId(), contractStatusHandle.getContractAddress(), -// contractStatusHandle.getGrantAddress()); -// ContractManageResult contractManageResult = -// JsonUtils.toJavaObject(res, ContractManageResult.class); -// if (contractManageResult.getCode() == 0) { -// log.info("end contractGrantManager useTime:{} contractManageResult:{}", -// Duration.between(startTime, Instant.now()).toMillis(), -// contractManageResult); -// return new BaseResponse(ConstantCode.RET_SUCCEED); -// } else { -// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), -// contractManageResult.getMsg()); -// } -// } catch (Exception e) { -// log.error("contractGrantManager exception:", e); -// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); -// } -// } -// -// private Object contractStatus(ContractStatusHandle contractStatusHandle) { -// Instant startTime = Instant.now(); -// log.info("start contractStatus startTime:{}", startTime.toEpochMilli()); -// try { -// String res = precompiledService.contractStatus(contractStatusHandle.getGroupId(), -// contractStatusHandle.getContractAddress()); -// if (res.contains("code")) { -// ContractManageResult contractManageResult = -// JsonUtils.toJavaObject(res, ContractManageResult.class); -// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), -// contractManageResult.getMsg()); -// } else { -// BaseResponse response = new BaseResponse(ConstantCode.RET_SUCCEED); -// response.setData(res); -// log.info("end contractStatus useTime:{} response:{}", -// Duration.between(startTime, Instant.now()).toMillis(), response); -// return response; -// } -// } catch (Exception e) { -// log.error("contractStatus exception:", e); -// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); -// } -// } -// -// private Object contractManagerList(ContractStatusHandle contractStatusHandle) { -// Instant startTime = Instant.now(); -// log.info("start contractManagerList startTime:{}", startTime.toEpochMilli()); -// try { -// List res = precompiledService.contractManagerList(contractStatusHandle.getGroupId(), -// contractStatusHandle.getContractAddress()); -// BaseResponse response = new BaseResponse(ConstantCode.RET_SUCCEED); -// response.setData(res); -// log.info("end contractManagerList useTime:{} response:{}", -// Duration.between(startTime, Instant.now()).toMillis(), response); -// return response; -// } catch (Exception e) { -// log.error("contractManagerList exception:", e); -// throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); +// CRUDParseUtils.checkUserTableParam(entry, descTable); +// int insertResult = precompiledService.insert(groupId, fromAddress, table, entry); +// log.info("end insert useTime:{} insertResult:{}", +// Duration.between(startTime, Instant.now()).toMillis(), insertResult); +// if (insertResult >= 0) { +// return new BaseResponse(ConstantCode.RET_SUCCESS, +// "Insert OK, " + insertResult + " row(s) affected."); +// } else { +// return new BaseResponse(insertResult, "Insert failed."); // } -// } -// -//} + + public Object update(int groupId, String fromAddress, String sql) throws Exception { + Instant startTime = Instant.now(); + log.info("start update startTime:{}, groupId:{},fromAddress:{},sql:{}", + startTime.toEpochMilli(), groupId, fromAddress, sql); + Table table = new Table(); + Entry entry = new Entry(); + Condition conditions = new Condition(); + + try { + log.debug("start parseUpdate. sql:{}", sql); + CRUDParseUtils.parseUpdate(sql, table, entry, conditions); + log.debug("end parseUpdate. table:{}, entry:{}, conditions:{}", table, entry, + conditions); + } catch (Exception e) { + log.error("parseUpdate error exception:[]", e); + CRUDParseUtils.invalidSymbol(sql); + return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); + } + + String tableName = table.getTableName(); + List> descTable = null; + try { + descTable = precompiledService.desc(groupId, tableName); + } catch (Exception e) { + log.error("updateTable Error exception:[]", e); + return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); + } + + String keyName = descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); + if (entry.getFieldNameToValue().containsKey(keyName)) { + return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, + "Please don't set the key field '" + keyName + "'.", + "Please don't set the key field '" + keyName + "'."); + } + table.setKey(keyName); + CRUDParseUtils.handleKey(table, conditions); + String updateResult = precompiledService.update(groupId, fromAddress, table, entry, conditions); + log.info("end update useTime:{} updateResult:{}", + Duration.between(startTime, Instant.now()).toMillis(), updateResult); + return updateResult; + } + + public Object remove(int groupId, String fromAddress, String sql) { + Instant startTime = Instant.now(); + log.info("start remove startTime:{}, groupId:{},fromAddress:{},sql:{}", + startTime.toEpochMilli(), groupId, fromAddress, sql); + Table table = new Table(); + Condition conditions = new Condition(); + + try { + log.debug("start parseRemove. sql:{}", sql); + CRUDParseUtils.parseRemove(sql, table, conditions); + log.debug("end parseRemove. table:{}, conditions:{}", table, conditions); + } catch (Exception e) { + log.error("parseRemove Error exception:[]", e); + CRUDParseUtils.invalidSymbol(sql); + return new BaseResponse(PrecompiledUtils.CRUD_SQL_ERROR, "Could not parse SQL statement."); + } + + List> descTable = null; + try { + descTable = precompiledService.desc(groupId, table.getTableName()); + } catch (Exception e) { + log.error("removeTable Error exception:[]", e); + return new BaseResponse(ConstantCode.FAIL_TABLE_NOT_EXISTS, "Table not exists"); + } + table.setKey(descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME)); + CRUDParseUtils.handleKey(table, conditions); + String removeResult = precompiledService.remove(groupId, fromAddress, table, conditions); + log.info("end remove useTime:{} removeResult:{}", + Duration.between(startTime, Instant.now()).toMillis(), removeResult); + return removeResult; + + } + + @ApiOperation(value = "contractStatusManage", notes = "contract status manage") + @PostMapping("contractStatusManage") + public Object contractStatusManage( + @Valid @RequestBody ContractStatusHandle contractStatusHandle) throws Exception { + log.debug("start contractStatusManage. contractStatusHandle:{}", contractStatusHandle); + switch (contractStatusHandle.getHandleType()) { + case PrecompiledUtils.CONTRACT_MANAGE_FREEZE: + return contractFreeze(contractStatusHandle); + case PrecompiledUtils.CONTRACT_MANAGE_UNFREEZE: + return contractUnfreeze(contractStatusHandle); + case PrecompiledUtils.CONTRACT_MANAGE_GRANTMANAGER: + return contractGrantManager(contractStatusHandle); + case PrecompiledUtils.CONTRACT_MANAGE_GETSTATUS: + return contractStatus(contractStatusHandle); + case PrecompiledUtils.CONTRACT_MANAGE_LISTMANAGER: + return contractManagerList(contractStatusHandle); + default: + log.error("end contractStatusManage. invalid contract handle type"); + throw new FrontException(ConstantCode.INVALID_CONTRACT_HANDLE_TYPE); + } + } + + private Object contractFreeze(ContractStatusHandle contractStatusHandle) { + Instant startTime = Instant.now(); + log.info("start contractFreeze startTime:{}", startTime.toEpochMilli()); + try { + if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { + log.error("signUserId is empty"); + throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); + } + String res = precompiledService.contractFreeze(contractStatusHandle.getGroupId(), + contractStatusHandle.getSignUserId(), + contractStatusHandle.getContractAddress()); + ContractManageResult contractManageResult = + JsonUtils.toJavaObject(res, ContractManageResult.class); + if (contractManageResult == null) { + return new FrontException(ConstantCode.FAIL_PARSE_JSON); + } + if (contractManageResult.getCode() == 0) { + log.info("end contractFreeze useTime:{} contractManageResult:{}", + Duration.between(startTime, Instant.now()).toMillis(), + contractManageResult); + return new BaseResponse(ConstantCode.RET_SUCCEED); + } else { + throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), + contractManageResult.getMsg()); + } + } catch (Exception e) { + log.error("contractFreeze exception:", e); + throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); + } + } + + private Object contractUnfreeze(ContractStatusHandle contractStatusHandle) throws Exception { + Instant startTime = Instant.now(); + log.info("start contractUnfreeze startTime:{}", startTime.toEpochMilli()); + try { + if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { + log.error("signUserId is empty"); + throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); + } + String res = precompiledService.contractUnfreeze(contractStatusHandle.getGroupId(), + contractStatusHandle.getSignUserId(), + contractStatusHandle.getContractAddress()); + ContractManageResult contractManageResult = + JsonUtils.toJavaObject(res, ContractManageResult.class); + if (contractManageResult.getCode() == 0) { + log.info("end contractUnfreeze useTime:{} contractManageResult:{}", + Duration.between(startTime, Instant.now()).toMillis(), + contractManageResult); + return new BaseResponse(ConstantCode.RET_SUCCEED); + } else { + throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), + contractManageResult.getMsg()); + } + } catch (Exception e) { + log.error("contractUnfreeze exception:", e); + throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); + } + } + + private Object contractGrantManager(ContractStatusHandle contractStatusHandle) { + Instant startTime = Instant.now(); + log.info("start contractGrantManager startTime:{}", startTime.toEpochMilli()); + try { + if (StringUtils.isBlank(contractStatusHandle.getSignUserId())) { + log.error("signUserId is empty"); + throw new FrontException(ConstantCode.PARAM_FAIL_SIGN_USER_ID_IS_EMPTY); + } + if (StringUtils.isBlank(contractStatusHandle.getGrantAddress())) { + log.error("grantAddress cannot be empty"); + throw new FrontException(ConstantCode.PARAM_FAIL_GRANT_ADDRESS_EMPTY); + } + String res = precompiledService.contractGrantManager(contractStatusHandle.getGroupId(), + contractStatusHandle.getSignUserId(), contractStatusHandle.getContractAddress(), + contractStatusHandle.getGrantAddress()); + ContractManageResult contractManageResult = + JsonUtils.toJavaObject(res, ContractManageResult.class); + if (contractManageResult.getCode() == 0) { + log.info("end contractGrantManager useTime:{} contractManageResult:{}", + Duration.between(startTime, Instant.now()).toMillis(), + contractManageResult); + return new BaseResponse(ConstantCode.RET_SUCCEED); + } else { + throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), + contractManageResult.getMsg()); + } + } catch (Exception e) { + log.error("contractGrantManager exception:", e); + throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); + } + } + + private Object contractStatus(ContractStatusHandle contractStatusHandle) { + Instant startTime = Instant.now(); + log.info("start contractStatus startTime:{}", startTime.toEpochMilli()); + try { + String res = precompiledService.contractStatus(contractStatusHandle.getGroupId(), + contractStatusHandle.getContractAddress()); + if (res.contains("code")) { + ContractManageResult contractManageResult = + JsonUtils.toJavaObject(res, ContractManageResult.class); + throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), + contractManageResult.getMsg()); + } else { + BaseResponse response = new BaseResponse(ConstantCode.RET_SUCCEED); + response.setData(res); + log.info("end contractStatus useTime:{} response:{}", + Duration.between(startTime, Instant.now()).toMillis(), response); + return response; + } + } catch (Exception e) { + log.error("contractStatus exception:", e); + throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); + } + } + + private Object contractManagerList(ContractStatusHandle contractStatusHandle) { + Instant startTime = Instant.now(); + log.info("start contractManagerList startTime:{}", startTime.toEpochMilli()); + try { + List res = precompiledService.contractManagerList(contractStatusHandle.getGroupId(), + contractStatusHandle.getContractAddress()); + BaseResponse response = new BaseResponse(ConstantCode.RET_SUCCEED); + response.setData(res); + log.info("end contractManagerList useTime:{} response:{}", + Duration.between(startTime, Instant.now()).toMillis(), response); + return response; + } catch (Exception e) { + log.error("contractManagerList exception:", e); + throw new FrontException(ConstantCode.FAIL_CONTRACT_HANDLE.getCode(), e.getMessage()); + } + } + +} diff --git a/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledService.java b/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledService.java index 0b05a5c81..bb8f97665 100644 --- a/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledService.java +++ b/src/main/java/com/webank/webase/front/precompiledapi/PrecompiledService.java @@ -1,229 +1,229 @@ -///* -// * Copyright 2014-2020 the original author or authors. -// * -// * Licensed under the Apache License, Version 2.0 (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 -// * -// * Unless required by applicable law or agreed to in writing, software distributed under the License -// * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express -// * or implied. See the License for the specific language governing permissions and limitations under -// * the License. -// */ -//package com.webank.webase.front.precompiledapi; -// -//import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_OBSERVER; -//import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_REMOVE; -//import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_SEALER; -// -//import com.webank.webase.front.base.code.ConstantCode; -//import com.webank.webase.front.base.exception.FrontException; -//import com.webank.webase.front.keystore.KeyStoreService; -//import com.webank.webase.front.precompiledapi.crud.CRUDParseUtils; -//import com.webank.webase.front.precompiledapi.crud.Table; -//import com.webank.webase.front.precompiledapi.entity.NodeInfo; -//import com.webank.webase.front.util.JsonUtils; -//import com.webank.webase.front.web3api.Web3ApiService; -//import java.io.IOException; -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.Collections; -//import java.util.List; -//import java.util.Map; -//import org.fisco.bcos.sdk.contract.precompiled.cns.CnsInfo; -//import org.fisco.bcos.sdk.contract.precompiled.cns.CnsService; -//import org.fisco.bcos.sdk.contract.precompiled.contractmgr.ContractLifeCycleService; -//import org.fisco.bcos.sdk.contract.precompiled.crud.TableCRUDService; -//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; -//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; -//import org.fisco.bcos.sdk.model.PrecompiledConstant; -//import org.fisco.bcos.sdk.transaction.model.exception.ContractException; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Service; -// -// -///** -// * Precompiled common service including management of CNS, node consensus status, CRUD based on -// * PrecompiledWithSignService -// */ -//@Service -//public class PrecompiledService { -// -// @Autowired -// private Web3ApiService web3ApiService; -// @Autowired -// private KeyStoreService keyStoreService; -// @Autowired -// private PrecompiledWithSignService precompiledWithSignService; -// -// /** -// * CNS config related -// */ -// public List queryCnsByName(int groupId, String contractName) throws ContractException { -// CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), -// keyStoreService.getCredentialsForQuery()); -// return cnsService.selectByName(contractName); -// } -// -// public List queryCnsByNameAndVersion(int groupId, String contractName, -// String version) throws ContractException { -// CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), -// keyStoreService.getCredentialsForQuery()); -// return cnsService.selectByNameAndVersion(contractName, version); -// } -// -// public String getAddressByContractNameAndVersion(int groupId, String contractName, -// String version) throws ContractException { -// CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), -// keyStoreService.getCredentialsForQuery()); -// return cnsService.getContractAddress(contractName, version); -// } -// -// /** -// * Consensus config related -// */ -// public String addSealer(int groupId, String signUserId, String nodeId) { -// String res = precompiledWithSignService.addSealer(groupId, signUserId, nodeId); -// return res; -// } -// -// public String addObserver(int groupId, String signUserId, String nodeId) { -// String res = precompiledWithSignService.addObserver(groupId, signUserId, nodeId); -// return res; -// } -// -// public String removeNode(int groupId, String signUserId, String nodeId) { -// String res = precompiledWithSignService.removeNode(groupId, signUserId, nodeId); -// return res; -// } -// -// public List getNodeList(int groupId) throws IOException { -// // nodeListWithType 组合多个带有类型的nodeid list -// List sealerList = -// web3ApiService.getWeb3j(groupId).getSealerList().getSealerList(); -// List observerList = -// web3ApiService.getWeb3j(groupId).getObserverList().getObserverList(); -// List peerList = web3ApiService.getWeb3j(groupId).getNodeIDList().getNodeIDList(); -// // process nodeList -// List nodeListWithType = new ArrayList<>(); -// -// // add all sealer and observer in List -// sealerList.forEach(sealer -> nodeListWithType.add(new NodeInfo(sealer, NODE_TYPE_SEALER))); -// observerList.forEach( -// observer -> nodeListWithType.add(new NodeInfo(observer, NODE_TYPE_OBSERVER))); -// // peer not in sealer/observer but connected is remove node(游离节点) -// peerList.stream().filter(peer -> !sealerList.contains(peer) && !observerList.contains(peer)) -// .forEach(peerToAdd -> nodeListWithType -// .add(new NodeInfo(peerToAdd, NODE_TYPE_REMOVE))); -// -// return nodeListWithType; -// } -// -// /** -// * CRUD related Table table - validation in controller -// */ -// public String createTable(int groupId, String signUserId, Table table) { -// String res = precompiledWithSignService.createTable(groupId, signUserId, table); -// return res; -// } -// -// /** -// * insert 校验tableName等操作放在controller -// */ -// public String insert(int groupId, String signUserId, Table table, Entry entry) { -// String res = precompiledWithSignService.insert(groupId, signUserId, table, entry); -// return res; -// } -// -// /** -// * update -// */ -// public String update(int groupId, String signUserId, Table table, Entry entry, Condition condition) -// { -// String res = precompiledWithSignService.update(groupId, signUserId, table, entry, condition); -// return res; -// } -// -// /** -// * remove -// */ -// public String remove(int groupId, String signUserId, Table table, Condition condition) { -// String res = precompiledWithSignService.remove(groupId, signUserId, table, condition); -// return res; -// } -// -// /** -// * desc -// */ -// public List> desc(int groupId, String tableName) throws Exception { -// TableCRUDService crudService = new TableCRUDService(web3ApiService.getWeb3j(groupId), -// keyStoreService.getCredentialsForQuery()); -// List> descRes = crudService.desc(tableName); -// if (!CRUDParseUtils.checkTableExistence(descRes)) { -// throw new FrontException(ConstantCode.FAIL_TABLE_NOT_EXISTS); -// } -// return descRes; -//// String tableKey = descRes.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); -//// String valueFields = descRes.get(0).get(PrecompiledConstant.VALUE_FIELD_NAME); -//// return new Table(tableName, tableKey, valueFields); -// } -// -// public String descTable(int groupId, String tableName) throws Exception { -// List> descRes = this.desc(groupId, tableName); -// if (!CRUDParseUtils.checkTableExistence(descRes)) { -// throw new FrontException(ConstantCode.FAIL_TABLE_NOT_EXISTS); -// } -// String tableInfo = JsonUtils.objToString(descRes); -// return CRUDParseUtils.formatJson(tableInfo); -// } -// -// /** -// * select -// */ -// public List> select(int groupId, Table table, -// Condition conditions) throws Exception { -// TableCRUDService crudService = new TableCRUDService(web3ApiService.getWeb3j(groupId), -// keyStoreService.getCredentialsForQuery()); -// List> selectRes = crudService.select(table.getTableName(), table.getKey(), conditions); -// return selectRes; -// } -// -// public String contractFreeze(int groupId, String signUserId, String contractAddress) -// { -// return precompiledWithSignService.contractFreeze(groupId, signUserId, contractAddress); -// } -// -// public String contractUnfreeze(int groupId, String signUserId, String contractAddress) -// { -// return precompiledWithSignService.contractUnfreeze(groupId, signUserId, contractAddress); -// } -// -// public String contractGrantManager(int groupId, String signUserId, String contractAddress, -// String grantAddress) { -// return precompiledWithSignService.contractGrantManager(groupId, signUserId, contractAddress, -// grantAddress); -// } -// -// public String contractStatus(int groupId, String contractAddress) throws Exception { -// ContractLifeCycleService contractStatusService = new ContractLifeCycleService( -// web3ApiService.getWeb3j(groupId), keyStoreService.getCredentialsForQuery()); -// String res = contractStatusService.getContractStatus(contractAddress); -// if (res.contains("frozen")) { -// // res: The account has been frozen. You can use this account after unfreezing it. -// return "1"; -// } else { -// // res: The address is nonexistent. -// // res: The account is available. -// // res: invalid -// // res: not a account address -// return "0"; -// } -// } -// -// public List contractManagerList(int groupId, String contractAddress) throws Exception { -// ContractLifeCycleService contractStatusService = new ContractLifeCycleService( -// web3ApiService.getWeb3j(groupId), keyStoreService.getCredentialsForQuery()); -// return contractStatusService.listManager(contractAddress); -// } -//} +/* + * Copyright 2014-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (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 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.webank.webase.front.precompiledapi; + +import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_OBSERVER; +import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_REMOVE; +import static com.webank.webase.front.util.PrecompiledUtils.NODE_TYPE_SEALER; + +import com.webank.webase.front.base.code.ConstantCode; +import com.webank.webase.front.base.exception.FrontException; +import com.webank.webase.front.keystore.KeyStoreService; +import com.webank.webase.front.precompiledapi.crud.CRUDParseUtils; +import com.webank.webase.front.precompiledapi.crud.Table; +import com.webank.webase.front.precompiledapi.entity.NodeInfo; +import com.webank.webase.front.util.JsonUtils; +import com.webank.webase.front.web3api.Web3ApiService; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.fisco.bcos.sdk.contract.precompiled.cns.CnsInfo; +import org.fisco.bcos.sdk.contract.precompiled.cns.CnsService; +import org.fisco.bcos.sdk.contract.precompiled.contractmgr.ContractLifeCycleService; +import org.fisco.bcos.sdk.contract.precompiled.crud.TableCRUDService; +import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; +import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; +import org.fisco.bcos.sdk.model.PrecompiledConstant; +import org.fisco.bcos.sdk.transaction.model.exception.ContractException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + +/** + * Precompiled common service including management of CNS, node consensus status, CRUD based on + * PrecompiledWithSignService + */ +@Service +public class PrecompiledService { + + @Autowired + private Web3ApiService web3ApiService; + @Autowired + private KeyStoreService keyStoreService; + @Autowired + private PrecompiledWithSignService precompiledWithSignService; + + /** + * CNS config related + */ + public List queryCnsByName(int groupId, String contractName) throws ContractException { + CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), + keyStoreService.getCredentialsForQuery()); + return cnsService.selectByName(contractName); + } + + public List queryCnsByNameAndVersion(int groupId, String contractName, + String version) throws ContractException { + CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), + keyStoreService.getCredentialsForQuery()); + return cnsService.selectByNameAndVersion(contractName, version); + } + + public String getAddressByContractNameAndVersion(int groupId, String contractName, + String version) throws ContractException { + CnsService cnsService = new CnsService(web3ApiService.getWeb3j(groupId), + keyStoreService.getCredentialsForQuery()); + return cnsService.getContractAddress(contractName, version); + } + + /** + * Consensus config related + */ + public String addSealer(int groupId, String signUserId, String nodeId) { + String res = precompiledWithSignService.addSealer(groupId, signUserId, nodeId); + return res; + } + + public String addObserver(int groupId, String signUserId, String nodeId) { + String res = precompiledWithSignService.addObserver(groupId, signUserId, nodeId); + return res; + } + + public String removeNode(int groupId, String signUserId, String nodeId) { + String res = precompiledWithSignService.removeNode(groupId, signUserId, nodeId); + return res; + } + + public List getNodeList(int groupId) throws IOException { + // nodeListWithType 组合多个带有类型的nodeid list + List sealerList = + web3ApiService.getWeb3j(groupId).getSealerList().getSealerList(); + List observerList = + web3ApiService.getWeb3j(groupId).getObserverList().getObserverList(); + List peerList = web3ApiService.getWeb3j(groupId).getNodeIDList().getNodeIDList(); + // process nodeList + List nodeListWithType = new ArrayList<>(); + + // add all sealer and observer in List + sealerList.forEach(sealer -> nodeListWithType.add(new NodeInfo(sealer, NODE_TYPE_SEALER))); + observerList.forEach( + observer -> nodeListWithType.add(new NodeInfo(observer, NODE_TYPE_OBSERVER))); + // peer not in sealer/observer but connected is remove node(游离节点) + peerList.stream().filter(peer -> !sealerList.contains(peer) && !observerList.contains(peer)) + .forEach(peerToAdd -> nodeListWithType + .add(new NodeInfo(peerToAdd, NODE_TYPE_REMOVE))); + + return nodeListWithType; + } + + /** + * CRUD related Table table - validation in controller + */ + public String createTable(int groupId, String signUserId, Table table) { + String res = precompiledWithSignService.createTable(groupId, signUserId, table); + return res; + } + + /** + * insert 校验tableName等操作放在controller + */ + public String insert(int groupId, String signUserId, Table table, Entry entry) { + String res = precompiledWithSignService.insert(groupId, signUserId, table, entry); + return res; + } + + /** + * update + */ + public String update(int groupId, String signUserId, Table table, Entry entry, Condition condition) + { + String res = precompiledWithSignService.update(groupId, signUserId, table, entry, condition); + return res; + } + + /** + * remove + */ + public String remove(int groupId, String signUserId, Table table, Condition condition) { + String res = precompiledWithSignService.remove(groupId, signUserId, table, condition); + return res; + } + + /** + * desc + */ + public List> desc(int groupId, String tableName) throws Exception { + TableCRUDService crudService = new TableCRUDService(web3ApiService.getWeb3j(groupId), + keyStoreService.getCredentialsForQuery()); + List> descRes = crudService.desc(tableName); + if (!CRUDParseUtils.checkTableExistence(descRes)) { + throw new FrontException(ConstantCode.FAIL_TABLE_NOT_EXISTS); + } + return descRes; +// String tableKey = descRes.get(0).get(PrecompiledConstant.KEY_FIELD_NAME); +// String valueFields = descRes.get(0).get(PrecompiledConstant.VALUE_FIELD_NAME); +// return new Table(tableName, tableKey, valueFields); + } + + public String descTable(int groupId, String tableName) throws Exception { + List> descRes = this.desc(groupId, tableName); + if (!CRUDParseUtils.checkTableExistence(descRes)) { + throw new FrontException(ConstantCode.FAIL_TABLE_NOT_EXISTS); + } + String tableInfo = JsonUtils.objToString(descRes); + return CRUDParseUtils.formatJson(tableInfo); + } + + /** + * select + */ + public List> select(int groupId, Table table, + Condition conditions) throws Exception { + TableCRUDService crudService = new TableCRUDService(web3ApiService.getWeb3j(groupId), + keyStoreService.getCredentialsForQuery()); + List> selectRes = crudService.select(table.getTableName(), table.getKey(), conditions); + return selectRes; + } + + public String contractFreeze(int groupId, String signUserId, String contractAddress) + { + return precompiledWithSignService.contractFreeze(groupId, signUserId, contractAddress); + } + + public String contractUnfreeze(int groupId, String signUserId, String contractAddress) + { + return precompiledWithSignService.contractUnfreeze(groupId, signUserId, contractAddress); + } + + public String contractGrantManager(int groupId, String signUserId, String contractAddress, + String grantAddress) { + return precompiledWithSignService.contractGrantManager(groupId, signUserId, contractAddress, + grantAddress); + } + + public String contractStatus(int groupId, String contractAddress) throws Exception { + ContractLifeCycleService contractStatusService = new ContractLifeCycleService( + web3ApiService.getWeb3j(groupId), keyStoreService.getCredentialsForQuery()); + String res = contractStatusService.getContractStatus(contractAddress); + if (res.contains("frozen")) { + // res: The account has been frozen. You can use this account after unfreezing it. + return "1"; + } else { + // res: The address is nonexistent. + // res: The account is available. + // res: invalid + // res: not a account address + return "0"; + } + } + + public List contractManagerList(int groupId, String contractAddress) throws Exception { + ContractLifeCycleService contractStatusService = new ContractLifeCycleService( + web3ApiService.getWeb3j(groupId), keyStoreService.getCredentialsForQuery()); + return contractStatusService.listManager(contractAddress); + } +} diff --git a/src/main/java/com/webank/webase/front/precompiledapi/crud/CRUDParseUtils.java b/src/main/java/com/webank/webase/front/precompiledapi/crud/CRUDParseUtils.java index 76ceb831b..748b8c227 100644 --- a/src/main/java/com/webank/webase/front/precompiledapi/crud/CRUDParseUtils.java +++ b/src/main/java/com/webank/webase/front/precompiledapi/crud/CRUDParseUtils.java @@ -1,622 +1,622 @@ -//package com.webank.webase.front.precompiledapi.crud; -// -//import com.webank.webase.front.base.code.ConstantCode; -//import com.webank.webase.front.base.exception.FrontException; -//import com.webank.webase.front.util.PrecompiledUtils; -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.HashSet; -//import java.util.LinkedHashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -//import net.sf.jsqlparser.JSQLParserException; -//import net.sf.jsqlparser.expression.BinaryExpression; -//import net.sf.jsqlparser.expression.Expression; -//import net.sf.jsqlparser.expression.ExpressionVisitorAdapter; -//import net.sf.jsqlparser.expression.Function; -//import net.sf.jsqlparser.expression.NotExpression; -//import net.sf.jsqlparser.expression.operators.conditional.OrExpression; -//import net.sf.jsqlparser.expression.operators.relational.ComparisonOperator; -//import net.sf.jsqlparser.expression.operators.relational.ExpressionList; -//import net.sf.jsqlparser.expression.operators.relational.InExpression; -//import net.sf.jsqlparser.expression.operators.relational.IsNullExpression; -//import net.sf.jsqlparser.expression.operators.relational.ItemsList; -//import net.sf.jsqlparser.expression.operators.relational.LikeExpression; -//import net.sf.jsqlparser.parser.CCJSqlParserUtil; -//import net.sf.jsqlparser.schema.Column; -//import net.sf.jsqlparser.statement.Statement; -//import net.sf.jsqlparser.statement.create.table.ColumnDefinition; -//import net.sf.jsqlparser.statement.create.table.CreateTable; -//import net.sf.jsqlparser.statement.create.table.Index; -//import net.sf.jsqlparser.statement.delete.Delete; -//import net.sf.jsqlparser.statement.insert.Insert; -//import net.sf.jsqlparser.statement.select.Limit; -//import net.sf.jsqlparser.statement.select.PlainSelect; -//import net.sf.jsqlparser.statement.select.Select; -//import net.sf.jsqlparser.statement.select.SelectExpressionItem; -//import net.sf.jsqlparser.statement.select.SelectItem; -//import net.sf.jsqlparser.statement.select.SubSelect; -//import net.sf.jsqlparser.statement.update.Update; -//import net.sf.jsqlparser.util.TablesNamesFinder; -//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; -//import org.fisco.bcos.sdk.contract.precompiled.crud.common.ConditionOperator; -//import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; -//import org.fisco.bcos.sdk.model.PrecompiledConstant; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -// -//public class CRUDParseUtils { -// private static final Logger logger = LoggerFactory.getLogger(CRUDParseUtils.class); -// public static final String PRIMARY_KEY = "primary key"; -// -// public static void parseCreateTable(String sql, Table table) -// throws JSQLParserException, FrontException { -// Statement statement = CCJSqlParserUtil.parse(sql); -// CreateTable createTable = (CreateTable) statement; -// -// // parse table name -// String tableName = createTable.getTable().getName(); -// table.setTableName(tableName); -// -// // parse key from index -// boolean keyFlag = false; -// List indexes = createTable.getIndexes(); -// if (indexes != null) { -// if (indexes.size() > 1) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Please provide only one primary key for the table."); -// } -// keyFlag = true; -// Index index = indexes.get(0); -// String type = index.getType().toLowerCase(); -// if (PRIMARY_KEY.equals(type)) { -// table.setKey(index.getColumnsNames().get(0)); -// table.setKeyFieldName(index.getColumnsNames().get(0)); -// } else { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Please provide only one primary key for the table."); -// } -// } -// List columnDefinitions = createTable.getColumnDefinitions(); -// // parse key from ColumnDefinition -// for (int i = 0; i < columnDefinitions.size(); i++) { -// List columnSpecStrings = columnDefinitions.get(i).getColumnSpecStrings(); -// if (columnSpecStrings == null) { -// continue; -// } else { -// if (columnSpecStrings.size() == 2 -// && "primary".equals(columnSpecStrings.get(0)) -// && "key".equals(columnSpecStrings.get(1))) { -// String key = columnDefinitions.get(i).getColumnName(); -// if (keyFlag) { -// if (!table.getKey().equals(key)) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Please provide only one primary key for the table."); -// } -// } else { -// keyFlag = true; -// table.setKey(key); -// } -// break; -// } -// } -// } -// if (!keyFlag) { -// throw new FrontException(ConstantCode.SQL_ERROR, "Please provide a primary key for the table."); -// } -// // parse value field -// List fieldsList = new ArrayList<>(); -// for (int i = 0; i < columnDefinitions.size(); i++) { -// String columnName = columnDefinitions.get(i).getColumnName(); -// if (fieldsList.contains(columnName)) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Please provide the field '" + columnName + "' only once."); -// } else { -// fieldsList.add(columnName); -// } -// } -// if (!fieldsList.contains(table.getKey())) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Please provide the field '" + table.getKey() + "' in column definition."); -// } else { -// fieldsList.remove(table.getKey()); -// } -// table.setValueFields(fieldsList); -// } -// -// public static String parseInsertedTableName(String sql) -// throws JSQLParserException, FrontException { -// Statement statement = CCJSqlParserUtil.parse(sql); -// Insert insert = (Insert) statement; -// -// if (insert.getSelect() != null) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The insert select clause is not supported."); -// } -// // parse table name -// return insert.getTable().getName(); -// } -// -// public static boolean parseInsert( -// String sql, Table table, Entry entry, Map tableDesc) -// throws JSQLParserException, FrontException { -// Statement statement = CCJSqlParserUtil.parse(sql); -// Insert insert = (Insert) statement; -// String valueFieldString = tableDesc.get(PrecompiledConstant.VALUE_FIELD_NAME); -// String[] valueFields = valueFieldString.split(","); -// String expectedValueField = -// tableDesc.get(PrecompiledConstant.KEY_FIELD_NAME) + ", " + valueFieldString; -// int expectedValueNum = valueFields.length + 1; -// -// if (insert.getSelect() != null) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The insert select clause is not supported."); -// } -// // parse table name -// String tableName = insert.getTable().getName(); -// table.setTableName(tableName); -// -// // parse columns -// List columns = insert.getColumns(); -// ItemsList itemsList = insert.getItemsList(); -// -// ExpressionList expressionList = (ExpressionList) itemsList; -// List expressions = expressionList.getExpressions(); -// -// String[] itemArr = new String[expressions.size()]; -// for (int i = 0; i < expressions.size(); i++) { -// itemArr[i] = expressions.get(i).toString().trim(); -// } -// if (columns != null) { -// if (columns.size() != itemArr.length) { -// throw new FrontException(ConstantCode.SQL_ERROR, "Column count doesn't match value count."); -// } -// if (expectedValueNum != columns.size()) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Column count doesn't match value count, fields size: " -// + valueFields.length -// + ", provided field value size: " -// + columns.size() -// + ", expected field list: " -// + expectedValueField); -// } -// List columnNames = new ArrayList<>(); -// for (Column column : columns) { -// String columnName = trimQuotes(column.toString()); -// if (columnNames.contains(columnName)) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Please provide the field '" + columnName + "' only once."); -// } else { -// columnNames.add(columnName); -// } -// } -// for (int i = 0; i < columnNames.size(); i++) { -// entry.getFieldNameToValue().put(columnNames.get(i), trimQuotes(itemArr[i])); -// } -// return false; -// } else { -// String keyField = tableDesc.get(PrecompiledConstant.KEY_FIELD_NAME); -// if (expectedValueNum != itemArr.length) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Column count doesn't match value count, fields size: " -// + valueFields.length -// + ", provided field value size: " -// + itemArr.length -// + ", expected field list: " -// + expectedValueField); -// } -// String[] allFields = new String[itemArr.length]; -// allFields[0] = keyField; -// System.arraycopy(valueFields, 0, allFields, 1, valueFields.length); -// for (int i = 0; i < itemArr.length; i++) { -// entry.getFieldNameToValue().put(allFields[i], trimQuotes(itemArr[i])); -// } -// return true; -// } -// } -// -// public static void parseSelect( -// String sql, Table table, Condition condition, List selectColumns) -// throws JSQLParserException, FrontException { -// Statement statement; -// statement = CCJSqlParserUtil.parse(sql); -// Select selectStatement = (Select) statement; -// -// // parse table name -// TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); -// List tableList = tablesNamesFinder.getTableList(selectStatement); -// if (tableList.size() != 1) { -// throw new FrontException(ConstantCode.SQL_ERROR, "Please provide only one table name."); -// } -// table.setTableName(tableList.get(0)); -// -// // parse where clause -// PlainSelect selectBody = (PlainSelect) selectStatement.getSelectBody(); -// if (selectBody.getOrderByElements() != null) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The order clause is not supported."); -// } -// if (selectBody.getGroupBy() != null) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The group clause is not supported."); -// } -// if (selectBody.getHaving() != null) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The having clause is not supported."); -// } -// if (selectBody.getJoins() != null) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The join clause is not supported."); -// } -// if (selectBody.getTop() != null) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The top clause is not supported."); -// } -// if (selectBody.getDistinct() != null) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The distinct clause is not supported."); -// } -// Expression expr = selectBody.getWhere(); -// condition = handleExpression(condition, expr); -// -// Limit limit = selectBody.getLimit(); -// if (limit != null) { -// parseLimit(condition, limit); -// } -// -// // parse select item -// List selectItems = selectBody.getSelectItems(); -// for (SelectItem item : selectItems) { -// if (item instanceof SelectExpressionItem) { -// SelectExpressionItem selectExpressionItem = (SelectExpressionItem) item; -// Expression expression = selectExpressionItem.getExpression(); -// if (expression instanceof Function) { -// Function func = (Function) expression; -// throw new FrontException(ConstantCode.SQL_ERROR, -// "The " + func.getName() + " function is not supported."); -// } -// } -// selectColumns.add(item.toString()); -// } -// } -// -// private static void checkExpression(Expression expression) throws FrontException { -// if (expression instanceof OrExpression) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The OrExpression is not supported."); -// } -// if (expression instanceof NotExpression) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The NotExpression is not supported."); -// } -// if (expression instanceof InExpression) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The InExpression is not supported."); -// } -// if (expression instanceof LikeExpression) { -// logger.debug("The LikeExpression is not supported."); -// throw new FrontException(ConstantCode.SQL_ERROR, "The LikeExpression is not supported."); -// } -// if (expression instanceof SubSelect) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The SubSelect is not supported."); -// } -// if (expression instanceof IsNullExpression) { -// throw new FrontException(ConstantCode.SQL_ERROR, "The IsNullExpression is not supported."); -// } -// } -// -// private static Condition handleExpression(Condition condition, Expression expr) -// throws FrontException { -// if (expr instanceof BinaryExpression) { -// condition = getWhereClause((BinaryExpression) (expr), condition); -// } -// checkExpression(expr); -// Map> conditions = condition.getConditions(); -// Set keys = conditions.keySet(); -// for (String key : keys) { -// Map value = conditions.get(key); -// ConditionOperator operation = value.keySet().iterator().next(); -// String itemValue = value.values().iterator().next(); -// String newValue = trimQuotes(itemValue); -// value.put(operation, newValue); -// conditions.put(key, value); -// } -// condition.setConditions(conditions); -// return condition; -// } -// -// public static String trimQuotes(String str) { -// char[] value = str.toCharArray(); -// int len = value.length; -// int st = 1; -// char[] val = value; /* avoid getfield opcode */ -// -// while ((st < len) && (val[st] == '"' || val[st] == '\'')) { -// st++; -// } -// while ((st < len) && (val[len - 1] == '"' || val[len - 1] == '\'')) { -// len--; -// } -// String string = ((st > 1) || (len < value.length)) ? str.substring(st, len) : str; -// return string; -// } -// -// public static void parseUpdate(String sql, Table table, Entry entry, Condition condition) -// throws JSQLParserException, FrontException { -// Statement statement = CCJSqlParserUtil.parse(sql); -// Update update = (Update) statement; -// -// // parse table name -// List tables = update.getTables(); -// String tableName = tables.get(0).getName(); -// table.setTableName(tableName); -// -// // parse columns -// List columns = update.getColumns(); -// List expressions = update.getExpressions(); -// int size = expressions.size(); -// String[] values = new String[size]; -// for (int i = 0; i < size; i++) { -// values[i] = expressions.get(i).toString(); -// } -// for (int i = 0; i < columns.size(); i++) { -// entry.getFieldNameToValue() -// .put(trimQuotes(columns.get(i).toString()), trimQuotes(values[i])); -// } -// -// // parse where clause -// Expression where = update.getWhere(); -// if (where != null) { -// BinaryExpression expr2 = (BinaryExpression) (where); -// handleExpression(condition, expr2); -// } -// Limit limit = update.getLimit(); -// parseLimit(condition, limit); -// } -// -// public static void parseRemove(String sql, Table table, Condition condition) -// throws JSQLParserException, FrontException { -// Statement statement = CCJSqlParserUtil.parse(sql); -// Delete delete = (Delete) statement; -// -// // parse table name -// net.sf.jsqlparser.schema.Table sqlTable = delete.getTable(); -// table.setTableName(sqlTable.getName()); -// -// // parse where clause -// Expression where = delete.getWhere(); -// if (where != null) { -// BinaryExpression expr = (BinaryExpression) (where); -// handleExpression(condition, expr); -// } -// Limit limit = delete.getLimit(); -// parseLimit(condition, limit); -// } -// -// private static void parseLimit(Condition condition, Limit limit) -// throws FrontException { -// if (limit != null) { -// Expression offset = limit.getOffset(); -// Expression count = limit.getRowCount(); -// try { -// if (offset != null) { -// condition.Limit( -// Integer.parseInt(offset.toString()), -// Integer.parseInt(count.toString())); -// } else { -// condition.Limit(Integer.parseInt(count.toString())); -// } -// } catch (NumberFormatException e) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Please provide limit parameters by non-negative integer mode, " -// + PrecompiledUtils.NonNegativeIntegerRange -// + "."); -// } -// } -// } -// -// private static Condition getWhereClause(Expression expr, Condition condition) -// throws FrontException { -// Set keySet = new HashSet<>(); -// Set conflictKeys = new HashSet<>(); -// Set unsupportedConditions = new HashSet<>(); -// expr.accept( -// new ExpressionVisitorAdapter() { -// @Override -// protected void visitBinaryExpression(BinaryExpression expr) { -// if (expr instanceof ComparisonOperator) { -// String key = trimQuotes(expr.getLeftExpression().toString()); -// if (keySet.contains(key)) { -// conflictKeys.add(key); -// } -// keySet.add(key); -// String operation = expr.getStringExpression(); -// String value = trimQuotes(expr.getRightExpression().toString()); -// switch (operation) { -// case "=": -// condition.EQ(key, value); -// break; -// case "!=": -// condition.NE(key, value); -// break; -// case ">": -// condition.GT(key, value); -// break; -// case ">=": -// condition.GE(key, value); -// break; -// case "<": -// condition.LT(key, value); -// break; -// case "<=": -// condition.LE(key, value); -// break; -// default: -// break; -// } -// } else { -// try { -// checkExpression(expr); -// } catch (FrontException e) { -// unsupportedConditions.add(e.getMessage()); -// } -// } -// super.visitBinaryExpression(expr); -// } -// }); -// if (conflictKeys.size() > 0) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Wrong condition! There cannot be the same field in the same condition! The conflicting field is: " -// + conflictKeys.toString()); -// } -// if (unsupportedConditions.size() > 0) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Wrong condition! Find unsupported conditions! message: " -// + unsupportedConditions.toString()); -// } -// return condition; -// } -// -// public static void invalidSymbol(String sql) throws FrontException { -// if (sql.contains(";")) { -// throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese semicolon."); -// } else if (sql.contains("“") -// || sql.contains("”") -// || sql.contains("‘") -// || sql.contains("’")) { -// throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese quotes."); -// } else if (sql.contains(",")) { -// throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese comma."); -// } -// } -// -// public static boolean checkTableExistence(List> descTable) { -// if (descTable.size() == 0 -// || descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME).equals("")) { -//// System.out.println("The table \"" + tableName + "\" doesn't exist!"); -// return false; -// } -// return true; -// } -// -// -// public static String formatJson(String jsonStr) { -// if (null == jsonStr || "".equals(jsonStr)) return ""; -// jsonStr = jsonStr.replace("\\n", ""); -// StringBuilder sb = new StringBuilder(); -// char last = '\0'; -// char current = '\0'; -// int indent = 0; -// boolean isInQuotationMarks = false; -// for (int i = 0; i < jsonStr.length(); i++) { -// last = current; -// current = jsonStr.charAt(i); -// switch (current) { -// case '"': -// if (last != '\\') { -// isInQuotationMarks = !isInQuotationMarks; -// } -// sb.append(current); -// break; -// case '{': -// case '[': -// sb.append(current); -// if (!isInQuotationMarks) { -// sb.append('\n'); -// indent++; -// addIndentBlank(sb, indent); -// } -// break; -// case '}': -// case ']': -// if (!isInQuotationMarks) { -// sb.append('\n'); -// indent--; -// addIndentBlank(sb, indent); -// } -// sb.append(current); -// break; -// case ',': -// sb.append(current); -// if (last != '\\' && !isInQuotationMarks) { -// sb.append('\n'); -// addIndentBlank(sb, indent); -// } -// break; -// case ' ': -// if (',' != jsonStr.charAt(i - 1)) { -// sb.append(current); -// } -// break; -// case '\\': -// sb.append("\\"); -// break; -// default: -// if (!(current == " ".charAt(0))) sb.append(current); -// } -// } -// -// return sb.toString(); -// } -// -// private static void addIndentBlank(StringBuilder sb, int indent) { -// for (int i = 0; i < indent; i++) { -// sb.append(" "); -// } -// } -// -// -// public static void handleKey(Table table, Condition condition) { -// -// String keyName = table.getKey(); -// String keyValue = ""; -// Map keyMap = condition.getConditions().get(keyName); -// if (keyMap == null) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Please provide a equal condition for the key field '" -// + keyName -// + "' in where clause."); -// } else { -// Set keySet = keyMap.keySet(); -// for (ConditionOperator enumOP : keySet) { -// if (enumOP != ConditionOperator.eq) { -// throw new FrontException(ConstantCode.SQL_ERROR, -// "Please provide a equal condition for the key field '" -// + keyName -// + "' in where clause."); -// } else { -// keyValue = keyMap.get(enumOP); -// } -// } -// } -// table.setKey(keyValue); -// } -// -// public static List> filterSystemColum(List> result) { -// -// List filteredColumns = Arrays.asList("_id_", "_hash_", "_status_", "_num_"); -// List> filteredResult = new ArrayList<>(result.size()); -// Map filteredRecords; -// for (Map records : result) { -// filteredRecords = new LinkedHashMap<>(); -// Set recordKeys = records.keySet(); -// for (String recordKey : recordKeys) { -// if (!filteredColumns.contains(recordKey)) { -// filteredRecords.put(recordKey, records.get(recordKey)); -// } -// } -// filteredResult.add(filteredRecords); -// } -// return filteredResult; -// } -// -// public static List> getSelectedColumn( -// List selectColumns, List> result) { -// List> selectedResult = new ArrayList<>(result.size()); -// Map selectedRecords; -// for (Map records : result) { -// selectedRecords = new LinkedHashMap<>(); -// for (String column : selectColumns) { -// Set recordKeys = records.keySet(); -// for (String recordKey : recordKeys) { -// if (recordKey.equals(column)) { -// selectedRecords.put(recordKey, records.get(recordKey)); -// } -// } -// } -// selectedResult.add(selectedRecords); -// } -// selectedResult.forEach(System.out::println); -// return selectedResult; -// } -//} +package com.webank.webase.front.precompiledapi.crud; + +import com.webank.webase.front.base.code.ConstantCode; +import com.webank.webase.front.base.exception.FrontException; +import com.webank.webase.front.util.PrecompiledUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.BinaryExpression; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.ExpressionVisitorAdapter; +import net.sf.jsqlparser.expression.Function; +import net.sf.jsqlparser.expression.NotExpression; +import net.sf.jsqlparser.expression.operators.conditional.OrExpression; +import net.sf.jsqlparser.expression.operators.relational.ComparisonOperator; +import net.sf.jsqlparser.expression.operators.relational.ExpressionList; +import net.sf.jsqlparser.expression.operators.relational.InExpression; +import net.sf.jsqlparser.expression.operators.relational.IsNullExpression; +import net.sf.jsqlparser.expression.operators.relational.ItemsList; +import net.sf.jsqlparser.expression.operators.relational.LikeExpression; +import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.schema.Column; +import net.sf.jsqlparser.statement.Statement; +import net.sf.jsqlparser.statement.create.table.ColumnDefinition; +import net.sf.jsqlparser.statement.create.table.CreateTable; +import net.sf.jsqlparser.statement.create.table.Index; +import net.sf.jsqlparser.statement.delete.Delete; +import net.sf.jsqlparser.statement.insert.Insert; +import net.sf.jsqlparser.statement.select.Limit; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.Select; +import net.sf.jsqlparser.statement.select.SelectExpressionItem; +import net.sf.jsqlparser.statement.select.SelectItem; +import net.sf.jsqlparser.statement.select.SubSelect; +import net.sf.jsqlparser.statement.update.Update; +import net.sf.jsqlparser.util.TablesNamesFinder; +import org.fisco.bcos.sdk.contract.precompiled.crud.common.Condition; +import org.fisco.bcos.sdk.contract.precompiled.crud.common.ConditionOperator; +import org.fisco.bcos.sdk.contract.precompiled.crud.common.Entry; +import org.fisco.bcos.sdk.model.PrecompiledConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CRUDParseUtils { + private static final Logger logger = LoggerFactory.getLogger(CRUDParseUtils.class); + public static final String PRIMARY_KEY = "primary key"; + + public static void parseCreateTable(String sql, Table table) + throws JSQLParserException, FrontException { + Statement statement = CCJSqlParserUtil.parse(sql); + CreateTable createTable = (CreateTable) statement; + + // parse table name + String tableName = createTable.getTable().getName(); + table.setTableName(tableName); + + // parse key from index + boolean keyFlag = false; + List indexes = createTable.getIndexes(); + if (indexes != null) { + if (indexes.size() > 1) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Please provide only one primary key for the table."); + } + keyFlag = true; + Index index = indexes.get(0); + String type = index.getType().toLowerCase(); + if (PRIMARY_KEY.equals(type)) { + table.setKey(index.getColumnsNames().get(0)); + table.setKeyFieldName(index.getColumnsNames().get(0)); + } else { + throw new FrontException(ConstantCode.SQL_ERROR, + "Please provide only one primary key for the table."); + } + } + List columnDefinitions = createTable.getColumnDefinitions(); + // parse key from ColumnDefinition + for (int i = 0; i < columnDefinitions.size(); i++) { + List columnSpecStrings = columnDefinitions.get(i).getColumnSpecStrings(); + if (columnSpecStrings == null) { + continue; + } else { + if (columnSpecStrings.size() == 2 + && "primary".equals(columnSpecStrings.get(0)) + && "key".equals(columnSpecStrings.get(1))) { + String key = columnDefinitions.get(i).getColumnName(); + if (keyFlag) { + if (!table.getKey().equals(key)) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Please provide only one primary key for the table."); + } + } else { + keyFlag = true; + table.setKey(key); + } + break; + } + } + } + if (!keyFlag) { + throw new FrontException(ConstantCode.SQL_ERROR, "Please provide a primary key for the table."); + } + // parse value field + List fieldsList = new ArrayList<>(); + for (int i = 0; i < columnDefinitions.size(); i++) { + String columnName = columnDefinitions.get(i).getColumnName(); + if (fieldsList.contains(columnName)) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Please provide the field '" + columnName + "' only once."); + } else { + fieldsList.add(columnName); + } + } + if (!fieldsList.contains(table.getKey())) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Please provide the field '" + table.getKey() + "' in column definition."); + } else { + fieldsList.remove(table.getKey()); + } + table.setValueFields(fieldsList); + } + + public static String parseInsertedTableName(String sql) + throws JSQLParserException, FrontException { + Statement statement = CCJSqlParserUtil.parse(sql); + Insert insert = (Insert) statement; + + if (insert.getSelect() != null) { + throw new FrontException(ConstantCode.SQL_ERROR, "The insert select clause is not supported."); + } + // parse table name + return insert.getTable().getName(); + } + + public static boolean parseInsert( + String sql, Table table, Entry entry, Map tableDesc) + throws JSQLParserException, FrontException { + Statement statement = CCJSqlParserUtil.parse(sql); + Insert insert = (Insert) statement; + String valueFieldString = tableDesc.get(PrecompiledConstant.VALUE_FIELD_NAME); + String[] valueFields = valueFieldString.split(","); + String expectedValueField = + tableDesc.get(PrecompiledConstant.KEY_FIELD_NAME) + ", " + valueFieldString; + int expectedValueNum = valueFields.length + 1; + + if (insert.getSelect() != null) { + throw new FrontException(ConstantCode.SQL_ERROR, "The insert select clause is not supported."); + } + // parse table name + String tableName = insert.getTable().getName(); + table.setTableName(tableName); + + // parse columns + List columns = insert.getColumns(); + ItemsList itemsList = insert.getItemsList(); + + ExpressionList expressionList = (ExpressionList) itemsList; + List expressions = expressionList.getExpressions(); + + String[] itemArr = new String[expressions.size()]; + for (int i = 0; i < expressions.size(); i++) { + itemArr[i] = expressions.get(i).toString().trim(); + } + if (columns != null) { + if (columns.size() != itemArr.length) { + throw new FrontException(ConstantCode.SQL_ERROR, "Column count doesn't match value count."); + } + if (expectedValueNum != columns.size()) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Column count doesn't match value count, fields size: " + + valueFields.length + + ", provided field value size: " + + columns.size() + + ", expected field list: " + + expectedValueField); + } + List columnNames = new ArrayList<>(); + for (Column column : columns) { + String columnName = trimQuotes(column.toString()); + if (columnNames.contains(columnName)) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Please provide the field '" + columnName + "' only once."); + } else { + columnNames.add(columnName); + } + } + for (int i = 0; i < columnNames.size(); i++) { + entry.getFieldNameToValue().put(columnNames.get(i), trimQuotes(itemArr[i])); + } + return false; + } else { + String keyField = tableDesc.get(PrecompiledConstant.KEY_FIELD_NAME); + if (expectedValueNum != itemArr.length) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Column count doesn't match value count, fields size: " + + valueFields.length + + ", provided field value size: " + + itemArr.length + + ", expected field list: " + + expectedValueField); + } + String[] allFields = new String[itemArr.length]; + allFields[0] = keyField; + System.arraycopy(valueFields, 0, allFields, 1, valueFields.length); + for (int i = 0; i < itemArr.length; i++) { + entry.getFieldNameToValue().put(allFields[i], trimQuotes(itemArr[i])); + } + return true; + } + } + + public static void parseSelect( + String sql, Table table, Condition condition, List selectColumns) + throws JSQLParserException, FrontException { + Statement statement; + statement = CCJSqlParserUtil.parse(sql); + Select selectStatement = (Select) statement; + + // parse table name + TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); + List tableList = tablesNamesFinder.getTableList(selectStatement); + if (tableList.size() != 1) { + throw new FrontException(ConstantCode.SQL_ERROR, "Please provide only one table name."); + } + table.setTableName(tableList.get(0)); + + // parse where clause + PlainSelect selectBody = (PlainSelect) selectStatement.getSelectBody(); + if (selectBody.getOrderByElements() != null) { + throw new FrontException(ConstantCode.SQL_ERROR, "The order clause is not supported."); + } + if (selectBody.getGroupBy() != null) { + throw new FrontException(ConstantCode.SQL_ERROR, "The group clause is not supported."); + } + if (selectBody.getHaving() != null) { + throw new FrontException(ConstantCode.SQL_ERROR, "The having clause is not supported."); + } + if (selectBody.getJoins() != null) { + throw new FrontException(ConstantCode.SQL_ERROR, "The join clause is not supported."); + } + if (selectBody.getTop() != null) { + throw new FrontException(ConstantCode.SQL_ERROR, "The top clause is not supported."); + } + if (selectBody.getDistinct() != null) { + throw new FrontException(ConstantCode.SQL_ERROR, "The distinct clause is not supported."); + } + Expression expr = selectBody.getWhere(); + condition = handleExpression(condition, expr); + + Limit limit = selectBody.getLimit(); + if (limit != null) { + parseLimit(condition, limit); + } + + // parse select item + List selectItems = selectBody.getSelectItems(); + for (SelectItem item : selectItems) { + if (item instanceof SelectExpressionItem) { + SelectExpressionItem selectExpressionItem = (SelectExpressionItem) item; + Expression expression = selectExpressionItem.getExpression(); + if (expression instanceof Function) { + Function func = (Function) expression; + throw new FrontException(ConstantCode.SQL_ERROR, + "The " + func.getName() + " function is not supported."); + } + } + selectColumns.add(item.toString()); + } + } + + private static void checkExpression(Expression expression) throws FrontException { + if (expression instanceof OrExpression) { + throw new FrontException(ConstantCode.SQL_ERROR, "The OrExpression is not supported."); + } + if (expression instanceof NotExpression) { + throw new FrontException(ConstantCode.SQL_ERROR, "The NotExpression is not supported."); + } + if (expression instanceof InExpression) { + throw new FrontException(ConstantCode.SQL_ERROR, "The InExpression is not supported."); + } + if (expression instanceof LikeExpression) { + logger.debug("The LikeExpression is not supported."); + throw new FrontException(ConstantCode.SQL_ERROR, "The LikeExpression is not supported."); + } + if (expression instanceof SubSelect) { + throw new FrontException(ConstantCode.SQL_ERROR, "The SubSelect is not supported."); + } + if (expression instanceof IsNullExpression) { + throw new FrontException(ConstantCode.SQL_ERROR, "The IsNullExpression is not supported."); + } + } + + private static Condition handleExpression(Condition condition, Expression expr) + throws FrontException { + if (expr instanceof BinaryExpression) { + condition = getWhereClause((BinaryExpression) (expr), condition); + } + checkExpression(expr); + Map> conditions = condition.getConditions(); + Set keys = conditions.keySet(); + for (String key : keys) { + Map value = conditions.get(key); + ConditionOperator operation = value.keySet().iterator().next(); + String itemValue = value.values().iterator().next(); + String newValue = trimQuotes(itemValue); + value.put(operation, newValue); + conditions.put(key, value); + } + condition.setConditions(conditions); + return condition; + } + + public static String trimQuotes(String str) { + char[] value = str.toCharArray(); + int len = value.length; + int st = 1; + char[] val = value; /* avoid getfield opcode */ + + while ((st < len) && (val[st] == '"' || val[st] == '\'')) { + st++; + } + while ((st < len) && (val[len - 1] == '"' || val[len - 1] == '\'')) { + len--; + } + String string = ((st > 1) || (len < value.length)) ? str.substring(st, len) : str; + return string; + } + + public static void parseUpdate(String sql, Table table, Entry entry, Condition condition) + throws JSQLParserException, FrontException { + Statement statement = CCJSqlParserUtil.parse(sql); + Update update = (Update) statement; + + // parse table name + List tables = update.getTables(); + String tableName = tables.get(0).getName(); + table.setTableName(tableName); + + // parse columns + List columns = update.getColumns(); + List expressions = update.getExpressions(); + int size = expressions.size(); + String[] values = new String[size]; + for (int i = 0; i < size; i++) { + values[i] = expressions.get(i).toString(); + } + for (int i = 0; i < columns.size(); i++) { + entry.getFieldNameToValue() + .put(trimQuotes(columns.get(i).toString()), trimQuotes(values[i])); + } + + // parse where clause + Expression where = update.getWhere(); + if (where != null) { + BinaryExpression expr2 = (BinaryExpression) (where); + handleExpression(condition, expr2); + } + Limit limit = update.getLimit(); + parseLimit(condition, limit); + } + + public static void parseRemove(String sql, Table table, Condition condition) + throws JSQLParserException, FrontException { + Statement statement = CCJSqlParserUtil.parse(sql); + Delete delete = (Delete) statement; + + // parse table name + net.sf.jsqlparser.schema.Table sqlTable = delete.getTable(); + table.setTableName(sqlTable.getName()); + + // parse where clause + Expression where = delete.getWhere(); + if (where != null) { + BinaryExpression expr = (BinaryExpression) (where); + handleExpression(condition, expr); + } + Limit limit = delete.getLimit(); + parseLimit(condition, limit); + } + + private static void parseLimit(Condition condition, Limit limit) + throws FrontException { + if (limit != null) { + Expression offset = limit.getOffset(); + Expression count = limit.getRowCount(); + try { + if (offset != null) { + condition.Limit( + Integer.parseInt(offset.toString()), + Integer.parseInt(count.toString())); + } else { + condition.Limit(Integer.parseInt(count.toString())); + } + } catch (NumberFormatException e) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Please provide limit parameters by non-negative integer mode, " + + PrecompiledUtils.NonNegativeIntegerRange + + "."); + } + } + } + + private static Condition getWhereClause(Expression expr, Condition condition) + throws FrontException { + Set keySet = new HashSet<>(); + Set conflictKeys = new HashSet<>(); + Set unsupportedConditions = new HashSet<>(); + expr.accept( + new ExpressionVisitorAdapter() { + @Override + protected void visitBinaryExpression(BinaryExpression expr) { + if (expr instanceof ComparisonOperator) { + String key = trimQuotes(expr.getLeftExpression().toString()); + if (keySet.contains(key)) { + conflictKeys.add(key); + } + keySet.add(key); + String operation = expr.getStringExpression(); + String value = trimQuotes(expr.getRightExpression().toString()); + switch (operation) { + case "=": + condition.EQ(key, value); + break; + case "!=": + condition.NE(key, value); + break; + case ">": + condition.GT(key, value); + break; + case ">=": + condition.GE(key, value); + break; + case "<": + condition.LT(key, value); + break; + case "<=": + condition.LE(key, value); + break; + default: + break; + } + } else { + try { + checkExpression(expr); + } catch (FrontException e) { + unsupportedConditions.add(e.getMessage()); + } + } + super.visitBinaryExpression(expr); + } + }); + if (conflictKeys.size() > 0) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Wrong condition! There cannot be the same field in the same condition! The conflicting field is: " + + conflictKeys.toString()); + } + if (unsupportedConditions.size() > 0) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Wrong condition! Find unsupported conditions! message: " + + unsupportedConditions.toString()); + } + return condition; + } + + public static void invalidSymbol(String sql) throws FrontException { + if (sql.contains(";")) { + throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese semicolon."); + } else if (sql.contains("“") + || sql.contains("”") + || sql.contains("‘") + || sql.contains("’")) { + throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese quotes."); + } else if (sql.contains(",")) { + throw new FrontException(ConstantCode.SQL_ERROR, "SyntaxError: Unexpected Chinese comma."); + } + } + + public static boolean checkTableExistence(List> descTable) { + if (descTable.size() == 0 + || descTable.get(0).get(PrecompiledConstant.KEY_FIELD_NAME).equals("")) { +// System.out.println("The table \"" + tableName + "\" doesn't exist!"); + return false; + } + return true; + } + + + public static String formatJson(String jsonStr) { + if (null == jsonStr || "".equals(jsonStr)) return ""; + jsonStr = jsonStr.replace("\\n", ""); + StringBuilder sb = new StringBuilder(); + char last = '\0'; + char current = '\0'; + int indent = 0; + boolean isInQuotationMarks = false; + for (int i = 0; i < jsonStr.length(); i++) { + last = current; + current = jsonStr.charAt(i); + switch (current) { + case '"': + if (last != '\\') { + isInQuotationMarks = !isInQuotationMarks; + } + sb.append(current); + break; + case '{': + case '[': + sb.append(current); + if (!isInQuotationMarks) { + sb.append('\n'); + indent++; + addIndentBlank(sb, indent); + } + break; + case '}': + case ']': + if (!isInQuotationMarks) { + sb.append('\n'); + indent--; + addIndentBlank(sb, indent); + } + sb.append(current); + break; + case ',': + sb.append(current); + if (last != '\\' && !isInQuotationMarks) { + sb.append('\n'); + addIndentBlank(sb, indent); + } + break; + case ' ': + if (',' != jsonStr.charAt(i - 1)) { + sb.append(current); + } + break; + case '\\': + sb.append("\\"); + break; + default: + if (!(current == " ".charAt(0))) sb.append(current); + } + } + + return sb.toString(); + } + + private static void addIndentBlank(StringBuilder sb, int indent) { + for (int i = 0; i < indent; i++) { + sb.append(" "); + } + } + + + public static void handleKey(Table table, Condition condition) { + + String keyName = table.getKey(); + String keyValue = ""; + Map keyMap = condition.getConditions().get(keyName); + if (keyMap == null) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Please provide a equal condition for the key field '" + + keyName + + "' in where clause."); + } else { + Set keySet = keyMap.keySet(); + for (ConditionOperator enumOP : keySet) { + if (enumOP != ConditionOperator.eq) { + throw new FrontException(ConstantCode.SQL_ERROR, + "Please provide a equal condition for the key field '" + + keyName + + "' in where clause."); + } else { + keyValue = keyMap.get(enumOP); + } + } + } + table.setKey(keyValue); + } + + public static List> filterSystemColum(List> result) { + + List filteredColumns = Arrays.asList("_id_", "_hash_", "_status_", "_num_"); + List> filteredResult = new ArrayList<>(result.size()); + Map filteredRecords; + for (Map records : result) { + filteredRecords = new LinkedHashMap<>(); + Set recordKeys = records.keySet(); + for (String recordKey : recordKeys) { + if (!filteredColumns.contains(recordKey)) { + filteredRecords.put(recordKey, records.get(recordKey)); + } + } + filteredResult.add(filteredRecords); + } + return filteredResult; + } + + public static List> getSelectedColumn( + List selectColumns, List> result) { + List> selectedResult = new ArrayList<>(result.size()); + Map selectedRecords; + for (Map records : result) { + selectedRecords = new LinkedHashMap<>(); + for (String column : selectColumns) { + Set recordKeys = records.keySet(); + for (String recordKey : recordKeys) { + if (recordKey.equals(column)) { + selectedRecords.put(recordKey, records.get(recordKey)); + } + } + } + selectedResult.add(selectedRecords); + } + selectedResult.forEach(System.out::println); + return selectedResult; + } +} diff --git a/src/main/java/com/webank/webase/front/transaction/TransService.java b/src/main/java/com/webank/webase/front/transaction/TransService.java index f442c48c7..9c99908ea 100644 --- a/src/main/java/com/webank/webase/front/transaction/TransService.java +++ b/src/main/java/com/webank/webase/front/transaction/TransService.java @@ -34,6 +34,7 @@ import com.webank.webase.front.keystore.entity.KeyStoreInfo; import com.webank.webase.front.keystore.entity.RspMessageHashSignature; import com.webank.webase.front.keystore.entity.RspUserInfo; +import com.webank.webase.front.precompiledapi.PrecompiledService; import com.webank.webase.front.transaction.entity.ContractFunction; import com.webank.webase.front.transaction.entity.ReqSignMessageHash; import com.webank.webase.front.transaction.entity.ReqTransHandle; @@ -121,8 +122,8 @@ public class TransService { @Autowired @Qualifier(value = "common") private CryptoSuite cryptoSuite; -// @Autowired -// private PrecompiledService precompiledService; + @Autowired + private PrecompiledService precompiledService; @Autowired private BcosSDK bcosSDK; /** @@ -144,20 +145,20 @@ public Object transHandleWithSign(ReqTransHandleWithSign req) throws FrontExcept List funcParam = req.getFuncParam() == null ? new ArrayList<>() : req.getFuncParam(); String contractAddress = req.getContractAddress(); // handle cns -// if (req.isUseCns()) { -// try { -// List cnsList = precompiledService.queryCnsByNameAndVersion(req.getGroupId(), -// req.getCnsName(), req.getVersion()); -// if (CollectionUtils.isEmpty(cnsList)) { -// throw new FrontException(VERSION_NOT_EXISTS); -// } -// contractAddress = cnsList.iterator().next().getAddress(); -// log.info("transHandleWithSign cns contractAddress:{}", contractAddress); -// } catch (ContractException e) { -// log.error("queryCnsByNameAndVersion ContractException fail:[]", e); -// throw new FrontException(ConstantCode.CNS_QUERY_FAIL); -// } -// } + if (req.isUseCns()) { + try { + List cnsList = precompiledService.queryCnsByNameAndVersion(req.getGroupId(), + req.getCnsName(), req.getVersion()); + if (CollectionUtils.isEmpty(cnsList)) { + throw new FrontException(VERSION_NOT_EXISTS); + } + contractAddress = cnsList.iterator().next().getAddress(); + log.info("transHandleWithSign cns contractAddress:{}", contractAddress); + } catch (ContractException e) { + log.error("queryCnsByNameAndVersion ContractException fail:[]", e); + throw new FrontException(ConstantCode.CNS_QUERY_FAIL); + } + } return this.transHandleWithSign(groupId, signUserId, contractAddress, abiStr, funcName, funcParam); } @@ -476,20 +477,20 @@ public Object transHandleLocal(ReqTransHandle req) { String userAddress = req.getUser(); String contractAddress = req.getContractAddress(); -// if (req.isUseCns()) { -// try { -// List cnsList = precompiledService.queryCnsByNameAndVersion(groupId, -// req.getCnsName(), req.getVersion()); -// if (CollectionUtils.isEmpty(cnsList)) { -// throw new FrontException(VERSION_NOT_EXISTS); -// } -// contractAddress = cnsList.iterator().next().getAddress(); -// log.info("transHandleLocal cns contractAddress:{}", contractAddress); -// } catch (ContractException e) { -// log.error("queryCnsByNameAndVersion ContractException fail:[]", e); -// throw new FrontException(ConstantCode.CNS_QUERY_FAIL); -// } -// } + if (req.isUseCns()) { + try { + List cnsList = precompiledService.queryCnsByNameAndVersion(groupId, + req.getCnsName(), req.getVersion()); + if (CollectionUtils.isEmpty(cnsList)) { + throw new FrontException(VERSION_NOT_EXISTS); + } + contractAddress = cnsList.iterator().next().getAddress(); + log.info("transHandleLocal cns contractAddress:{}", contractAddress); + } catch (ContractException e) { + log.error("queryCnsByNameAndVersion ContractException fail:[]", e); + throw new FrontException(ConstantCode.CNS_QUERY_FAIL); + } + } String encodeFunction = this.encodeFunction2Str(abiStr, funcName, funcParam); @@ -719,14 +720,14 @@ public String createRawTxEncoded(boolean isLocal, String user, boolean isUseCns, String cnsName, String cnsVersion, String funcName, List funcParam) throws Exception { -// if (isUseCns) { -// List cnsList = precompiledService.queryCnsByNameAndVersion(groupId, cnsName, cnsVersion); -// if (CollectionUtils.isEmpty(cnsList)) { -// throw new FrontException(VERSION_NOT_EXISTS); -// } -// contractAddress = cnsList.iterator().next().getAddress(); -// log.info("transHandleWithSign cns contractAddress:{}", contractAddress); -// } + if (isUseCns) { + List cnsList = precompiledService.queryCnsByNameAndVersion(groupId, cnsName, cnsVersion); + if (CollectionUtils.isEmpty(cnsList)) { + throw new FrontException(VERSION_NOT_EXISTS); + } + contractAddress = cnsList.iterator().next().getAddress(); + log.info("transHandleWithSign cns contractAddress:{}", contractAddress); + } // encode function String encodeFunction = this.encodeFunction2Str(JsonUtils.objToString(contractAbi), funcName, funcParam); // check groupId