Commit 2eeeeb74 by cc150520900118

Merge remote-tracking branch 'origin/dev' into dev

parents 56424409 7dc88d70
......@@ -20,5 +20,11 @@
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency>
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.1</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.founder.commonutils.util;
import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.Properties;
@Slf4j
public class PropertieUtil {
/**
* 读取配置文件某属性绝对路径下的token
*/
public static String readTokenValue(String key, String url) {
String value = "";
try {
Properties prop = new Properties();
FileInputStream fileInputStream = new FileInputStream(url);
prop.load(fileInputStream);
value = prop.getProperty(key);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
log.error(ExceptionUtil.getMessage(e));
}
return value;
}
/**
* 将值写入配置文件绝对路径下的token
*/
public static void writeTokenProperties(String token_url, String parameterName, String parameterValue) throws Exception {
String filePath = token_url;
// 获取配置文件
Properties pps = new Properties();
FileInputStream fileInputStream = new FileInputStream(filePath);
InputStream in = new BufferedInputStream(fileInputStream);
InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
pps.load(inputStreamReader);
inputStreamReader.close();
in.close();
fileInputStream.close();
//true表示追加打开,false表示每次都是清空重写
OutputStream out = new FileOutputStream(filePath);
// 设置配置名称和值
pps.setProperty(parameterName, parameterValue);
// comments 等于配置文件的注释
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, "UTF-8");
pps.store(outputStreamWriter, "Update " + parameterName + " name");
out.flush();
outputStreamWriter.close();
out.close();
}
}
package com.founder.commonutils.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.*;
/**
* @ClassName: HttpClient
* @Auther: 杨洋
* @Description: java类作用描述
* @CreateDate: 2021-03-18
* @Version: 1.0
*/
@Component
public class TokenUtils {
private static Log logger = LogFactory.getLog(HttpClient.class);
private static RequestConfig requestConfig = null;
private static String tokenPath="";
private static String yt_tokenUrl="";
/**
* 静态属性注册配置文件中的值
* @param tokenPath
*/
@Value("${tokenPath}")
void setTokenPath(String tokenPath){
this.tokenPath=tokenPath;
}
@Value("${token_url}")
void setYtgs_tokenUrl(String yt_tokenUrl) {
this.yt_tokenUrl = yt_tokenUrl;
}
static{
// 设置请求和传输超时时间
//setConnectTimeout:设置连接超时时间,单位毫秒。
//setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
//setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒
requestConfig = RequestConfig.custom().setSocketTimeout(120000).setConnectTimeout(120000).build();
try{
// tokenPath=ResourceUtils.getURL("classpath:").getPath()+"token.properties";
}catch (Exception e){
e.printStackTrace();
}
}
// 云天token
public static String getYtgsToken(){
String result_token = "";
try{
//1 先比较已有token是否过期
long nowtime = new Date().getTime();
//获取绝对路径下的token属性文件
String token= PropertieUtil.readTokenValue("token",tokenPath);;
String expiration =PropertieUtil.readTokenValue("expiration",tokenPath);
if(StringUtils.isEmpty(token) || StringUtils.isEmpty(expiration)){
result_token=readeWriteYtToken(nowtime);
}else{
//token值已过期
if(nowtime > Long.valueOf(expiration)){
result_token=readeWriteYtToken(nowtime);
}else{
result_token = token;
}
}
}catch (Exception e){
e.printStackTrace();
logger.info(e.getMessage());
}
return result_token;
}
//读和写云天的token值
public static String readeWriteYtToken(long nowtime){
String result_token="";
//2 如果过期先获取新的token值
String Authorization =PropertieUtil.readTokenValue("Authorization",tokenPath);
String ContentType =PropertieUtil.readTokenValue("Content-Type",tokenPath);
Map headerMap=new HashMap();
headerMap.put("Authorization",Authorization);
headerMap.put("Content-Type",ContentType);
String username =PropertieUtil.readTokenValue("username",tokenPath);
String password =PropertieUtil.readTokenValue("password",tokenPath);
String grant_type =PropertieUtil.readTokenValue("grant_type",tokenPath);
String scope =PropertieUtil.readTokenValue("scope",tokenPath);
String client_secret=PropertieUtil.readTokenValue("client_secret",tokenPath);
String client_id =PropertieUtil.readTokenValue("client_id",tokenPath);
JSONObject object = new JSONObject();
object.put("username", username);
object.put("password", password);
object.put("grant_type", grant_type);
object.put("scope", scope);
object.put("client_secret", client_secret);
object.put("client_id", client_id);
String token_url =yt_tokenUrl;
try {
String resultString = doPostUrlEncodedFormEntity(token_url,headerMap,JSONObject.toJSONString(object));
if (!StringUtils.isEmpty(resultString)) {
JSONObject result=JSONObject.parseObject(resultString);
result_token = result.getString("access_token");
String expires_in = result.getString("expires_in");//有效时间段 单位为秒
String result_expiration = nowtime+Integer.parseInt(expires_in)*1000+"";
//写入新的token值和本次token的过期时间
PropertieUtil.writeTokenProperties(tokenPath, "token", result_token);
PropertieUtil.writeTokenProperties(tokenPath, "expiration", result_expiration);
}
}catch (Exception e){
e.printStackTrace();
logger.info(e.getMessage());
}
return result_token;
}
/**
* 将参数拼接为?key1=a&key2=b形式提交
* @param url
* @param headers
* @param jsonParam
* @return
*/
public static String doPostUrlEncodedFormEntity(String url, Map<String, String> headers, String jsonParam){
String resultString = "";
HttpPost httpPost = new HttpPost(url);
try{
//给httpPost请求设置header
if(null!=headers&&headers.size()>0){
for(String key:headers.keySet()){
httpPost.addHeader(key,headers.get(key));
}
}
// 设置参数解决中文乱码
if (null != jsonParam){
List<NameValuePair> paramList=new ArrayList<>();
Map<String, String> paramMap=(Map<String, String>) JSON.parse(jsonParam);
paramMap.forEach((key,value) -> paramList.add(new BasicNameValuePair(key,value)));
//模拟表单
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(paramList);
entity.setContentEncoding("UTF-8");
httpPost.setEntity(entity);
}
// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
//创建客户端连接请求
CloseableHttpClient httpClient = HttpClients.createDefault();
// 发送请求
CloseableHttpResponse result = httpClient.execute(httpPost);
System.out.println("StatusCode===="+result.getStatusLine().getStatusCode());
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
// 读取服务器返回的json数据(然后解析)
resultString = EntityUtils.toString(result.getEntity(), "utf-8");
}
}catch (Exception e){
e.printStackTrace();
logger.info(e.getMessage());
}finally{
httpPost.releaseConnection();
}
return resultString;
}
}
......@@ -73,6 +73,12 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- spring2.X集成redis所需common-pool2
<dependency>
<groupId>org.apache.commons</groupId>
......
......@@ -18,6 +18,7 @@ public class SwaggerConfig {
public static final String asjApi = "com.founder.asj";
public static final String esApi = "com.founder.eszy";
public static final String publicApi = "com.founder.publicapi";
public static final String imageApi = "com.founder.ytlf";
//public static final String carApi = "com.founder.asj.controller2";
@Bean
public Docket asjApi(){
......@@ -53,6 +54,17 @@ public class SwaggerConfig {
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
@Bean
public Docket imageApi(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("imageApi")
.apiInfo(webApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(imageApi))
.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
......
......@@ -52,7 +52,7 @@
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.RELEASE</version>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
......
package com.founder.asj.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* Created by changc on 2018/9/7.
*
允许任何域名使用
允许任何头
允许任何方法(post、get等)
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1
corsConfiguration.addAllowedHeader("*"); // 2
corsConfiguration.addAllowedMethod("*"); // 3
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}
\ No newline at end of file
......@@ -26,7 +26,7 @@ public class CodeGenerator {
// 2、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir("F:\\MyProject\\map-parent\\service\\es" + "/src/main/java");//生成路径
gc.setOutputDir("D:\\MyProject\\map-parent\\serviceapi\\imagrapi" + "/src/main/java");//生成路径
gc.setAuthor("chent");//作者
gc.setOpen(false); //生成后是否打开资源管理器
......
package com.founder.ytlf.controller;
import com.founder.commonutils.publicEntity.MapRestResult;
import com.founder.commonutils.util.TokenUtils;
import com.founder.servicebase.logs.OperLog;
import com.founder.servicebase.logs.OperationType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
/**
* <p>
* 云天接口管理 前端控制器
* </p>
*
* @author yangyang
* @since 2021-03-18
*/
@Api(description = "云天接口管理")
@RestController
@RequestMapping("/ytlf")
public class YtlfController {
//案件查询(存储reids)
@OperLog(message = "token获取",operation = OperationType.QUERY)
@ApiOperation(value = "token获取")
@PostMapping("/token")
public MapRestResult getToken() {
//获取token
String accessToken = TokenUtils.getYtgsToken();
return MapRestResult.build(202,"成功获取token信息",accessToken);
}
}
......@@ -2,4 +2,9 @@
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@47.92.129.99:1600:orcl
spring.datasource.username=XZXT
spring.datasource.password=XZXT
\ No newline at end of file
spring.datasource.password=XZXT
####################云天请求token配置参数##开始#################
token_url=http://26.3.12.56:8083/api/oauth/token
tokenPath=G:\\token\\token.properties
####################云天请求token配置参数##结束#################
\ No newline at end of file
......@@ -2,4 +2,9 @@
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@10.100.17.120:1521:XZXT
spring.datasource.username=XZXT
spring.datasource.password=XzxtPwd#15
\ No newline at end of file
spring.datasource.password=XzxtPwd#15
####################云天请求token配置参数##开始#################
token_url=http://26.3.12.56:8083/api/oauth/token
tokenPath=/data/software/token/token.properties
####################云天请求token配置参数##结束#################
\ No newline at end of file
####################\u4E91\u5929\u839E\u5F0F\u8BF7\u6C42token\u914D\u7F6E\u53C2\u6570##\u5F00\u59CB#################
#header
Authorization=Basic Y2xpZW50YXBwOjEyMzQ1Ng==
Content-Type=application/x-www-form-urlencoded
#body
username=fzuser
password=5397cc0fe5a1ef4b6be36b6352012787
grant_type=password
scope=read write
client_secret=123456
client_id=clientapp
#token\u503C
token=
#\u8FC7\u671F\u65F6\u95F4
expiration=
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment