org.fisco.bcos.web3j.protocol.ObjectMapperFactory Java Examples

The following examples show how to use org.fisco.bcos.web3j.protocol.ObjectMapperFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransService.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * checkAndSaveAbiFromDb.
 *
 * @param req request
 */
public boolean checkAndSaveAbiFromDb(ContractOfTrans req) throws Exception {
    Contract contract = contractRepository.findByGroupIdAndContractPathAndContractName(
            req.getGroupId(), req.getContractPath(), req.getContractName());
    log.info("checkAndSaveAbiFromDb contract:{}", contract);
    if (Objects.isNull(contract)) {
        log.info("checkAndSaveAbiFromDb contract is null");
        return false;
    }
    // save abi
    ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
    List<AbiDefinition> abiDefinitionList =
            objectMapper.readValue(contract.getContractAbi(), objectMapper.getTypeFactory()
                    .constructCollectionType(List.class, AbiDefinition.class));
    ContractAbiUtil.setFunctionFromAbi(req.getContractName(), req.getContractPath(),
            abiDefinitionList, new ArrayList<>());
    return true;
}
 
Example #2
Source File: WalletUtils.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public static String generateWalletFile(
        String password, ECKeyPair ecKeyPair, File destinationDirectory, boolean useFullScrypt)
        throws CipherException, IOException {

    WalletFile walletFile;
    if (useFullScrypt) {
        walletFile = Wallet.createStandard(password, ecKeyPair);
    } else {
        walletFile = Wallet.createLight(password, ecKeyPair);
    }

    String fileName = getWalletFileName(walletFile);
    File destination = new File(destinationDirectory, fileName);

    ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
    objectMapper.writeValue(destination, walletFile);

    return fileName;
}
 
Example #3
Source File: KeyInfo.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/** @author: fisco-dev */
@Override
public int storeKeyInfo(String keyFile) {
    try {
        // Map<String, String> keyMap = new HashMap<String, String>();
        Account key = new Account();
        key.setPrivateKey(getPrivateKey());
        key.setPublicKey(getPublicKey());
        key.setAccount(getAccount());

        String keyJsonInfo = ObjectMapperFactory.getObjectMapper().writeValueAsString(key);
        System.out.println("== SAVED KEY INFO: " + keyJsonInfo);
        return writeFile(keyFile, keyJsonInfo);
    } catch (Exception e) {
        System.out.println(
                "store keyInfo to " + keyFile + " failed, error message: " + e.getMessage());
        logger.error(
                "store keyInfo to " + keyFile + " failed, error message: " + e.getMessage());
        return RetCode.storeKeyInfoFailed;
    }
}
 
Example #4
Source File: CRUDService.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public int update(Table table, Entry entry, Condition condition) throws Exception {

        if (table.getKey().length() > PrecompiledCommon.TABLE_KEY_MAX_LENGTH) {
            throw new PrecompileMessageException(
                    "The value of the table key exceeds the maximum limit("
                            + PrecompiledCommon.TABLE_KEY_MAX_LENGTH
                            + ").");
        }
        String entryJsonStr =
                ObjectMapperFactory.getObjectMapper().writeValueAsString(entry.getFields());
        String conditionStr =
                ObjectMapperFactory.getObjectMapper().writeValueAsString(condition.getConditions());
        TransactionReceipt receipt =
                crud.update(
                                table.getTableName(),
                                table.getKey(),
                                entryJsonStr,
                                conditionStr,
                                table.getOptional())
                        .send();
        return PrecompiledCommon.handleTransactionReceiptForCRUD(receipt);
    }
 
Example #5
Source File: CRUDService.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public int insert(Table table, Entry entry) throws Exception {

        if (table.getKey().length() > PrecompiledCommon.TABLE_KEY_MAX_LENGTH) {
            throw new PrecompileMessageException(
                    "The value of the table key exceeds the maximum limit("
                            + PrecompiledCommon.TABLE_KEY_MAX_LENGTH
                            + ").");
        }
        String entryJsonStr =
                ObjectMapperFactory.getObjectMapper().writeValueAsString(entry.getFields());

        TransactionReceipt receipt =
                crud.insert(table.getTableName(), table.getKey(), entryJsonStr, table.getOptional())
                        .send();
        return PrecompiledCommon.handleTransactionReceiptForCRUD(receipt);
    }
 
Example #6
Source File: ContractAbiUtil.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * @param contractAbi
 * @return
 */
public static List<AbiDefinition> getEventAbiDefinitions(String contractAbi) {

    List<AbiDefinition> result = new ArrayList<>();
    try {
        ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
        AbiDefinition[] abiDefinitions =
                objectMapper.readValue(contractAbi, AbiDefinition[].class);

        for (AbiDefinition abiDefinition : abiDefinitions) {
            if (TYPE_EVENT.equals(abiDefinition.getType())) {
                result.add(abiDefinition);
            }
        }
    } catch (JsonProcessingException e) {
        logger.warn(" invalid json, abi: {}, e: {} ", contractAbi, e);
    }
    return result;
}
 
Example #7
Source File: ContractAbiUtil.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * @param contractAbi
 * @return
 */
public static List<AbiDefinition> getFuncAbiDefinition(String contractAbi) {
    List<AbiDefinition> result = new ArrayList<>();
    try {
        ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
        AbiDefinition[] abiDefinitions =
                objectMapper.readValue(contractAbi, AbiDefinition[].class);

        for (AbiDefinition abiDefinition : abiDefinitions) {
            if (TYPE_FUNCTION.equals(abiDefinition.getType())
                    || TYPE_CONSTRUCTOR.equals(abiDefinition.getType())) {
                result.add(abiDefinition);
            }
        }
    } catch (JsonProcessingException e) {
        logger.warn(" invalid json, abi: {}, e: {} ", contractAbi, e);
    }
    return result;
}
 
Example #8
Source File: ContractAbiUtil.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * @param contractAbi
 * @return
 */
public static AbiDefinition getConstructorAbiDefinition(String contractAbi) {
    try {
        ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
        AbiDefinition[] abiDefinitions =
                objectMapper.readValue(contractAbi, AbiDefinition[].class);

        for (AbiDefinition abiDefinition : abiDefinitions) {
            if (TYPE_CONSTRUCTOR.equals(abiDefinition.getType())) {
                return abiDefinition;
            }
        }
    } catch (JsonProcessingException e) {
        logger.warn(" invalid  json, abi: {}, e: {} ", contractAbi, e);
    }
    return null;
}
 
Example #9
Source File: TransactionDecoder.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * @param logs
 * @return
 * @throws BaseException
 * @throws IOException
 */
public String decodeEventReturnJson(String logs) throws BaseException, IOException {
    // log json trans to list log
    ObjectMapper mapper = ObjectMapperFactory.getObjectMapper();
    CollectionType listType =
            mapper.getTypeFactory().constructCollectionType(ArrayList.class, Log.class);
    @SuppressWarnings("unchecked")
    List<Log> logList = (List<Log>) mapper.readValue(logs, listType);

    // decode event
    Map<String, List<List<EventResultEntity>>> resultEntityMap =
            decodeEventReturnObject(logList);
    String result = mapper.writeValueAsString(resultEntityMap);

    return result;
}
 
Example #10
Source File: TransactionDecoder.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * @param input
 * @return
 * @throws JsonProcessingException
 * @throws TransactionException
 * @throws BaseException
 */
public String decodeInputReturnJson(String input)
        throws JsonProcessingException, TransactionException, BaseException {

    input = addHexPrefixToString(input);

    // select abi
    AbiDefinition abiFunc = selectAbiDefinition(input);

    // decode input
    InputAndOutputResult inputAndOutputResult = decodeInputReturnObject(input);
    // format result to json
    String result =
            ObjectMapperFactory.getObjectMapper().writeValueAsString(inputAndOutputResult);

    return result;
}
 
Example #11
Source File: ConnectionCallback.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public void sendUpdateTopicMessage(ChannelHandlerContext ctx) throws JsonProcessingException {

        Message message = new Message();
        message.setResult(0);
        message.setType((short) ChannelMessageType.AMOP_CLIENT_TOPICS.getType());
        message.setSeq(UUID.randomUUID().toString().replaceAll("-", ""));

        topics.add("_block_notify_" + channelService.getGroupId());

        message.setData(ObjectMapperFactory.getObjectMapper().writeValueAsBytes(topics.toArray()));

        String content = new String(message.getData());

        ByteBuf out = ctx.alloc().buffer();
        message.writeHeader(out);
        message.writeExtra(out);

        ctx.writeAndFlush(out);

        logger.info(
                " send update topic message request, seq: {}, content: {}",
                message.getSeq(),
                content);
    }
 
Example #12
Source File: PrecompiledWithSignService.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * CRUD: update table through webase-sign
 */
public int update(int groupId, String signUserId, Table table,
				  Entry entry, Condition condition) throws Exception {
	checkTableKeyLength(table);
	// trans
	String entryJsonStr =
			ObjectMapperFactory.getObjectMapper().writeValueAsString(entry.getFields());
	String conditionStr =
			ObjectMapperFactory.getObjectMapper().writeValueAsString(condition.getConditions());
	List<Object> funcParams = new ArrayList<>();
	funcParams.add(table.getTableName());
	funcParams.add(table.getKey());
	funcParams.add(entryJsonStr);
	funcParams.add(conditionStr);
	funcParams.add(table.getOptional());
	TransactionReceipt receipt = (TransactionReceipt) transService.transHandleWithSignForPrecompile(groupId,
			signUserId, PrecompiledTypes.CRUD, FUNC_UPDATE, funcParams);
	return PrecompiledCommon.handleTransactionReceiptForCRUD(receipt);
}
 
Example #13
Source File: PrecompiledWithSignService.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * CRUD: remove table through webase-sign
 */
public int remove(int groupId, String signUserId, Table table, Condition condition)
        throws Exception {
    checkTableKeyLength(table);
    // trans
    String conditionStr =
            ObjectMapperFactory.getObjectMapper().writeValueAsString(condition.getConditions());
    List<Object> funcParams = new ArrayList<>();
    funcParams.add(table.getTableName());
    funcParams.add(table.getKey());
    funcParams.add(conditionStr);
    funcParams.add(table.getOptional());
    TransactionReceipt receipt =
            (TransactionReceipt) transService.transHandleWithSignForPrecompile(groupId,
                    signUserId, PrecompiledTypes.CRUD, FUNC_REMOVE, funcParams);
    return PrecompiledCommon.handleTransactionReceiptForCRUD(receipt);
}
 
Example #14
Source File: HeartBeatParser.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public byte[] encode(String value) throws JsonProcessingException {

        byte[] result = null;

        switch (getVersion()) {
            case VERSION_1:
                {
                    result = value.getBytes();
                }
                break;
            default:
                {
                    BcosHeartbeat bcosHeartbeat = new BcosHeartbeat();
                    bcosHeartbeat.setHeartBeat(Integer.parseInt(value));
                    result = ObjectMapperFactory.getObjectMapper().writeValueAsBytes(bcosHeartbeat);
                }
                break;
        }

        return result;
    }
 
Example #15
Source File: HeartBeatParser.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public BcosHeartbeat decode(String data)
        throws JsonParseException, JsonMappingException, IOException {
    BcosHeartbeat bcosHeartbeat = new BcosHeartbeat();

    switch (getVersion()) {
        case VERSION_1:
            {
                bcosHeartbeat.setHeartBeat(Integer.parseInt(data));
            }
            break;
        default:
            {
                bcosHeartbeat =
                        ObjectMapperFactory.getObjectMapper()
                                .readValue(data, BcosHeartbeat.class);
            }
            break;
    }

    return bcosHeartbeat;
}
 
Example #16
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public WebSocketService(
        WebSocketClient webSocketClient,
        ScheduledExecutorService executor,
        boolean includeRawResponses) {
    this.webSocketClient = webSocketClient;
    this.executor = executor;
    this.objectMapper = ObjectMapperFactory.getObjectMapper(includeRawResponses);
}
 
Example #17
Source File: KeyInfo.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * @author: fisco-dev
 * @param keyFile: file that contains the key information
 */
@Override
public int loadKeyInfo(String keyFile) {
    String keyInfoJsonStr = readFile(keyFile);
    if (keyInfoJsonStr == null) {
        System.out.println("load key information failed");
        logger.error("load key information failed");
        return RetCode.openFileFailed;
    }
    System.out.println("");
    System.out.println("===key info:" + keyInfoJsonStr);
    try {
        Account key =
                ObjectMapperFactory.getObjectMapper().readValue(keyInfoJsonStr, Account.class);

        privateKey = key.getPrivateKey();
        publicKey = key.getPublicKey();
        account = key.getAccount();

        System.out.println("");
        System.out.println("====LOADED KEY INFO ===");
        System.out.println("* private key:" + privateKey);
        System.out.println("* public key :" + publicKey);
        System.out.println("* account: " + account);
        return RetCode.success;
    } catch (Exception e) {
        System.out.println(
                "load private key from "
                        + keyFile
                        + " failed, error message:"
                        + e.getMessage());
        return RetCode.loadKeyInfoFailed;
    }
}
 
Example #18
Source File: ContractStatusService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public String listManager(String addr) throws Exception {
    if (!WalletUtils.isValidAddress(addr)) {
        return PrecompiledCommon.transferToJson(PrecompiledCommon.InvalidAddress);
    }

    Tuple2<BigInteger, List<String>> send = contractLifeCycle.listManager(addr).send();

    if (!(send.getValue1().intValue() == PrecompiledCommon.Success)) {
        return PrecompiledCommon.transferToJson(send.getValue1().intValue());
    }

    return ObjectMapperFactory.getObjectMapper().writeValueAsString(send.getValue2());
}
 
Example #19
Source File: ChainGovernanceService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public List<PermissionInfo> listOperators() throws Exception {
    String operatorsInfo = chainGovernance.listOperators().send();
    ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
    return objectMapper.readValue(
            operatorsInfo,
            objectMapper
                    .getTypeFactory()
                    .constructCollectionType(List.class, PermissionInfo.class));
}
 
Example #20
Source File: ChainGovernanceService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public List<PermissionInfo> listCommitteeMembers() throws Exception {
    String committeeMembersInfo = chainGovernance.listCommitteeMembers().send();
    ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
    return objectMapper.readValue(
            committeeMembersInfo,
            objectMapper
                    .getTypeFactory()
                    .constructCollectionType(List.class, PermissionInfo.class));
}
 
Example #21
Source File: PermissionService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public List<PermissionInfo> queryPermission(String address) throws Exception {
    String permissionyInfo = permission.queryPermission(address).send();
    ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
    return objectMapper.readValue(
            permissionyInfo,
            objectMapper
                    .getTypeFactory()
                    .constructCollectionType(List.class, PermissionInfo.class));
}
 
Example #22
Source File: PermissionService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private List<PermissionInfo> list(String tableName) throws Exception {
    String permissionyInfo = permission.queryByName(tableName).send();
    ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
    return objectMapper.readValue(
            permissionyInfo,
            objectMapper
                    .getTypeFactory()
                    .constructCollectionType(List.class, PermissionInfo.class));
}
 
Example #23
Source File: CnsService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public List<CnsInfo> queryCnsByName(String name) throws Exception {
    CNS cns = lookupResolver();
    String cnsInfo = cns.selectByName(name).send();
    ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
    return objectMapper.readValue(
            cnsInfo,
            objectMapper.getTypeFactory().constructCollectionType(List.class, CnsInfo.class));
}
 
Example #24
Source File: CnsService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public List<CnsInfo> queryCnsByNameAndVersion(String name, String version) throws Exception {
    CNS cns = lookupResolver();
    String cnsInfo = cns.selectByNameAndVersion(name, version).send();
    ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
    return objectMapper.readValue(
            cnsInfo,
            objectMapper.getTypeFactory().constructCollectionType(List.class, CnsInfo.class));
}
 
Example #25
Source File: CnsService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private List<CnsInfo> jsonToCNSInfos(String contractAddressInfo) throws IOException {

        ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
        List<CnsInfo> cnsInfo =
                objectMapper.readValue(
                        contractAddressInfo,
                        objectMapper
                                .getTypeFactory()
                                .constructCollectionType(List.class, CnsInfo.class));
        return cnsInfo;
    }
 
Example #26
Source File: CRUDService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public int remove(Table table, Condition condition) throws Exception {

        if (table.getKey().length() > PrecompiledCommon.TABLE_KEY_MAX_LENGTH) {
            throw new PrecompileMessageException(
                    "The value of the table key exceeds the maximum limit("
                            + PrecompiledCommon.TABLE_KEY_MAX_LENGTH
                            + ").");
        }
        String conditionStr =
                ObjectMapperFactory.getObjectMapper().writeValueAsString(condition.getConditions());
        TransactionReceipt receipt =
                crud.remove(table.getTableName(), table.getKey(), conditionStr, table.getOptional())
                        .send();
        return PrecompiledCommon.handleTransactionReceiptForCRUD(receipt);
    }
 
Example #27
Source File: CRUDService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<Map<String, String>> select(Table table, Condition condition) throws Exception {

    if (table.getKey().length() > PrecompiledCommon.TABLE_KEY_MAX_LENGTH) {
        throw new PrecompileMessageException(
                "The value of the table key exceeds the maximum limit("
                        + PrecompiledCommon.TABLE_KEY_MAX_LENGTH
                        + ").");
    }
    ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
    String conditionJsonStr = objectMapper.writeValueAsString(condition.getConditions());
    String resultStr =
            crud.select(
                            table.getTableName(),
                            table.getKey(),
                            conditionJsonStr,
                            table.getOptional())
                    .send();
    List<Map<String, String>> result =
            (List<Map<String, String>>)
                    objectMapper.readValue(
                            resultStr,
                            objectMapper
                                    .getTypeFactory()
                                    .constructCollectionType(List.class, Map.class));
    return result;
}
 
Example #28
Source File: CompilationResult.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@JsonIgnore
public static CompilationResult parse(String rawJson) throws IOException {
    if (rawJson == null || rawJson.isEmpty()) {
        CompilationResult empty = new CompilationResult();
        empty.contracts = Collections.emptyMap();
        empty.version = "";

        return empty;
    } else {
        return ObjectMapperFactory.getObjectMapper()
                .readValue(rawJson, CompilationResult.class);
    }
}
 
Example #29
Source File: Abi.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public String toJson() {
    try {
        return ObjectMapperFactory.getObjectMapper().writeValueAsString(this);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #30
Source File: PrecompiledWithSignService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * CRUD: insert table through webase-sign
 */
public int insert(int groupId, String signUserId, Table table, Entry entry) throws Exception {
	checkTableKeyLength(table);
	// trans
	String entryJsonStr =
			ObjectMapperFactory.getObjectMapper().writeValueAsString(entry.getFields());
	List<Object> funcParams = new ArrayList<>();
	funcParams.add(table.getTableName());
	funcParams.add(table.getKey());
	funcParams.add(entryJsonStr);
	funcParams.add(table.getOptional());
	TransactionReceipt receipt = (TransactionReceipt) transService.transHandleWithSignForPrecompile(groupId,
			signUserId, PrecompiledTypes.CRUD, FUNC_INSERT, funcParams);
	return PrecompiledCommon.handleTransactionReceiptForCRUD(receipt);
}