6 Commits

Author SHA1 Message Date
fengjunfeng
6f5b42cc73 修改数据返回结构 2022-01-27 16:06:20 +08:00
fengjunfeng
5bf71b65b3 误删代码 2022-01-27 13:47:54 +08:00
fengjunfeng
2b21e289d9 Merge remote-tracking branch 'origin/master' into develop_22.02 2022-01-27 11:04:38 +08:00
fengjunfeng
d05bc18690 Merge remote-tracking branch 'origin/master' into develop_22.02
# Conflicts:
#	src/main/java/com/license/bean/Rets.java
#	src/main/java/com/license/controller/LicenseController.java
2022-01-26 09:26:46 +08:00
fengjunfeng
5cd51759d8 服务来源有效认证 2022-01-24 10:39:27 +08:00
fengjunfeng
f21a67fc7e 目录修改 2022-01-21 16:20:07 +08:00
9 changed files with 383 additions and 21 deletions

15
pom.xml
View File

@@ -59,6 +59,21 @@
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.4.1</version>
</dependency>
</dependencies>
<build>

View File

@@ -19,5 +19,7 @@ public class LicenseInfo {
// 1 获取指纹 2 更新license 3 获取license信息 4 验证license信息
private Integer type;
//提供服务标识
private String serverId;
}

View File

@@ -1,5 +1,6 @@
package com.license.bean;
public class Rets {
public static Ret success(Object data) {

View File

@@ -0,0 +1,53 @@
package com.license.cache;
import org.springframework.stereotype.Component;
import java.util.HashMap;
/**
* @author fengjunfeng
* @date 2022/1/20
* @time 10:24
* @description
**/
@Component
public class CacheManager {
/**
*/
private static HashMap<String, String> map = new HashMap<>();
// /**
// * 保存时间
// */
// private static int liveTime = 60;
/**
* 信息缓存
* @param key
* @param v
* @return
*/
public static boolean addCache(String key,String v){
map.put(key,v);
return true;
}
/**
* 缓存信息
* @param key
* @return
*/
public static boolean delCache(String key){
map.remove(key);
return true;
}
/**
* @param key
* @return
*/
public static String getCache(String key){
return map.get(key);
}
}

View File

@@ -0,0 +1,121 @@
package com.license.config;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
*
* @author fengjunfeng
* @date 2022/1/20
* @time 11:12
* @description
*
**/
@Configuration
public class RestTemplateConfig {
@Value("${http.maxTotal}")
private String maxTotal;
@Value("${http.defaultMaxPerRoute}")
private String defaultMaxPerRoute;
@Value("${http.connectTimeout}")
private String connectTimeout;
@Value("${http.connectionRequestTimeout}")
private String connectionRequestTimeout;
@Value("${http.socketTimeout}")
private String socketTimeout;
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
//重新设置StringHttpMessageConverter字符集为UTF-8解决中文乱码问题
HttpMessageConverter<?> converterTarget = null;
for (HttpMessageConverter<?> item : converterList) {
if (StringHttpMessageConverter.class == item.getClass()) {
converterTarget = item;
break;
}
}
if (null != converterTarget) {
converterList.remove(converterTarget);
}
converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
/**
* restTemplate 异常处理类 , 解决返回不了除了200之外的状态码
*/
ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
return true;
}
@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
}
};
restTemplate.setErrorHandler(responseErrorHandler);
return restTemplate;
}
@Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
@Bean
public HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(Integer.valueOf(this.maxTotal));
connectionManager.setDefaultMaxPerRoute(Integer.valueOf(this.defaultMaxPerRoute));
RequestConfig requestConfig = RequestConfig.custom()
//服务器返回数据(response)的时间超过抛出read timeout
.setSocketTimeout(Integer.valueOf(this.socketTimeout))
//连接上服务器(握手成功)的时间超出抛出connect timeout
.setConnectTimeout(Integer.valueOf(this.connectTimeout))
//从连接池中获取连接的超时时间超时间未拿到可用连接会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
.setConnectionRequestTimeout(Integer.valueOf(this.connectionRequestTimeout))
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.setConnectionManagerShared(true)
.build();
}
}

View File

@@ -1,12 +1,26 @@
package com.license.controller;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.license.bean.LicenseInfo;
import com.license.bean.Rets;
import com.license.cache.CacheManager;
import com.license.utils.Constant;
import com.license.utils.GetIpProtUtil;
import com.license.utils.HaspUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
/**
* @author fengjunfeng
@@ -17,8 +31,10 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class LicenseController {
private static final Log log = Log.get();
@Autowired
public RestTemplate restTemplate;
@Value("${bifang-api.server.port}")
private String port;
/**
* license锁信息交互
*
@@ -26,22 +42,64 @@ public class LicenseController {
*/
@PostMapping("/licenseOperation")
public Object licenseOperation(@RequestBody LicenseInfo licenseInfo) {
if (!verify(licenseInfo.getServerId())){
return Rets.failure("");
}
if (licenseInfo.getType().equals(Constant.LICENSE_C2V)){
//获取C2V信息
return HaspUtil.readC2V(licenseInfo.getVendorCode(),licenseInfo.getFeatureId());
return Rets.success(HaspUtil.readC2V(licenseInfo.getVendorCode(),licenseInfo.getFeatureId()));
}else if (licenseInfo.getType().equals(Constant.LICENSE_UPDATE)){
//上传license信息
return HaspUtil.updateKeyWithLicense(licenseInfo.getV2C());
return Rets.success(HaspUtil.updateKeyWithLicense(licenseInfo.getV2C()));
}else if (licenseInfo.getType().equals(Constant.LICENSE_QUERY)){
//获取license信息
return HaspUtil.getLicenseInfo(licenseInfo.getVendorCode(),licenseInfo.getFeatureId());
return Rets.success(HaspUtil.getLicenseInfo(licenseInfo.getVendorCode(),licenseInfo.getFeatureId()));
}else if (licenseInfo.getType().equals(Constant.LICENSE_VERIFY)){
//验证license信息
return HaspUtil.verify(licenseInfo.getVendorCode(),licenseInfo.getFeatureId());
return Rets.success(HaspUtil.verify(licenseInfo.getVendorCode(),licenseInfo.getFeatureId()));
}else {
log.info("type error");
return null;
return Rets.failure("");
}
}
/**
*
* @author fengjunfeng
* @date 2022/1/20
* @time 11:14
* @description
*
**/
public boolean verify(String serverId){
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
HttpEntity<JSONObject> httpEntity = new HttpEntity<>(null, headers);
String url = "http://" + GetIpProtUtil.getLocalIP() +":" + port + "/getServerId";
String str = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class).getBody();
log.info("license bifang_api server id: {}", str);
if (str.equals(serverId)){
return true;
}
}catch (SocketException | UnknownHostException e){
log.error("获取ip出错");
}
return false;
}
// @PostMapping("/test")
// public Object test() {
// verify("1111");
//
// if (CacheManager.getCache("test") == null){
// CacheManager.addCache("test","11111");
// }else {
// System.out.println(CacheManager.getCache("test"));
// }
// return null;
// }
}

View File

@@ -0,0 +1,86 @@
package com.license.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class GetIpProtUtil {
/**
* 获取Linux下的IP地址
*
* @return IP地址
* @throws SocketException
*/
private static String getLinuxLocalIp() throws SocketException {
String ip = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
&& !ipaddress.contains("fe80")) {
ip = ipaddress;
}
}
}
}
}
} catch (SocketException ex) {
ip = "127.0.0.1";
ex.printStackTrace();
}
return ip;
}
/**
* 判断操作系统是否是Windows
*
* @return
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
// 注这里的system系统指的是 JRE (runtime)system不是指 OS
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
/**
* 获取本地IP地址
*
* @throws SocketException
*/
public static String getLocalIP() throws UnknownHostException, SocketException {
if (isWindowsOS()) {
return InetAddress.getLocalHost().getHostAddress();
} else {
return getLinuxLocalIp();
}
}
public static String getLocalPort() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServerPort() + "";
}
public static String getIp() {
String ip = "127.0.0.1";
return ip;
}
// public static void main(String[] args) throws MalformedObjectNameException, SocketException, UnknownHostException {
// System.out.println(getLocalIP());
// }
}

View File

@@ -163,17 +163,19 @@ public class HaspUtil {
// log.info("license status: {}", status);
if(status == HaspStatus.HASP_STATUS_OK) {
//如果已经安装过license ,读取指纹和 hasp id
String info = hasp.getSessionInfo(KEY_ID_FORMAT);
Document document = XmlUtil.parseXml(info);
Element rootEle = document.getDocumentElement();
Element haspElement=XmlUtil.getElement(rootEle,"hasp");
String id = haspElement.getAttribute("id");
String licenseInfo = hasp.getInfo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
"<haspscope>\n" +
" <hasp " +
"id= \"" + id +"\""+
"/>\n" +
"</haspscope>",KEY_C2V_FORMAT,vendorCode);
String licenseInfo = hasp.getSessionInfo(KEY_C2V_FORMAT);
// String info = hasp.getSessionInfo(KEY_ID_FORMAT);
// Document document = XmlUtil.parseXml(info);
// Element rootEle = document.getDocumentElement();
// Element haspElement=XmlUtil.getElement(rootEle,"hasp");
// String id = haspElement.getAttribute("id");
// String licenseInfo = hasp.getInfo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
// "<haspscope>\n" +
// " <hasp " +
// "id= \"" + id +"\""+
// "/>\n" +
// "</haspscope>",KEY_C2V_FORMAT,vendorCode);
status = hasp.getLastError();
log.info("getLicense c2v license status: {}", status);
if (status != HaspStatus.HASP_STATUS_OK) {

View File

@@ -8,3 +8,27 @@ server.tomcat.accept-count=1000
server.tomcat.min-spare-threads=100
#server.address=127.0.0.1
bifang-api.server.port=8080
#设置连接超时时间,单位毫秒
http.connectTimeout=120000
#http clilent中从connetcion pool中获得一个connection的超时时间,单位毫秒
http.connectionRequestTimeout=120000
#请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
http.socketTimeout=120000
http.maxTotal=20
http.defaultMaxPerRoute=2
# 开启https,配置跟证书对应
#server.ssl.enabled=true
#server.ssl.key-store=D:/tomcat.keystore
## server.ssl.key-store-type=JKS
#server.ssl.key-store-type=JKS
## 密码
#server.ssl.key-store-password=tomcat
## springboot2.x不需要配置
#server.ssl.key-password=tomcat
## 别名
#server.ssl.key-alias=tomcat