Commit 2da3ac05 by 苗权威

11.1

parent b6a8d101
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -34,16 +34,20 @@ ...@@ -34,16 +34,20 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>1.18.8</version> <version>1.18.8</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
...@@ -63,22 +67,9 @@ ...@@ -63,22 +67,9 @@
<version>1.9.3</version> <version>1.9.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--<dependency>--> <!--<dependency>-->
<!--<groupId>org.springframework.security.oauth</groupId>--> <!--<groupId>org.springframework.security.oauth</groupId>-->
<!--<artifactId>spring-security-oauth2</artifactId>--> <!--<artifactId>spring-security-oauth2</artifactId>-->
...@@ -92,14 +83,10 @@ ...@@ -92,14 +83,10 @@
<scope>system</scope> <scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath> <systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath>
</dependency> </dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>testTool</finalName>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
......
package ai.qiwu.com.third_party_load; package ai.qiwu.com.third_party_load;
import ai.qiwu.com.third_party_load.common.BaseHolder;
import ai.qiwu.com.third_party_load.entity.game.GameProjectPO;
import ai.qiwu.com.third_party_load.repository.game.GameProjectTBRepository;
import ai.qiwu.com.third_party_load.repository.xiaodu.XiaoDuTBRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
@SpringBootApplication @SpringBootApplication
@EnableJpaAuditing
@Slf4j
public class ThirdPartyLoadApplication implements CommandLineRunner { public class ThirdPartyLoadApplication implements CommandLineRunner {
@Autowired
private GameProjectTBRepository gameProjectTBRepository;
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(ThirdPartyLoadApplication.class, args); SpringApplication.run(ThirdPartyLoadApplication.class, args);
} }
@Transactional
@Override @Override
public void run(String... args) throws Exception { public void run(String... args) throws Exception {
// GameProjectTBRepository gameProjectTBRepository = BaseHolder.getBean("gameProjectTBRepository");
// List<GameProjectPO> games = gameProjectTBRepository.getAll();
// int i = 0;
// for (GameProjectPO game: games) {
// String name = game.getName();
// List<String> nicknames = Arrays.asList(game.getNickname().split(","));
// for (int j = i+1; j < games.size(); j++) {
// GameProjectPO other = games.get(j);
// if (other.getOwnerId().equals(game.getOwnerId())) {
// continue;
// }
// if (other.getName().equals(name)) {
// log.info("name equal:{},id:{} -> {}, ownerId:{} -> {}, username:{} -> {}", name, game.getId(),
// other.getId(), game.getOwnerId(), other.getOwnerId(), game.getUserNickname(), other.getUserNickname());
// }
// List<String> otherNicknames = Arrays.asList(other.getNickname().split(","));
// if (!CollectionUtils.isEmpty(otherNicknames)) {
// boolean originNickListIsEmpty = CollectionUtils.isEmpty(nicknames);
// for (String nickName: otherNicknames) {
// if (StringUtils.isBlank(nickName)) continue;
// if (name.equals(nickName)) {
// log.info("name equal other nickname:{},id:{} -> {}; ownerId:{} -> {}, username:{} -> {}",
// name, game.getId(), other.getId(), game.getOwnerId(), other.getOwnerId(),
// game.getUserNickname(), other.getUserNickname());
// }
// if (!originNickListIsEmpty && nicknames.contains(nickName)) {
// log.info("nickname equal:{}, id:{} -> {}, ownerId:{} -> {}, username:{} -> {}",
// nickName, game.getId(), other.getId(), game.getOwnerId(), other.getOwnerId(),
// game.getUserNickname(), other.getUserNickname());
// }
// }
// }
// }
// i++;
// }
new Thread(() -> {
GameProjectPO projectPO = gameProjectTBRepository.getById(823L);
projectPO.setNickname("ceshi");
gameProjectTBRepository.save(projectPO);
}).start();
new Thread(() -> {
GameProjectPO projectPO = gameProjectTBRepository.getById(823L);
projectPO.setUserNickname("ceshigegui");
gameProjectTBRepository.save(projectPO);
int a = 1/0;
}).start();
} }
} }
package ai.qiwu.com.third_party_load.browser.handler;
import ai.qiwu.com.third_party_load.pojo.SimpleResponse;
import ai.qiwu.com.third_party_load.properties.LoginType;
import ai.qiwu.com.third_party_load.properties.SecurityProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author 苗权威
* @dateTime 19-7-17 上午10:38
*/
@Component
@Slf4j
public class MqwAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private SecurityProperties securityProperties;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
log.info("登录失败");
if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setContentType("application/json;charset=UTF-8");
//将authentication这个对象转成json格式的字符串
response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(exception.getMessage())));
} else {
super.onAuthenticationFailure(request, response, exception);
}
}
}
package ai.qiwu.com.third_party_load.browser.handler;
import ai.qiwu.com.third_party_load.properties.LoginType;
import ai.qiwu.com.third_party_load.properties.SecurityProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author 苗权威
* @dateTime 19-7-17 上午9:46
*/
@Component
@Slf4j
public class MqwAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private SecurityProperties securityProperties;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
log.info("登录成功");
if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(authentication));
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
package ai.qiwu.com.third_party_load.common;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author 苗权威
* @dateTime 19-8-21 下午8:42
*/
@Component
public class BaseHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BaseHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static <T> T getBean(String beanName) {
return (T) applicationContext.getBean(beanName);
}
}
package ai.qiwu.com.third_party_load.common;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
/**
* @author 苗权威
* @dateTime 19-11-1 上午10:09
*/
public class Code {
// 41
private static int firstMissingPso1(int[] arr) {
if (arr == null || arr.length == 0) return 1;
int minPos = 2, maxPos = 0;
for (int i1 : arr) {
if (i1 > 0) {
if (i1 < minPos) minPos = i1;
else if (i1 > maxPos) maxPos = i1;
}
}
if (minPos == 2) return 1;
if (maxPos == 0) return 2;
int result = recur(arr, minPos, maxPos, true);
if (result == -1) result = maxPos+1;
return result;
}
private static int recur(int[] arr, int lo, int hi, boolean allExist) {
int mid = (hi-lo)/2+lo;
if (mid == lo) {
if (allExist) return -1;
else return mid+1;
}
boolean midExist = doesTheNumExist(arr, mid);
if (midExist) {
int result = recur(arr, lo, mid, true);
if (result != -1) return result;
return recur(arr, mid, hi, allExist);
}
return recur(arr, lo, mid, false);
}
private static boolean doesTheNumExist(int[] arr, int num) {
for (int i: arr) {
if (i == num) return true;
}
return false;
}
// 相比上面一种解法,相同的空间复杂度,更快的执行速度
private static int firstMissingPso(int[] nums) {
int i = 0, n = nums.length;
while (i < nums.length) {
if(nums[i] > n || nums[i] <= 0) {
i++;
continue;
}
if(nums[i] - 1 == i || nums[nums[i] - 1] == nums[i]) {
i++;
continue;
}
int temp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = temp;
}
for (i = 0; i < n; i++) {
if(nums[i] != i + 1)
return i + 1;
}
return n + 1;
}
//44
public static boolean isMatch(String s, String p) {
if (s == null && p == null) return true;
else if (s == null || p == null) return false;
ArrayDeque<Character> sq = new ArrayDeque<>();
ArrayDeque<Character> pq = new ArrayDeque<>();
for (char sc: s.toCharArray()) sq.addLast(sc);
for (char pc: p.toCharArray()) pq.addLast(pc);
return recur(sq, pq);
}
private static boolean recur(ArrayDeque<Character> sq, ArrayDeque<Character> pq) {
boolean sqEmpty = sq.isEmpty();
boolean pqEmpty = pq.isEmpty();
if (sqEmpty && pqEmpty) return true;
else if (pqEmpty) return false;
else if (sqEmpty){
for (char c: pq) {
if (c != '*') return false;
}
return true;
}
char sc = sq.pollFirst();
char pc = pq.pollFirst();
if (sc == pc || pc == '?') return recur(sq, pq);
else if (pc != '*') return false;
else {
while (!pq.isEmpty() && pq.peekFirst() == '*') pq.pollFirst();
sq.addFirst(sc);
while (!sq.isEmpty()) {
if (!recur(new ArrayDeque<>(sq), new ArrayDeque<>(pq))) {
sq.pollFirst();
} else {
return true;
}
}
return recur(sq, pq);
}
}
public static void main(String[] args) {
// // test 41
// System.out.println(firstMissingPso(new int[]{3, 4, -1, 1}));
// System.out.println(firstMissingPso(new int[]{1,2,0}));
// System.out.println(firstMissingPso(new int[]{7,8,9,11,12}));
// System.out.println(firstMissingPso(new int[]{1}));
// System.out.println(firstMissingPso(new int[]{-1,4,2,1,9,10}));
// System.out.println(firstMissingPso(new int[]{-1,3,4,2,1,5,6,7,9,10}));
// test 44
// System.out.println(isMatch("aa", "a"));
// System.out.println(isMatch("aa", "*"));
// System.out.println(isMatch("cb", "?a"));
// System.out.println(isMatch("adceb", "*a*b"));
// System.out.println(isMatch("acdcb", "a*c?b"));
// System.out.println(isMatch("aaabbbaabaaaaababaabaaabbabbbbbbbbaabababbabbbaaaaba", "a*******b"));
System.out.println(isMatch("babbbbaabababaabbababaababaabbaabababbaaababbababaaaaaabbabaaaabababbabbababbbaaaababbbabbbbbbbbbbaabbb",
"b**bb**a**bba*b**a*bbb**aba***babbb*aa****aabb*bbb***a"));
}
}
package ai.qiwu.com.third_party_load.common.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* @author 苗权威
* @dateTime 19-8-22 下午2:23
*/
@Configuration
public class DataSourceConfig {
// @Primary
// @Bean(name = "primaryDatasourceProperties")
// @Qualifier("primaryDatasourceProperties")
// @ConfigurationProperties(prefix = "spring.datasource.primary")
// public DataSourceProperties primaryDatasourceProperties() {
// return new DataSourceProperties();
// }
@Bean("primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean("secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
package ai.qiwu.com.third_party_load.common.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-8-22 下午2:30
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary",
basePackages = {"ai.qiwu.com.third_party_load.repository.game"})
public class PrimaryConfig {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties,
HibernateProperties hibernateProperties) {
Map<String, Object> properties = hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(),
new HibernateSettings());
return builder
.dataSource(primaryDataSource)
.properties(properties)
.packages("ai.qiwu.com.third_party_load.entity.game")
.persistenceUnit("primaryPersistenceUnit")
.build();
}
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties,HibernateProperties hibernateProperties) {
return entityManagerFactoryPrimary(builder, jpaProperties,hibernateProperties).getObject().createEntityManager();
}
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties,HibernateProperties hibernateProperties) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder, jpaProperties, hibernateProperties).getObject());
}
}
package ai.qiwu.com.third_party_load.common.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-8-22 下午3:21
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary",
basePackages = {"ai.qiwu.com.third_party_load.repository.xiaodu"})
public class SecondaryConfig {
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties,
HibernateProperties hibernateProperties) {
Map<String, Object> properties = hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(),
new HibernateSettings());
return builder
.dataSource(secondaryDataSource)
.properties(properties)
.packages("ai.qiwu.com.third_party_load.entity.xiaodu")
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties, HibernateProperties hibernateProperties) {
return entityManagerFactoryPrimary(builder, jpaProperties,hibernateProperties).getObject().createEntityManager();
}
@Bean(name = "transactionManagerSecondary")
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties, HibernateProperties hibernateProperties) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder, jpaProperties, hibernateProperties).getObject());
}
}
package ai.qiwu.com.third_party_load.config;
import ai.qiwu.com.third_party_load.properties.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
/**
* @author 苗权威
* @dateTime 19-7-17 上午10:01
*/
public class AbstractChannelSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler mqwAuthenticationSuccessHandler;
@Autowired
private AuthenticationFailureHandler mqwAuthenticationFailureHandler;
protected void applyPasswordAuthenticationConfig(HttpSecurity httpSecurity) throws Exception {
httpSecurity.formLogin()
.loginPage(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)
.loginProcessingUrl(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
.successHandler(mqwAuthenticationSuccessHandler)
.failureHandler(mqwAuthenticationFailureHandler);
}
}
package ai.qiwu.com.third_party_load.config;
import ai.qiwu.com.third_party_load.properties.OAuth2ClientProperties;
import ai.qiwu.com.third_party_load.properties.SecurityProperties;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-7-15 上午10:40
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private SecurityProperties securityProperties;
@Autowired
private TokenStore tokenStore;
@Autowired(required = false)
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Autowired(required = false)
private TokenEnhancer jwtTokenEnhancer;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
if (jwtAccessTokenConverter != null && jwtTokenEnhancer != null) {
TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> enhancers = new ArrayList<>();
enhancers.add(jwtTokenEnhancer);
enhancers.add(jwtAccessTokenConverter);
enhancerChain.setTokenEnhancers(enhancers);
endpoints.tokenEnhancer(enhancerChain)
.accessTokenConverter(jwtAccessTokenConverter);
}
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
if (ArrayUtils.isNotEmpty(securityProperties.getOauth2().getClients())) {
for (OAuth2ClientProperties config : securityProperties.getOauth2().getClients()) {
builder.withClient(config.getClientId())
.secret(config.getClientSecret())
.authorizedGrantTypes("refresh_token","password","authorization_code")
.refreshTokenValiditySeconds(2592000)
.scopes("all","read","write");
}
}
}
}
package ai.qiwu.com.third_party_load.config;
import ai.qiwu.com.third_party_load.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
/**
* @author 苗权威
* @dateTime 19-7-15 下午6:05
*/
@Configuration
@EnableResourceServer
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and().requestMatchers().antMatchers("/api/**");
}
}
package ai.qiwu.com.third_party_load.config;
import ai.qiwu.com.third_party_load.properties.SecurityProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
/**
* @author 苗权威
* @dateTime 19-7-15 上午10:34
*/
//@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user")
.password("123456").roles("USER").and().passwordEncoder(passwordEncoder());
}
@Bean
public static BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().formLogin().permitAll();
}
}
package ai.qiwu.com.third_party_load.config;
import ai.qiwu.com.third_party_load.properties.SecurityProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author 苗权威
* @dateTime 19-7-17 上午9:41
*/
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityCoreConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
package ai.qiwu.com.third_party_load.controller;
import ai.qiwu.com.third_party_load.pojo.SimpleResponse;
import ai.qiwu.com.third_party_load.properties.SecurityConstants;
import ai.qiwu.com.third_party_load.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author 苗权威
* @dateTime 19-7-17 上午10:47
*/
@RestController
@Slf4j
public class BrowserSecurityController {
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Autowired
private SecurityProperties securityProperties;
/**
* 当需要身份认证时,跳转到这里
* @param request
* @param response
* @return
*/
@RequestMapping(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
@ResponseStatus(code = HttpStatus.UNAUTHORIZED) //401
public SimpleResponse requireAuthentication(HttpServletRequest request,
HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String target = savedRequest.getRedirectUrl();
log.info("引发跳转的请求是:{}", target);
if (StringUtils.endsWithIgnoreCase(target, ".html")) {
redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
}
}
return new SimpleResponse("访问的服务需要身份认证,引导用户到登录页");
}
}
package ai.qiwu.com.third_party_load.controller;
import ai.qiwu.com.third_party_load.pojo.UserProfile;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 苗权威
* @dateTime 19-7-15 下午6:00
*/
@RestController
public class UserController {
@RequestMapping("/api/profile")
public ResponseEntity<UserProfile> profile() {
User user = (User) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
String email = user.getUsername() + "@email.com";
UserProfile profile = new UserProfile();
profile.setName(user.getUsername());
profile.setEmail(email);
return ResponseEntity.ok(profile);
}
}
package ai.qiwu.com.third_party_load.entity.game;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Table(name = "game_project_tb")
@Getter
@Setter
public class GameProjectPO {
@Id
@GeneratedValue
private Long id;
@Column
private String name;
@Column
private String nickname;
@Column(name = "bot_account")
private String botAccount;
@Column
private String username;
@Column(name = "user_nickname")
private String userNickname;
@Column(name = "owner_id")
private Long ownerId;
}
package ai.qiwu.com.third_party_load.entity.xiaodu;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.sql.Timestamp;
/**
* @author 苗权威
* @dateTime 19-10-31 上午10:15
*/
@Getter
@Setter
@Entity
@Table(name = "xiaodu_history_tb")
@EntityListeners(AuditingEntityListener.class)
public class XiaoduHistoryTB {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "bot_id")
private String botId;
@Column(name = "xiaodu_user_id")
private String xiaoduUserId;
@Column(name = "last_time")
private Long lastTime;
@CreatedDate
@Column(name = "create_time", updatable = false, nullable = false)
private Timestamp createTime;
@LastModifiedDate
@Column(name = "update_time")
private Timestamp updateTime;
}
package ai.qiwu.com.third_party_load.handler;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author 苗权威
* @dateTime 19-7-15 下午1:59
*/
public class XiaoDuLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
String header = request.getHeader("Authorization");
String name = authentication.getName();
if (header == null || !header.startsWith("Basic ")) {
throw new UnapprovedClientAuthenticationException("请求头中无client信息");
}
}
}
...@@ -2,6 +2,7 @@ package ai.qiwu.com.third_party_load.pojo; ...@@ -2,6 +2,7 @@ package ai.qiwu.com.third_party_load.pojo;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.apache.commons.lang3.math.NumberUtils;
/** /**
* @author 苗权威 * @author 苗权威
...@@ -12,4 +13,9 @@ import lombok.Setter; ...@@ -12,4 +13,9 @@ import lombok.Setter;
public class UserProfile { public class UserProfile {
private String email; private String email;
private String name; private String name;
private Integer test;
public static void main(String[] args) {
System.out.println(NumberUtils.INTEGER_TWO.equals(new UserProfile().getTest()));;
}
} }
package ai.qiwu.com.third_party_load.properties;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-17 上午10:30
*/
@Getter
@Setter
public class BrowserProperties {
/**
* 登录页面,当引发登录行为的url以html结尾时,会跳到这里配置的url上
*/
private String loginPage = SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM;
/**
* 退出成功时跳转的url,如果配置了,则跳到指定的url,如果没配置,则返回json数据
*/
private String signOutUrl;
/**
* 登录响应的方式,默认是json
*/
private LoginType loginType = LoginType.JSON;
/**
* 登录成功后跳转的地址,如果设置了此属性,则登录成功后总是会跳到这个地址上。
* 只在signInResponseType为REDIRECT时生效
*/
private String signInSuccessUrl;
}
package ai.qiwu.com.third_party_load.properties;
import ai.qiwu.com.third_party_load.config.AbstractChannelSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationMetadata;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import javax.sql.DataSource;
/**
* @author 苗权威
* @dateTime 19-7-17 上午9:51
*/
@Configuration
public class BrowserSecurityConfig extends AbstractChannelSecurityConfig {
@Autowired
private SecurityProperties securityProperties;
@Autowired
private DataSource dataSource;
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
//这是密码登录相关的配置
applyPasswordAuthenticationConfig(http);
super.configure(http);
}
}
package ai.qiwu.com.third_party_load.properties;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-16 上午10:43
*/
@Getter
@Setter
public class OAuth2ClientProperties {
private String clientId;
private String clientSecret;
private String redirectUris;
/**
* 针对此应用发出的token的有效时间
*/
private int accessTokenValiditySeconds = 7200;
private int refreshAccessTokenValidateSeconds = 2592000;
}
package ai.qiwu.com.third_party_load.properties;
/**
* @author 苗权威
* @dateTime 19-7-17 上午10:06
*/
public interface SecurityConstants {
/**
* 当请求需要身份认证时,默认跳转的url
*
*/
String DEFAULT_UNAUTHENTICATION_URL = "/authentication/require";
/**
* 默认的用户名密码登录请求处理url
*/
String DEFAULT_LOGIN_PROCESSING_URL_FORM = "/authentication/form";
}
package ai.qiwu.com.third_party_load.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author 苗权威
* @dateTime 19-7-16 上午10:39
*/
@Component
@ConfigurationProperties(prefix = "qiwu.security")
@Getter
@Setter
public class SecurityProperties {
private OAuth2Properties oauth2 = new OAuth2Properties();
private BrowserProperties browser = new BrowserProperties();
}
package ai.qiwu.com.third_party_load.repository.game;
import ai.qiwu.com.third_party_load.entity.game.GameProjectPO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-10-30 下午2:10
*/
@Repository
public interface GameProjectTBRepository extends JpaRepository<GameProjectPO, Long> {
@Query(value = "select id,name,nickname,bot_account,user_nickname,owner_id,username from game_project_tb", nativeQuery = true)
List<GameProjectPO> getAll();
GameProjectPO getById(Long id);
@Override
<S extends GameProjectPO> S save(S s);
}
package ai.qiwu.com.third_party_load.repository.xiaodu;
import ai.qiwu.com.third_party_load.entity.xiaodu.XiaoduHistoryTB;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* @author 苗权威
* @dateTime 19-10-31 上午11:13
*/
@Repository
public interface XiaoDuTBRepository extends JpaRepository<XiaoduHistoryTB, Long> {
@Override
<S extends XiaoduHistoryTB> S save(S s);
}
package ai.qiwu.com.third_party_load.service;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/**
* @author 苗权威
* @dateTime 19-7-16 下午2:31
*/
public class BootUserDetailService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return null;
}
}
#server: server:
# port: 9090 port: 8989
# servlet:
# context-path: /security
security: spring:
user: datasource:
name: user primary:
password: 123456 # url: jdbc:mysql://localhost:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
\ No newline at end of file jdbc-url: jdbc:mysql://aliyun-hz1.chewrobot.com:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root
password: 3g9^pWQs#ft7
driver-class-name: com.mysql.cj.jdbc.Driver
secondary:
jdbc-url: jdbc:mysql://aliyun-hz1.chewrobot.com:3306/interface_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root
password: 3g9^pWQs#ft7
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
database: mysql
#控制台显示SQL
show-sql: true
hibernate:
ddl-auto: none
output:
ansi:
enabled: detect
\ No newline at end of file
...@@ -126,7 +126,7 @@ ...@@ -126,7 +126,7 @@
|参数 |必选 |类型 |说明 |默认值 |参考值 | |参数 |必选 |类型 |说明 |默认值 |参考值 |
|---- |---- |---- |---- |---- |---- | |---- |---- |---- |---- |---- |---- |
|_type | false |string |获取b64文件名列表| - | filename | |_type | false |string |获取b64文件名列表| - | 见下面注释 |
|botname| false |string|作品标识| 中控 | - | |botname| false |string|作品标识| 中控 | - |
|platform| false |string| npc名称 | - | - | |platform| false |string| npc名称 | - | - |
|text_info_ls | true |arr| 请求信息列表 | -|-| |text_info_ls | true |arr| 请求信息列表 | -|-|
...@@ -137,16 +137,45 @@ ...@@ -137,16 +137,45 @@
|speed|false|double|语速|1|-| |speed|false|double|语速|1|-|
|volume|false|double|音量|0|-| |volume|false|double|音量|0|-|
|npcName|false|string|代表优先寻找人工语音文件|-|-| |npcName|false|string|代表优先寻找人工语音文件|-|-|
注释:
- filename:文件名列表;
- url:mp3请求地址列表;
- b64:b64文件数据列表;
- urlFile:mp3请求地址和文件名列表;
- urlB64:mp3请求地址和b64文件数据列表;
- fileB64:b64文件名和其数据列表
#### Response #### Response
- ResponseBody: - ResponseBody:
```{"status":200,"message":"成功","audio":"音频文件URL"}``` 正确返回:
- 返回字段说明:若plateform为xiaoai则返回合并后的文件的请求URL;否则根据_type来选择返回的是b64文件内容列表或是b64文件名列表 ```
{
"status": 200,
"audio": [
{
"filename": "xxx",
"b64": "xxx",
"url": "xxx",
"text": "xxx"
},
{}
]
}
```
错误返回:
```$xslt
{
"status": 404,
"message": "xxx"
}
```
- 返回字段说明:若plateform为xiaoai则返回合并后的文件的请求URL;否则根据_type来选择返回内容
|返回字段 |必有 |类型 | 说明 | |返回字段 |必有 |类型 | 说明 |
|---- |---- |---- |---- | |---- |---- |---- |---- |
|status | true | int |返回状态| |status | true | int |返回状态|
|message | false |string|返回信息| |message | false |string|返回信息|
|audio|false|string|音频文件URL| |audio|false|object|返回内容|
<br/> <br/>
<br/> <br/>
......
### 请求多个音频文件
#### Request
- URL:```/api/tts_ls```
- METHOD:**POST**
- URL Parameters|TYPE: JSON
```
{
"_type": "filename",
"platform": "xiaoai",
"botname": "miao",
"text_info_ls": [
{
"person": "A12_offline",
"tone": "正常",
"text": "用来进行测试的碰碰车不是小孩努力学习皮皮再将它皮皮 。",
"pitch": 0,
"speed": 1.3,
"volume": 0,
"npcName": "xiaoming"
}
]
}
```
- 参数说明:
|参数 |必选 |类型 |说明 |默认值 |参考值 |
|---- |---- |---- |---- |---- |---- |
|_type | false |string |获取b64文件名列表| - | 见下面注释 |
|botname| false |string|作品标识| 中控 | - |
|platform| false |string| npc名称 | - | - |
|text_info_ls | true |arr| 请求信息列表 | -|-|
|person|false|string|语音人物标识|正常|-|
|tone|false|string|情绪|正常|-|
|text|true|string|文本内容|-|-|
|pitch|false|double|语调|0|-|
|speed|false|double|语速|1|-|
|volume|false|double|音量|0|-|
|npcName|false|string|代表优先寻找人工语音文件|-|-|
注释:
- filename:文件名列表;
- url:mp3请求地址列表;
- b64:b64文件数据列表;
- urlFile:mp3请求地址和文件名列表;
- urlB64:mp3请求地址和b64文件数据列表;
- fileB64:b64文件名和其数据列表
#### Response
- ResponseBody:
正确返回:
```
{
"status": 200,
"audio": [
{
"filename": "xxx",
"b64": "xxx",
"url": "xxx",
"text": "xxx"
},
{}
]
}
```
错误返回:
```$xslt
{
"status": 404,
"message": "xxx"
}
```
- 返回字段说明:若plateform为xiaoai则返回合并后的文件的请求URL;否则根据_type来选择返回内容
|返回字段 |必有 |类型 | 说明 |
|---- |---- |---- |---- |
|status | true | int |返回状态|
|message | false |string|返回信息|
|audio|false|object|返回内容|
\ No newline at end of file
...@@ -134,7 +134,7 @@ ...@@ -134,7 +134,7 @@
|参数 |必选 |类型 |说明 |默认值 |参考值 | |参数 |必选 |类型 |说明 |默认值 |参考值 |
|---- |---- |---- |---- |---- |---- | |---- |---- |---- |---- |---- |---- |
|_type | false |string |获取b64文件名列表| - | filename | |_type | false |string |获取b64文件名列表| - | 见下面注释 |
|botname| false |string|作品标识| 中控 | - | |botname| false |string|作品标识| 中控 | - |
|platform| false |string| npc名称 | - | - | |platform| false |string| npc名称 | - | - |
|text_info_ls | true |arr| 请求信息列表 | -|-| |text_info_ls | true |arr| 请求信息列表 | -|-|
...@@ -145,16 +145,44 @@ ...@@ -145,16 +145,44 @@
|speed|false|double|语速|1|-| |speed|false|double|语速|1|-|
|volume|false|double|音量|0|-| |volume|false|double|音量|0|-|
|npcName|false|string|代表优先寻找人工语音文件|-|-| |npcName|false|string|代表优先寻找人工语音文件|-|-|
注释:
- filename:文件名列表;
- url:mp3请求地址列表;
- b64:b64文件数据列表;
- urlFile:mp3请求地址和文件名列表;
- urlB64:mp3请求地址和b64文件数据列表;
- fileB64:b64文件名和其数据列表
#### Response #### Response
- ResponseBody: - ResponseBody:
```{"status":200,"message":"成功","audio":"音频文件URL"}``` 正确返回:
- 返回字段说明:若plateform为xiaoai则返回合并后的文件的请求URL;否则根据_type来选择返回的是b64文件内容列表或是b64文件名列表 ```
{
"status": 200,
"audio": {
"filename": [],
"url": [],
"b64": [],
"urlFile": [],
"urlB64": [],
"fileB64": []
}
}
```
错误返回:
```$xslt
{
"status": 404,
"message": "xxx"
}
```
- 返回字段说明:若plateform为xiaoai则返回合并后的文件的请求URL;否则根据_type来选择返回内容
|返回字段 |必有 |类型 | 说明 | |返回字段 |必有 |类型 | 说明 |
|---- |---- |---- |---- | |---- |---- |---- |---- |
|status | true | int |返回状态| |status | true | int |返回状态|
|message | false |string|返回信息| |message | false |string|返回信息|
|audio|false|string|音频文件URL| |audio|false|object|返回内容|
<br/> <br/>
<br/> <br/>
......
...@@ -20,7 +20,7 @@ public class CallPython { ...@@ -20,7 +20,7 @@ public class CallPython {
/** /**
* python解释器位置 * python解释器位置
*/ */
private static String INTERPRETER = "/root/.local/share/virtualenvs/tts-D3FZ1eZ4/bin/python"; private static String INTERPRETER = "/root/.local/share/virtualenvs/TTS-service-Fv_rYXsK/bin/python";
/** /**
* 生成sox命令,命令行执行 * 生成sox命令,命令行执行
......
...@@ -81,8 +81,9 @@ public class OkHttp3Utils { ...@@ -81,8 +81,9 @@ public class OkHttp3Utils {
paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue())); paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
builder.url(urlBuild.build()).headers(headerBuilder.build()); builder.url(urlBuild.build()).headers(headerBuilder.build());
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
return response.body().string(); try (ResponseBody body = response.body()){
return body.string();
} }
} }
...@@ -107,12 +108,13 @@ public class OkHttp3Utils { ...@@ -107,12 +108,13 @@ public class OkHttp3Utils {
paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue())); paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
builder.url(urlBuild.build()).headers(headerBuilder.build()); builder.url(urlBuild.build()).headers(headerBuilder.build());
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
try (ResponseBody body = response.body()){
String contentType = response.header("Content-Type"); String contentType = response.header("Content-Type");
if ("audio/pcm".equals(contentType)) { if ("audio/pcm".equals(contentType)) {
return response.body().bytes(); return body.bytes();
}else { }else {
log.error("猎狐返回的response中Content-Type不是audio/pcm,是{}, json数据:{}", contentType, response.body().string()); log.error("猎狐返回的response中Content-Type不是audio/pcm,是{}, json数据:{}", contentType, body.string());
} }
}catch (SocketTimeoutException e) { }catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString()); log.error("捕获到SocketTimeoutException:{}", e.toString());
...@@ -174,8 +176,9 @@ public class OkHttp3Utils { ...@@ -174,8 +176,9 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr)); builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
return response.body().string(); try (ResponseBody body = response.body()){
return body.string();
}catch (SocketTimeoutException e) { }catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString()); log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll(); client.dispatcher().cancelAll();
...@@ -200,9 +203,10 @@ public class OkHttp3Utils { ...@@ -200,9 +203,10 @@ public class OkHttp3Utils {
headBuilder.add("Content-Type","application/json; charset=utf-8"); headBuilder.add("Content-Type","application/json; charset=utf-8");
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr)); builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
try (ResponseBody body = response.body()){
int code = response.code(); int code = response.code();
response.body().string(); body.string();
return code; return code;
}catch (SocketTimeoutException e) { }catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString()); log.error("捕获到SocketTimeoutException:{}", e.toString());
...@@ -241,18 +245,19 @@ public class OkHttp3Utils { ...@@ -241,18 +245,19 @@ public class OkHttp3Utils {
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr)); builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
ResponseCodeWithData codeWithData = null; ResponseCodeWithData codeWithData = null;
try (Response response = timeoutClient.newCall(builder.build()).execute()){ Response response = timeoutClient.newCall(builder.build()).execute();
try (ResponseBody body = response.body()){
//log.info("doPostTimeout请求返回:{}", response.code()); //log.info("doPostTimeout请求返回:{}", response.code());
// log.info("response3333333 :{}",response.header("usetime")); // log.info("response3333333 :{}",response.header("usetime"));
int code = response.code(); int code = response.code();
if (code == 200) { if (code == 200) {
if (file != null) { if (file != null) {
try (BufferedSink sink = Okio.buffer(Okio.sink(file))){ try (BufferedSink sink = Okio.buffer(Okio.sink(file))){
sink.writeAll(Objects.requireNonNull(response.body()).source()); sink.writeAll(Objects.requireNonNull(body).source());
codeWithData = new ResponseCodeWithData(code); codeWithData = new ResponseCodeWithData(code);
} }
} else { } else {
codeWithData = new ResponseCodeWithData(code, response.body().string()); codeWithData = new ResponseCodeWithData(code, body.string());
} }
return codeWithData; return codeWithData;
} }
...@@ -293,9 +298,9 @@ public class OkHttp3Utils { ...@@ -293,9 +298,9 @@ public class OkHttp3Utils {
RequestBody.create(MediaType.parse("application/octet-stream"), file)); RequestBody.create(MediaType.parse("application/octet-stream"), file));
} }
builder.headers(headBuilder.build()).post(requestBuilder.build()); builder.headers(headBuilder.build()).post(requestBuilder.build());
Response response = client.newCall(builder.build()).execute();
try (Response response = client.newCall(builder.build()).execute()){ try (ResponseBody body = response.body()){
return response.body().string(); return body.string();
} }
} }
...@@ -356,9 +361,9 @@ public class OkHttp3Utils { ...@@ -356,9 +361,9 @@ public class OkHttp3Utils {
RequestBody.create(MediaType.parse("application/octet-stream"), fileByte)); RequestBody.create(MediaType.parse("application/octet-stream"), fileByte));
} }
builder.headers(headBuilder.build()).post(requestBuilder.build()); builder.headers(headBuilder.build()).post(requestBuilder.build());
Response response = client.newCall(builder.build()).execute();
try (Response response = client.newCall(builder.build()).execute()){ try (ResponseBody body = response.body()){
return response.body().string(); return body.string();
} }
} }
...@@ -380,8 +385,9 @@ public class OkHttp3Utils { ...@@ -380,8 +385,9 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr)); builder.headers(headBuilder.build()).put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
return response.body().string(); try (ResponseBody body = response.body()){
return body.string();
} }
} }
...@@ -403,8 +409,9 @@ public class OkHttp3Utils { ...@@ -403,8 +409,9 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr)); builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
return response.body().string(); try (ResponseBody body = response.body()){
return body.string();
} }
} }
...@@ -426,7 +433,9 @@ public class OkHttp3Utils { ...@@ -426,7 +433,9 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonStr)); builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute();ResponseBody body = response.body()){ Response response = client.newCall(builder.build()).execute();
try (ResponseBody body = response.body()){
body.string();
return response.code(); return response.code();
}catch (SocketTimeoutException e) { }catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString()); log.error("捕获到SocketTimeoutException:{}", e.toString());
......
package ai.qiwu.com.tts_service.common; package ai.qiwu.com.tts_service.common;
import org.apache.tomcat.util.http.LegacyCookieProcessor;
import org.springframework.boot.autoconfigure.web.servlet.TomcatServletWebServerFactoryCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
...@@ -19,4 +23,15 @@ public class SpecialCharURLConfig { ...@@ -19,4 +23,15 @@ public class SpecialCharURLConfig {
factory.addConnectorCustomizers(connector -> connector.setProperty("relaxedQueryChars", "[]{}")); factory.addConnectorCustomizers(connector -> connector.setProperty("relaxedQueryChars", "[]{}"));
return factory; return factory;
} }
/**
* 从Tomcat 8,Cookie的解析已经符合RFC 6265。
* 由于RFC 6265不再接受以前允许的逗号分隔符(例如RFC 2109)
* "Cookie:KEY 1 = VAL 1,KEY 2 = VAL 2"的格式被视为非法
* @return
*/
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
return factory -> factory.addContextCustomizers(context -> context.setCookieProcessor(new LegacyCookieProcessor()));
}
} }
...@@ -3,6 +3,7 @@ package ai.qiwu.com.tts_service.common; ...@@ -3,6 +3,7 @@ package ai.qiwu.com.tts_service.common;
import ai.qiwu.com.tts_service.pojo.MP3Response; import ai.qiwu.com.tts_service.pojo.MP3Response;
import ai.qiwu.com.tts_service.pojo.ResponseStatusWithList; import ai.qiwu.com.tts_service.pojo.ResponseStatusWithList;
import ai.qiwu.com.tts_service.pojo.TTSResponse; import ai.qiwu.com.tts_service.pojo.TTSResponse;
import ai.qiwu.com.tts_service.pojo.TtsLsResponse;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException; import org.apache.catalina.connector.ClientAbortException;
...@@ -117,6 +118,19 @@ public class TTServiceUtil { ...@@ -117,6 +118,19 @@ public class TTServiceUtil {
} }
} }
public static void buildNewTtsLsResponse(HttpServletResponse response, TtsLsResponse ttsLsResponse, int status) {
String ttsResJsonStr = JSON.toJSONString(ttsLsResponse);
response.setStatus(status);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
try (PrintWriter out = response.getWriter()){
out.append(ttsResJsonStr);
out.flush();
} catch (Exception e) {
log.error("buildNewTtsLsResponse()出错:{}",e.toString());
}
}
/** /**
* 构建tts接口请求的响应信息 * 构建tts接口请求的响应信息
* @param servletResponse HttpServletResponse对象 * @param servletResponse HttpServletResponse对象
......
...@@ -5,6 +5,7 @@ import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData; ...@@ -5,6 +5,7 @@ import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData;
import ai.qiwu.com.tts_service.service.Initialize; import ai.qiwu.com.tts_service.service.Initialize;
import ai.qiwu.com.tts_service.service.TTService; import ai.qiwu.com.tts_service.service.TTService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
...@@ -108,7 +109,14 @@ public class TTSController { ...@@ -108,7 +109,14 @@ public class TTSController {
*/ */
@PostMapping("/api/tts_ls") @PostMapping("/api/tts_ls")
public void tts_ls(@RequestBody TTSLSRequest request, HttpServletResponse response) { public void tts_ls(@RequestBody TTSLSRequest request, HttpServletResponse response) {
ttService.tts_ls(request, response); // long start = System.currentTimeMillis();
try {
ttService.tts_ls(request, response);
} catch (Exception e) {
response.setStatus(500);
log.error(ExceptionUtils.getStackTrace(e));
}
// log.info("tts_ls耗时:{}", System.currentTimeMillis()-start);
} }
/** /**
......
...@@ -26,6 +26,7 @@ public class GeneralMP3Data { ...@@ -26,6 +26,7 @@ public class GeneralMP3Data {
private String format; private String format;
private String npcName; private String npcName;
private String tmpName;
public GeneralMP3Data(String server, String text, String person, String tone, String botname, public GeneralMP3Data(String server, String text, String person, String tone, String botname,
Boolean cache, Double volume, Double speed, Double pitch) { Boolean cache, Double volume, Double speed, Double pitch) {
......
package ai.qiwu.com.third_party_load.properties; package ai.qiwu.com.tts_service.pojo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-7-16 上午10:41 * @dateTime 19-10-29 上午11:33
*/ */
@Getter @Getter
@Setter @Setter
public class OAuth2Properties { @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class TtsLsAudio {
private String jwtStringKey = "qiwu"; private String filename;
private String b64;
private OAuth2ClientProperties[] clients = {}; private String url;
private String text;
} }
package ai.qiwu.com.tts_service.pojo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-10-29 上午11:32
*/
@Getter
@Setter
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class TtsLsResponse {
private Integer status;
private String message;
private List<TtsLsAudio> audio = new ArrayList<>();
}
package ai.qiwu.com.third_party_load.properties; package ai.qiwu.com.tts_service.pojo;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-7-17 上午9:49 * @dateTime 19-10-29 上午11:20
*/ */
public enum LoginType { public enum TtsLsType {
REDIRECT, JSON filename,url,b64,urlFile,urlB64,fileB64
} }
package ai.qiwu.com.tts_service.service; package ai.qiwu.com.tts_service.service;
import ai.qiwu.com.tts_service.common.TTSUtils; import ai.qiwu.com.tts_service.common.TTSUtils;
import ai.qiwu.com.tts_service.pojo.TtsLsAudio;
import ai.qiwu.com.tts_service.pojo.TtsLsResponse;
import ai.qiwu.com.tts_service.pojo.TtsLsType;
import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData; import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData;
import com.alibaba.fastjson.JSON;
import com.csvreader.CsvReader; import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
...@@ -9,6 +13,7 @@ import org.apache.commons.lang3.exception.ExceptionUtils; ...@@ -9,6 +13,7 @@ import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.*; import java.io.*;
import java.math.BigInteger;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files; import java.nio.file.Files;
import java.text.ParseException; import java.text.ParseException;
...@@ -17,6 +22,8 @@ import java.util.*; ...@@ -17,6 +22,8 @@ import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static ai.qiwu.com.tts_service.pojo.TtsLsType.*;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-9-27 下午1:56 * @dateTime 19-9-27 下午1:56
...@@ -215,67 +222,17 @@ public class Test { ...@@ -215,67 +222,17 @@ public class Test {
} }
public static void main(String[] args) throws IOException, ParseException { public static void main(String[] args) throws IOException, ParseException {
// long start = System.currentTimeMillis(); Date date = new Date(1572522571234L);
// uploadOneNpc(null); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// System.out.println(System.currentTimeMillis()-start); System.out.println(format.format(date));
// BigInteger bigInteger = new BigInteger("1572522571");
// String folder = "/home/yf01/下载/tts/test/齐齐"; // BigInteger[] mas = bigInteger.divideAndRemainder(new BigInteger("60"));
// File file = new File(folder); // BigInteger second = mas[1];
// int i = 0; // BigInteger[] ham = mas[0].divideAndRemainder((new BigInteger("60")));
// for (File f: file.listFiles()) { // BigInteger minute = ham[1];
// if (f.getName().length() <= 8) { // BigInteger hour = ham[0].remainder(new BigInteger("24"));
// i++; // System.out.println(hour+":"+minute+":"+second);
// System.out.println(f.getName()+" "); System.out.println(TTSUtils.buildMP3Filename("你看向铁塔,发现一个男人正站在斜塔的高处,手里拿着一大一小两个铁球,而你身边的人也在不断的议论纷纷,一个身穿褐色长袍的男人愤愤的说,"));
// } System.out.println(TTSUtils.buildMP3Filename("你看向铁塔,发现一个男人正站在斜塔的高处,手里拿着一大一小两个铁球,而你身边的人也在不断的议论纷纷,一个穿褐色长袍的男人愤愤的说,"));
// }
// System.out.println(i);
//test4();
//test6();
// String ss = "哈{/ha/}哈{/ha/}哈{/ha4/}哈{/ha4/},好久没有如此畅快了!再{/zai4/}来{/lai2/}!红叶香山挂满枝,尘嚣欲留雨洗池。过风迷眼人踪处,客换却道知不知? 此招题目是什么?!";
// String t = "哈{/ha/}哈{/ha/}哈{/ha4/}哈{/ha4/},好久没有如此畅快了!再{/zai4/}来{/lai2/}!红叶香山挂满枝,尘嚣欲留雨洗池。过风迷眼人踪处,客换却道知不知??此招题目是什么?!";
// String bukong = "哈{/ha/}哈{/ha/}哈{/ha4/}哈{/ha4/},好久没有如此畅快了!再{/zai4/}来{/lai2/}!红叶香山挂满枝,尘嚣欲留雨洗池。过风迷眼人踪处,客换却道知不知? 此招题目是什么?!";
// String kong = "哈{/ha/}哈{/ha/}哈{/ha4/}哈{/ha4/},好久没有如此畅快了!再{/zai4/}来{/lai2/}!红叶香山挂满枝,尘嚣欲留雨洗池。过风迷眼人踪处,客换却道知不知? 此招题目是什么?! ";
//
// String sss = "回答错误,正确答案为 :疑是地上霜。 当前体力值为 ";
// System.out.println(TTSUtils.buildMP3Filename(sss));
// SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US);
// Date date = sdf.parse("Sat Sep 28 20:51:14 CST 2019");
//
// String tt = ":";
// tt = tt.replaceAll("\\p{P}", "");
// System.out.println(StringUtils.isBlank(tt));
//
// String ss3 = "你当{/dang1/}前分{/fen1/}数{/shu4/}是\uD83C\uDD70\uD83C\uDD71。";
// String ss4 = "挑战旁白:你当{/dang1/}前分{/fen1/}数{/shu4/}是\uD83C\uDD7010\uD83C\uDD71";
// System.out.println(TTSUtils.buildMP3Filename(ss3));
// System.out.println(TTSUtils.buildMP3Filename(ss4));
//
// System.out.println("=======================");
// String tt1 = "\uD83C\uDD702424\uD83C\uDD71sgag\uD83C\uDD70657\uD83C\uDD71agasgh";
// TreeMap<String, String> combineMp3Text2FilePath = new TreeMap<>(Comparator.comparingInt(tt1::indexOf));
// Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
// Matcher matcher = pattern.matcher(tt1);
// while (matcher.find()) {
// combineMp3Text2FilePath.put(matcher.group(1), matcher.group(1));
// }
// String[] arr = pattern.split(tt1);
// System.out.println(Arrays.toString(arr));
// for (String s: arr) {
// combineMp3Text2FilePath.put(s, s);
// }
// System.out.println(combineMp3Text2FilePath.values());
//
// System.out.println("=======================");
//
// String mr = "igaijgoj©️ge要不断he";
// System.out.println(mr.replaceAll("\\p{P}", ""));
// System.out.println(mr.replaceAll("\\W", ""));
//
// String ssss = "你当{/dang1/}前分{/fen1/}数{/shu4/}是\uD83C\uDD700\uD83C\uDD71。";
// System.out.println(ssss.indexOf("\uD83C\uDD70"));
String tts = "其实进炼气期之后给的储物袋里有介绍这个的玉简。我们这些没有什么特长的也就接着体力活混点资源,如果会炼丹炼器这些,贡献点增长可就快了。";
System.out.println(TTSUtils.buildMP3Filename(tts));
} }
} }
...@@ -25,6 +25,8 @@ logging: ...@@ -25,6 +25,8 @@ logging:
# path: /root/GameEditor/mqw/project/ttsTest/logs # path: /root/GameEditor/mqw/project/ttsTest/logs
level: level:
root: info root: info
okhttp3:
OkHttpClient: FINE
server: server:
port: 9663 port: 9663
# port: 8188 # port: 8188
...@@ -33,5 +35,6 @@ server: ...@@ -33,5 +35,6 @@ server:
enabled: true enabled: true
pattern: '%h %l %u %t "%r" %s %b bytes %D ms' pattern: '%h %l %u %t "%r" %s %b bytes %D ms'
directory: /home/ubuntu/project/tts/tomcat directory: /home/ubuntu/project/tts/tomcat
# directory: /root/GameEditor/mqw/project/ttsTest/tomcat max-threads: 1024
connection-timeout: 240000 # directory: /root/GameEditor/mqw/project/ttsTest/tomcat
connection-timeout: 2000
...@@ -44,8 +44,9 @@ public class OkHttp3Utils { ...@@ -44,8 +44,9 @@ public class OkHttp3Utils {
paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue())); paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
builder.url(urlBuild.build()).headers(headerBuilder.build()); builder.url(urlBuild.build()).headers(headerBuilder.build());
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
return response.body().string(); try (ResponseBody body = response.body()) {
return body.string();
} }
} }
...@@ -72,8 +73,9 @@ public class OkHttp3Utils { ...@@ -72,8 +73,9 @@ public class OkHttp3Utils {
// headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); // headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr)); builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
return response.body().string(); try (ResponseBody body = response.body()){
return body.string();
}catch (SocketTimeoutException e) { }catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString()); log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll(); client.dispatcher().cancelAll();
...@@ -92,8 +94,9 @@ public class OkHttp3Utils { ...@@ -92,8 +94,9 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr)); builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
return response.body().string(); try (ResponseBody body = response.body()){
return body.string();
}catch (SocketTimeoutException e) { }catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString()); log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll(); client.dispatcher().cancelAll();
...@@ -144,9 +147,9 @@ public class OkHttp3Utils { ...@@ -144,9 +147,9 @@ public class OkHttp3Utils {
RequestBody.create(MediaType.parse("application/octet-stream"), file)); RequestBody.create(MediaType.parse("application/octet-stream"), file));
} }
builder.headers(headBuilder.build()).post(requestBuilder.build()); builder.headers(headBuilder.build()).post(requestBuilder.build());
Response response = client.newCall(builder.build()).execute();
try (Response response = client.newCall(builder.build()).execute()){ try (ResponseBody body = response.body()){
return response.body().string(); return body.string();
} }
} }
...@@ -171,9 +174,9 @@ public class OkHttp3Utils { ...@@ -171,9 +174,9 @@ public class OkHttp3Utils {
RequestBody.create(MediaType.parse("application/octet-stream"), fileByte)); RequestBody.create(MediaType.parse("application/octet-stream"), fileByte));
} }
builder.headers(headBuilder.build()).post(requestBuilder.build()); builder.headers(headBuilder.build()).post(requestBuilder.build());
Response response = client.newCall(builder.build()).execute();
try (Response response = client.newCall(builder.build()).execute()){ try (ResponseBody body = response.body()){
return response.body().string(); return body.string();
} }
} }
...@@ -187,8 +190,9 @@ public class OkHttp3Utils { ...@@ -187,8 +190,9 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr)); builder.headers(headBuilder.build()).put(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
return response.body().string(); try (ResponseBody body = response.body()){
return body.string();
} }
} }
...@@ -202,8 +206,9 @@ public class OkHttp3Utils { ...@@ -202,8 +206,9 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr)); builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){ Response response = client.newCall(builder.build()).execute();
return response.body().string(); try (ResponseBody body = response.body()){
return body.string();
} }
} }
......
package ai.qiwu.com.xiaoduhome.common; package ai.qiwu.com.xiaoduhome.common;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/** /**
* @author 苗权威 * @author 苗权威
...@@ -13,47 +7,6 @@ import java.util.Map; ...@@ -13,47 +7,6 @@ import java.util.Map;
*/ */
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
String old = "105463045 225830125 3377841230 5676775731 6701820674 844142256\n" +
"1270260186 2317741281 3451399937 5680433720 679786552 8443780996\n" +
"129554816 236055939 3953909652 573677395 6823941516 8512764381\n" +
"1319246985 2382677892 3977898978 5741775745 6828091493 8666831550\n" +
"147614308 24024206 400828730 576085455 6854303973 8907881060\n" +
"1483080963 2428131253 4010431623 5842366428 7051119238 895119889\n" +
"1606067284 249646023 4077876805 5935461946 7094375730 9086594830\n" +
"1619186778 2501460915 4151097686 602060014 7206220924 909823100\n" +
"1800148835 251440645 425569307 6035298742 7237124566 9159908109\n" +
"1814141710 259741977 4366487183 6080626246 7248854152 927936967\n" +
"1845949389 2675579304 4436643416 608322788 7355973668 9346692436\n" +
"191786926 2815623868 4707303948 6259213309 7414315062 9386970292\n" +
"197591333 281647119 4758925745 6342520523 775958237 9395788731\n" +
"2072955971 2850282206 4775675552 6350303840 80449325 946062731\n" +
"2078508735 2866985233 5059399282 6468672492 8048230081 948644704\n" +
"2090828382 289568194 5134779537 6506984096 816254767 977180886\n" +
"2117067137 2958839358 528743718 6587660996 82899304 9965361790\n" +
"2131112347 318451742 556138651 6641799260 8343905461 miao\n" +
"2178577413 323374327 560117740 666266085 8357861424 tmp\n" +
"2198001446 334045489 562358308 6698994869 8409603662";
String fresh2 = "105463045 302351783 560117740 666266085 746248650 928403654\n" +
"129554816 323374327 562358308 6732814591 775958237 9395788731\n" +
"1704438748 336928756 5741775745 679786552 8048230081 946062731\n" +
"1845949389 4077876805 576085455 6823941516 823307669 948644704\n" +
"2078508735 4151097686 5903691804 6854303973 82899304 977180886\n" +
"2382677892 4779893096 59494295 703543985 8343905461 980770230\n" +
"249646023 494372549 602060014 7206220924 839091027 miao\n" +
"275290675 5059399282 608322788 7414315062 8512764381 tmp\n" +
"297326874 556138651 665686051 743677363 910965323";
fresh2 = fresh2.replaceAll("\\s+", ",");
old = old.replaceAll("\\s+", ",");
System.out.println(fresh2);
// List<String> oldArr = new ArrayList<>(Arrays.asList(old.split(",")));
// List<String> freshArr2 = new ArrayList<>(Arrays.asList(fresh2.split(",")));
// oldArr.removeAll(freshArr2);
// System.out.println(oldArr);
// System.out.println(fresh);
// System.out.println(old);
} }
} }
...@@ -248,7 +248,6 @@ public class ScheduleService implements InitializingBean { ...@@ -248,7 +248,6 @@ public class ScheduleService implements InitializingBean {
deleteUnPayedOrder(); deleteUnPayedOrder();
tian(); tian();
getAsideImg(); getAsideImg();
Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE);
} }
private void tian(){ private void tian(){
......
...@@ -25,4 +25,6 @@ spring: ...@@ -25,4 +25,6 @@ spring:
logging: logging:
path: /home/dc2-user/projects/audiobox/duai/logs path: /home/dc2-user/projects/audiobox/duai/logs
level: level:
root: info root: info
\ No newline at end of file okhttp3:
OkHttpClient: FINE
\ No newline at end of file
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