Skip to content

Commit

Permalink
Merge pull request #137 from WeBankFinTech/feature/dev-abandon-xmls
Browse files Browse the repository at this point in the history
Invalidate Spring based context.xml to use external properties file
  • Loading branch information
junqizhang-dev committed Jun 5, 2019
2 parents 1893187 + 3b63a64 commit 2d844f5
Show file tree
Hide file tree
Showing 19 changed files with 419 additions and 206 deletions.
6 changes: 3 additions & 3 deletions build-tools/bin/setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ java_source_code_dir=$2
temp_file=$(date +%s)".temp"
config_file=${java_source_code_dir}/dist/bin/run.config
app_xml_config_dir=${java_source_code_dir}/dist/conf/
app_xml_config_tpl=${java_source_code_dir}/src/main/resources/applicationContext.xml.tpl
app_xml_config=${java_source_code_dir}/src/main/resources/applicationContext.xml
app_xml_config_tpl=${java_source_code_dir}/src/main/resources/fisco.properties.tpl
app_xml_config=${java_source_code_dir}/src/main/resources/fisco.properties

CLASSPATH=${java_source_code_dir}/dist/conf

Expand Down Expand Up @@ -122,7 +122,7 @@ function gradle_build_sdk()
if [ ! -z ${content} ];then
content="${content}\n"
fi
content="${content}<value>WeIdentity@$var</value>"
content="${content}WeIdentity@$var;"
done
export BLOCKCHIAN_NODE_INFO=$(echo -e ${content})
export WEID_ADDRESS="0x0"
Expand Down
2 changes: 0 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ 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-jdbc:$spring_version",
"org.springframework:spring-test:$spring_version"
]

Expand Down
10 changes: 6 additions & 4 deletions ci/script/build-ci.sh
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#!/bin/bash
java_source_code_dir=$(pwd)

app_xml_config=${java_source_code_dir}/src/main/resources/applicationContext.xml
app_xml_config_tpl=${java_source_code_dir}/src/main/resources/applicationContext.xml.tpl

app_xml_config_tpl=${java_source_code_dir}/src/main/resources/fisco.properties.tpl
app_xml_config=${java_source_code_dir}/src/main/resources/fisco.properties

function modify_config()
{
Expand All @@ -22,6 +21,9 @@ function modify_config()
envsubst ${MYVARS} < ${app_xml_config_tpl} >${app_xml_config}
cp ${app_xml_config} ${java_source_code_dir}/src/test/resources/
cp ${java_source_code_dir}/src/main/resources/weidentity.properties ${java_source_code_dir}/src/test/resources/
if [ -e ${java_source_code_dir}/privateKey.txt ];then
cp ${java_source_code_dir}/privateKey.txt ${java_source_code_dir}/src/test/resources/
fi
#cat $app_xml_config
echo "modify sdk config finished..."
}
Expand All @@ -31,7 +33,7 @@ function gradle_build_sdk()
{
#run gradle build

content="<value>WeIdentity@$NODE_IP</value>"
content="WeIdentity@$NODE_IP"
export BLOCKCHIAN_NODE_INFO=${content}
export WEID_ADDRESS="0x0"
export CPT_ADDRESS="0x0"
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/com/webank/weid/config/ContractConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,12 @@

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
* contract address config.
*
* @author tonychen 2018.9.29
*/
@Component("ContractConfig")
@Data
public class ContractConfig {

Expand Down
150 changes: 150 additions & 0 deletions src/main/java/com/webank/weid/config/FiscoConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package com.webank.weid.config;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;

/**
* FISCO-BCOS Config that loaded by java process, not Spring applicationContext anymore.
*
* @author chaoxinhu
* @since 2019.6
*/
@Data
@PropertySource(value = "classpath:fisco.properties")
public class FiscoConfig {

private static final Logger logger = LoggerFactory.getLogger(FiscoConfig.class);

// Note that all keys are appended with a colon ":" to support regex auto-loading

@Value("${bcos.version:}")
private String version;

@Value("${orgid:}")
private String orgId;

@Value("${nodes:}")
private String nodes;

@Value("${weId.contractaddress:}")
private String weIdAddress;

@Value("${cpt.contractaddress:}")
private String cptAddress;

@Value("${issuer.contractaddress:}")
private String issuerAddress;

@Value("${evidence.contractaddress:}")
private String evidenceAddress;

@Value("${specificissuer.contractaddress:}")
private String specificIssuerAddress;

@Value("${web3sdk.timeout:10000}")
private String web3sdkTimeout;

@Value("${web3sdk.core-pool-size:100}")
private String web3sdkCorePoolSize;

@Value("${web3sdk.max-pool-size:200}")
private String web3sdkMaxPoolSize;

@Value("${web3sdk.queue-capacity:1000}")
private String web3sdkQueueSize;

@Value("${web3sdk.keep-alive-seconds:60}")
private String web3sdkKeepAliveSeconds;

@Value("${v1.ca-crt-path:ca.crt}")
private String v1CaCrtPath;

@Value("${v1.client-crt-password:123456}")
private String v1ClientCrtPassword;

@Value("${v1.client-key-store-path:client.keystore}")
private String v1ClientKeyStorePath;

@Value("${v1.key-store-password:123456}")
private String v1KeyStorePassword;

@Value("${v2.ca-crt-path:./v2/ca.crt}")
private String v2CaCrtPath;

@Value("${v2.node-crt-path:./v2/node.crt}")
private String v2NodeCrtPath;

@Value("${v2.node-key-path:./v2/node.key}")
private String v2NodeKeyPath;

/**
* load configuration without Spring context required.
*
* @return true if success, else false
*/
public boolean load() {
if (!FiscoConfig.class.isAnnotationPresent(PropertySource.class)) {
logger.error("set configuration file name use @PropertySource");
return false;
}

PropertySource propertySource = FiscoConfig.class.getAnnotation(PropertySource.class);
String[] files = propertySource.value();
if (!files[0].startsWith("classpath:")) {
logger.error("configuration file must be in classpath");
return false;
}
logger.info("load properties from file: {}", files[0]);

// be careful of the path
String file = "/" + files[0].replace("classpath:", "");
try (InputStream inputStream = FiscoConfig.class.getResourceAsStream(file)) {
Properties properties = new Properties();
properties.load(inputStream);

Field[] fields = FiscoConfig.class.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Value.class)) {
Value value = field.getAnnotation(Value.class);

//String.split can not support this regex
Pattern pattern = Pattern.compile("\\$\\{(\\S+):(\\S*)}");
Matcher matcher = pattern.matcher(value.value());
String k = "";
String v = "";
if (matcher.find()) {
if (matcher.groupCount() >= 1) {

k = matcher.group(1);
}
if (matcher.groupCount() >= 2) {
v = matcher.group(2);
}
}

if (properties.containsKey(k)) {
v = properties.getProperty(k);
}
field.setAccessible(true);
Object obj = field.getType().getConstructor(String.class).newInstance(v);
field.set(this, obj);
}
}
} catch (Exception e) {
logger.error("load properties failed", e);
return false;
}

logger.info("read from fisco.properties: {}", this);
return true;
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/webank/weid/constant/WeIdConstant.java
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public final class WeIdConstant {
* The Constant pipeline character.
*/
public static final String PIPELINE = "|";

/**
* The Constant separator character.
*/
Expand Down
40 changes: 28 additions & 12 deletions src/main/java/com/webank/weid/contract/deploy/DeployContract.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@

import org.apache.commons.lang3.StringUtils;
import org.bcos.channel.client.Service;
import org.bcos.contract.tools.ToolConf;
import org.bcos.web3j.abi.datatypes.Address;
import org.bcos.web3j.crypto.Credentials;
import org.bcos.web3j.crypto.GenCredential;
Expand All @@ -42,9 +41,8 @@
import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.webank.weid.config.FiscoConfig;
import com.webank.weid.constant.WeIdConstant;
import com.webank.weid.contract.AuthorityIssuerController;
import com.webank.weid.contract.AuthorityIssuerData;
Expand All @@ -57,6 +55,8 @@
import com.webank.weid.contract.SpecificIssuerController;
import com.webank.weid.contract.SpecificIssuerData;
import com.webank.weid.contract.WeIdContract;
import com.webank.weid.exception.InitWeb3jException;
import com.webank.weid.util.TransactionUtils;
import com.webank.weid.util.WeIdUtils;

/**
Expand All @@ -77,9 +77,9 @@ public class DeployContract {
private static final Integer DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS = 15;

/**
* The context.
* The Fisco Config bundle.
*/
protected static final ApplicationContext context;
protected static final FiscoConfig fiscoConfig;

/**
* The credentials.
Expand All @@ -92,7 +92,11 @@ public class DeployContract {
private static Web3j web3j;

static {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
fiscoConfig = new FiscoConfig();
if (!fiscoConfig.load()) {
logger.error("[BaseService] Failed to load Fisco-BCOS blockchain node information.");
}
loadConfig();
}

/**
Expand All @@ -112,12 +116,17 @@ public static void main(String[] args) {
* @return true, if successful
*/
private static boolean loadConfig() {
return (initWeb3j() && initCredentials());
}

Service service = context.getBean(Service.class);
private static boolean initWeb3j() {
logger.info("[BaseService] begin to init web3j instance..");
Service service = TransactionUtils.buildFiscoBcosService(fiscoConfig);
try {
service.run();
} catch (Exception e) {
logger.error("[BaseService] Service init failed. ", e);
throw new InitWeb3jException(e);
}

ChannelEthereumService channelEthereumService = new ChannelEthereumService();
Expand All @@ -127,17 +136,24 @@ private static boolean loadConfig() {
logger.error("[BaseService] web3j init failed. ");
return false;
}
return true;
}

ToolConf toolConf = context.getBean(ToolConf.class);

logger.info("begin init credentials");
credentials = GenCredential.create(toolConf.getPrivKey());
/**
* Inits the credentials.
*
* @return true, if successful
*/
private static boolean initCredentials() {
logger.info("[BaseService] begin to init credentials..");
credentials = GenCredential.create();

if (credentials == null) {
logger.error("[BaseService] credentials init failed. ");
return false;
}

String privateKey = credentials.getEcKeyPair().getPrivateKey().toString();
writeAddressToFile(privateKey, "privateKey.txt");
return true;
}

Expand Down

0 comments on commit 2d844f5

Please sign in to comment.