项目源码

This commit is contained in:
dimengzhe
2025-04-12 01:31:45 +08:00
commit e2e0d9bf0b
715 changed files with 82684 additions and 0 deletions

140
ksafepack-framework/pom.xml Normal file
View File

@@ -0,0 +1,140 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.kelp</groupId>
<artifactId>ksafepack</artifactId>
<version>1.0.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ksafepack-framework</artifactId>
<description>
framework框架核心
</description>
<dependencies>
<!-- SpringBoot Web容器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot 拦截器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!--阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<!--验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<exclusions>
<exclusion>
<artifactId>javax.servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
</dependency>
<!-- 系统模块-->
<dependency>
<groupId>com.kelp</groupId>
<artifactId>ksafepack-system</artifactId>
</dependency>
<!-- 获取系统信息 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
</dependency>
<!-- urlrewrite -->
<dependency>
<groupId>org.tuckey</groupId>
<artifactId>urlrewritefilter</artifactId>
<version>4.0.4</version>
</dependency>
<!-- apache httpcomponents 目前使用在webservice中 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<!-- axis webservice -->
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>axis</groupId>
<artifactId>axis-jaxrpc</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>opensymphony</groupId>
<artifactId>oscache</artifactId>
<version>2.4.1</version>
<exclusions>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,66 @@
package com.kelp.framework.aspect;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.kelp.common.annotation.DataSource;
import com.kelp.common.config.datasource.DynamicDataSourceContextHolder;
/**
* 多数据源处理
*
* @author kelp
*/
@Aspect
@Order(1)
@Component
public class DataSourceAspect {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("@annotation(com.kelp.common.annotation.DataSource)"
+ "|| @within(com.kelp.common.annotation.DataSource)")
public void dsPointCut() {
}
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
DataSource dataSource = getDataSource(point);
if (dataSource != null) {
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
}
try {
return point.proceed();
} finally {
// 销毁数据源 在执行方法之后
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
/**
* 获取需要切换的数据源
*/
public DataSource getDataSource(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
Class<? extends Object> targetClass = point.getTarget().getClass();
DataSource targetDataSource = targetClass.getAnnotation(DataSource.class);
if (targetDataSource != null) {
return targetDataSource;
}
Method method = signature.getMethod();
DataSource dataSource = method.getAnnotation(DataSource.class);
return dataSource;
}
}

View File

@@ -0,0 +1,168 @@
package com.kelp.framework.base.controller;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.kelp.common.config.RedisBean;
import com.kelp.common.utils.CookieUtil;
import com.kelp.common.utils.jwt.JwtUtil;
/**
* web层通用数据处理
*
* @author kelp
*/
public class BaseController {
protected final Logger logger = LoggerFactory.getLogger(BaseController.class);
protected String RESULT = "result";
protected String MESSAGE = "message";
@Autowired
protected RedisBean redisBean;
/**
* 获取token
* @param request
* @return
*/
protected String getToken(HttpServletRequest request) {
return CookieUtil.getCookie(request, "token");
}
/**
* 获取account id可能是plat accountId也可能是enterprise accountId/member accountId
*
* @param token
* @return
*/
protected String getAccountId(String token) {
return JwtUtil.getId(token);
}
/**
* 通用account id
*
* @param request
* @return
*/
protected String getAccountId(HttpServletRequest request) {
return getAccountId(getToken(request));
}
/**
* 取得所有参数
* @param request
* @return
*/
protected Map<String,String> getParameters(HttpServletRequest request){
Enumeration<String> parameterNames = request.getParameterNames();
Map<String,String> params = new HashMap<String, String>();
while (parameterNames.hasMoreElements()) {
String parameterName = parameterNames.nextElement();
params.put(parameterName, request.getParameter(parameterName));
}
return params;
}
/**
* get member id
*
* @param request
* @return
*/
protected String getMemberId(HttpServletRequest request) {
return JwtUtil.getId(request.getHeader("token"));
}
/**
* role,key=plat_role/member_role/enterprise_role
*
* @param token
* @return
*/
protected String getRoleId(String token, String key) {
return redisBean.hget(getAccountId(token), key);
}
/**
* 企业管理员获取departmentId
* @param token
* @return
*/
protected String getDepartmentId(HttpServletRequest request) {
return redisBean.hget(getAccountId(request), "e_department");
}
/**
* 企业管理员获取enterpriseId
* @param token
* @return
*/
protected String getEnterpriseId(HttpServletRequest request) {
return redisBean.hget(getAccountId(request), "e_enterprise");
}
protected String getEnterpriseIdPath(HttpServletRequest request) {
return redisBean.hget(getAccountId(request), "e_eidpath");
}
protected String getDepartmentIdPath(HttpServletRequest request) {
return redisBean.hget(getAccountId(request), "e_didpath");
}
/**
* 取得客户端IP
*
* @param request
* @return
*/
protected String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if (ip.equals("0:0:0:0:0:0:0:1")) {
ip = getLocalIP();
}
}
return ip;
}
private String getLocalIP() {
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
}
byte[] ipAddr = addr.getAddress();
String ipAddrStr = "";
for (int i = 0; i < ipAddr.length; i++) {
if (i > 0) {
ipAddrStr += ".";
}
ipAddrStr += ipAddr[i] & 0xFF;
}
return ipAddrStr;
}
}

View File

@@ -0,0 +1,27 @@
package com.kelp.framework.base.controller;
public class ErrorMessage {
private String message;
private Boolean status;
public ErrorMessage(String message,Boolean status){
this.message = message;
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
}

View File

@@ -0,0 +1,84 @@
package com.kelp.framework.config;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import static com.google.code.kaptcha.Constants.*;
/**
* 验证码配置
*
* @author kelp
*/
@Configuration
public class CaptchaConfig {
@Bean(name = "captchaProducer")
public DefaultKaptcha getKaptchaBean() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 是否有边框 默认为true 我们可以自己设置yesno
properties.setProperty(KAPTCHA_BORDER, "yes");
// 验证码文本字符颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
// 验证码图片宽度 默认为200
properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
// 验证码图片高度 默认为50
properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "70");
// 验证码文本字符大小 默认为40
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38");
// KAPTCHA_SESSION_KEY
properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode");
// 验证码文本字符长度 默认为5
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
// 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
// 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple
// 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
// 阴影com.google.code.kaptcha.impl.ShadowGimpy
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
@Bean(name = "captchaProducerMath")
public DefaultKaptcha getKaptchaBeanMath() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 是否有边框 默认为true 我们可以自己设置yesno
properties.setProperty(KAPTCHA_BORDER, "yes");
// 边框颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
// 验证码文本字符颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
// 验证码图片宽度 默认为200
properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
// 验证码图片高度 默认为50
properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "70");
// 验证码文本字符大小 默认为40
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38");
// KAPTCHA_SESSION_KEY
properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath");
// 验证码文本生成器
properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.kelp.framework.config.CaptchaTextCreator");
// 验证码文本字符间距 默认为2
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3");
// 验证码文本字符长度 默认为5
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6");
// 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
// 验证码噪点颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_NOISE_COLOR, "white");
// 干扰实现类
properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
// 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple
// 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
// 阴影com.google.code.kaptcha.impl.ShadowGimpy
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}

View File

@@ -0,0 +1,61 @@
package com.kelp.framework.config;
import java.security.SecureRandom;
import java.util.Random;
import com.google.code.kaptcha.text.impl.DefaultTextCreator;
/**
* 验证码文本生成器
*
* @author kelp
*/
public class CaptchaTextCreator extends DefaultTextCreator {
private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");
@Override
public String getText() {
Integer result = 0;
Random random = new SecureRandom();
int x = random.nextInt(10);
int y = random.nextInt(10);
StringBuilder suChinese = new StringBuilder();
int randomoperands = (int) Math.round(Math.random() * 2);
if (randomoperands == 0) {
result = x * y;
suChinese.append(CNUMBERS[x]);
suChinese.append("*");
suChinese.append(CNUMBERS[y]);
} else if (randomoperands == 1) {
if (!(x == 0) && y % x == 0) {
result = y / x;
suChinese.append(CNUMBERS[y]);
suChinese.append("/");
suChinese.append(CNUMBERS[x]);
} else {
result = x + y;
suChinese.append(CNUMBERS[x]);
suChinese.append("+");
suChinese.append(CNUMBERS[y]);
}
} else if (randomoperands == 2) {
if (x >= y) {
result = x - y;
suChinese.append(CNUMBERS[x]);
suChinese.append("-");
suChinese.append(CNUMBERS[y]);
} else {
result = y - x;
suChinese.append(CNUMBERS[y]);
suChinese.append("-");
suChinese.append(CNUMBERS[x]);
}
} else {
result = x + y;
suChinese.append(CNUMBERS[x]);
suChinese.append("+");
suChinese.append(CNUMBERS[y]);
}
suChinese.append("=?@" + result);
return suChinese.toString();
}
}

View File

@@ -0,0 +1,30 @@
/**
* 对传入参数进行处理
*/
package com.kelp.framework.config;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
@ControllerAdvice
public class ControllerConfig {
/**
* 应用到所有@RequestMapping注解方法在其执行之前初始化数据绑定器
*
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class,new StringTrimmerEditor(true));
binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false));
//对敏感词不过滤
//binder.registerCustomEditor(String.class, new ControllerTextEditor());
}
}

View File

@@ -0,0 +1,19 @@
/**
* 对传入参数进行处理
*/
package com.kelp.framework.config;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.web.bind.annotation.ControllerAdvice;
import com.kelp.common.utils.security.SensitivewordUtils;
@ControllerAdvice
public class ControllerTextEditor extends PropertiesEditor {
@Override
public void setAsText(String text) throws IllegalArgumentException {
//对敏感字符进行过虑
setValue(new SensitivewordUtils().replaceSensitiveWord(text, 1, "*"));
}
}

View File

@@ -0,0 +1,13 @@
package com.kelp.framework.config;
import org.springframework.stereotype.Component;
@Component
public class CronJob {
// @Scheduled(cron = "${scheduler.interval}")
// public void task() {
// System.out.println("----------------------------");
// }
}

View File

@@ -0,0 +1,75 @@
package com.kelp.framework.config;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.kelp.common.enums.DataSourceType;
import com.kelp.framework.config.properties.DataSourceProperties;
import com.kelp.framework.datasource.DynamicDataSource;
/**
* druid 配置多数据源
*
* @author kelp
*/
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.master")
public DataSource masterDataSource(DataSourceProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.slave")
@ConditionalOnProperty(prefix = "spring.datasource.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource(DataSourceProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource);
return new DynamicDataSource(masterDataSource, targetDataSources);
}
@Primary
@Bean(name = "entityManager")
public EntityManager entityManager(EntityManagerFactoryBuilder builder,DynamicDataSource dynamicDataSource) {
return entityManagerFactory(builder,dynamicDataSource).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,DynamicDataSource dynamicDataSource) {
return builder.dataSource(dynamicDataSource)
.packages("com.kelp.zhishu.entity","com.kelp.plat.entity","com.kelp.biz.entity","com.kelp.business.entity","com.kelp.jwy.entity","com.kelp.crm.entity") // 设置实体类所在位置
.persistenceUnit("persistenceUnit").build();
}
@Primary
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder,DynamicDataSource dynamicDataSource) {
return new JpaTransactionManager(entityManagerFactory(builder,dynamicDataSource).getObject());
}
}

View File

@@ -0,0 +1,122 @@
package com.kelp.framework.config;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 验证码配置
*
* @author kelp
*/
@Configuration
public class ElasticSearchConfig {
/**
* http连接超时时间
*/
@Value("${elasticsearch.connectTimeout}")
private String connectTimeout;
/**
* socket连接超时时间
*/
@Value("${elasticsearch.socketTimeout}")
private String socketTimeout;
/**
* 获取连接的超时时间
*/
@Value("${elasticsearch.connectionRequestTimeout}")
private String connectionRequestTimeout;
/**
* 最大连接数
*/
@Value("${elasticsearch.maxConnTotal}")
private String maxConnTotal;
/**
* 最大路由连接数
*/
@Value("${elasticsearch.maxConnPerRoute}")
private String maxConnPerRoute;
/**
* 用户名
*/
@Value("${elasticsearch.username}")
private String userName;
/**
* 密码
*/
@Value("${elasticsearch.password}")
private String password;
/**
* 协议
*/
@Value("${elasticsearch.protocol}")
private String protocol;
/**
* http访问路径
*/
@Value("${elasticsearch.hosts}")
private String httpHosts;
@Bean
public RestHighLevelClient restHighLevelClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(userName, password));
// 初始化ES客户端的构造器
RestClientBuilder builder = RestClient.builder(httpHosts());
// 异步的请求配置
builder.setRequestConfigCallback(builder_ -> {
// http连接超时时间 默认-1
builder_.setConnectTimeout(Integer.parseInt(connectTimeout));
// socket连接超时时间
builder_.setSocketTimeout(Integer.parseInt(socketTimeout));
// 获取连接的超时时间 默认-1
builder_.setConnectionRequestTimeout(Integer.parseInt(connectionRequestTimeout));
return builder_;
});
// 异步的httpclient连接数配置
builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
// 最大连接数
httpAsyncClientBuilder.setMaxConnTotal(Integer.parseInt(maxConnTotal));
// 最大路由连接数
httpAsyncClientBuilder.setMaxConnPerRoute(Integer.parseInt(maxConnPerRoute));
// 赋予连接凭证
httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
return httpAsyncClientBuilder;
});
return new RestHighLevelClient(builder);
}
/**
* 为了应对集群部署的es使用以下写法返回HttpHost数组
*/
private HttpHost[] httpHosts() {
String[] hosts = httpHosts.split(",");
HttpHost[] httpHosts = new HttpHost[hosts.length];
for (int i = 0; i < hosts.length; i++) {
String ip = hosts[i].split(":")[0];
int port = Integer.parseInt(hosts[i].split(":")[1]);
httpHosts[i] = new HttpHost(ip, port, protocol);
}
return httpHosts;
}
}

View File

@@ -0,0 +1,101 @@
/**
* 这个类需要注意的是处理Json及View异常其方法的捕获的异常类不能相同这样会给Spring造成歧义不知道调用哪个方法
* 建议自定义异常类进行处理这样的问题
*/
package com.kelp.framework.config;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.ModelAndView;
import com.kelp.framework.exception.E_NOGrantException;
import com.kelp.framework.exception.E_NOLoginException;
import com.kelp.framework.exception.M_NOGrantException;
import com.kelp.framework.exception.M_NOLoginException;
import com.kelp.framework.exception.P_NOGrantException;
import com.kelp.framework.exception.P_NOLoginException;
@ControllerAdvice
public class GlobalExceptionConfig {
@Value("${file.max-file-size}")
private String maxFileSize;
@ResponseBody
@ExceptionHandler(M_NOLoginException.class)
public Map<String, Object> m_nologinExceptionHandler(M_NOLoginException e) {
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMessage());
return map;
}
@ResponseBody
@ExceptionHandler(M_NOGrantException.class)
public Map<String, Object> m_nograntExceptionHandler(M_NOGrantException e) {
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMessage());
return map;
}
@ResponseBody
@ExceptionHandler(MultipartException.class)
public Map<String, Object> fileUploadExceptionHandler(MultipartException e) {
Map<String, Object> map = new HashMap<>();
map.put("result", false);
map.put("message", "上传文件超出不能超过" + maxFileSize);
return map;
}
@ExceptionHandler(E_NOLoginException.class)
public ModelAndView e_nologinExceptionHandler(E_NOLoginException e) {
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMessage());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/crm/login");
modelAndView.addObject(map);
return modelAndView;
}
@ExceptionHandler(E_NOGrantException.class)
public ModelAndView e_nograntExceptionHandler(E_NOGrantException e) {
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMessage());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/crm/login");
modelAndView.addObject(map);
return modelAndView;
}
@ExceptionHandler(P_NOLoginException.class)
public ModelAndView p_nologinExceptionHandler(P_NOLoginException e) {
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMessage());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/plat/login");
modelAndView.addObject(map);
return modelAndView;
}
@ExceptionHandler(P_NOGrantException.class)
public ModelAndView p_nograntExceptionHandler(P_NOGrantException e) {
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMessage());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/plat/login");
modelAndView.addObject(map);
return modelAndView;
}
}

View File

@@ -0,0 +1,39 @@
package com.kelp.framework.config;
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
/**
* 资源文件配置加载
*
* @author kelp
*/
@Configuration
public class I18nConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
// 默认语言
slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
// 参数名
lci.setParamName("lang");
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}

View File

@@ -0,0 +1,19 @@
package com.kelp.framework.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.kelp.common.utils.IdWorker;
/**
* 雪花算法生成器
*
* @author kelp
*/
@Configuration
public class IdWorkerConfig {
@Bean
public IdWorker idWorker() {
return new IdWorker(1,1,1);
}
}

View File

@@ -0,0 +1,78 @@
package com.kelp.framework.config;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.kelp.framework.interceptor.EInterceptor;
import com.kelp.framework.interceptor.PApiInterceptor;
import com.kelp.framework.interceptor.PInterceptor;
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Bean
public PApiInterceptor pApiInterceptor() {
return new PApiInterceptor();
}
@Bean
public PInterceptor pInterceptor() {
return new PInterceptor();
}
@Bean
public EInterceptor eInterceptor() {
return new EInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(pApiInterceptor()).addPathPatterns("/api/p/**");
registry.addInterceptor(pInterceptor()).addPathPatterns("/plat/**").excludePathPatterns("/plat/index","/plat/login");
registry.addInterceptor(eInterceptor()).addPathPatterns("/crm/**").excludePathPatterns("/crm/index","/crm/login");
}
/**
* @param registry 配置静态资源放行
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
/**
* 序列换成json时,将所有的long变成string
* 因为js中得数字类型不能包含所有的java long值
*/
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jackson2HttpMessageConverter);
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setWriteAcceptCharset(false);
converters.add(stringConverter);
}
}

View File

@@ -0,0 +1,49 @@
package com.kelp.framework.config;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.DispatcherType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.opensymphony.oscache.web.filter.CacheFilter;
/**
* Filter配置
*
* @author kelp
*/
@Configuration
public class OSCacheFilterConfig {
@Value("${oscache.enabled}")
private String enabled;
@Value("${oscache.excludes}")
private String excludes;
@Value("${oscache.urlPatterns}")
private String urlPatterns;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public FilterRegistrationBean oscacheFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new CacheFilter());
registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
registration.setName("oscacheFilter");
registration.setOrder(Integer.MAX_VALUE);
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("excludes", excludes);
initParameters.put("enabled", enabled);
initParameters.put("time", "3600");
initParameters.put("scope", "application");
registration.setInitParameters(initParameters);
return registration;
}
}

View File

@@ -0,0 +1,37 @@
package com.kelp.framework.config;
import java.io.InputStream;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;
/**
* 验证码配置
*
* @author kelp
*/
@Configuration
public class OscacheManagerConfig {
private static final String URL_OSCACHE = "/oscache.properties";
@Bean(name = "oscacheManager")
public GeneralCacheAdministrator getOscacheBean() {
try {
Properties properties = new Properties();
// 使用InPutStream流读取properties文件
InputStream in = OscacheManagerConfig.class.getResourceAsStream(URL_OSCACHE);
properties.load(in);
return new GeneralCacheAdministrator(properties);
} catch (Exception e) {
return null;
}
}
}

View File

@@ -0,0 +1,32 @@
package com.kelp.framework.config;
import java.io.IOException;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.tuckey.web.filters.urlrewrite.Conf;
import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter;
@Configuration
public class UrlRewriteFilterConfig extends UrlRewriteFilter {
private static final String URL_REWRITE = "classpath:/urlrewrite.xml";
@Value(URL_REWRITE)
private Resource resource;
// Override the loadUrlRewriter method, and write your own implementation
protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
try {
// Create a UrlRewrite Conf object with the injected resource
Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(),
"kelp-urlrewrite");
checkConf(conf);
} catch (IOException ex) {
throw new ServletException("Unable to load URL rewrite configuration file from " + URL_REWRITE, ex);
}
}
}

View File

@@ -0,0 +1,47 @@
package com.kelp.framework.config;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.DispatcherType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.kelp.common.xss.XssFilter;
/**
* Filter配置
*
* @author kelp
*/
@Configuration
public class XSSFilterConfig {
@Value("${xss.enabled}")
private String enabled;
@Value("${xss.excludes}")
private String excludes;
@Value("${xss.urlPatterns}")
private String urlPatterns;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public FilterRegistrationBean xssFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new XssFilter());
registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
registration.setName("xssFilter");
registration.setOrder(Integer.MAX_VALUE - 1);
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("excludes", excludes);
initParameters.put("enabled", enabled);
registration.setInitParameters(initParameters);
return registration;
}
}

View File

@@ -0,0 +1,78 @@
package com.kelp.framework.config.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
/**
* druid 配置属性
*
* @author kelp
*/
@Configuration
public class DataSourceProperties {
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.maxEvictableIdleTimeMillis}")
private int maxEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
public DruidDataSource dataSource(DruidDataSource datasource) {
/** 配置初始化大小、最小、最大 */
datasource.setInitialSize(initialSize);
datasource.setMaxActive(maxActive);
datasource.setMinIdle(minIdle);
/** 配置获取连接等待超时的时间 */
datasource.setMaxWait(maxWait);
/** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
/** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
/**
* 用来检测连接是否有效的sql要求是一个查询语句常用select
* 'x'。如果validationQuery为nulltestOnBorrow、testOnReturn、testWhileIdle都不会起作用。
*/
datasource.setValidationQuery(validationQuery);
/**
* 建议配置为true不影响性能并且保证安全性。申请连接的时候检测如果空闲时间大于timeBetweenEvictionRunsMillis执行validationQuery检测连接是否有效。
*/
datasource.setTestWhileIdle(testWhileIdle);
/** 申请连接时执行validationQuery检测连接是否有效做了这个配置会降低性能。 */
datasource.setTestOnBorrow(testOnBorrow);
/** 归还连接时执行validationQuery检测连接是否有效做了这个配置会降低性能。 */
datasource.setTestOnReturn(testOnReturn);
return datasource;
}
}

View File

@@ -0,0 +1,25 @@
package com.kelp.framework.datasource;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import com.kelp.common.config.datasource.DynamicDataSourceContextHolder;
/**
* 动态数据源
*
* @author kelp
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}

View File

@@ -0,0 +1,16 @@
package com.kelp.framework.exception;
import com.kelp.common.exception.BaseException;
public class E_NOGrantException extends BaseException {
/**
*
*/
private static final long serialVersionUID = 1L;
public E_NOGrantException(String code,String msg) {
super(code, msg);
}
}

View File

@@ -0,0 +1,17 @@
package com.kelp.framework.exception;
import com.kelp.common.exception.BaseException;
public class E_NOLoginException extends BaseException {
/**
*
*/
private static final long serialVersionUID = 1L;
public E_NOLoginException(String code,String msg) {
super(code, msg);
}
}

View File

@@ -0,0 +1,16 @@
package com.kelp.framework.exception;
import com.kelp.common.exception.BaseException;
public class M_NOGrantException extends BaseException {
/**
*
*/
private static final long serialVersionUID = 1L;
public M_NOGrantException(String code,String msg) {
super(code, msg);
}
}

View File

@@ -0,0 +1,16 @@
package com.kelp.framework.exception;
import com.kelp.common.exception.BaseException;
public class M_NOLoginException extends BaseException {
/**
*
*/
private static final long serialVersionUID = 1L;
public M_NOLoginException(String code,String msg) {
super(code, msg);
}
}

View File

@@ -0,0 +1,16 @@
package com.kelp.framework.exception;
import com.kelp.common.exception.BaseException;
public class P_NOGrantException extends BaseException {
/**
*
*/
private static final long serialVersionUID = 1L;
public P_NOGrantException(String code,String msg) {
super(code, msg);
}
}

View File

@@ -0,0 +1,16 @@
package com.kelp.framework.exception;
import com.kelp.common.exception.BaseException;
public class P_NOLoginException extends BaseException {
/**
*
*/
private static final long serialVersionUID = 1L;
public P_NOLoginException(String code,String msg) {
super(code, msg);
}
}

View File

@@ -0,0 +1,142 @@
/**
* 解决nginx负载均衡问题
*/
package com.kelp.framework.interceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.kelp.common.config.RedisBean;
import com.kelp.common.constant.KeyConstant;
import com.kelp.common.utils.AuthenticationBean;
import com.kelp.common.utils.CookieUtil;
import com.kelp.common.utils.jwt.JwtUtil;
import com.kelp.framework.exception.E_NOGrantException;
import com.kelp.framework.exception.E_NOLoginException;
import com.kelp.plat.service.E_RFService;
import com.opensymphony.oscache.util.StringUtil;
public class EInterceptor extends HandlerInterceptorAdapter{
private static Logger log = LoggerFactory.getLogger(EInterceptor.class);
@Autowired
private RedisBean redisBean;
@Resource
private E_RFService rfService;
@Value("${token.alive.time}")
private int tokenLiveCount;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("enterprise interceptor ----- ");
String url = request.getRequestURL().toString();
if (url.lastIndexOf("crm") > 0) {
url = url.substring(url.lastIndexOf("crm") - 1);
}
System.out.println("enterprise u r accessing : " + url);
log.error("enterprise u r accessing : " + url);
String token = CookieUtil.getCookie(request, "token");
//如果没有token则没有登录
if(StringUtil.isEmpty(token)){
log.error("accessed without token.");
throw new E_NOLoginException("EL-001","accessed without token.");
}
//验证token是否合法不合法则登录
if(!JwtUtil.verify(token, KeyConstant.JWTKEY)){
System.out.println("the token is : expired...");
log.error("the token is : expired...");
throw new E_NOLoginException("EL-002","the token has expired.");
}
String accountId = JwtUtil.getId(token);
String host = JwtUtil.getHost(token);
//判断是否在另外的设备上登录
if(!request.getSession().getId().equals(host)){
System.out.println("u were logined on anather device.");
log.error("u logined on anather device.");
throw new E_NOLoginException("EL-003","u logined on anather device.");
}
//如果redis中没有本次访问的token或本次访问的token与redis中不同
if(null == redisBean.hget(accountId, "e_token") || !redisBean.hget(accountId, "e_token").equals(token)){
System.out.println("there is no token in redis.");
log.error("there is no token in redis.");
throw new E_NOLoginException("EL-004","the token don't match token in at.");
}
//从redis中获取departmentId
String departmentId = redisBean.hget(accountId, "e_department");
//如果没有找到,则视为没有登录
if(departmentId == null){
System.out.println("ur department is not valid.");
log.error("ur department is not valid.");
throw new E_NOLoginException("EL-005","the token of department has expired.");
}
//从redis中获取roleId
String roleId = redisBean.hget(accountId, "e_role");
//如果没有找到,则视为没有登录
if(roleId == null){
System.out.println("ur role is not valid.");
log.error("ur role is not valid.");
throw new E_NOLoginException("EL-006","the token of role has expired.");
}
//判断此account在本系统中的权限
if(!AuthenticationBean.getERfMap().containsKey(roleId)){
AuthenticationBean.getERfMap().put(roleId, rfService.getSRFs(roleId));
}
if(!AuthenticationBean.getERfMap().get(roleId).containsKey(url)){
System.out.println(url +",u r not granted to access this url.");
log.error("u r not granted to access this url.");
throw new E_NOGrantException("EG-001","u r not granted to access this url.");
}
//更新token
token = JwtUtil.sign(accountId, request.getSession().getId(), KeyConstant.JWTKEY);
//更新redis
redisBean.hset(accountId, "e_token",token);
redisBean.hset(accountId, "e_role",roleId);
redisBean.hset(accountId, "e_department",departmentId);
//更新cookie
CookieUtil.editCookie(request, response, "token", token);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
super.afterCompletion(request, response, handler, ex);
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
}

View File

@@ -0,0 +1,158 @@
/**
* 解决nginx负载均衡问题plat 小程序使用的API
*/
package com.kelp.framework.interceptor;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kelp.common.config.RedisBean;
import com.kelp.common.constant.KeyConstant;
import com.kelp.common.utils.AuthenticationBean;
import com.kelp.common.utils.jwt.JwtUtil;
import com.kelp.framework.palt.entity.KError;
import com.kelp.plat.service.RFService;
import com.opensymphony.oscache.util.StringUtil;
public class PApiInterceptor extends HandlerInterceptorAdapter{
private static Logger log = LoggerFactory.getLogger(PApiInterceptor.class);
@Autowired
private RedisBean redisBean;
@Resource
private RFService rfService;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("plat api interceptor ----- ");
String url = request.getRequestURL().toString();
//放行不需要登录的
if (url.lastIndexOf("api/p/n/") > 0) {
url = url.substring(url.lastIndexOf("api/p/n/") - 1);
System.out.println("plat api u r accessing : " + url);
return true;
}
if (url.lastIndexOf("api/p/") > 0) {
url = url.substring(url.lastIndexOf("api/p/") - 1);
}
System.out.println("plat api u r accessing : " + url);
log.error("plat u r accessing : " + url);
String token = request.getHeader("token");
System.out.println("token ===== " + token);
//如果没有token则没有登录
if(StringUtil.isEmpty(token)){
error(response, "10", "the token is invalid.");
System.out.println("the token is invalid.");
log.error("accessed without token.");
return false;
}
//验证token是否合法不合法则登录
if(!JwtUtil.verify(token, KeyConstant.JWTKEY)){
error(response, "11", "the token is : expired...");
System.out.println("the token is : expired...");
log.error("the token is : expired...");
return false;
}
String accountId = JwtUtil.getId(token);
//判断是否在另外的设备上登录,由于微信有可能出错,这里不再判断
// if(!request.getSession().getId().equals(host)){
// error(response, "12", "u were logined on anather device.");
// System.out.println("u were logined on anather device.");
// log.error("u were logined on anather device.");
// return false;
// }
//如果redis中没有本次访问的token或本次访问的token与redis中不同
if(null == redisBean.hget(accountId, "p_token") || !redisBean.hget(accountId, "p_token").equals(token)){
error(response, "13", "there is no token in redis.");
System.out.println("there is no token in redis.");
log.error("there is no token in redis.");
return false;
}
//从redis中获取roleId
String roleId = redisBean.hget(accountId, "p_role");
//如果没有找到,则视为没有登录
if(roleId == null){
error(response, "14", "ur role is not valid.");
System.out.println("ur role is not valid.");
log.error("ur role is not valid.");
return false;
}
//判断此account在本系统中的权限
if(!AuthenticationBean.getPRfMap().containsKey(roleId)){
AuthenticationBean.getPRfMap().put(roleId, rfService.getSRFs(roleId));
}
if(!AuthenticationBean.getPRfMap().get(roleId).containsKey(url)){
error(response, "15", "u r not granted to access this url.");
System.out.println(url +",u r not granted to access this url.");
log.error("u r not granted to access this url.");
return false;
}
//更新token
token = JwtUtil.sign(accountId, request.getSession().getId(), KeyConstant.JWTKEY);
//更新redis
redisBean.hset(accountId, "p_token",token);
redisBean.hset(accountId, "p_role",roleId);
//更新header
response.setHeader("token", token);
return true;
}
private void error(HttpServletResponse response, String code, String message) throws IOException {
KError rst = new KError();
rst.setCode(code);
rst.setMessage(message);
response.setContentType("application/json");
PrintWriter out = response.getWriter();
ObjectMapper mapper = new ObjectMapper();
String jsonOfRST = "{\"error\":" + mapper.writeValueAsString(rst) + "}";
out.print(jsonOfRST);
out.flush();
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
super.afterCompletion(request, response, handler, ex);
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
}

View File

@@ -0,0 +1,153 @@
/**
* 解决nginx负载均衡问题
*/
package com.kelp.framework.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.kelp.common.config.RedisBean;
import com.kelp.common.constant.KeyConstant;
import com.kelp.common.utils.AuthenticationBean;
import com.kelp.common.utils.CookieUtil;
import com.kelp.common.utils.jwt.JwtUtil;
import com.kelp.framework.exception.P_NOGrantException;
import com.kelp.framework.exception.P_NOLoginException;
import com.kelp.plat.service.RFService;
import com.opensymphony.oscache.util.StringUtil;
public class PInterceptor extends HandlerInterceptorAdapter{
private static Logger log = LoggerFactory.getLogger(PInterceptor.class);
@Autowired
private RedisBean redisBean;
@Autowired
private RFService rfService;
@Value("${token.alive.time}")
private int tokenLiveCount;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("mis interceptor ----- ");
String url = request.getRequestURL().toString();
if (url.lastIndexOf("plat") > 0) {
url = url.substring(url.lastIndexOf("plat") - 1);
}
System.out.println("mis u r accessing : " + url);
log.error("mis u r accessing : " + url);
String token = CookieUtil.getCookie(request, "token");
//如果没有token则没有登录
if(StringUtil.isEmpty(token)){
log.error("accessed without token.");
throw new P_NOLoginException("PL-001","accessed without token.");
}
//验证token是否合法不合法则登录
if(!JwtUtil.verify(token, KeyConstant.JWTKEY)){
System.out.println("the token is : expired...");
log.error("the token is : expired...");
throw new P_NOLoginException("PL-002","the token has expired.");
}
String accountId = JwtUtil.getId(token);
String host = JwtUtil.getHost(token);
//判断是否在另外的设备上登录
if(!request.getSession().getId().equals(host)){
System.out.println("u were logined on anather device.");
log.error("u logined on anather device.");
throw new P_NOLoginException("PL-003","u logined on anather device.");
}
//如果redis中没有本次访问的token或本次访问的token与redis中不同
String tc = redisBean.hget(accountId, "mis_token");
String tcb = redisBean.hget(accountId, "mis_token_backup");
if(tc == null || tcb == null) {
System.out.println("there is no token in redis.");
log.error("there is no token in redis.");
throw new P_NOLoginException("PL-004","the token don't match token in at.");
}
String []tcs = tc.split("\\|");
String []tcbs = tcb.split("\\|");
if(tcs.length != 2 || tcbs.length != 2 || (!tcs[0].equals(token) && !tcbs[0].equals(token))){
System.out.println("there is no token in redis.");
log.error("there is no token in redis.");
throw new P_NOLoginException("PL-004","the token don't match token in at.");
}
//从redis中获取roleId
String roleId = redisBean.hget(accountId, "mis_role");
//如果没有找到,则视为没有登录
if(roleId == null){
System.out.println("ur role is not valid.");
log.error("ur role is not valid.");
throw new P_NOLoginException("PL-005","the token of role has expired.");
}
//判断此account在本系统中的权限
if(!AuthenticationBean.getPRfMap().containsKey(roleId)){
AuthenticationBean.getPRfMap().put(roleId, rfService.getSRFs(roleId));
}
if(!AuthenticationBean.getPRfMap().get(roleId).containsKey(url)){
System.out.println(url +",u r not granted to access this url.");
log.error("u r not granted to access this url.");
throw new P_NOGrantException("PG-001","u r not granted to access this url.");
}
//前面半桶
int tokenLiveCount_ = Integer.valueOf(tcs[1]);
if(tokenLiveCount_ > (tokenLiveCount/2)) {
//更新redis
redisBean.hset(accountId, "mis_token",tcs[0] + "|" + (--tokenLiveCount_));
} else {
//更新token
token = JwtUtil.sign(accountId, request.getSession().getId(), KeyConstant.JWTKEY);
redisBean.hset(accountId, "mis_token",token + "|" + tokenLiveCount);
}
//另外半桶
int tokenLiveCount4Backup_ = Integer.valueOf(tcbs[1]);
if(tokenLiveCount4Backup_ > 0) {
redisBean.hset(accountId, "mis_token_backup",tcbs[0] + "|" + (--tokenLiveCount4Backup_));
} else {
redisBean.hset(accountId, "mis_token_backup",tcs[0] + "|" + tokenLiveCount_);
}
redisBean.hset(accountId, "mis_role",roleId);
//更新cookie
CookieUtil.editCookie(request, response, "token", token);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
super.afterCompletion(request, response, handler, ex);
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
}

View File

@@ -0,0 +1,32 @@
package com.kelp.framework.palt.entity;
public class KError {
/**
* 返回码
*/
private String code;
/**
* 返回消息
*/
private String message;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@@ -0,0 +1,216 @@
package com.kelp.framework.palt.entity;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import com.kelp.common.utils.Arith;
import com.kelp.common.utils.IpUtils;
import com.kelp.framework.palt.entity.server.Cpu;
import com.kelp.framework.palt.entity.server.Jvm;
import com.kelp.framework.palt.entity.server.Mem;
import com.kelp.framework.palt.entity.server.Sys;
import com.kelp.framework.palt.entity.server.SysFile;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;
/**
* 服务器相关信息
*
* @author kelp
*/
public class Server {
private static final int OSHI_WAIT_SECOND = 1000;
/**
* CPU相关信息
*/
private Cpu cpu = new Cpu();
/**
* 內存相关信息
*/
private Mem mem = new Mem();
/**
* JVM相关信息
*/
private Jvm jvm = new Jvm();
/**
* 服务器相关信息
*/
private Sys sys = new Sys();
/**
* 磁盘相关信息
*/
private List<SysFile> sysFiles = new LinkedList<SysFile>();
public Cpu getCpu() {
return cpu;
}
public void setCpu(Cpu cpu) {
this.cpu = cpu;
}
public Mem getMem() {
return mem;
}
public void setMem(Mem mem) {
this.mem = mem;
}
public Jvm getJvm() {
return jvm;
}
public void setJvm(Jvm jvm) {
this.jvm = jvm;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public List<SysFile> getSysFiles() {
return sysFiles;
}
public void setSysFiles(List<SysFile> sysFiles) {
this.sysFiles = sysFiles;
}
public void copyTo() throws Exception {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
setCpuInfo(hal.getProcessor());
setMemInfo(hal.getMemory());
setSysInfo();
setJvmInfo();
setSysFiles(si.getOperatingSystem());
}
/**
* 设置CPU信息
*/
private void setCpuInfo(CentralProcessor processor) {
// CPU信息
long[] prevTicks = processor.getSystemCpuLoadTicks();
Util.sleep(OSHI_WAIT_SECOND);
long[] ticks = processor.getSystemCpuLoadTicks();
long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
cpu.setCpuNum(processor.getLogicalProcessorCount());
cpu.setTotal(totalCpu);
cpu.setSys(cSys);
cpu.setUsed(user);
cpu.setWait(iowait);
cpu.setFree(idle);
}
/**
* 设置内存信息
*/
private void setMemInfo(GlobalMemory memory) {
mem.setTotal(memory.getTotal());
mem.setUsed(memory.getTotal() - memory.getAvailable());
mem.setFree(memory.getAvailable());
}
/**
* 设置服务器信息
*/
private void setSysInfo() {
Properties props = System.getProperties();
sys.setComputerName(IpUtils.getHostName());
sys.setComputerIp(IpUtils.getHostIp());
sys.setOsName(props.getProperty("os.name"));
sys.setOsArch(props.getProperty("os.arch"));
sys.setUserDir(props.getProperty("user.dir"));
}
/**
* 设置Java虚拟机
*/
private void setJvmInfo() throws UnknownHostException {
Properties props = System.getProperties();
jvm.setTotal(Runtime.getRuntime().totalMemory());
jvm.setMax(Runtime.getRuntime().maxMemory());
jvm.setFree(Runtime.getRuntime().freeMemory());
jvm.setVersion(props.getProperty("java.version"));
jvm.setHome(props.getProperty("java.home"));
}
/**
* 设置磁盘信息
*/
private void setSysFiles(OperatingSystem os) {
FileSystem fileSystem = os.getFileSystem();
OSFileStore[] fsArray = fileSystem.getFileStores();
for (OSFileStore fs : fsArray) {
long free = fs.getUsableSpace();
long total = fs.getTotalSpace();
long used = total - free;
SysFile sysFile = new SysFile();
sysFile.setDirName(fs.getMount());
sysFile.setSysTypeName(fs.getType());
sysFile.setTypeName(fs.getName());
sysFile.setTotal(convertFileSize(total));
sysFile.setFree(convertFileSize(free));
sysFile.setUsed(convertFileSize(used));
sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100));
sysFiles.add(sysFile);
}
}
/**
* 字节转换
*
* @param size 字节大小
* @return 转换后值
*/
public String convertFileSize(long size) {
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb) {
return String.format("%.1f GB", (float) size / gb);
} else if (size >= mb) {
float f = (float) size / mb;
return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
} else if (size >= kb) {
float f = (float) size / kb;
return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
} else {
return String.format("%d B", size);
}
}
}

View File

@@ -0,0 +1,88 @@
package com.kelp.framework.palt.entity.server;
import com.kelp.common.utils.Arith;
/**
* CPU相关信息
*
* @author kelp
*/
public class Cpu {
/**
* 核心数
*/
private int cpuNum;
/**
* CPU总的使用率
*/
private double total;
/**
* CPU系统使用率
*/
private double sys;
/**
* CPU用户使用率
*/
private double used;
/**
* CPU当前等待率
*/
private double wait;
/**
* CPU当前空闲率
*/
private double free;
public int getCpuNum() {
return cpuNum;
}
public void setCpuNum(int cpuNum) {
this.cpuNum = cpuNum;
}
public double getTotal() {
return Arith.round(Arith.mul(total, 100), 2);
}
public void setTotal(double total) {
this.total = total;
}
public double getSys() {
return Arith.round(Arith.mul(sys / total, 100), 2);
}
public void setSys(double sys) {
this.sys = sys;
}
public double getUsed() {
return Arith.round(Arith.mul(used / total, 100), 2);
}
public void setUsed(double used) {
this.used = used;
}
public double getWait() {
return Arith.round(Arith.mul(wait / total, 100), 2);
}
public void setWait(double wait) {
this.wait = wait;
}
public double getFree() {
return Arith.round(Arith.mul(free / total, 100), 2);
}
public void setFree(double free) {
this.free = free;
}
}

View File

@@ -0,0 +1,92 @@
package com.kelp.framework.palt.entity.server;
import java.lang.management.ManagementFactory;
import com.kelp.common.utils.Arith;
/**
* JVM相关信息
*
* @author kelp
*/
public class Jvm {
/**
* 当前JVM占用的内存总数(M)
*/
private double total;
/**
* JVM最大可用内存总数(M)
*/
private double max;
/**
* JVM空闲内存(M)
*/
private double free;
/**
* JDK版本
*/
private String version;
/**
* JDK路径
*/
private String home;
public double getTotal() {
return Arith.div(total, (1024 * 1024), 2);
}
public void setTotal(double total) {
this.total = total;
}
public double getMax() {
return Arith.div(max, (1024 * 1024), 2);
}
public void setMax(double max) {
this.max = max;
}
public double getFree() {
return Arith.div(free, (1024 * 1024), 2);
}
public void setFree(double free) {
this.free = free;
}
public double getUsed() {
return Arith.div(total - free, (1024 * 1024), 2);
}
public double getUsage() {
return Arith.mul(Arith.div(total - free, total, 4), 100);
}
/**
* 获取JDK名称
*/
public String getName() {
return ManagementFactory.getRuntimeMXBean().getVmName();
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
}

View File

@@ -0,0 +1,53 @@
package com.kelp.framework.palt.entity.server;
import com.kelp.common.utils.Arith;
/**
* 內存相关信息
*
* @author kelp
*/
public class Mem {
/**
* 内存总量
*/
private double total;
/**
* 已用内存
*/
private double used;
/**
* 剩余内存
*/
private double free;
public double getTotal() {
return Arith.div(total, (1024 * 1024 * 1024), 2);
}
public void setTotal(long total) {
this.total = total;
}
public double getUsed() {
return Arith.div(used, (1024 * 1024 * 1024), 2);
}
public void setUsed(long used) {
this.used = used;
}
public double getFree() {
return Arith.div(free, (1024 * 1024 * 1024), 2);
}
public void setFree(long free) {
this.free = free;
}
public double getUsage() {
return Arith.mul(Arith.div(used, total, 4), 100);
}
}

View File

@@ -0,0 +1,73 @@
package com.kelp.framework.palt.entity.server;
/**
* 系统相关信息
*
* @author kelp
*/
public class Sys {
/**
* 服务器名称
*/
private String computerName;
/**
* 服务器Ip
*/
private String computerIp;
/**
* 项目路径
*/
private String userDir;
/**
* 操作系统
*/
private String osName;
/**
* 系统架构
*/
private String osArch;
public String getComputerName() {
return computerName;
}
public void setComputerName(String computerName) {
this.computerName = computerName;
}
public String getComputerIp() {
return computerIp;
}
public void setComputerIp(String computerIp) {
this.computerIp = computerIp;
}
public String getUserDir() {
return userDir;
}
public void setUserDir(String userDir) {
this.userDir = userDir;
}
public String getOsName() {
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public String getOsArch() {
return osArch;
}
public void setOsArch(String osArch) {
this.osArch = osArch;
}
}

View File

@@ -0,0 +1,99 @@
package com.kelp.framework.palt.entity.server;
/**
* 系统文件相关信息
*
* @author kelp
*/
public class SysFile {
/**
* 盘符路径
*/
private String dirName;
/**
* 盘符类型
*/
private String sysTypeName;
/**
* 文件类型
*/
private String typeName;
/**
* 总大小
*/
private String total;
/**
* 剩余大小
*/
private String free;
/**
* 已经使用量
*/
private String used;
/**
* 资源的使用率
*/
private double usage;
public String getDirName() {
return dirName;
}
public void setDirName(String dirName) {
this.dirName = dirName;
}
public String getSysTypeName() {
return sysTypeName;
}
public void setSysTypeName(String sysTypeName) {
this.sysTypeName = sysTypeName;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getFree() {
return free;
}
public void setFree(String free) {
this.free = free;
}
public String getUsed() {
return used;
}
public void setUsed(String used) {
this.used = used;
}
public double getUsage() {
return usage;
}
public void setUsage(double usage) {
this.usage = usage;
}
}

View File

@@ -0,0 +1,80 @@
/**
* webservice调用类,axis xml
*
* SOAP 1.1为text/xml 1.2为 application/soap+xml
*/
package com.kelp.framework.util.ws;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
public class WS4AxisUtil {
private static Logger log = LoggerFactory.getLogger(WS4AxisUtil.class);
/**
* axis传递xml方式调用
*
* @param wsdlUrl - wsdl路径
* @param namespace
* @param localPart -入口参数名称
* @param method
* @param xmlData - 只需要从参数部分开始的XML内容
* @return
*/
public static JSONObject xmlPost(String wsdlUrl, String namespace, String localPart, String method,
String xmlData) {
try {
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new URL(wsdlUrl));
// 命名空间和调用接口的方法名
call.setOperationName(new QName(namespace, method));
call.setSOAPActionURI(namespace + method);
call.setUseSOAPAction(true);
call.addParameter(new QName(namespace, localPart), XMLType.XSD_STRING, ParameterMode.IN);// 可多个.addParameterMode
// 设置返回类型
call.setReturnType(XMLType.XSD_STRING);
// 使用invoke调用方法Object数据放传入的参数值可多个
Object object = call.invoke(new Object[] { xmlData });
return JSONObject.fromObject(new XMLSerializer().read(object.toString()).toString());
} catch (Exception e) {
log.error(e.toString());
return null;
}
}
public static void main(String[] args) {
String aa = "<Request>" + " <TransactionCode>4201</TransactionCode>" + " <ExtUserID>12580</ExtUserID>"
+ " <ExtUserPwd>12580</ExtUserPwd>" + " <ExtOrgCode>12580</ExtOrgCode>" + " <Param>"
+ " <HospitalBranchHisId>1</HospitalBranchHisId>" + " <Type>0</Type>"
+ " <StartDate>2015-01-01</StartDate>" + " <EndDate>2015-01-08</EndDate>" + "</Param>"
+ "</Request>";
try {
JSONObject ressult = xmlPost("http://jzysjc.ticp.net:20098/WebService1.asmx?wsdl", "http://tempuri.org/",
"strXml", "testMethod", aa);
System.out.println("返回的json结果:" + ressult);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,173 @@
/**
* webservice接口,post xml
*
* SOAP 1.1为text/xml ; 1.2为 application/soap+xml
*/
package com.kelp.framework.util.ws;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.NameValuePair;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
public class WS4HttpUtil {
private static Logger log = LoggerFactory.getLogger(WS4HttpUtil.class);
/**
* http post xml的方式调用(map方式)
*
* @param url - 必须加方法名
* @param namespace
* @param method
* @param xmlData - 加soap协议部分的XML内容
* @return
*/
public static JSONObject xmlMap4Http(String url, String namespace, String method, String xmlData) {
String result = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost(url);
try {
List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
NameValuePair nvp = new BasicNameValuePair("requestXml", xmlData);
nvpList.add(nvp);
httpPost.setEntity(new UrlEncodedFormEntity(nvpList, "UTF-8"));
response = httpclient.execute(httpPost);
if (response != null) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
log.error(e.toString());
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
if (httpclient != null)
httpclient.close();
} catch (IOException e) {
log.error(e.toString());
}
}
if (result.length() == 0) {
return null;
}
return JSONObject.fromObject(new XMLSerializer().read(StringEscapeUtils.unescapeXml(result)).toString());
}
/**
* xml url调用方式
*
* @param url - 不带方法名
* @param namespace
* @param method
* @param xmlData - 其中的参数部分必须转义,在这里推荐commons-lang.jar中的StringEscapeUtils类
* @return - 返回值必须反转义,在这里推荐commons-lang.jar中的StringEscapeUtils类
*/
public static JSONObject xml4Url(String url, String namespace, String method, String xmlData) {
try {
URL url_ = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url_.openConnection();
connection.setRequestProperty("Content-Length", String.valueOf(xmlData.getBytes("UTF-8").length));
connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
connection.setRequestProperty("soapActionString", namespace + method);
connection.setRequestMethod("POST");
connection.setConnectTimeout(1 * 60 * 1000);
connection.setReadTimeout(1 * 60 * 1000);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(xmlData.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byte[] data = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
inputStream.close();
return JSONObject.fromObject(
new XMLSerializer().read(StringEscapeUtils.unescapeXml(new String(data))).toString());
}
} catch (Exception e) {
log.error(e.toString());
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String aa = "<Request>" + " <TransactionCode>4201</TransactionCode>" + " <ExtUserID>12580</ExtUserID>"
+ " <ExtUserPwd>12580</ExtUserPwd>" + " <ExtOrgCode>12580</ExtOrgCode>" + " <Param>"
+ " <HospitalBranchHisId>1</HospitalBranchHisId>" + " <Type>0</Type>"
+ " <StartDate>2015-01-01</StartDate>" + " <EndDate>2015-01-08</EndDate>" + "</Param>"
+ "</Request>";
String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ " <soap:Body>" + " <testMethod xmlns=\"http://tempuri.org/\">" + " <requestXml>"
+ StringEscapeUtils.escapeXml(aa) + "</requestXml>" + // 注意这里需要对参数部分进行转义
" </testMethod>" + " </soap:Body>" + "</soap:Envelope>";
try {
JSONObject post = xmlMap4Http("http://jzysjc.ticp.net:20098/WebService1.asmx/testMethod",
"http://tempuri.org/", "testMethod", soap);
System.out.println("---------------------" + post);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,23 @@
package com.kelp.framework.util.wx;
import com.kelp.common.utils.http.HttpUtil;
import net.sf.json.JSONObject;
public class WXUtil {
public static String getOpenId(String appId, String appSecret, String wxUrl, String code) {
String url = wxUrl + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code
+ "&grant_type=authorization_code";
JSONObject json = JSONObject.fromObject(HttpUtil.https(url, "POST", null, "UTF-8"));
if (json.get("openid") != null) {
return json.getString("openid");
}
return null;
}
}