public MychainClient() {
this.isStart = Boolean.FALSE;
this.logger = LoggerFactory.getLogger(MychainClient.class);
}
public boolean init(ClientEnv env) {
if (!this.isStart && env != null) {
if (env.getLogger() == null) {
return false;
} else {
Throwable e;
try {
if (env.isUseBtn()) {
BtnClient btnClient = env.getBtnClient();
if (btnClient == null) {
BtnOption btnOption = env.getBtnOption();
BtnNetworkOption networkOption = btnOption.getBtnNetworkOption();
networkOption.setSocketAddressList(btnOption.getBtnMasterIpAndPortList(), btnOption.getBtnSlaveIpAndPortList());
ISslOption sslOption = (new SslOption.Builder()).keyFilePath(btnOption.getBtnKeyFilePath()).keyPassword(btnOption.getBtnKeyFilePassword()).certFilePath(btnOption.getBtnCertFilePath()).trustStoreFilePath(btnOption.getBtnTrustStoreFilePath()).trustStorePassword(btnOption.getBtnTrustStoreFilePassword()).build();
NodeRegisterConfig nodeRegisterConfig = btnOption.getNodeRegisterConfig();
NodeGroupRegisterConfig nodeGroupRegisterConfig = btnOption.getNodeGroupRegisterConfig();
btnClient = new BtnClient(networkOption, sslOption, nodeRegisterConfig, nodeGroupRegisterConfig);
RequestOption requestOption = btnOption.getBtnRequestOption();
btnClient.setRequestOption(requestOption);
ChainConfig chainConfig = new ChainConfig();
chainConfig.setChainBid(btnOption.getChainBid());
chainConfig.setChainNids(btnOption.getChainNids());
chainConfig.setDynamicGetChainNodeNums(btnOption.getDynamicGetChainNodeNums());
btnClient.setChainConfig(chainConfig);
env.setBtnClient(btnClient);
}
if (!btnClient.isStarted()) {
boolean startup = btnClient.startup();
if (!startup) {
env.getLogger().error("BtnClient启动失败");
return false;
}
env.getLogger().info("BtnClient启动成功");
} else {
env.getLogger().info("btnClient在外部已经启动,不用再次启动了");
}
if (btnClient.getChainConfig().getChainNids().size() == 0) {
String chainUrl = btnClient.getChainConfig().getPreHeadChainNode(Hex.toHexString(env.getNetworkOption().getChainIdOption().getMyChainId().getData()));
ClientReqChainNodesEntity.ClientReqChainNodes clientReqChainNodes = ClientReqChainNodes.newBuilder().setChainUri(ByteString.copyFrom(chainUrl.getBytes())).setMaxNodes(btnClient.getChainConfig().getDynamicGetChainNodeNums()).build();
env.getLogger().info("请求的查询链节点的参数:chainBid = {}", chainUrl);
Result<ClientReqChainNodesRespEntity.ClientReqChainNodesResp> clientReqChainNodesRespResult = btnClient.clientReqChainNodes(clientReqChainNodes);
if (!clientReqChainNodesRespResult.getErrorCode().isSuccess()) {
env.getLogger().error("从btn server获取链节点id失败");
return false;
}
ClientReqChainNodesRespEntity.ClientReqChainNodesResp clientReqChainNodesResp = (ClientReqChainNodesRespEntity.ClientReqChainNodesResp)clientReqChainNodesRespResult.getData();
env.getLogger().info("响应的查询链节点的参数:chainUrl = {}", new String(clientReqChainNodesResp.getChainUri().toByteArray()));
List<ByteString> nodeListList = clientReqChainNodesResp.getNodeListList();
List<String> totalChainNodeList = new ArrayList();
if (nodeListList == null || nodeListList.isEmpty()) {
env.getLogger().error("没有动态获取到链节点id集合, sdk没有可以连接的链节点,sdk启动失败");
return false;
}
env.getLogger().info("动态获取节点的数量配置:{}, 实际动态获取到的节点的数量: {}", btnClient.getChainConfig().getDynamicGetChainNodeNums(), nodeListList.size());
Iterator var24 = nodeListList.iterator();
while(var24.hasNext()) {
ByteString bytes = (ByteString)var24.next();
totalChainNodeList.add(btnClient.getChainConfig().getChainBid() + "/" + new String(bytes.toByteArray()));
env.getLogger().info("查询到的链节点id = {}", new String(bytes.toByteArray()));
}
btnClient.getChainConfig().setTotalChainNodeIdList(totalChainNodeList);
}
}
if (env.getNeedPrivacy()) {
NativeLibraryLoader.loadFirstAvailable(MychainClient.class.getClassLoader(), new String[]{"PrivacyLib"});
}
this.env = env;
HashFactory.setHashTypeEnum(this.env.getDigestOption().getDefaultDigestType());
this.network = NetworkFactory.getClientNetwork(env.getNetworkOption().getNetworkType());
this.timerTaskManager = new TimerTaskManager();
this.timerTaskManager.startTimerTask();
boolean result = this.network.startup(this.env.getNetworkOption(), this.env.getSslOption(), this.timerTaskManager, this.env.getLogger(), this.env);
if (!result) {
if (this.network != null) {
this.network.shutDown();
}
if (this.timerTaskManager != null) {
this.timerTaskManager.shutdown();
}
return false;
}
if (env.getMetricsOption().isEnableMetrics()) {
MetricsTask metricsTask = new MetricsTask(env.getMetricsOption().getInterval(), TaskType.ALWAYS, env.getLogger());
this.timerTaskManager.registerTask(metricsTask, TimerTaskType.METRICS_TASK);
}
this.serviceManager = new ServiceManager(this.network, this.timerTaskManager, this.env);
this.serviceManager.startServices(this);
} catch (Throwable var12) {
e = var12;
env.getLogger().error("init caught exception, cause: {}\n{}", e.getMessage(), ExceptionUtils.getStackTrace(e));
return false;
}
if (env.getRequestOption().getRequestAnchorOption() != null && env.getRequestOption().getRequestAnchorOption().getEnableAnchorData()) {
QueryAnchorDataTask queryAnchorDataTask = new QueryAnchorDataTask(this.network, env.getRequestOption().getRequestAnchorOption().getQueryAnchorIntervalMs(), env.getRequestOption().getQueryReceiptTimeoutMs(), env.getLogger());
queryAnchorDataTask.setNextTime(queryAnchorDataTask.getNextTime() + (long)queryAnchorDataTask.getInterval());
queryAnchorDataTask.run();
this.timerTaskManager.registerTask(queryAnchorDataTask, TimerTaskType.ANCHOR_TASK);
}
this.isStart = true;
try {
if (env.isLoadZkLib()) {
NativeLibraryLoader.loadFirstAvailable(MychainClient.class.getClassLoader(), new String[]{"zk_lib"});
}
} catch (Throwable var11) {
e = var11;
env.getLogger().error("init zk snark library error:{}", e.getMessage(), e);
}
env.getLogger().info("mychainClient启动成功");
return true;
}
} else {
return false;
}
}
public boolean shutDown() {
if (!this.isStart) {
return false;
} else {
int errorFlag = 0;
List<Exception> exceptions = new ArrayList();
boolean result;
Exception e;
if (this.serviceManager != null) {
try {
result = this.serviceManager.stopServices();
if (!result) {
this.logger.error("【MychainClient】serviceManager stopServices failed");
++errorFlag;
}
} catch (Exception var14) {
e = var14;
this.logger.error("【MychainClient】serviceManager stopServices error", e);
exceptions.add(e);
++errorFlag;
}
}
if (this.network != null) {
try {
result = this.network.shutDown();
if (!result) {
this.logger.error("【MychainClient】network shutDown failed");
++errorFlag;
}
} catch (Exception var13) {
e = var13;
this.logger.error("【MychainClient】network shutDown error", e);
exceptions.add(e);
++errorFlag;
}
}
if (this.timerTaskManager != null) {
try {
this.timerTaskManager.shutdown();
} catch (Exception var12) {
e = var12;
this.logger.error("【MychainClient】timerTaskManager shutdown error", e);
exceptions.add(e);
++errorFlag;
}
}
if (this.env != null && this.env.isUseBtn()) {
try {
result = this.env.getBtnClient().shutDown();
if (!result) {
this.logger.error("【MychainClient】btn shutdown failed");
++errorFlag;
}
} catch (Exception var11) {
e = var11;
this.logger.error("【MychainClient】btn shutdown error", e);
exceptions.add(e);
++errorFlag;
}
}
if (errorFlag == 0) {
this.isStart = false;
return true;
} else if (exceptions.size() <= 0) {
return false;
} else {
StringBuilder stringBuilder = new StringBuilder();
Iterator var5 = exceptions.iterator();
while(var5.hasNext()) {
Exception exception = (Exception)var5.next();
stringBuilder.append("\t").append(exception.getMessage()).append("\n");
StackTraceElement[] var7 = exception.getStackTrace();
int var8 = var7.length;
for(int var9 = 0; var9 < var8; ++var9) {
StackTraceElement stackTraceElement = var7[var9];
stringBuilder.append("\t\t").append(stackTraceElement.toString()).append("\n");
}
stringBuilder.append("\n");
}
throw new MychainSdkException(ErrorCode.SDK_SHUTDOWN_FAILED, stringBuilder.toString());
}
}
}
public AccountService getAccountService() {
return this.serviceManager.getAccountService();
}
public ContractService getContractService() {
return this.serviceManager.getContractService();
}
public QueryService getQueryService() {
return this.serviceManager.getQueryService();
}
public AdminService getAdminService() {
return this.serviceManager.getAdminService();
}
public EventService getEventService() {
return this.serviceManager.getEventService();
}
public ConfidentialService getConfidentialService() {
return this.serviceManager.getConfidentialService();
}
public EnvelopeService getEnvelopeService() {
return this.serviceManager.getEnvelopeService();
}
public SpvService getSPVService() {
return this.serviceManager.getSPVService();
}
public DetectService getDetectService() {
return this.serviceManager.getDetectService();
}
public ClientEnv getMychainClientEnv() {
return this.env;
}
public ServiceManager getServiceManager() {
return this.serviceManager;
}
public INetwork getNetwork() {
return this.network;
}
public TimerTaskManager getTimerTaskManager() {
return this.timerTaskManager;
}
}
直接跳到 boolean result = this.network.startup(this.env.getNetworkOption(), this.env.getSslOption(), this.timerTaskManager, this.env.getLogger(), this.env);
if (!result) {
if (this.network != null) {
this.network.shutDown();
}
code
if (this.timerTaskManager != null) {
this.timerTaskManager.shutdown();
}
return false;
}这里是什么意思?怎么解决?
Assistant
The section of code you are referring to is part of the init method within the MychainClient class. Let's break down its purpose and what it's doing:
Purpose:
The code is initializing the network component of the MychainClient. If the network startup fails, it performs clean-up operations by shutting down the network and the timer task manager to ensure that the client is left in a consistent state.
Code Explanation:
Network Startup:
java
boolean result = this.network.startup(this.env.getNetworkOption(), this.env.getSslOption(), this.timerTaskManager, this.env.getLogger(), this.env);
This line attempts to start the network component.
It uses the configuration options obtained from the env object (networkOption, sslOption, etc.) to initialize the network.
timerTaskManager and logger are also handed over to the network to manage time-related tasks and logging, respectively.
The result variable indicates whether the startup was successful or not.
Error Handling on Startup Failure:
java
if (!result) {
if (this.network != null) {
this.network.shutDown();
}
if (this.timerTaskManager != null) {
this.timerTaskManager.shutdown();
}
return false;
}
If result is false, the network initialization has failed.
The block checks if network and timerTaskManager are non-null and calls their shutdown methods to clean any resources.
Finally, it returns false indicating the init method failed to complete successfully.
How to Address Issues:
If you're encountering an issue where this block is not executing as expected, you'll need to perform the following checks:
Ensure Correct Configurations:
Verify that the configurations in ClientEnv for network and SSL options are correct and complete.
com.alipay.mychain.sdk.api.logging.AbstractLoggerFactory - Using SLF4J as the default logging framework
21:32:10.621 [main] DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
21:32:10.621 [main] DEBUG io.netty.channel.MultithreadEventLoopGroup - -Dio.netty.eventLoopThreads: 32
21:32:10.636 [main] DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.noKeySetOptimization: false
21:32:10.636 [main] DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.selectorAutoRebuildThreshold: 512
21:32:10.643 [main] DEBUG io.netty.util.internal.PlatformDependent - Platform: Windows
21:32:10.643 [main] DEBUG io.netty.util.internal.PlatformDependent0 - -Dio.netty.noUnsafe: false
21:32:10.643 [main] DEBUG io.netty.util.internal.PlatformDependent0 - Java version: 23
21:32:10.645 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available
21:32:10.645 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available
21:32:10.645 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available
21:32:10.648 [main] DEBUG io.netty.util.internal.PlatformDependent0 - direct buffer constructor: unavailable
java.lang.NoSuchMethodException: java.nio.DirectByteBuffer.(long,int)
at java.base/java.lang.Class.getConstructor0(Class.java:3833)
at java.base/java.lang.Class.getDeclaredConstructor(Class.java:3004)
at io.netty.util.internal.PlatformDependent0$4.run(PlatformDependent0.java:223)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:319)
at io.netty.util.internal.PlatformDependent0.(PlatformDependent0.java:218)
at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:208)
at io.netty.util.internal.PlatformDependent.(PlatformDependent.java:79)
at io.netty.channel.nio.NioEventLoop.newTaskQueue(NioEventLoop.java:252)
at io.netty.util.concurrent.SingleThreadEventExecutor.(SingleThreadEventExecutor.java:165)
at io.netty.channel.SingleThreadEventLoop.(SingleThreadEventLoop.java:58)
at io.netty.channel.nio.NioEventLoop.(NioEventLoop.java:135)
at io.netty.channel.nio.NioEventLoopGroup.newChild(NioEventLoopGroup.java:127)
at io.netty.channel.nio.NioEventLoopGroup.newChild(NioEventLoopGroup.java:36)
at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:84)
at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:58)
at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:47)
at io.netty.channel.MultithreadEventLoopGroup.(MultithreadEventLoopGroup.java:59)
at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:77)
at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:72)
at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:59)
at com.alipay.mychain.sdk.network.netty.AbstractClientTransport.init(AbstractClientTransport.java:50)
at com.alipay.mychain.sdk.network.netty.AbstractClientTransport.(AbstractClientTransport.java:46)
at com.alipay.mychain.sdk.network.netty.TcpClientTransport.(TcpClientTransport.java:23)
at com.alipay.mychain.sdk.network.netty.TcpChannel.init(TcpChannel.java:18)
at com.alipay.mychain.sdk.network.NetworkConnection.(NetworkConnection.java:95)
at com.alipay.mychain.sdk.network.ConnectionPoolManager.startUp(ConnectionPoolManager.java:145)
at com.alipay.mychain.sdk.network.ClientNetwork.startup(ClientNetwork.java:77)
at com.alipay.mychain.sdk.api.MychainClient.init(MychainClient.java:155)
at org.example.Deposit.initSdk(Deposit.java:163)
at org.example.Deposit.main(Deposit.java:90)怎么解决?
Assistant
从你提供的日志和异常信息来看,问题的核心是在尝试通过 Netty 创建直接字节缓冲区时,出现了一个 NoSuchMethodException,表示找不到相应的构造方法。这通常可能是因为 Java 版本的不兼容或 API 变化导致的。
如上配置没有问题,但是需要特别注意动态库和 JAR 文件路径的正确设置及在运行时的加载。这种方式要求你手动处理本地库配置,如果可行,建议考虑使用一些工具库如 JavaCPP 已封装的 OpenCV,这些库会自动处理依赖关系和平台特定的动态库问题。
User
java.lang.UnsupportedOperationException: Reflective setAccessible(true) disabled
at io.netty.util.internal.ReflectionUtil.trySetAccessible(ReflectionUtil.java:31)
at io.netty.util.internal.PlatformDependent05.run(PlatformDependent0.java:273)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:318)
at io.netty.util.internal.PlatformDependent0.(PlatformDependent0.java:266)
at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:208)
at io.netty.util.internal.PlatformDependent.(PlatformDependent.java:79)
at io.netty.channel.nio.NioEventLoop.newTaskQueue(NioEventLoop.java:252)
at io.netty.util.concurrent.SingleThreadEventExecutor.(SingleThreadEventExecutor.java:165)
at io.netty.channel.SingleThreadEventLoop.(SingleThreadEventLoop.java:58)
at io.netty.channel.nio.NioEventLoop.(NioEventLoop.java:135)
at io.netty.channel.nio.NioEventLoopGroup.newChild(NioEventLoopGroup.java:127)
at io.netty.channel.nio.NioEventLoopGroup.newChild(NioEventLoopGroup.java:36)
at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:84)
at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:58)
at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:47)
at io.netty.channel.MultithreadEventLoopGroup.(MultithreadEventLoopGroup.java:59)
at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:77)
at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:72)
at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:59)
at com.alipay.mychain.sdk.network.netty.AbstractClientTransport.init(AbstractClientTransport.java:53)
at com.alipay.mychain.sdk.network.netty.AbstractClientTransport.(AbstractClientTransport.java:49)
at com.alipay.mychain.sdk.network.netty.TcpClientTransport.(TcpClientTransport.java:23)
at com.alipay.mychain.sdk.network.netty.TcpChannel.init(TcpChannel.java:18)
at com.alipay.mychain.sdk.network.NetworkConnection.(NetworkConnection.java:80)
at com.alipay.mychain.sdk.network.ClientNetwork.startup(ClientNetwork.java:60)
at com.alipay.mychain.sdk.api.MychainClient.init(MychainClient.java:60)
at org.example.Deposit.initSdk(Deposit.java:162)
at org.example.Deposit.main(Deposit.java:89)
22:18:10.029 [main] DEBUG io.netty.util.internal.PlatformDependent0 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable
java.lang.IllegalAccessException: class io.netty.util.internal.PlatformDependent06.run(PlatformDependent0.java:315)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:318)
at io.netty.util.internal.PlatformDependent0.(PlatformDependent0.java:306)
at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:208)
at io.netty.util.internal.PlatformDependent.(PlatformDependent.java:79)
at io.netty.channel.nio.NioEventLoop.newTaskQueue(NioEventLoop.java:252)
at io.netty.util.concurrent.SingleThreadEventExecutor.(SingleThreadEventExecutor.java:165)
at io.netty.channel.SingleThreadEventLoop.(SingleThreadEventLoop.java:58)
at io.netty.channel.nio.NioEventLoop.(NioEventLoop.java:135)
at io.netty.channel.nio.NioEventLoopGroup.newChild(NioEventLoopGroup.java:127)
at io.netty.channel.nio.NioEventLoopGroup.newChild(NioEventLoopGroup.java:36)
at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:84)
at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:58)
at io.netty.util.concurrent.MultithreadEventExecutorGroup.(MultithreadEventExecutorGroup.java:47)
at io.netty.channel.MultithreadEventLoopGroup.(MultithreadEventLoopGroup.java:59)
at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:77)
at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:72)
at io.netty.channel.nio.NioEventLoopGroup.(NioEventLoopGroup.java:59)
at com.alipay.mychain.sdk.network.netty.AbstractClientTransport.init(AbstractClientTransport.java:53)
at com.alipay.mychain.sdk.network.netty.AbstractClientTransport.(AbstractClientTransport.java:49)
at com.alipay.mychain.sdk.network.netty.TcpClientTransport.(TcpClientTransport.java:23)
at com.alipay.mychain.sdk.network.netty.TcpChannel.init(TcpChannel.java:18)
at com.alipay.mychain.sdk.network.NetworkConnection.(NetworkConnection.java:80)
at com.alipay.mychain.sdk.network.ClientNetwork.startup(ClientNetwork.java:60)
at com.alipay.mychain.sdk.api.MychainClient.init(MychainClient.java:60)
at org.example.Deposit.initSdk(Deposit.java:162)
at org.example.Deposit.main(Deposit.java:89)
22:18:10.030 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.DirectByteBuffer.(long, int): unavailable 为什么jdk17出现这个问题?
Ensure that the environment in which you are running the client has the necessary network access and permissions.
Review Log Output:
Use the provided logger to capture detailed logs before and after the startup call to understand what went wrong. Look for errors or exceptions logged during startup.
Debugging:
Consider debugging the this.network.startup method to step through and observe where it fails.
Network Dependencies:
Double-check that all dependencies, such as native libraries for cryptographic or network operations, are available and properly loaded.
Exception Handling:
Investigate whether additional exception handling should be added around the network startup to capture more specific error details.
If further analysis is needed, more specific diagnostic information from the logs should point out what part of initialization is failing, and you can focus on that area to resolve the issue.