gpt4 book ai didi

java - 重构/优化 Java 代码以获取 HostNameVerifier

转载 作者:行者123 更新时间:2023-11-30 02:33:48 26 4
gpt4 key购买 nike

我有下面的java类,它检查instance是否不为空并且匹配dev/qa/stg/staging/prodhostnameVerificationtrue,然后 getHostnameVerifierForInstance 返回自定义的 主机名 validator

public class SSLConfig {
private static final String PROD_INSTANCE = "Prod";
private static final String STG_INSTANCE1 = "Staging";
private static final String STG_INSTANCE2 = "Stg";
private static final String QA_INSTANCE = "QA";
private static final String DEV_INSTANCE = "DEV";

private static HostnameVerifier getHostnameVerifierForInstance(String instance, String hostnameVerification) {
LOGGER.info("HostnameVerifier For Instance = {}, hostnameVerification = {}",instance,hostnameVerification);
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
if(StringUtils.isNotBlank(instance)) {
if ((instance.trim().toLowerCase().startsWith(PROD_INSTANCE.toLowerCase()) || instance.trim().toLowerCase().startsWith(STG_INSTANCE1.toLowerCase()) || instance.trim().toLowerCase().startsWith(STG_INSTANCE2.toLowerCase()) || instance.trim().toLowerCase().startsWith(QA_INSTANCE.toLowerCase()) || instance.trim().toLowerCase().startsWith(DEV_INSTANCE.toLowerCase())) && StringUtils.isNotBlank(hostnameVerification) && hostnameVerification.trim().toLowerCase().equalsIgnoreCase("true")) {
hostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
DefaultHostnameVerifier verifier = new DefaultHostnameVerifier();
return verifier.verify(hostname, session);
}
};
}
}
return hostnameVerifier;
}
}

我想知道这个方法可以重构/改进为更好的版本吗?

最佳答案

重构后的代码应该是这样的:

public class SSLConfig {
private static final String PROD_INSTANCE = "Prod";
private static final String STG_INSTANCE1 = "Staging";
private static final String STG_INSTANCE2 = "Stg";
private static final String QA_INSTANCE = "QA";
private static final String DEV_INSTANCE = "DEV";

private static HostnameVerifier getHostnameVerifierForInstance(String instance,
String enabled){
return Boolean.parseBoolean(enabled)&&reject(instance) ? denyAll()
: permitAll();
}

private static boolean reject(String instance) {
return rejections().anyMatch(instance.trim().toLowerCase()::startsWith);
}

private static Stream<String> rejections() {
return Stream.of(PROD_INSTANCE, STG_INSTANCE1,
STG_INSTANCE2, QA_INSTANCE, DEV_INSTANCE).map(String::toLowerCase);
}

private static HostnameVerifier denyAll() {
return (hostname, session) -> false;
}

private static HostnameVerifier permitAll() {
return (hostname, session) -> true;
}
}

关于java - 重构/优化 Java 代码以获取 HostNameVerifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43644054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com