Commit d11ac25f authored by 黄福新's avatar 黄福新

[add] 新增wj-common

parent feab5fb7
...@@ -3,16 +3,468 @@ ...@@ -3,16 +3,468 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <parent>
<artifactId>traffic-signal-platform</artifactId>
<groupId>net.wanji</groupId>
<version>0.2.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>net.wanji</groupId> <groupId>net.wanji</groupId>
<artifactId>wj-common</artifactId> <artifactId>wj-common</artifactId>
<version>0.2.1</version> <version>1.0.0</version>
<name>wj-common</name> <name>wj-common</name>
<description>wj-common</description>
<!-- 依赖版本 -->
<properties>
<hibernate.version>6.0.14.Final</hibernate.version>
<el.version>3.0.0</el.version>
<ignite.version>2.8.1</ignite.version>
<mail.version>1.5.2</mail.version>
<fastjson.version>1.2.56</fastjson.version>
<dom4j.version>1.6.1</dom4j.version>
<ws.rs.version>2.1.1</ws.rs.version>
<dubbo.version>2.1.1.RELEASE</dubbo.version>
<swagger.version>2.8.0</swagger.version>
</properties>
<description> <dependencies>
wj-common <!--rest参数校验 start -->
</description> <dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${el.version}</version>
</dependency>
<!--rest参数校验 end -->
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-core</artifactId>
<version>${ignite.version}</version>
</dependency>
<!-- mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>${mail.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
<!--es start-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.8.5</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.8.5</version>
</dependency>
<!--es end-->
<!-- Excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<!--ehcache-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- xml转json -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>${dom4j.version}</version>
</dependency>
<!--restful 注解-->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${ws.rs.version}</version>
</dependency>
<!--provided没有传递性-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--spring boot-->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<!--common resttool使用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-logging</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!--热加载用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!--log4j2 日志实现-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jul</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jul</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.apache.logging.log4j</groupId>-->
<!--<artifactId>log4j-slf4j-impl</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--dubbo依赖,各个微服务都有-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
<version>${dubbo.version}</version>
</dependency>
<!--spring start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!--spring end-->
<!--curator start-->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>2.12.0</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
<exclusion>
<artifactId>netty</artifactId>
<groupId>io.netty</groupId>
</exclusion>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<!--curator end-->
<!--lombok start-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--lombok end-->
<dependency>
<groupId>com.alipay.jarslink</groupId>
<artifactId>jarslink-api</artifactId>
<version>1.6.1.20180301</version>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<exclusions>
<exclusion>
<artifactId>javassist</artifactId>
<groupId>org.javassist</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<!--groovy-->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.12</version>
</dependency>
<!--SQLServer-->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!--任务调度器-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--zip4j压缩和解压-->
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- MP相关 start -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus-version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus-version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${mybatis-plus-version}</version>
</dependency>
<!-- MP相关 end -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
<scope>compile</scope>
</dependency>
<!--jftp xfile-->
<dependency>
<groupId>org.objectweb.joram</groupId>
<artifactId>jftp</artifactId>
<version>1.52</version>
</dependency>
<!--FastDFS -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.27.2</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- rabbitmq -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.9.0</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20200518</version>
</dependency>
<dependency>
<groupId>com.googlecode.aviator</groupId>
<artifactId>aviator</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<version>7.41.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>7.41.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>7.41.0.Final</version>
</dependency>
<dependency>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-core</artifactId>
<version>1.18.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-geojson</artifactId>
<version>26.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/eu.bitwalker/UserAgentUtils -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
</dependency>
<!--Jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.8</version>
</dependency>
<!-- curl工具 -->
<dependency>
<groupId>org.toile-libre.libe</groupId>
<artifactId>curl</artifactId>
<version>LATEST</version>
</dependency>
</dependencies>
</project> </project>
\ No newline at end of file
package com.wanji.common.action;
import com.wanji.common.annotation.ActionBean;
import com.wanji.common.annotation.ActionMethod;
import com.wanji.common.annotation.ActionMethodParameter;
import com.wanji.common.enums.Datatype;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;
/**
* <>
*
* @author wanji
* 2020/6/21 0:33
*/
@Slf4j
public class BuiltInActionLibraryUtils {
private static List<SpringBean> springBeans;
private static List<Class<?>> builtInClass;
static {
springBeans = Lists.newArrayList();
builtInClass = Lists.newArrayList();
builtInClass.add(DateAction.class);
builtInClass.add(StringAction.class);
}
/**
* 获取内置方法
*
* @return List
*/
public static List<SpringBean> getBuiltInActions() {
return BuiltInActionLibraryUtils.springBeans;
}
public static void init() {
BuiltInActionLibraryUtils.springBeans.clear();
for (Class<?> clazz : BuiltInActionLibraryUtils.builtInClass) {
ActionBean annotation = clazz.getAnnotation(ActionBean.class);
if (Objects.isNull(annotation)) {
return;
}
SpringBean springBean = new SpringBean();
springBean.setName(clazz.getSimpleName());
springBean.setLabel(annotation.name());
springBean.setPath(clazz.getName());
springBean.setMethods(buildMethods(clazz.getMethods()));
BuiltInActionLibraryUtils.springBeans.add(springBean);
}
}
/**
* 构建内置方法
*
* @param methods 反射的方法数组
* @return List
*/
private static List<Method> buildMethods(java.lang.reflect.Method[] methods) {
List<Method> methodList = org.apache.commons.compress.utils.Lists.newArrayList();
for (java.lang.reflect.Method method : methods) {
ActionMethod methodAnnotation = method.getAnnotation(ActionMethod.class);
if (Objects.isNull(methodAnnotation)) {
continue;
}
//返回值类型
AnnotatedType annotatedReturnType = method.getAnnotatedReturnType();
String methodName = method.getName();
Method builtInMethod = new Method();
builtInMethod.setMethodName(methodName);
builtInMethod.setLabel(methodAnnotation.name());
if (Objects.nonNull(annotatedReturnType)) {
try {
Type type = annotatedReturnType.getType();
Datatype datatype = Datatype.Object;
if (type instanceof Class) {
datatype = buildDatatype((Class<?>) type);
} else if (type instanceof ParameterizedTypeImpl) {
datatype = buildDatatype(((ParameterizedTypeImpl) type).getRawType());
}
builtInMethod.setDatatype(datatype.name());
} catch (Exception e) {
log.error("初始化内置方法异常", e);
}
}
methodList.add(builtInMethod);
ActionMethodParameter methodParam = method.getAnnotation(ActionMethodParameter.class);
List<String> parameterNames = org.apache.commons.compress.utils.Lists.newArrayList();
if (Objects.nonNull(methodParam)) {
String[] paramNames = methodParam.names();
Collections.addAll(parameterNames, paramNames);
}
builtInMethod.setParameters(buildParameters(method, parameterNames));
}
return methodList;
}
/**
* 构建内置方法的参数集合
*
* @param method 反射的方法
* @param parameterNames 参数名
* @return
*/
private static List<Parameter> buildParameters(java.lang.reflect.Method method, List<String> parameterNames) {
List<Parameter> parameters = org.apache.commons.compress.utils.Lists.newArrayList();
Class<?>[] paramClasses = method.getParameterTypes();
for (int i = 0; i < paramClasses.length; i++) {
Class<?> paramClass = paramClasses[i];
String name = "";
if (parameterNames.size() > i) {
name = parameterNames.get(i);
}
Parameter parameter = new Parameter();
parameter.setLabel(name);
parameter.setDatatype(buildDatatype(paramClass).name());
parameters.add(parameter);
}
return parameters;
}
/**
* 构建数据类型
*
* @param clazz
* @return Datatype
*/
private static Datatype buildDatatype(Class<?> clazz) {
if ("java.lang.Object".equals(clazz.getName())) {
return Datatype.Object;
}
if (clazz.isAssignableFrom(Integer.class) || clazz.isAssignableFrom(int.class)) {
return Datatype.Integer;
} else if (clazz.isAssignableFrom(Long.class) || clazz.isAssignableFrom(long.class)) {
return Datatype.Long;
} else if (clazz.isAssignableFrom(Double.class) || clazz.isAssignableFrom(double.class)) {
return Datatype.Double;
} else if (clazz.isAssignableFrom(Float.class) || clazz.isAssignableFrom(float.class)) {
return Datatype.Float;
} else if (clazz.isAssignableFrom(BigDecimal.class)) {
return Datatype.BigDecimal;
} else if (clazz.isAssignableFrom(Boolean.class) || clazz.isAssignableFrom(boolean.class)) {
return Datatype.Boolean;
} else if (clazz.isAssignableFrom(Date.class)) {
return Datatype.Date;
} else if (clazz.isAssignableFrom(List.class)) {
return Datatype.List;
} else if (clazz.isAssignableFrom(Set.class)) {
return Datatype.Set;
} else if (clazz.isAssignableFrom(Enum.class)) {
return Datatype.Enum;
} else if (clazz.isAssignableFrom(Map.class)) {
return Datatype.Map;
} else if (clazz.isAssignableFrom(String.class)) {
return Datatype.String;
} else if (clazz.isAssignableFrom(Character.class) || clazz.isAssignableFrom(char.class)) {
return Datatype.Char;
} else {
return Datatype.Object;
}
}
}
package com.wanji.common.action;
import com.wanji.common.annotation.ActionBean;
import com.wanji.common.annotation.ActionMethod;
import com.wanji.common.annotation.ActionMethodParameter;
import org.apache.commons.lang3.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* <>
*
* @author wanji
* 2020/6/7 16:59
*/
@ActionBean(name = "日期")
public class DateAction {
@ActionMethod(name = "当前日期字符串")
@ActionMethodParameter(names = {})
public static String getDateStr() {
return format(new Date(), "yyyy-MM-dd");
}
@ActionMethod(name = "格式化当前日期字符串")
@ActionMethodParameter(names = {"格式"})
public static String getFormatDateStr(String format) {
if (StringUtils.isBlank(format)) {
format = "yyyy-MM-dd";
}
return format(new Date(), format);
}
@ActionMethod(name = "当前日期")
@ActionMethodParameter(names = {})
public static Date getDate() {
return new Date();
}
@ActionMethod(name = "取指定月份天数")
@ActionMethodParameter(names = {"开始日期", "结束日期", "月份"})
public static int buildIncludeMonthDays(Object startDate, Object endDate, String months) {
return DateAction.buildIncludeMonthDays(startDate, endDate, months, true);
}
@ActionMethod(name = "取非指定月份天数")
@ActionMethodParameter(names = {"开始日期", "结束日期", "月份"})
public int buildExcludeMonthDays(Object startDate, Object endDate, String months) {
return DateAction.buildIncludeMonthDays(startDate, endDate, months, false);
}
@ActionMethod(name = "取指定月份天数")
@ActionMethodParameter(names = {"开始日期", "结束日期", "月份"})
private static int buildIncludeMonthDays(Object startDateObj, Object endDateObj, String month, boolean in) {
if (Objects.isNull(startDateObj)) {
throw new RuntimeException("开始日期不能为空!");
}
if (Objects.isNull(endDateObj)) {
throw new RuntimeException("开始日期不能为空!");
}
Date startDate = DateAction.parse(startDateObj);
Date endDate = DateAction.parse(endDateObj);
if (startDate.compareTo(endDate) > 0) {
throw new RuntimeException("开始日期必须要小于结束日期!");
}
int inDay = 0;
int notInDay = 0;
String[] months = month.split(",");
List<String> monthList = Arrays.asList(months);
Calendar calendar;
for (; startDate.compareTo(endDate) <= 0; startDate = calendar.getTime()) {
calendar = Calendar.getInstance();
calendar.setTime(startDate);
int startMonth = calendar.get(Calendar.MONTH) + 1;
if (monthList.contains(String.valueOf(startMonth))) {
if (in) {
++inDay;
}
} else if (!in) {
++notInDay;
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
if (in) {
return inDay;
} else {
return notInDay;
}
}
private static Date parse(Object obj) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
if (obj instanceof Date) {
Date date = (Date) obj;
String format = simpleDateFormat.format(date);
try {
return simpleDateFormat.parse(format);
} catch (ParseException e) {
throw new RuntimeException(e);
}
} else {
String str = obj.toString();
try {
return simpleDateFormat.parse(str);
} catch (ParseException var8) {
simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
try {
return simpleDateFormat.parse(str);
} catch (ParseException e) {
throw new RuntimeException("不能将[" + e + "]解析成日期");
}
}
}
}
@ActionMethod(name = "解析字符串为日期")
@ActionMethodParameter(names = {"日期字符串", "格式"})
public static Date formatString(String dateStr, String format) {
if (StringUtils.isBlank(dateStr)) {
return null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return sdf.parse(dateStr);
} catch (ParseException var5) {
throw new RuntimeException(var5);
}
}
}
@ActionMethod(name = "格式化日期")
@ActionMethodParameter(names = {"目标日期", "格式"})
public static String format(Date date, String format) {
if (date == null) {
return null;
} else {
SimpleDateFormat var3 = new SimpleDateFormat(format);
return var3.format(date);
}
}
@ActionMethod(name = "加日期")
@ActionMethodParameter(names = {"目标日期", "年数", "月数", "天数", "小时", "分钟", "秒数"})
public static Date addDate(Date date, int year, int month, int day, int hour, int minute, int second) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR, year);
calendar.add(Calendar.MONTH, month);
calendar.add(Calendar.DAY_OF_MONTH, day);
calendar.add(Calendar.HOUR_OF_DAY, hour);
calendar.add(Calendar.MINUTE, minute);
calendar.add(Calendar.SECOND, second);
return calendar.getTime();
}
}
@ActionMethod(name = "日期加年")
@ActionMethodParameter(names = {"目标日期", "年数"})
public static Date addDateForYear(Date date, int year) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR, year);
return calendar.getTime();
}
}
@ActionMethod(name = "日期加月")
@ActionMethodParameter(names = {"目标日期", "月数"})
public static Date addDateForMonth(Date date, int month) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, month);
return calendar.getTime();
}
}
@ActionMethod(name = "日期加天")
@ActionMethodParameter(names = {"目标日期", "天数"})
public static Date addDateForDay(Date date, int day) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, day);
return calendar.getTime();
}
}
@ActionMethod(name = "日期加小时")
@ActionMethodParameter(names = {"目标日期", "小时数"})
public static Date addDateForHour(Date date, int hour) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hour);
return calendar.getTime();
}
}
@ActionMethod(name = "日期加分钟")
@ActionMethodParameter(names = {"目标日期", "分钟数"})
public static Date addDateForMinute(Date date, int minute) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, minute);
return calendar.getTime();
}
}
@ActionMethod(name = "日期加秒")
@ActionMethodParameter(names = {"目标日期", "秒数"})
public static Date addDateForSecond(Date date, int second) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, second);
return calendar.getTime();
}
}
@ActionMethod(name = "减日期")
@ActionMethodParameter(names = {"目标日期", "年数", "月数", "天数", "小时", "分钟", "秒数"})
public static Date subDate(Date date, int year, int month, int day, int hour, int minute, int second) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR, -year);
calendar.add(Calendar.MONTH, -month);
calendar.add(Calendar.DAY_OF_MONTH, -day);
calendar.add(Calendar.HOUR_OF_DAY, -hour);
calendar.add(Calendar.MINUTE, -minute);
calendar.add(Calendar.SECOND, -second);
return calendar.getTime();
}
}
@ActionMethod(name = "减日期减年")
@ActionMethodParameter(names = {"目标日期", "年数"})
public static Date subDateForYear(Date date, int year) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR, -year);
return calendar.getTime();
}
}
@ActionMethod(name = "减日期减月")
@ActionMethodParameter(names = {"目标日期", "月数"})
public static Date subDateForMonth(Date date, int month) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, -month);
return calendar.getTime();
}
}
@ActionMethod(name = "减日期减天")
@ActionMethodParameter(names = {"目标日期", "天数"})
public static Date subDateForDay(Date date, int day) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -day);
return calendar.getTime();
}
}
@ActionMethod(name = "减日期减小时")
@ActionMethodParameter(names = {"目标日期", "小时"})
public static Date subDateForHour(Date date, int hour) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, -hour);
return calendar.getTime();
}
}
@ActionMethod(name = "减日期减分钟")
@ActionMethodParameter(names = {"目标日期", "分钟"})
public static Date subDateForMinute(Date date, int minute) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, -minute);
return calendar.getTime();
}
}
@ActionMethod(name = "减日期减秒")
@ActionMethodParameter(names = {"目标日期", "秒数"})
public static Date subDateForSecond(Date date, int second) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, -second);
return calendar.getTime();
}
}
@ActionMethod(name = "取年份")
@ActionMethodParameter(names = {"目标日期"})
public static Integer getYear(Date date) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
}
@ActionMethod(name = "取月份")
@ActionMethodParameter(names = {"目标日期"})
public Integer getMonth(Date date) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH);
}
}
@ActionMethod(
name = "取星期"
)
@ActionMethodParameter(
names = {"目标日期"}
)
public static Integer getWeek(Date date) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
}
@ActionMethod(name = "取天")
@ActionMethodParameter(names = {"目标日期"})
public static Integer getDay(Date date) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH);
}
}
@ActionMethod(name = "取小时")
@ActionMethodParameter(names = {"目标日期"})
public static Integer getHour(Date date) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.HOUR_OF_DAY);
}
}
@ActionMethod(name = "取分钟")
@ActionMethodParameter(names = {"目标日期"})
public static Integer getMinute(Date date) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MINUTE);
}
}
@ActionMethod(name = "取秒")
@ActionMethodParameter(names = {"目标日期"})
public static Integer getSecond(Date date) {
if (date == null) {
return null;
} else {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.SECOND);
}
}
@ActionMethod(name = "日期相减返回秒")
@ActionMethodParameter(names = {"日期", "减去的日期"})
public static Long dateDifSecond(Date startDate, Date endDate) {
if (startDate != null && endDate != null) {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
long startMillis = startCalendar.getTimeInMillis();
long endMillis = endCalendar.getTimeInMillis();
return (startMillis - endMillis) / 1000L;
} else {
return null;
}
}
@ActionMethod(
name = "日期相减返回分钟"
)
@ActionMethodParameter(
names = {"日期", "减去的日期"}
)
public static Long dateDifMinute(Date startDate, Date endDate) {
if (startDate != null && endDate != null) {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
long startMillis = startCalendar.getTimeInMillis();
long endMillis = endCalendar.getTimeInMillis();
return (startMillis - endMillis) / 60000L;
} else {
return null;
}
}
@ActionMethod(name = "日期相减返回小时")
@ActionMethodParameter(names = {"日期", "减去的日期"})
public static Long dateDifHour(Date startDate, Date endDate) {
if (startDate != null && endDate != null) {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
long startMillis = startCalendar.getTimeInMillis();
long endMillis = endCalendar.getTimeInMillis();
return (startMillis - endMillis) / 3600000L;
} else {
return null;
}
}
@ActionMethod(name = "日期相减返回天")
@ActionMethodParameter(names = {"日期", "减去的日期"})
public static Long dateDifDay(Date startDate, Date endDate) {
if (startDate != null && endDate != null) {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
long startMillis = startCalendar.getTimeInMillis();
long endMillis = endCalendar.getTimeInMillis();
return (startMillis - endMillis) / 86400000L;
} else {
return null;
}
}
@ActionMethod(
name = "日期相减返回星期"
)
@ActionMethodParameter(
names = {"日期", "减去的日期"}
)
public static Long dateDifWeek(Date startDate, Date endDate) {
if (startDate != null && endDate != null) {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
long startMillis = startCalendar.getTimeInMillis();
long endMillis = endCalendar.getTimeInMillis();
return (startMillis - endMillis) / 604800000L;
} else {
return null;
}
}
@ActionMethod(name = "日期相减返回月")
@ActionMethodParameter(names = {"日期", "减去的日期"})
public Integer dateDifMonth(Date startDate, Date endDate) {
if (startDate != null && endDate != null) {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
int startYear = startCalendar.get(Calendar.YEAR);
int endYear = endCalendar.get(Calendar.YEAR);
int startMonth = startCalendar.get(Calendar.MONTH);
int endMonth = endCalendar.get(Calendar.MONTH);
return 12 * (startYear - endYear) + (startMonth - endMonth);
} else {
return null;
}
}
}
package com.wanji.common.action;
import com.wanji.common.enums.Datatype;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.compress.utils.Lists;
import java.util.List;
/**
* <>
*
* @author wanji
* 2020/6/7 21:50
*/
@Getter
@Setter
public class Method {
private String label;
private String methodName;
/**
* {@link Datatype}
*/
private String datatype;
private List<Parameter> parameters;
public void addParameter(Parameter parameter) {
if (this.parameters == null) {
this.parameters = Lists.newArrayList();
}
this.parameters.add(parameter);
}
}
package com.wanji.common.action;
import com.wanji.common.enums.Datatype;
import lombok.Getter;
import lombok.Setter;
/**
* <>
*
* @author wanji
* 2020/6/7 21:50
*/
@Getter
@Setter
public class Parameter {
/**
* 标签
*/
private String label;
/**
* {@link Datatype}
*/
private String datatype;
}
package com.wanji.common.action;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* <>
*
* @author wanji
* 2020/6/7 21:50
*/
@Getter
@Setter
public class SpringBean {
private String actionId;
private String name;
private String label;
private String path;
private List<Method> methods;
}
package com.wanji.common.action;
import com.wanji.common.annotation.ActionBean;
import com.wanji.common.annotation.ActionMethod;
import com.wanji.common.annotation.ActionMethodParameter;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* <>
*
* @author wanji
* 2020/6/11 17:42
*/
@ActionBean(name = "字符串")
public class StringAction {
@ActionMethod(name = "去空格")
@ActionMethodParameter(names = {"目标字符串"})
public static String trim(String str) {
return str == null ? str : str.trim();
}
@ActionMethod(name = "指定起始的字符串截取")
@ActionMethodParameter(names = {"目标字符串", "开始位置", "结束位置"})
public static String substring(String target, int start, int end) {
return target == null ? null : target.substring(start, end);
}
@ActionMethod(name = "指定开始的字符串截取")
@ActionMethodParameter(names = {"目标字符串", "开始位置"})
public static String substringForStart(String target, int start) {
return target == null ? null : target.substring(start);
}
@ActionMethod(name = "指定结束的字符串截取")
@ActionMethodParameter(names = {"目标字符串", "结束位置"})
public static String substringForEnd(String target, int end) {
return target == null ? null : target.substring(0, end);
}
@ActionMethod(name = "转小写")
@ActionMethodParameter(names = {"目标字符串"})
public static String toLowerCase(String target) {
return target == null ? null : target.toLowerCase();
}
@ActionMethod(name = "转大写")
@ActionMethodParameter(names = {"目标字符串"})
public static String toUpperCase(String target) {
return target == null ? null : target.toUpperCase();
}
@ActionMethod(name = "获取长度")
@ActionMethodParameter(names = {"目标字符串"})
public static Integer length(String target) {
return target == null ? null : target.length();
}
@ActionMethod(name = "获取字符")
@ActionMethodParameter(names = {"目标字符串", "位置"})
public static Character charAt(String target, int index) {
return target == null ? null : target.charAt(index);
}
@ActionMethod(name = "字符首次出现位置")
@ActionMethodParameter(names = {"目标字符串", "要查找的字符串"})
public static Integer indexOf(String target, String str) {
return target == null ? null : target.indexOf(str);
}
@ActionMethod(name = "字符最后出现位置")
@ActionMethodParameter(names = {"目标字符串", "要查找的字符串"})
public static Integer lastIndexOf(String target, String str) {
return target == null ? null : target.lastIndexOf(str);
}
@ActionMethod(name = "替换字符串")
@ActionMethodParameter(names = {"目标字符串", "原字符串", "新字符串"})
public static String replace(String target, String oldStr, String newStr) {
return target == null ? null : target.replace(oldStr, newStr);
}
@ActionMethod(name = "拆分字符串为集合")
@ActionMethodParameter(names = {"目标字符串", "拆分的字符"})
public static List<String> split(String target, String regex) {
if (StringUtils.isBlank(target)) {
return new ArrayList<>();
} else {
String[] split = target.split(regex);
return Arrays.asList(split);
}
}
}
package com.wanji.common.annotation;
import org.springframework.stereotype.Component;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author jm.zou
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface ActionBean {
String name();
}
package com.wanji.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author jm.zou
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionMethod {
String name();
}
package com.wanji.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionMethodParameter {
String[] names();
}
package com.wanji.common.enums;
import java.util.Arrays;
/**
* <>
*
* @author wanji
* 2020/6/5 12:26
*/
public enum Datatype {
/**
* String
*/
String,
/**
* integer
*/
Integer,
/**
* char
*/
Char,
/**
* double
*/
Double,
/**
* long
*/
Long,
/**
* float
*/
Float,
/**
* bigdecimal
*/
BigDecimal,
/**
* boolean
*/
Boolean,
/**
* date
*/
Date,
/**
* list
*/
List,
/**
* set
*/
Set,
/**
* map
*/
Map,
/**
* enum
*/
Enum,
/**
* object
*/
Object;
public static Datatype parse(String datatype){
return Arrays.stream(values())
.filter(v -> v.toString().equals(datatype))
.findFirst()
.orElse(null);
}
}
package com.wanji.common.enums;
public enum FormOfWayEnum {
/**
* FormOfWay
*/
FORMOFWAY_1(1,"上下线分离"),
FORMOFWAY_2(2,"交叉点内"),
FORMOFWAY_3(3,"JCT"),
FORMOFWAY_4(4,"环岛"),
FORMOFWAY_5(5,"引路"),
FORMOFWAY_53(53,"服务区+JCT"),
FORMOFWAY_56(56,"服务区+引路"),
FORMOFWAY_58(58,"服务区+引路+JCT"),
FORMOFWAY_6(6,"引路"),
FORMOFWAY_7(7,"辅路"),
FORMOFWAY_8(8,"引路+JCT"),
FORMOFWAY_9(9,"出口"),
FORMOFWAY_10(10,"入口"),
FORMOFWAY_11(11,"右转车道A"),
FORMOFWAY_12(12,"右转车道B"),
FORMOFWAY_13(13,"左转车道A"),
FORMOFWAY_14(14,"左转车道B"),
FORMOFWAY_15(15,"左右转车道"),
FORMOFWAY_16(16,"普通道路"),
FORMOFWAY_17(17,"非机动车道借道");
private int code;
private String name;
private FormOfWayEnum(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return this.code;
}
public String getName() {
return this.name;
}
}
package com.wanji.common.enums;
public enum RoadClassEnum {
/**
* FormOfWay
高速公路 41000
城市快速路 43000
国道 42000
主要道路 44000
省道 51000
主要道路 44000
县道 52000
次要道路 45000
乡镇道路 53000
普通道路 47000
*/
ROADCLASS_41000("41000","高速公路"),
ROADCLASS_42000("42000","国道"),
ROADCLASS_43000("43000","城市快速路"),
ROADCLASS_44000("44000","主要道路"),
ROADCLASS_45000("45000","次要道路"),
ROADCLASS_47000("47000","普通道路"),
ROADCLASS_51000("51000","51000"),
ROADCLASS_52000("52000","县道"),
ROADCLASS_53000("53000","乡镇道路");
private String code;
private String name;
private RoadClassEnum(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return this.code;
}
public String getName() {
return this.name;
}
}
package com.wanji.common.framework;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
/**
* EnvConstants.java
*
* @author mapabc
*/
public final class Constants {
/*记录当前用户*/
public static ThreadLocal<String> current_user_id = ThreadLocal.withInitial(() -> "");
//gisc-develop 工作流事务全局标识,默认不开启
public static ThreadLocal<Boolean> OPEN_GLOBAL_TRANSACTION = ThreadLocal.withInitial(() -> Boolean.FALSE);
//gisc-develop D2A事务实现,db操作临时conn存放
public static ThreadLocal<List<Connection>> DB_CONNS = ThreadLocal.withInitial(ArrayList::new);
//日志消息名称关键字
public static final String BP_LOG = "log";
//数据扩展表关键字
public static final String TABLE_RELATION="_relation";
public final class MessageES{
public static final String MESSAGE_HISTORY = "message_history";
public static final String MESSAGE_CONSUME_HISTORY = "message_consume_history";
public static final String MESSAGE_FILTER_HISTORY = "message_filter_history";
}
public final class WebsocketMessage{
public static final String NEW_UNREAD_MESSAGE = "";
public static final String GET_UNREAD_COUNT="";
public static final String GET_READ_MESSAGE="";
public static final String GET_UNREAD_MESSAGE="";
}
public final class igniteCacheName {
//bp design 模块缓存名称
public static final String BP_DESIGN_CACHE = "gisc-portal-cache-name";
public static final String BP_GATEWAY_CACHE = "gisc-gateway-cache-name";
public static final String GATEWAY_CACHE = "gatewayCache";
public static final String API_RESTFUL_CACHE = "apiRestfulCache";
public static final String A2A_RESTFUL_CACHE = "a2aRestfulCache";
public static final String D2A_TABLE_RESTFUL_CACHE = "d2aTableRestfulCache";
public static final String BP_ROADNET_CACHE = "gisc-roadnet-cache-name";
}
public final class Env {
public static final String BASE_HOME = "";
public static final String WORKFLOW_HOME = "configs/workflow/";
}
// RepoModuleType 分类
public final class RepoModuleTypeType {
public static final String RULE = "rule";
public static final String COMMON = "common";
public static final String APPLICATION = "application";
}
public final class MqTopic {
public static final String JAVA_MODULE_OFFLINE_TOPIC = "javaModuleOffline";
public static final String JAVA_MODULE_ONLINE_TOPIC = "javaModuleOnline";
}
public final class MqKey {
}
public final class ImportExport {
public static final String IMPORT = "import";
public static final String EXPORT = "export";
}
public final class DevExport {
public static final String MAN_DEV_APP = "MAN_DEV_APP.csv";
public static final String MAN_DEV_APPTHEME = "MAN_DEV_APPTHEME.csv";
public static final String MAN_APP_TYPE = "MAN_APP_TYPE.csv";
public static final String MAN_GW_D2A_DATABASE = "MAN_GW_D2A_DATABASE.csv";
public static final String MAN_DEV_API_RESTFUL = "MAN_DEV_API_RESTFUL.csv";
public static final String MAN_GW_D2A_TABLE_RESTFUL = "MAN_GW_D2A_TABLE_RESTFUL.csv";
public static final String MAN_DEV_RESTFUL = "MAN_DEV_RESTFUL.csv";
public static final String MAN_GW_D2A_TABLE = "MAN_GW_D2A_TABLE.csv";
public static final String MAN_GW_D2A_TABLE_FIELDS = "MAN_GW_D2A_TABLE_FIELDS.csv";
public static final String MAN_DEV_DATA_DICT_CONTENT = "MAN_DEV_DATA_DICT_CONTENT.csv";
public static final String MAN_DEV_DATA_DICT_TYPE = "MAN_DEV_DATA_DICT_TYPE.csv";
public static final String MAN_GW_M2A_MAIL = "MAN_GW_M2A_MAIL.csv";
public static final String MAN_REPO_MODULE_TYPE = "MAN_REPO_MODULE_TYPE.csv";
public static final String MAN_REPO_MODULE = "MAN_REPO_MODULE.csv";
public static final String MAN_DEV_MODULE = "MAN_DEV_MODULE.csv";
public static final String MAN_MSG_TOPIC = "MAN_MSG_TOPIC.csv";
public static final String MAN_MSG_ROUTE = "MAN_MSG_ROUTE.csv";
public static final String MAN_MSG_SUBSCRIBE = "MAN_MSG_SUBSCRIBE.csv";
public static final String MAN_MSG_FILTER_ITEM = "MAN_MSG_FILTER_ITEM.csv";
public static final String CLI_IC_APP_BUSINESS_ACCOUNT = "CLI_IC_APP_BUSINESS_ACCOUNT.csv";
public static final String CLI_IC_ORGANIZATION = "CLI_IC_ORGANIZATION.csv";
public static final String CLI_IC_ROLE = "CLI_IC_ROLE.csv";
public static final String CLI_IC_ROLE_BUSINESSACCOUNT_RLAT = "CLI_IC_ROLE_BUSINESSACCOUNT_RLAT.csv";
public static final String CLI_DEV_MENU = "CLI_DEV_MENU.csv";
public static final String MAN_MSG_TOPIC_FILTER_ITEM_RLAT= "MAN_MSG_TOPIC_FILTER_ITEM_RLAT.csv";
public static final String MAN_DEV_PLUGIN_PARAM="MAN_DEV_PLUGIN_PARAM.csv";
}
public final class BpmExport {
//导出流程定义表
public static final String WORKFLOW = "MAN_BPM_WORKFLOW.csv";
//导出流程实例表
public static final String WORKFLOW_INST = "MAN_BPM_WORKFLOW_INST.csv";
//导出流程任务表
public static final String WORKFLOW_INST_TASK = "MAN_BPM_WORKFLOW_TASK.csv";
//导出流程任务处理人表
public static final String WORKFLOW_INST_TASK_PERSON = "MAN_BPM_WORKFLOW_TASK_PERSON.csv";
//导出流程任务会签表
public static final String WORKFLOW_INST_TASK_SIGN = "MAN_BPM_WORKFLOW_TASK_COUNTERSIGN.csv";
//导出流程通知表
public static final String WORKFLOW_NOTICE = "MAN_BPM_WORKFLOW_NOTICE.csv";
//导出流程分类表
public static final String WORKFLOW_TYPE = "MAN_BPM_WORKFLOW_TYPE.csv";
//导出流程参数表
public static final String WORKFLOW_BPM_VAR = "MAN_BPM_VAR.csv";
//导出流程规则表
public static final String WORKFLOW_BPM_RULE = "MAN_BPM_RULE.csv";
//导出流程节点表
public static final String WORKFLOW_BPM_PLUGIN_PARAM = "MAN_BPM_PLUGIN_PARAM.csv";
//导出流程邮件日志表
public static final String WORKFLOW_MAIL_LOG = "MAN_BPM_MAIL_LOG.csv";
//导出流程原因表
public static final String WORKFLOW_LEAVE_INFO = "MAN_BPM_LEAVE_INFO.csv";
//导出流程form表单表
public static final String WORKFLOW_BPM_FORM = "MAN_BPM_FORM.csv";
//导出页面表
public static final String PAGE_WEB = "CLI_DEV_WEB_PAGE.csv";
//导出组件表
public static final String COMPONENT = "CLI_DEV_COMPONENT.csv";
//导出组件组表
public static final String COMPONENT_GROUP = "CLI_DEV_COMPONENT_GROUP.csv";
//导出组件版本表
public static final String COMPONENT_VERSION = "CLI_DEV_COMPONENT_VERSION.csv";
}
/**
* 系统基础服务路径
*/
public final class RestPathPrefix {
public static final String PREFIX = "bp/";
public static final String DEVELOP_PREFIX = "develop/";
public static final String LOG_PREFIX = "log/";
public static final String DESIGN_PREFIX = "design/";
public static final String MODEL_CONSOLE = "design/console/";
public static final String MODEL_IDENTITYAUTH = "bp/auth/";
public static final String MODEL_RESTFUL = "develop/restful/";
public static final String MODEL_IDENTITY = "bp/identity/";
public static final String MODEL_MSP = "bp/msp/";
public static final String MODEL_DATAMANAGE = "design/datamanage/";
public static final String MODEL_SGW = "design/sgw/";
public static final String MODEL_DISPLAYCENTER = "design/displaycenter/";
public static final String MODEL_TASKSCHEDULE = "design/taskschedule/";
public static final String MODEL_WEB = "design/web/";
public static final String FRONT_DEVELOP = "design/frontdevelop/";
public static final String MODEL_BPM_MANAGER = "design/bpm/";
public static final String MODEL_COMMON = "design/common/";
public static final String MODEL_PROCESS_QUERY = "develop/processquery/";
public static final String MODEL_MESSAGECENTER = "design/messagecenter/";
public static final String MODEL_DEV = "design/develop/";
public static final String MODEL_RULE = "design/rule/";
public static final String MODEL_DATA_CHECK = "design/datacheck/";
public static final String MODEL_TOOLS = "design/tools/";
public static final String MODEL_CONFIG_CENTER = "design/configcenter/";
public static final String MODEL_APPMANAGE = "design/appmanage/";
public static final String MODEL_COMPONENT = "design/component/";
public static final String MODEL_PORTAL = "design/portal/";
public static final String MODEL_LOG = "log/logcenter/";
public static final String MODEL_OPERATION_MONITOR = "design/operationmonitor/";
public static final String MODEL_SYSTEM_SETTING = "design/systemsetting/";
public static final String MODEL_STATISTICS = "bp/statistics/";
public static final String MODEL_IM = "bp/im/";
public static final String MODEL_DEVICE = "bp/things/";
public static final String MODEL_IM_USER = "bp/user/";
public static final String MODEL_IM_MESSAGE = "bp/message/";
public static final String MODEL_IM_GROUP = "bp/group/";
public static final String MODEL_IM_CHANNEL = "bp/channel/";
public static final String MODEL_IM_ORGANIZATION = "bp/organization/";
public static final String MODEL_IM_ORGAN_USER = "bp/organuser/";
public static final String MODEL_IM_STATISTICS = "bp/statistics";
public static final String MODEL_IM_TASK = "bp/task/";
//数据源
public static final String MODEL_DATASOURCE = "develop/datasource/";
//数据资源
public static final String MODEL_RESOURCE = "develop/resource/";
//数据资源管理
public static final String MODEL_RESOURCE_DATA = "develop/resourcedata/";
//基础数据
public static final String MODEL_BASE_DATA = "design/basedata/";
//服务接口
public static final String MODEL_DEV_SERVICE="develop/service/";
//基础设置
public static final String MODEL_CONFIG_DATA = "design/config/";
//MSP
public static final String MODEL_MSP_STYLECONFIG = "bp/msp/config/";
//geoServer
public static final String GEOSERVER = "geoserver/";
/**
* msp相关path定义
*/
public static final String MODEL_MSP_SERVICE = "bp/msp/service/";
public static final String MODEL_MSP_RESOURCE = "bp/msp/resource/";
public static final String MODEL_MSP_CONFIG = "bp/msp/config/";
public static final String MODEL_MSP_TOOL = "bp/msp/tool/";
public static final String MODEL_MSP_SCENSE = "bp/msp/sense/";
/***
* 路网api定义
*/
public static final String ROADNET_API = "api/roadnet/";
/**
* 设备信息
*/
public static final String DEVICE_API = "api/device/";
}
public final class ServiceDevPathPrefix{
/**
* 数据库接口
*/
public static final String DEV_DB_INTERFACE = "sgw/dbInterface";
/**
* 服务接口接口
*
*/
public static final String DEV_API_INTERFACE="sgw/apiInterface";
/**
* dev 注册服务
*/
public static final String DEV_SGW_SERVICE = "develop/sgw/serviceInterface/";
/**
* vt 矢量栅格服务
*/
public static final String DEV_VT_SERVICE="develop/vt/";
}
/**
* 数据能力标签,元数据驱动的核心代码
*/
public final class DataTag{
/**
* geometry
* 空间表
* --
* export
* 导出
* --
* nest
* 套和
* --
* hook
* 挂接
* --
* cache
* 缓存
* --
* publish
* 发布
* --
* edit
*/
public static final String DATA_TAG_EXPORT="export";
public static final String DATA_TAG_GEOMETRY="geometry";
public static final String DATA_TAG_NEST="nest";
public static final String DATA_TAG_HOOK="hook";
public static final String DATA_TAG_CACHE="cache";
public static final String DATA_TAG_PUBLISH="publish";
public static final String DATA_TAG_EDIT="edit";
}
/**
* Restful 对外的静态变量
*/
public final class JsonView {
public static final String STATUS_SUCCESS = "success";
public static final String STATUS_FAIL = "fail";
public static final String MESSAGE_FAIL = "操作失败";
public static final String MESSAGE_SUCCESS = "操作成功";
public static final String MESSAGE_PARAM_ERROR = "参数错误";
public static final String MESSAGE_FROMAT_ERROR = "请求格式错误";
public static final String MESSAGE_GET_PARAM_ERROR = "GET请求参数错误,注:暂不支持对象嵌套及数组";
public static final String MESSAGE_LOGIN_SUCCESS = "登录成功";
public static final String DELETE_ERROR_MSG = "表单【%s】已被流程【%s】使用";
}
/**
* 接口服务参数
*/
public static class ServiceConstants {
public static final String API_URL = "url";
public static final String API_ACCESS_METHOD = "method";
public static final String API_ACCESS_GET = "get";
public static final String API_ACCESS_POST = "post";
public static final String API_ACCESS_PUT = "put";
public static final String API_ACCESS_DELETE = "delete";
public static final String API_BODY = "body";
public static final String API_HEADER = "header";
public static final String API_QUERY = "query";
public static final String API_PATH = "pathParam";
}
/**
* @Description: 网关表,类型相关参数
* @return
* @Author mapabc8
* @Date 2020/2/14 10:10
**/
public static class ServiceType {
public static final String SERVICE_D2A = "d2a";
public static final String SERVICE_A2A = "a2a";
public static final String SERVICE_WEB_SERVICE = "webservice";
public static final String SERVICE_M2A = "m2a";
public static final String SERVICE_ORCHESTRATION = "orchestration";
public static final String SERVICE_DEVELOP = "develop";
public static final String SERVICE_BASIC = "basic";
public static final String SERVICE_BUSINESS = "business";
}
public static class AppType {
public static final String APP_REPOSITORY = "repository";
public static final String APP_EXTERNAL = "external";
public static final String APP_ORCHESTRATION = "orchestration";
public static final String APP_DEVELOP = "develop";
public static final String APP_INTERNAL = "internal";
}
/*
* apiType
* api 类型
*/
public static class RestfulApiType {
//内部系统
public static final String SERVICE_INSIDE = "inside";
//外部系统
public static final String SERVICE_OUTSIDE = "outside";
}
/*
* apiParam
* api 参数
*/
public static class ApiParam {
// mock
public static final String MOCK = "mock";
public static final String UNMOCK = "unmock";
}
/*
* spring application name
*/
public static class applicationName {
public static final String BP_RESTFUL = "gisc-restful";
public static final String BP_GATEWAY = "gisc-gateway";
public static final String BP_DESIGN = "gisc-portal";
public static final String BP_DEVELOP = "gisc-develop";
public static final String BP_IDENTITY = "gisc-identity";
public static final String BP_MSP = "gisc-msp";
}
/**
* 缓存名称
*/
public final class Cache {
public static final String USER = "user";
public static final String ONLINE_USER = "online_user";
public static final String ONLINE_MOBILE_USER = "online_mobile_user";
public static final String SYSTEM_SESSION = "system_session";
public static final String LOGIN_CACHE = "login_cache";
public static final String ETL_CACHE = "etl_workflow_cache";
public static final String RE_CACHE = "re_workflow_cache";
public static final String RE_CACHE_TOPIC = "re_workflow_cache_topic";
}
public final static class SystemParam {
/**
* 逗号分隔符
*/
public static String COMMA_SPLIT = ",";
/**
* 冒号分隔符
*/
public static String COLON_SPLIT = ":";
/**
* 空Json串
*/
public static String BLANK_JSON_STRING = "{}";
}
/**
* mysql 的字段类型
*/
public final static class MysqlColumn {
public final static String YEAR = "YEAR";
public final static String DATE = "DATE";
public final static String DATETIME = "DATETIME";
public final static String TIMESTAMP = "TIMESTAMP";
public final static String BINARY = "BINARY";
public final static String VARBINARY = "VARBINARY";
public final static String TINYINT = "TINYINT";
public final static String SMALLINT = "SMALLINT";
public final static String MEDIUMINT = "MEDIUMINT";
public final static String INT = "INT";
public final static String BIGINT = "BIGINT";
public final static String BIT = "BIT";
public final static String CHAR = "CHAR";
public final static String VARCHAR = "VARCHAR";
public final static String TEXT = "TEXT";
public final static String LONGTEXT = "LONGTEXT";
public final static String DECIMAL = "DECIMAL";
public final static String DOUBLE = "DOUBLE";
public final static String FLOAT = "FLOAT";
}
/**
* postgresql 的字段类型
*/
public final static class PostGreSqlColumn {
public final static String TEXT = "text"; // string
public final static String BPCHAR = "char"; // string
public final static String VARCHAR = "varchar"; // string
public final static String INT4 = "int4"; // integer
public final static String INT2 = "int2"; // integer
public final static String FLOAT4 = "float4"; // float
public final static String FLOAT8 = "float8"; // double
public final static String MONEY = "money"; // double
public final static String BIT = "bit"; // boolean
public final static String NUMERIC = "numeric"; // BigDecimal
public final static String BOOL = "bool"; // boolean
public final static String INT8 = "int8"; // long
public final static String TIMESTAMP = "timestamp"; // timestamp
public final static String TIME = "time"; // time
public final static String DATE = "date"; // time
public final static String BYTEA = "bytea"; // ?
public final static String BOX = "box"; // object
public final static String CIDR = "cidr"; // object
public final static String INET = "inet"; // object
public final static String MACADDR = "macaddr"; // object
public final static String VARBIT = "varbit"; // object
public final static String CIRCLE = "circle"; // object
public final static String INTERVAL = "interval"; // object
public final static String LINE = "line"; // object
public final static String LSEG = "lseg"; // object
public final static String POLYGON = "polygon"; // object
public final static String POINT = "point"; // object
public final static String PATH = "path"; // object
}
/**
* oracle 的字段类型
*/
public final static class OracleColumn {
public final static String VARCHAR2 = "VARCHAR2";
public final static String VARCHAR = "VARCHAR";
public final static String ORACLE_CHAR = "CHAR";
public final static String TIMESTAMP = "TIMESTAMP";
public final static String DATE = "DATE";
public final static String RAW = "RAW";
public final static String NVARCHAR2 = "NVARCHAR2";
public final static String TIMESTAMP_WITH_LOCAL_TIME_ZONE = "TIMESTAMP_WITH_LOCAL_TIME_ZONE";
public final static String TIMESTAMP_WITH_TIME_ZONE = "TIMESTAMP_WITH_TIME_ZONE";
public final static String INTERVAL_DAY_TO_SECOND = "INTERVAL_DAY_TO_SECOND";
public final static String INTERVAL_YEAR_TO_MONTH = "INTERVAL_YEAR_TO_MONTH";
public final static String NUMBER = "NUMBER";
public final static String FLOAT = "FLOAT";
}
/**
* @Description: sqlserver 的字段类型
* @return
* @Author mapabc8
* @Date 2020/3/12 17:47
**/
public final static class SqlServerColumn {
// Character 字符串
public final static String CHAR = "char";
public final static String VARCHAR = "varchar";
public final static String TEXT = "text";
// Number 类型
public final static String TINYINT = "tinyint";
public final static String SMALLINT = "smallint";
public final static String INT = "int";
public final static String BIGINT = "bigint";
public final static String FLOAT = "float";
// Binary类型
public final static String BIT = "bit";
public final static String BINARY = "binary";
public final static String VARBINARY = "varbinary";
// Date 类型
public final static String DATETIME = "datetime";
public final static String DATETIME2 = "datetime2";
public final static String TIMESTAMP = "timestamp";
}
/**
* 数据表相关
*/
public final static class TableInfo {
public static final String COLUMN_NAME = "COLUMN_NAME";
public static final String TYPE_NAME = "TYPE_NAME";
public static final String COLUMN_SIZE = "COLUMN_SIZE";
public static final String IS_PK = "IS_PK";
public static final String ISNULL = "ISNULL";
public static final String IS_BUSINESS_PK = "IS_BUSINESS_PK";
public static final String NULLABLE = "NULLABLE";
public static final String COLUMN_DEF = "COLUMN_DEF";
public static final String DECIMAL_DIGITS = "DECIMAL_DIGITS";
}
/**
* 数据库
*/
public final static class DataBase {
public static final String MYSQL = "mysql";
public static final String ORACLE = "oracle";
public static final String BEYONDB = "beyondb";
public static final String POSTGRESQL = "postgresql";
public static final String SQLSERVER="sqlserver";
}
/**
* 数据源的驱动
*/
public static final class DbDriver {
public static final String MYSQL = "com.mysql.jdbc.Driver";
public static final String ORACLE = "oracle.jdbc.driver.OracleDriver";
public static final String BEYONDB = "org.postgresql.Driver";
public static final String IMPALA = "com.cloudera.impala.jdbc41.Driver";
public static final String SQLSERVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static final String POSTGRESQL = "org.postgresql.Driver";
}
private static final String DATE_FORMAT_DAY = "yyyy-MM-dd";
private static final String DATE_FORMAT_HOUR = "yyyy-MM-dd HH";
private static final String DATE_FORMAT_MINUTE = "yyyy-MM-dd HH:mm";
private static final String DATE_FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss";
private static final String DATE_FORMAT_MILLIS = "yyyy-MM-dd HH:mm:ss.SSS";
private static final String DATE_FORMAT_TIME = "HH:mm:ss";
private static final String DATE_FORMAT_WEEKDAY = "EEEE";
public enum DATE_FORMAT {
// 平台指定的时间格式字符串
E_DATE_FORMAT_DAY(DATE_FORMAT_DAY),
E_DATE_FORMAT_HOUR(DATE_FORMAT_HOUR),
E_DATE_FORMAT_MINUTE(DATE_FORMAT_MINUTE),
E_DATE_FORMAT_SECOND(DATE_FORMAT_SECOND),
E_DATE_FORMAT_MILLIS(DATE_FORMAT_MILLIS),
E_DATE_FORMAT_TIME(DATE_FORMAT_TIME),
E_DATE_FORMAT_WEEKDAY(DATE_FORMAT_WEEKDAY);
private final String strFormat;
DATE_FORMAT(String strFormat) {
this.strFormat = strFormat;
}
public String getStrFormat() {
return strFormat;
}
}
public static final class ServicePluginParamArea {
public static final String GLOBAL = "global";
public static final String PARAM = "param";
public static final String OUTPUT = "output";
}
/*流程服务封装公用变量定义*/
public final class ProcessService {
public static final String ERROR_PARAM = "参数错误";
public static final String NO_PROCESS_OPERATE = "参数错误,无对应流程操作";
public static final String OPERATE_FAILD = "操作失败";
public static final String DEPLOY_SUCCESS = "部署成功";
public static final String DEPLOY_FAILD = "部署失败";
public static final String UNDEPLOY_SUCCESS = "取消部署成功";
public static final String UNDEPLOY_FAILD = "取消部署失败";
public static final String SUCCEED_COUNT = "成功条数";
public static final String FAILED_COUNT = "失败条数";
public static final String FAILED_USER_ID = "失败用户id";
public static final String START_ROWNUM = "startRowNum";
public static final String PAGE_SIZE = "pageSize";
public static final String PARAM_ERROR = "参数错误: processId=%s, userId=%s";
public static final String NODE_CONFIG_ERROR = "节点配置错误";
public static final String CANNOT_DEAL = "无法处理此任务,用户无对应操作权限或流程被暂停";
public static final String COMMENT_TYPE_PASS = "PASS";
public static final String COMMENT_TYPE_NO_PASS = "NO_PASS";
public static final String NR_OF_INSTANCES_VAR_NAME = "nrOfInstances";
public static final String NR_OF_ACTIVE_INSTANCES_VAR_NAME = "nrOfActiveInstances";
public static final String APPROVED_COUNTER_VAR_NAME = "approvedCounter";
public static final String COMMENT_BACK = "驳回";
public static final String COMMENT_TYPE_BACK = "BACK";
public static final String PAUSE_PROCESS = "流程已暂停,无法操作";
public static final String ADMIN_ID = "admin";
public static final String ALREADY_ACTIVE = "流程已激活,请勿重复操作";
public static final String ALREADY_ASSIGNED = "任务已分配到指定用户,无需重复操作";
public static final String COMMENT_ASSIGNE = "委派处理";
public static final String REJECT_ASSIGNE = "驳回处理";
public static final String COMMENT_TYPE_DEFAULT = "comment";
public static final String PROCESS_START_EVENT = "start";
public static final String PROCESS_END_EVENT = "end";
public static final String START_USER_ID = "startUserId";
public static final String PROCESS_INSTANCE_NAME = "processInstanceName";
public static final String NEED_EMAIL_VAR_NAME = "needEmail";
public static final String EMAIL_SERVICE_BEAN_NAME = "emailService";
public static final String CANDIDATE_USERS_VAR_NAME = "candidateUsers";
public static final String NOTICE_TYPE_START = "start";
public static final String NOTICE_TYPE_NEXT = "next";
/*流程表单保存在流程变量中的名称*/
public static final String FORM_DATA_USER_DEFINED_VAR_NAME = "formDataUserDefined";
public static final String START_FORM_DATA_USER_DEFINED_VAR_NAME = "startFormDataUserDefined";
/*流程是否通过流程变量*/
public static final String IS_APPROVED_VAR_NAME = "isApproved";
}
/*流程操作,枚举常量*/
public enum ProcessOperateType {
/*启动流程*/
start,
//审批,通过-不通过,通过变量控制
approve,
//驳回,到指定节点
back,
//委派
transfer,
//暂停
suspend,
//激活
active,
//作废
delete,
//抄送标记为已读
readCopyTo,
//抄送标记为未读
unReadCopyTo;
}
/*流程节点权限计算,枚举常量*/
public enum AUTH_CALCULATE_TYPE {
//根据指定企业
withCompany,
//根据指定部门
withDepartment,
//根据岗位
withStation,
//根据角色
withRole,
//根据企业用户
withCompanyUser,
//求并集
withUnion,
//求交集
withIntersection;
}
/**
* 流程定义bpmn20.xml生成字符属性
*/
public final static class Process {
public static final String DEFAULT_CHARSET = "UTF-8"; //编码格式utf-8定义
public static final String BPMN_XML_SUFFIX = ".bpmn20.xml"; //编码格式utf-8定义
/*bpmn20.xml节点定义 start*/
public static final String BPMN_DEFINITIONS = "definitions";
public static final String BPMN_XMLNS = "xmlns";
public static final String BPMN_XMLNS_CONTENT = "http://www.omg.org/spec/BPMN/20100524/MODEL";
public static final String BPMN_XMLNS_ACTIVITI = "xmlns:activiti";
public static final String BPMN_XMLNS_ACTIVITI_CONTENT = "http://activiti.org/bpmn";
public static final String BPMN_TARGET_NAMESPACE = "targetNamespace";
public static final String BPMN_TARGET_NAMESPACE_CONTENT = "http://activiti.org/bpmn20";
public static final String BPMN_XMLNS_XSI = "xmlns:xsi";
public static final String BPMN_XMLNS_XSI_CONTENT = "http://www.w3.org/2001/XMLSchema-instance";
public static final String BPMN_PROCESS = "process";
public static final String BPMN_ID = "id";
public static final String BPMN_PROCESS_ID = "processId";
public static final String BPMN_NAME = "name";
public static final String BPMN_SOURCE_REF = "sourceRef";
public static final String BPMN_TARGET_REF = "targetRef";
public static final String BPMN_CALLED_ELEMENT = "calledElement";
public static final String BPMN_EXTENSION_ELEMENTS = "extensionElements";
public static final String BPMN_SOURCE = "source";
public static final String BPMN_TARGET = "target";
public static final String BPMN_ACTIVITI_IN = "activiti:in";
public static final String BPMN_ACTIVITI_OUT = "activiti:out";
public static final String BPMN_CONDITION_EXPRESSION = "conditionExpression";
public static final String BPMN_XSI_TYPE = "xsi:type";
public static final String BPMN_FORMAL_EXPRESSION = "tFormalExpression";
public static final String BPMN_ACTIVITI_TASKLISTENER = "activiti:taskListener";
public static final String BPMN_EVENT = "event";
public static final String BPMN_CREATE = "create";
public static final String BPMN_CLASS = "class";
public static final String BPMN_ACTIVITI_CLASS = "activiti:class";
public static final String BPMN_ACTIVITI_EXECUTION_LISTENER = "activiti:executionListener";
public static final String BPMN_START = "start";
public static final String BPMN_END = "end";
public static final String BPMN_COMPLETE = "complete";
public static final String BPMN_EXPRESSION = "expression";
public static final String BPMN_COMPLETE_EXPRESSION_METHOD = "${userTaskHandler.postComplete(execution)}";
public static final String BPMN_START_EXPRESSION_METHOD = "${userTaskHandler.preStart(execution)}";
public static final String BPMN_ACTIVITI_CANDIDATE_USERS = "activiti:candidateUsers";
public static final String BPMN_ACTIVITI_CANDIDATE_USERS_VALUE = "${candidates}";
public static final String BPMN_MULTI_INSTANCE_LOOP_CHARACTERISTICS = "multiInstanceLoopCharacteristics";
public static final String BPMN_IS_SEQUENTIAL = "isSequential";
public static final String BPMN_IS_SEQUENTIAL_VALUE = "false";
public static final String BPMN_ACTIVITI_COLLECTION = "activiti:collection";
public static final String BPMN_ACTIVITI_COLLECTION_METHOD_NAME = "${userTaskHandler.getActorUser(execution)}";
public static final String BPMN_ACTIVITI_ELEMENT_VARIABLE = "activiti:elementVariable";
public static final String BPMN_CANDIDATES = "candidates";
public static final String BPMN_COMPLETION_CONDITION = "completionCondition";
public static final String BPMN_COMPLETION_CONDITION_CONTENT = "${userTaskHandler.dealComplete(execution)}";
public static final String BPMN_PROCESS_EXECUTION_LISTENER_NAME = "com.wanji.design.engine.operate.impl.ProcessExecutionListener";
public static final String BPMN_ACTIVITI_CLASS_NAME = "com.wanji.design.engine.operate.impl.AutoNodeServiceTask";
/*bpmn20.xml节点定义 end*/
/*流程设计器元素类型常量定义 start*/
public static final String START_NODE = "startNode";
public static final String END_NODE = "endNode";
public static final String APPROVAL_NODE = "approvalNode";
public static final String CONDITION_LINE = "conditionLine";
public static final String FORK_NODE = "forkNode";
public static final String CALL_ACTIVITY_NODE = "callActivityNode";
public static final String AUTO_NODE = "autoNode";
/*流程设计器元素类型常量定义 end*/
/*xml创建节点类型,枚举常量*/
public enum NodeType {
START("startEvent"),
END("endEvent"),
USERTASK("userTask"),
CONDITION("inclusiveGateway"),
FLOW("sequenceFlow"),
AUTO_NODE("serviceTask"),
CALL_ACTIVITY("callActivity");
private String value;
NodeType(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
}
/*审批节点类型*/
public enum ApprovalNodeType {
SINGLE_INSTANCE, //非会签节点
MULTI_INSTANCE, //会签节点
COPY_TO; //抄送节点, 通过任务接收人实现, 用权限控制
}
}
/* 消息类型 */
public enum MessageType {
// 工作流消息
BPM_MESSAGE_LOG("bpm_log");
private String value;
MessageType(String value) {
this.value = value;
}
public static MessageType getEnumByValue(String value) {
for (MessageType msgType : MessageType.values()) {
if (msgType.toString().equals(value)) {
return msgType;
}
}
return null;
}
@Override
public String toString() {
return this.value;
}
}
/*日志保存操作类型*/
public enum LogType {
//接口日志 D2A
D2A_INTERFACE_API_LOG("d2a_interface_api_log"),
//接口日志 A2A
A2A_INTERFACE_API_LOG("a2a_interface_api_log"),
//接口日志 webservice
WEBSERVICE_INTERFACE_API_LOG("webservice_interface_api_log"),
//接口日志 基础接口
BASE_INTERFACE_API_LOG("base_interface_api_log"),
//接口日志 业务接口
BUSINESS_INTERFACE_API_LOG("business_interface_api_log"),
//接口日志 集成接口
INTEGRATION_INTERFACE_API_LOG("integration_interface_api_log"),
//接口日志 服务编排接口
SGW_INTERFACE_API_LOG("sgw_interface_api_log"),
//接口日志 邮件接口
MAIL_INTERFACE_API_LOG("mail_interface_api_log"),
//调度日志 d2a接口
SCHEDULE_D2A_INTERFACE_API_LOG("schedule_d2a_interface_api_log"),
//调度日志 A2A接口
SCHEDULE_A2A_INTERFACE_API_LOG("schedule_a2a_interface_api_log"),
//调度日志 基础接口
MICROSERVICE_BASE_INTERFACE_API_LOG("microservice_base_interface_api_log"),
//调度日志 业务接口
MICROSERVICE_BUSINESS_INTERFACE_API_LOG("microservice_business_interface_api_log"),
//调度日志 集成接口
MICROSERVICE_INTEGRATION_INTERFACE_API_LOG("microservice_integration_interface_api_log"),
//调度日志 服务编排
MICROSERVICE_ORCHESTRATION_INTERFACE_API_LOG("microservice_orchestration_interface_api_log"),
//调度日志 系统日志
SYSTEM_TASK_LOG("system_task_log"),
// 授权日志
AUTH_LOG("auth_log"),
//网关日志 基础接口日志
GATEWAY_BASE_INTERFACE_API_LOG("gateway_base_interface_api_log"),
//网关日志 业务接口日志
GATEWAY_BUSINESS_INTERFACE_API_LOG("gateway_business_interface_api_log"),
//网关日志 集成接口日志
GATEWAY_INTEGRATION_INTERFACE_API_LOG("gateway_integration_interface_api_log"),
//网关日志 a2a
GATEWAY_A2A_INTERFACE_API_LOG("gateway_a2a_interface_api_log"),
//网关日志 d2a
GATEWAY_D2A_INTERFACE_API_LOG("gateway_d2a_interface_api_log"),
//网关日志 服务编排
GATEWAY_ORCHESTRATION_INTERFACE_API_LOG("gateway_orchestration_interface_api_log"),
//服务开发插件日志
DEV_SERVICE_PLUGIN_LOG("dev_service_plugin_log"),
//服务开发流程日志
DEV_SERVICE_FLOW_LOG("dev_service_flow_log"),
//服务编排任务调度日志
DEV_SCHEDULE_LOG("dev_schedule_log"),
//服务编排发布日志
SGW_SERVICE_PUBLISH_LOG("sgw_service_publish_log"),
//服务编排插件日志
SGW_SERVICE_PLUGIN_LOG("sgw_service_plugin_log"),
//服务编排流程日志
SGW_SERVICE_FLOW_LOG("sgw_service_flow_log"),
//服务网关D2A日志
SGW_D2A_SERVICE_LOG("sgw_d2a_service_log"),
// 操作日志
OPERATION_LOG("operation_log"),
// 登录日志
LOGIN_LOG("login_log");
private String value;
LogType(String value) {
this.value = value;
}
public static LogType getEnumByValue(String value) {
for (LogType logType : LogType.values()) {
if (logType.toString().equals(value)) {
return logType;
}
}
return null;
}
@Override
public String toString() {
return this.value;
}
}
/**
* 重构移植 重新划分模块后,把之前bp-domain下的constants移植过来 start 20200514
*/
public static class ConsoleConstants {
public static final class User {
public static final String USER = "user";
public static final String SYS_USER = "sysUser";
public static final String TOKEN = "token";
}
}
public static class FunctionManageConstants {
public static final class FunctionJar {
public static final String DOWNLOAD_PATH_KEY = "folder";
}
}
public static class ServiceDevelopConstants {
public static final class TableOperationLogConst {
public static final String RES_TYPE = "table";
// 业务表的操作类型。
public static final String CREATE_TABLE_OPERATION = "new";
public static final String DELETE_TABLE_OPERATION = "delete";
public static final String UPDATE_TABLE_OPERATION = "update";
public static final String IMPORT_TABLE_OPERATION = "import";
}
}
public static class ServiceGateWayConstants {
public static final class D2ADataBase {
public static final String DB_MYSQL = "mysql";
public static final String DB_ORACLE = "oracle";
public static final String DB_SQLSERVER = "sqlserver";
public static final String DB_BEYONDB = "beyondb";
public static final String DB_POSTGRESQL = "postgresql";
}
public static final class DataSource {
public static final String DB_ELASTICSEARCH = "elasticsearch";
public static final String DB_KAFKA = "kafka";
public static final String DB_RABBITMQ = "rabbitmq";
public static final String DB_REDIS = "redis";
public static final String DB_WEBSOCKET = "websocket";
public static final String DB_WEBSERVICE = "webservice";
public static final String DB_MONGODB="mongo";
}
public static final class TableRestfulConstants {
public final static String INTERFACE_CODE_BY_PAGE = "findByPage";
public final static String INTERFACE_CODE_BY_CONDITION = "findByWhere";
public final static String INTERFACE_CODE_BY_ID = "findById";
public final static String INTERFACE_CODE_INSERT = "insert";
public final static String INTERFACE_CODE_UPDATE = "update";
public final static String INTERFACE_CODE_DELETE = "delete";
public final static String INTERFACE_CODE_BY_SQL = "multiTable";//bySql
}
}
public static class ServicePublishConstants {
public final class SqlConstants {
public static final String BLANK = " ";
public static final String FIELD_NAME_EN = "fieldNameEn";
public static final String FIELD_TYPE = "type";
public static final String FIELD_VALUE = "value";
public static final String FIELD_FLAG = "flag";
public static final String OPERATIONS = "operations";
public static final String CONDITION_COLUMNS = "condition_columns";
public static final String TYPES_AND_VALUES = "typesAndValues";
public static final String CONDITION = "condition";
public static final String SET = "set";
public static final String OPERATION = "operation";
public static final String BETWEEN_OPERATION = "between";
public static final String PAGE_SIZE = "pageSize";
public static final String PAGE_NUM = "pageNum";
public static final String ORDER="order";
public static final String IN_OPERATION="in";
public static final String DESC_OPERATION="DESC";
public static final String ASC_OPERATION="ASC";
public static final String LIKE_OPERATION="like";
}
/**
* 数据库类型常量定义
*/
public final class DBType {
public final static String MYSQL = "mysql";
public final static String ORACLE = "oracle";
public final static String SQLSERVER = "sqlserver";
public final static String BEYONDB = "beyondb";
}
}
public static class TaskScheduleConstants {
public static class ScheduleStatus {
public static final String STOP = "0";
public static final String START = "1";
}
}
public static class StatisticalConstants {
public static class UserTrends {
public static final String LOGIN_TIME = "loginTime";
public static final String START_DATE = "startDate";
public static final String END_DATE = "endDate";
public static final String CHART_DATA = "chartData";
public static final String DAILY_ACTIVE_USER = "dailyActiveUser";
public static final String DAILY_NEW_USER = "dailyNewUser";
public static final String DAILY_OLD_USER = "dailyOldUser";
public static final String DAILY_USER_VISITS = "dailyUserVisits";
public static final String DEDICATED_HOSTING_IP = "dedicatedHostingIp";
public static final String DAILY_UPDATE_USER = "dailyUpdateUser";
public static final String DAILY_NEWANDUPDATE_USER = "dailyNewAndUpdateUser";
public static final String DAILY_STARTUP = "dailyStartup";
}
}
/**
* IM类型
*/
public final class IM {
public static final String IM_CLIENT_ID = "IMClientId";
public static final String IM_PLATFORM = "IMPlatform";
public static final String IM_USER = "IMUser";
public static final String IM_TOKEN = "IMToken";
}
public final class Idnetity {
public static final String UNI_USER_AGENT = "X-Uni-User-Agent";
}
/**重构移植 end 20200514*/
/**
* 空间数据表
*/
public final class tableNameConstants {
public static final String RID_RID = "rid_rid";
public static final String RID_CROSS = "rid_cross";
public static final String RID_LANE_OBJ = "rid_lane_obj";
public static final String RID_AXF_THREE = "rid_axf_three";
public static final String ROAD_SEGMENT = "data_roadsegment";
}
/**
* 路网数据更新状态
*/
public final class DataConstants {
// 数据状态 0继承,1删除,2增加,3修改
public final static String DATA_MODE_EXTENTD = "0";
public final static String DATA_MODE_DELETE = "1";
public final static String DATA_MODE_ADD = "2";
public final static String DATA_MODE_EDIT = "3";
}
}
package com.wanji.common.framework;
/**
* Ajax 请求时的自定义查询状态码,主要参考Http状态码,但并不完全对应
*
* Created by dong on 2018/6/28.
*/
public enum HttpCode {
/** 200请求成功 */
SUCCESS(200),
/** 207频繁操作 */
MULTI_STATUS(207),
/** 400请求参数出错 */
BAD_REQUEST(400),
/** 401没有登录 */
UNAUTHORIZED(401),
/** 402登录失败 */
LOGIN_FAIL(402),
/** 403没有权限 */
FORBIDDEN(403),
/** 404找不到页面 */
NOT_FOUND(404),
/** 405请求方法不能被用于请求相应的资源 */
METHOD_NOT_ALLOWED(405),
/** 406内容特性不满足 */
NOT_ACCEPTABLE(406),
/** token过期 */
TOKEN_EXPIRED(407),
/** 408请求超时 */
REQUEST_TIMEOUT(408),
/** 409发生冲突 */
CONFLICT(409),
/** 410已被删除 */
GONE(410),
/** 411没有定义长度 */
LENGTH_REQUIRED(411),
/** 412条件不满足 */
PRECONDITION_FAILED(412),
/** 413数据太大 */
ENTITY_TOO_LARGE(413),
/** 415不是服务器中所支持的格式 */
UNSUPPORTED_MEDIA_TYPE(415),
/** 421连接数过多 */
TOO_MANY_CONNECTIONS(421),
/** 423已被锁定 */
LOCKED(423),
/** 451法律不允许 */
UNAVAILABLE_LEGAL(451),
/** 500服务器出错 */
INTERNAL_SERVER_ERROR(500),
/** 501不支持当前请求所需要的某个功能 */
NOT_IMPLEMENTED(501),
/** 503服务器升级中,暂时不可用 */
SERVICE_UNAVAILABLE(503),
/** 501获取资源所需要的策略并没有被满足 */
NOT_EXTENDED(510);
private final Integer value;
private HttpCode(Integer value) {
this.value = value;
}
/**
* Return the integer value of this status code.
*/
public Integer value() {
return this.value;
}
@Override
public String toString() {
return this.value.toString();
}
}
package com.wanji.common.framework.config;
import com.wanji.common.framework.Constants;
import com.wanji.common.utils.tool.DateUtil;
import com.wanji.common.utils.file.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
/**
* 资源文件帮助类,加载配置信息
*
* @author mapabc
* @date 2016/10/27
*/
@Slf4j
public class ConfigHelper {
private static Properties properties;
private static String filePath;
private static final String PROPERTIES_FILE_NAME = "application.yml";
static {
System.out.println("[" + DateUtil.getDateTimeInSecond() + "] Loading application.yml");
try {
filePath = FileUtil.getFilePath(PROPERTIES_FILE_NAME, Constants.Env.BASE_HOME);
if (filePath != null) {
//系统参数配置
properties = loadProperties();
}
} catch (Exception e) {
log.error("配置文件读取失败!", e);
}
}
private static Properties loadProperties() {
Properties prop = new Properties();
try {
File file = FileUtil.getFile(ConfigHelper.PROPERTIES_FILE_NAME, Constants.Env.BASE_HOME);
if (file != null) {
InputStream input = new FileInputStream(file);
prop.load(input);
}
} catch (Exception e) {
log.error("Loading application.properties fails", e);
}
return prop;
}
/**
* 根据Key 得到config文件中key对应的数据
*
* @param key
* @return
*/
public static String getValue(String key) {
String value = null;
try {
value = properties.getProperty(key);
} catch (Exception e) {
log.error("key:" + key + " 资源参数加载失败!", e);
}
return value;
}
/**
* @param key
* @param value
*/
public static void setProperties(String key, String value) {
try {
FileInputStream input = new FileInputStream(filePath);
SafeProperties safeProp = new SafeProperties();
safeProp.load(input);
input.close();
if (StringUtils.isNotEmpty(value)) {
safeProp.put(key, value);
}
if (key != null) {
if (StringUtils.isEmpty(value)) {
safeProp.remove(key);
}
}
FileOutputStream output = new FileOutputStream(filePath);
safeProp.store(output, null);
output.close();
} catch (Exception e) {
log.error("Visit " + filePath + " for updating " + key + " value error", e);
}
}
/**
* 删除
*
* @param key
*/
public static void removeProperties(String key) {
try {
FileInputStream input = new FileInputStream(filePath);
SafeProperties safeProp = new SafeProperties();
safeProp.load(input);
input.close();
if (key != null) {
safeProp.remove(key);
}
FileOutputStream output = new FileOutputStream(filePath);
safeProp.store(output, null);
output.close();
} catch (Exception e) {
log.error("Visit " + filePath + " for updating " + key + " value error", e);
}
}
}
package com.wanji.common.framework.config;
import com.google.common.collect.Lists;
import java.io.*;
import java.util.List;
import java.util.Properties;
/**
* @author mapabc
* @date 2016/10/27
*/
public class SafeProperties extends Properties {
private static final long serialVersionUID = 5011694856722313621L;
private static final String KEY_VALUE_SEPARATORS = "=: \t\r\n\f";
private static final String STRICT_KEY_VALUE_SEPARATORS = "=:";
private static final String SPECIAL_SAVE_CHARS = "=: \t\r\n\f#!";
private static final String WHITE_SPACE_CHARS = " \t\r\n\f";
private PropertiesContext context = new PropertiesContext();
public PropertiesContext getContext() {
return context;
}
@Override
public synchronized void load(InputStream inStream) throws IOException {
BufferedReader in;
in = new BufferedReader(new InputStreamReader(inStream, "8859_1"));
while (true) {
// Get next line
String line = in.readLine();
// intract property/comment string
String intactLine = line;
if (line == null) {
return;
}
if (line.length() > 0) {
// Find start of key
int len = line.length();
int keyStart;
for (keyStart = 0; keyStart < len; keyStart++) {
if (WHITE_SPACE_CHARS.indexOf(line.charAt(keyStart)) == -1) {
break;
}
}
// Blank lines are ignored
if (keyStart == len) {
continue;
}
// Continue lines that end in slashes if they are not comments
char firstChar = line.charAt(keyStart);
if ((firstChar != '#') && (firstChar != '!')) {
while (continueLine(line)) {
String nextLine = in.readLine();
intactLine = intactLine + "\n" + nextLine;
if (nextLine == null) {
nextLine = "";
}
String loppedLine = line.substring(0, len - 1);
// Advance beyond whitespace on new line
int startIndex;
for (startIndex = 0; startIndex < nextLine.length(); startIndex++) {
if (WHITE_SPACE_CHARS.indexOf(nextLine
.charAt(startIndex)) == -1) {
break;
}
}
nextLine = nextLine.substring(startIndex,
nextLine.length());
line = loppedLine + nextLine;
len = line.length();
}
// Find separation between key and value
int separatorIndex;
for (separatorIndex = keyStart; separatorIndex < len; separatorIndex++) {
char currentChar = line.charAt(separatorIndex);
if (currentChar == '\\') {
separatorIndex++;
} else if (KEY_VALUE_SEPARATORS.indexOf(currentChar) != -1) {
break;
}
}
// Skip over whitespace after key if any
int valueIndex;
for (valueIndex = separatorIndex; valueIndex < len; valueIndex++) {
if (WHITE_SPACE_CHARS.indexOf(line.charAt(valueIndex)) == -1) {
break;
}
}
// Skip over one non whitespace key value separators if any
if (valueIndex < len) {
if (STRICT_KEY_VALUE_SEPARATORS.indexOf(line
.charAt(valueIndex)) != -1) {
valueIndex++;
}
}
// Skip over white space after other separators if any
while (valueIndex < len) {
if (WHITE_SPACE_CHARS.indexOf(line.charAt(valueIndex)) == -1) {
break;
}
valueIndex++;
}
String key = line.substring(keyStart, separatorIndex);
String value = (separatorIndex < len) ? line.substring(
valueIndex, len) : "";
// Convert then store key and value
key = loadConvert(key);
value = loadConvert(value);
// memorize the property also with the whold string
put(key, value, intactLine);
} else {
// memorize the comment string
context.addCommentLine(intactLine);
}
} else {
// memorize the string even the string is empty
context.addCommentLine(intactLine);
}
}
}
/*
* Converts encoded &#92;uxxxx to unicode chars and changes special saved
* chars to their original forms
*/
private String loadConvert(String theString) {
char aChar;
int len = theString.length();
StringBuilder outBuffer = new StringBuilder(len);
for (int x = 0; x < len; ) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't') {
outBuffer.append('\t'); /* ibm@7211 */
} else if (aChar == 'r') {
outBuffer.append('\r'); /* ibm@7211 */
} else if (aChar == 'n') {
outBuffer.append('\n'); /* ibm@8897 ibm@7211 */
} else if (aChar == 'f') {
outBuffer.append('\f'); /* ibm@7211 */
} else
/* ibm@7211 */ {
outBuffer.append(aChar); /* ibm@7211 */
}
}
} else {
outBuffer.append(aChar);
}
}
return outBuffer.toString();
}
@Override
@SuppressWarnings("rawtypes")
public synchronized void store(OutputStream out, String header)
throws IOException {
BufferedWriter aWriter;
aWriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
if (header != null) {
writeln(aWriter, "#" + header);
}
List entries = context.getCommentOrEntrys();
for (Object obj : entries) {
if (obj.toString() != null) {
writeln(aWriter, obj.toString());
}
}
aWriter.flush();
}
private static void writeln(BufferedWriter bw, String s) throws IOException {
bw.write(s);
bw.newLine();
}
private boolean continueLine(String line) {
int slashCount = 0;
int index = line.length() - 1;
while ((index >= 0) && (line.charAt(index--) == '\\')) {
slashCount++;
}
return (slashCount % 2 == 1);
}
/*
* Converts unicodes to encoded &#92;uxxxx and writes out any of the
* characters in SPECIAL_SAVE_CHARS with a preceding slash
*/
private String saveConvert(String theString, boolean escapeSpace) {
int len = theString.length();
StringBuilder outBuffer = new StringBuilder(len * 2);
for (int x = 0; x < len; x++) {
char aChar = theString.charAt(x);
switch (aChar) {
case ' ':
if (x == 0 || escapeSpace) {
outBuffer.append('\\');
}
outBuffer.append(' ');
break;
case '\\':
outBuffer.append('\\');
outBuffer.append('\\');
break;
case '\t':
outBuffer.append('\\');
outBuffer.append('t');
break;
case '\n':
outBuffer.append('\\');
outBuffer.append('n');
break;
case '\r':
outBuffer.append('\\');
outBuffer.append('r');
break;
case '\f':
outBuffer.append('\\');
outBuffer.append('f');
break;
default:
if ((aChar < 0x0020) || (aChar > 0x007e)) {
outBuffer.append('\\');
outBuffer.append('u');
outBuffer.append(toHex((aChar >> 12) & 0xF));
outBuffer.append(toHex((aChar >> 8) & 0xF));
outBuffer.append(toHex((aChar >> 4) & 0xF));
outBuffer.append(toHex(aChar & 0xF));
} else {
if (SPECIAL_SAVE_CHARS.indexOf(aChar) != -1) {
outBuffer.append('\\');
}
outBuffer.append(aChar);
}
}
}
return outBuffer.toString();
}
/**
* Convert a nibble to a hex character
*
* @param nibble the nibble to convert.
*/
private static char toHex(int nibble) {
return HEX_DIGIT[(nibble & 0xF)];
}
/**
* A table of hex digits
*/
private static final char[] HEX_DIGIT = {'0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
@Override
public synchronized Object put(Object key, Object value) {
context.putOrUpdate(key.toString(), value.toString());
return super.put(key, value);
}
public synchronized Object put(Object key, Object value, String line) {
context.putOrUpdate(key.toString(), value.toString(), line);
return super.put(key, value);
}
@Override
public synchronized Object remove(Object key) {
context.remove(key.toString());
return super.remove(key);
}
class PropertiesContext {
@SuppressWarnings("rawtypes")
private List commentOrEntrys = Lists.newArrayList();
@SuppressWarnings("rawtypes")
public List getCommentOrEntrys() {
return commentOrEntrys;
}
@SuppressWarnings("unchecked")
public void addCommentLine(String line) {
commentOrEntrys.add(line);
}
@SuppressWarnings("unchecked")
public void putOrUpdate(PropertyEntry pe) {
remove(pe.getKey());
commentOrEntrys.add(pe);
}
@SuppressWarnings("unchecked")
public void putOrUpdate(String key, String value, String line) {
PropertyEntry pe = new PropertyEntry(key, value, line);
remove(key);
commentOrEntrys.add(pe);
}
@SuppressWarnings("unchecked")
public void putOrUpdate(String key, String value) {
int j = this.getLine(key, value);
PropertyEntry pe = new PropertyEntry(key, value);
if (j == 0) {
remove(key);
commentOrEntrys.add(pe);
} else {
remove(key);
commentOrEntrys.add(j, pe);
}
}
public void remove(String key) {
for (int i = 0; i < commentOrEntrys.size(); i++) {
Object obj = commentOrEntrys.get(i);
if (obj != null) {
if (obj instanceof PropertyEntry) {
if (key.equals(((PropertyEntry) obj).getKey())) {
commentOrEntrys.remove(obj);
}
}
}
}
}
public int getLine(String key, String value) {
int j = 0;
for (int i = 0; i < commentOrEntrys.size(); i++) {
Object obj = commentOrEntrys.get(i);
if (obj != null) {
if (obj instanceof PropertyEntry) {
//String key_ = ((PropertyEntry) obj).getKey();
//System.out.println(key_+"-----"+key);
if (key.equals(((PropertyEntry) obj).getKey())) {
// commentOrEntrys.remove(obj);
// ((PropertyEntry) obj).setValue(value);
// line = ((PropertyEntry) obj).getLine();
j = i;
}
}
}
}
return j;
}
class PropertyEntry {
private String key;
private String value;
private String line;
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public PropertyEntry(String key, String value) {
this.key = key;
this.value = value;
}
/**
* @param key
* @param value
* @param line
*/
public PropertyEntry(String key, String value, String line) {
this(key, value);
this.line = line;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
if (line != null) {
return line;
}
if (key != null && value != null) {
String k = saveConvert(key, true);
String v = saveConvert(value, false);
return k + "=" + v;
}
return null;
}
}
}
/**
* @param comment
*/
public void addComment(String comment) {
if (comment != null) {
try {
comment = this.changeCharset(comment, "ISO_8859_1");
context.addCommentLine("#" + comment);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String changeCharset(String str, String newCharset) throws Exception {
if (str != null) {
// 用默认字符编码解码字符串。
byte[] bs = str.getBytes();
// 用新的字符编码生成字符串
return new String(bs, newCharset);
}
return null;
}
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("c:/config.properties");
SafeProperties safeProp = new SafeProperties();
safeProp.load(input);
input.close();
// safeProp.addComment("New Comment测试");
safeProp.put("shell.path", "5566666222222266555555");
FileOutputStream output = new FileOutputStream("c:/config.properties");
safeProp.store(output, null);
output.close();
} catch (Exception e) {
//ignore
}
}
}
package com.wanji.common.framework.db;
import com.wanji.common.framework.db.impl.MysqlDBImpl;
import com.wanji.common.framework.db.impl.OracleDBImpl;
import com.wanji.common.framework.db.impl.PostgresqlDBImpl;
import com.wanji.common.framework.db.impl.SQLServerDBImpl;
import com.wanji.common.framework.domain.Db;
import com.wanji.common.framework.spring.ServiceBeanContext;
import static com.wanji.common.framework.Constants.DataBase.*;
import static com.wanji.common.framework.Constants.ServicePublishConstants.DBType.SQLSERVER;
/**
* 数据库基础接口简单工厂类
*/
public class DbFactory {
private DbFactory() {
}
private static class InnerClass {
private static DbFactory dbBaseFactory = new DbFactory();
}
public static DbFactory getInstance() {
return InnerClass.dbBaseFactory;
}
/**
* 根据数据库类型 得到DBBaseInterface 的实现
*
* @param dbType 数据库连接信息。
* @return DBBaseInterface 的实现。
*/
public DbInterface getDbInterface(String dbType) {
DbInterface bdBaseInterface;
switch (dbType) {
case MYSQL:
bdBaseInterface = new MysqlDBImpl();
break;
case POSTGRESQL:
bdBaseInterface = new PostgresqlDBImpl();
break;
case ORACLE:
bdBaseInterface = new OracleDBImpl();
break;
case SQLSERVER:
bdBaseInterface = new SQLServerDBImpl();
break;
default:
bdBaseInterface = new MysqlDBImpl();
break;
}
return bdBaseInterface;
}
}
package com.wanji.common.framework.db;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.domain.Db;
import com.wanji.common.framework.domain.View;
import com.wanji.common.framework.exception.NodeException;
import com.wanji.common.framework.rest.Page;
import com.wanji.common.tool.dbtools.DSUtils;
import com.wanji.common.utils.tool.StringUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.*;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.BETWEEN_OPERATION;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.IN_OPERATION;
/**
* Sql拼接:复杂的使用已经封装好的MySQL、Oracle sql构造器即可。
* <p>
* Sql参数:拼接sql时用?做占位符,将处理好的占位符实际值,按照顺序,依据类型转化为java包装类对象,存入Object[] 中即可。
* <p>
* 执行Sql:使用apache common的 DbUtils工具类进行操作。
*
* @Author mapabc6
* @Date 2020/3/11 16:10
*/
public interface DbInterface {
String getDriver();
String getDBUrl(Db dataBase);
String getFindByPageSQL(String tableName, Page page,
List<Map<String, Object>> whereParams,
int startRowNum,
List<Map<String, String>> orderMap);
String getFindPageBySqlSQL(Page page,
int startRowNum,
String sql);
String getFindByWhereSQL(String tableName, List<Map<String, Object>> whereParams, List<Map<String, String>> orderMap);
String getFindCountSQL(String tableName, List<Map<String, Object>> whereParams);
String getFindCountBySqlSQL(String sql);
String getFindByIdSQL(String tableName, String id);
String getDeleteSQL(String tableName, List<Map<String, Object>> whereParams);
String getInsertSQL(String tableName, List<Map<String, Object>> insertParams);
String getUpdateSQL(String tableName, List<Map<String, Object>> updateParams,
List<Map<String, Object>> whereParams);
Object typeHandler(String fieldType, String fieldValue) throws NodeException;
//Object[] typeHandler(List<Map<String, Object>> paramList);
// throws NodeException {
/* List<Object> list = new ArrayList<>();
for (Map<String, Object> paramMap : paramList) {
String fieldType = String.valueOf(paramMap.get(FIELD_TYPE));
String fieldValue = String.valueOf(paramMap.get(FIELD_VALUE));
String operation = String.valueOf(paramMap.get(OPERATION));
if (StringUtils.equalsIgnoreCase(fieldValue, "null")) {
list.add(null);
} else {
if (LIKE_OPERATION.equals(operation)) {
list.add("%" + fieldValue + "%");
} else if (BETWEEN_OPERATION.equals(operation)) {
String[] split = fieldValue.split("~");
list.add(String.valueOf(typeHandler(fieldType, split[0])));
list.add(String.valueOf(typeHandler(fieldType, split[1])));
} else if (IN_OPERATION.equals(operation)) {
String[] split = fieldValue.split(",");
for (String s : split) {
list.add(String.valueOf(typeHandler(fieldType, s)));
}
} else {
list.add(typeHandler(fieldType, fieldValue));
}
}
}
return list.toArray();
}*/
}
package com.wanji.common.framework.db.impl;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.db.DbInterface;
import com.wanji.common.framework.domain.Db;
import com.wanji.common.framework.exception.NodeException;
import com.wanji.common.framework.rest.Page;
import com.wanji.common.tool.dbtools.MySQL;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.DbDriver.MYSQL;
import static com.wanji.common.framework.Constants.MysqlColumn.*;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.BLANK;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.FIELD_NAME_EN;
/**
* Mysql数据库的基础操作接口实现
*
* @author mapabc
*/
@Slf4j
public class MysqlDBImpl implements DbInterface {
@Override
public String getDriver() {
return Constants.DbDriver.MYSQL;
}
@Override
public String getDBUrl(Db dataBase) {
return new StringBuilder("jdbc:mysql://")
.append(dataBase.getIp()).append(":")
.append(dataBase.getPort()).append("/")
.append(dataBase.getName())
.append("?useUnicode=true&characterEncoding=UTF-8").toString();
}
@Override
public String getInsertSQL(String tableName, List<Map<String, Object>> insertParams) {
// 拼接带有占位符的insertSql: insert into table (col1, col2...) values (val1, val2...)
StringBuilder columns = new StringBuilder("(");
StringBuilder values = new StringBuilder("(");
int paramSize = insertParams.size();
for (int i = 0; i < paramSize; i++) {
Map<String, Object> insertParam = insertParams.get(i);
String fieldName = insertParam.get(FIELD_NAME_EN).toString();
if (i == (paramSize - 1)) {
columns.append(fieldName).append(")");
values.append("?)");
} else {
columns.append(fieldName).append(",");
values.append("?,");
}
}
return new StringBuilder("INSERT INTO").append(BLANK)
.append(tableName).append(BLANK)
.append(columns).append(BLANK)
.append("VALUES").append(BLANK)
.append(values).toString();
}
@Override
public String getUpdateSQL(String tableName, List<Map<String, Object>> updateParams,
List<Map<String, Object>> whereParams) {
return new MySQL.SqlBuilder()
.update(tableName)
.buildSet(updateParams)
.buildWhere(whereParams)
.build()
.toString();
}
@Override
public String getDeleteSQL(String tableName, List<Map<String, Object>> whereParams) {
return new MySQL.SqlBuilder()
.delete()
.buildFrom(tableName)
.buildWhere(whereParams)
.build().toString();
}
@Override
public String getFindByIdSQL(String tableName, String id) {
return new MySQL.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.build()
.toString() + " where " + id + " = ? ";
}
@Override
public String getFindByWhereSQL(String tableName,
List<Map<String, Object>> whereParams,
List<Map<String, String>> orderMap) {
return new MySQL.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.buildWhere(whereParams)
.buildOrder(orderMap)
.build()
.toString();
}
@Override
public String getFindCountSQL(String tableName, List<Map<String, Object>> whereParams) {
return new MySQL.SqlBuilder()
.select()
.buildCount()
.buildFrom(tableName)
.buildWhere(whereParams)
.build()
.toString();
}
@Override
public String getFindByPageSQL(String tableName, Page page,
List<Map<String, Object>> whereParams,
int startRowNum,
List<Map<String, String>> orderMap) {
return new MySQL.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.buildWhere(whereParams)
.buildOrder(orderMap)
.buildLimit(startRowNum, page.getPageSize())
.build()
.toString();
}
@Override
public String getFindPageBySqlSQL(Page page, int startRowNum, String sql) {
String select = new MySQL.SqlBuilder()
.select()
.buildAllColumns()
.build()
.toString();
String limit = new MySQL.SqlBuilder()
.buildLimit(startRowNum, page.getPageSize())
.build()
.toString();
return select + " " + sql + " " + limit;
}
@Override
public String getFindCountBySqlSQL(String sql) {
String count = new MySQL.SqlBuilder()
.select()
.buildCount()
.build()
.toString();
return count + " " + sql;
}
/**
* 确定将要替代sql中占位符的实际值的类型。
*
* @throws NodeException 如果是未知MySQL类型。
*/
@Override
public Object typeHandler(String fieldType, String fieldValue) throws NodeException {
switch (fieldType) {
case DATE:
case YEAR:
case DATETIME:
case TIMESTAMP:
case TEXT:
case LONGTEXT:
case VARCHAR:
case CHAR:
return fieldValue;
case INT:
case TINYINT:
case SMALLINT:
case MEDIUMINT:
return Integer.valueOf(fieldValue);
case BIT:
return Boolean.valueOf(fieldValue);
case FLOAT:
return Float.valueOf(fieldValue);
case DOUBLE:
return Double.valueOf(fieldValue);
default:
throw new NodeException("[MysqlTypeHandler] 未支持的类型" + fieldType);
}
}
}
package com.wanji.common.framework.db.impl;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.db.DbInterface;
import com.wanji.common.framework.domain.Db;
import com.wanji.common.framework.exception.NodeException;
import com.wanji.common.framework.rest.Page;
import com.wanji.common.tool.dbtools.Oracle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.DbDriver.ORACLE;
import static com.wanji.common.framework.Constants.OracleColumn.*;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.BLANK;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.FIELD_NAME_EN;
/**
* Oracle数据库的基础操作接口实现
*
* @author mapabc
*/
@Slf4j
public class OracleDBImpl implements DbInterface {
@Override
public String getDriver() {
return Constants.DbDriver.ORACLE;
}
@Override
public String getDBUrl(Db dataBase) {
return new StringBuilder("jdbc:oracle:thin:@")
.append(dataBase.getIp()).append(":")
.append(dataBase.getPort()).append(":")
.append(dataBase.getName())
.toString();
}
@Override
public String getInsertSQL(String tableName, List<Map<String, Object>> insertParams) {
// 2、拼接带有占位符的insertSql
StringBuilder columns = new StringBuilder("(");
StringBuilder values = new StringBuilder("(");
int paramSize = insertParams.size();
for (int i = 0; i < paramSize; i++) {
Map<String, Object> insertParam = insertParams.get(i);
String fieldName = insertParam.get(FIELD_NAME_EN).toString();
if (i == (paramSize - 1)) {
columns.append("\"").append(fieldName).append("\"").append(")");
values.append("?)");
} else {
columns.append("\"").append(fieldName).append("\"").append(",");
values.append("?,");
}
}
return new StringBuilder("INSERT INTO").append(BLANK)
.append(tableName).append(BLANK)
.append(columns).append(BLANK)
.append("VALUES").append(BLANK)
.append(values).toString();
}
@Override
public String getUpdateSQL(String tableName, List<Map<String, Object>> updateParams,
List<Map<String, Object>> whereParams) {
return new Oracle.SqlBuilder()
.update(tableName)
.buildSet(updateParams)
.buildWhere(whereParams)
.build()
.toString();
}
@Override
public String getDeleteSQL(String tableName, List<Map<String, Object>> whereParams) {
return new Oracle.SqlBuilder()
.delete()
.buildFrom(tableName)
.buildWhere(whereParams)
.build().toString();
}
@Override
public String getFindByIdSQL(String tableName, String id) {
return new Oracle.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.build()
.toString() + " WHERE \"" + id + "\" = ? ";
}
@Override
public String getFindByWhereSQL(String tableName,
List<Map<String, Object>> whereParams,
List<Map<String, String>> orderMap) {
return new Oracle.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.buildWhere(whereParams)
.buildOrder(orderMap)
.build()
.toString();
}
@Override
public String getFindCountSQL(String tableName, List<Map<String, Object>> whereParams) {
return new Oracle.SqlBuilder()
.select()
.buildCount()
.buildFrom(tableName)
.buildWhere(whereParams)
.build()
.toString();
}
@Override
public String getFindByPageSQL(String tableName, Page page,
List<Map<String, Object>> whereParams,
int startRowNum,
List<Map<String, String>> orderMap) {
String prefixSql = "SELECT * FROM ( SELECT all_rows.*, ROWNUM RN FROM (";
String infixSelectSql = new Oracle.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.buildWhere(whereParams)
.buildOrder(orderMap)
.build()
.toString();
int endRowNum = page.getPageSize() + startRowNum;
String postfixSql = ") all_rows WHERE ROWNUM <= " + endRowNum + ") WHERE RN > " + startRowNum;
return prefixSql + infixSelectSql + postfixSql;
}
@Override
public String getFindPageBySqlSQL(Page page, int startRowNum, String sql) {
String select = new Oracle.SqlBuilder()
.select()
.buildAllColumns()
.build()
.toString();
int endRowNum = page.getPageSize() + startRowNum;
String postfixSql = ") all_rows WHERE ROWNUM <= " + endRowNum + ") WHERE RN > " + startRowNum;
return select + " " + sql + " " + postfixSql;
}
@Override
public String getFindCountBySqlSQL(String sql) {
String count = new Oracle.SqlBuilder()
.select()
.buildCount()
.build()
.toString();
return count + " " + sql;
}
/**
* 确定将要替代sql中占位符的实际值的类型。
*
* @throws NodeException 如果是未知Oracle类型。
*/
public Object typeHandler(String fieldType, String fieldValue) throws NodeException {
switch (fieldType) {
case ORACLE_CHAR:
case VARCHAR2:
case VARCHAR:
return fieldValue;
case NUMBER:
return Long.valueOf(fieldValue);
case FLOAT:
return Double.valueOf(fieldValue);
case TIMESTAMP:
case DATE:
return Timestamp.valueOf(fieldValue);
default:
throw new NodeException("[OracleTypeHandler] 未支持的类型" + fieldType);
}
}
}
package com.wanji.common.framework.db.impl;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.db.DbInterface;
import com.wanji.common.framework.domain.Db;
import com.wanji.common.framework.exception.NodeException;
import com.wanji.common.framework.rest.Page;
import com.wanji.common.tool.dbtools.PostgreSQL;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.PostGreSqlColumn.*;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.BLANK;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.FIELD_NAME_EN;
/**
* Mysql数据库的基础操作接口实现
*
* @author mapabc
*/
@Slf4j
public class PostgresqlDBImpl implements DbInterface {
@Override
public String getDriver() {
return Constants.DbDriver.POSTGRESQL;
}
@Override
public String getDBUrl(Db dataBase) {
return new StringBuilder("jdbc:postgresql://")
.append(dataBase.getIp()).append(":")
.append(dataBase.getPort()).append("/")
.append(dataBase.getName())
.toString();
}
@Override
public String getInsertSQL(String tableName, List<Map<String, Object>> insertParams) {
// 拼接带有占位符的insertSql: insert into table (col1, col2...) values (val1, val2...)
StringBuilder columns = new StringBuilder("(");
StringBuilder values = new StringBuilder("(");
int paramSize = insertParams.size();
for (int i = 0; i < paramSize; i++) {
Map<String, Object> insertParam = insertParams.get(i);
String fieldName = insertParam.get(FIELD_NAME_EN).toString();
if (i == (paramSize - 1)) {
columns.append(fieldName).append(")");
values.append("?)");
} else {
columns.append(fieldName).append(",");
values.append("?,");
}
}
return new StringBuilder("INSERT INTO").append(BLANK)
.append(tableName).append(BLANK)
.append(columns).append(BLANK)
.append("VALUES").append(BLANK)
.append(values).toString();
}
@Override
public String getUpdateSQL(String tableName, List<Map<String, Object>> updateParams,
List<Map<String, Object>> whereParams) {
return new PostgreSQL.SqlBuilder()
.update(tableName)
.buildSet(updateParams)
.buildWhere(whereParams)
.build()
.toString();
}
@Override
public String getDeleteSQL(String tableName, List<Map<String, Object>> whereParams) {
return new PostgreSQL.SqlBuilder()
.delete()
.buildFrom(tableName)
.buildWhere(whereParams)
.build().toString();
}
@Override
public String getFindByIdSQL(String tableName, String id) {
return new PostgreSQL.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.build()
.toString() + " where " + id + " = ? ";
}
@Override
public String getFindByWhereSQL(String tableName,
List<Map<String, Object>> whereParams,
List<Map<String, String>> orderMap) {
return new PostgreSQL.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.buildWhere(whereParams)
.buildOrder(orderMap)
.build()
.toString();
}
@Override
public String getFindCountSQL(String tableName, List<Map<String, Object>> whereParams) {
return new PostgreSQL.SqlBuilder()
.select()
.buildCount()
.buildFrom(tableName)
.buildWhere(whereParams)
.build()
.toString();
}
@Override
public String getFindByPageSQL(String tableName, Page page,
List<Map<String, Object>> whereParams,
int startRowNum,
List<Map<String, String>> orderMap) {
return new PostgreSQL.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.buildWhere(whereParams)
.buildOrder(orderMap)
.buildLimit(startRowNum, page.getPageSize())
.build()
.toString();
}
@Override
public String getFindPageBySqlSQL(Page page, int startRowNum, String sql) {
String select = new PostgreSQL.SqlBuilder()
.select()
.buildAllColumns()
.build()
.toString();
String limit = new PostgreSQL.SqlBuilder()
.buildLimit(startRowNum, page.getPageSize())
.build()
.toString();
return select + " " + sql + " " + limit;
}
@Override
public String getFindCountBySqlSQL(String sql) {
String count = new PostgreSQL.SqlBuilder()
.select()
.buildCount()
.build()
.toString();
return count + " " + sql;
}
/**
* 确定将要替代sql中占位符的实际值的类型。
*
* @throws NodeException 如果是未知 Beyon 类型。
*/
@Override
public Object typeHandler(String fieldType, String fieldValue) throws NodeException {
switch (fieldType) {
case FLOAT4:
return Float.valueOf(fieldValue);
case FLOAT8:
case MONEY:
return Double.valueOf(fieldValue);
case INT4:
case INT2:
return Integer.valueOf(fieldValue);
case BOOL:
case com.wanji.common.framework.Constants.PostGreSqlColumn.BIT:
return Boolean.valueOf(fieldValue);
case NUMERIC:
return new BigDecimal(fieldValue);
case INT8:
return Long.valueOf(fieldValue);
case TIMESTAMP:
return Timestamp.valueOf(fieldValue);
case TIME:
return Time.valueOf(fieldValue);
case DATE:
return Date.valueOf(fieldValue);
case BYTEA:
case TEXT:
case BPCHAR:
case com.wanji.common.framework.Constants.PostGreSqlColumn.VARCHAR:
case BOX:
case CIDR:
case INET:
case MACADDR:
case VARBIT:
case CIRCLE:
case INTERVAL:
case LINE:
case LSEG:
case POLYGON:
case POINT:
case PATH:
return fieldValue;
default:
throw new NodeException("[BeyonTypeHandler] 未支持的类型:" + fieldType);
}
}
}
package com.wanji.common.framework.db.impl;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.db.DbInterface;
import com.wanji.common.framework.domain.Db;
import com.wanji.common.framework.exception.NodeException;
import com.wanji.common.framework.rest.Page;
import com.wanji.common.tool.dbtools.SQLServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.DbDriver.SQLSERVER;
import static com.wanji.common.framework.Constants.MysqlColumn.*;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.BLANK;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.FIELD_NAME_EN;
import static com.wanji.common.framework.Constants.SqlServerColumn.DATETIME2;
/**
* SQLServer 数据库的基础操作接口实现
*
* @author mapabc
*/
@Slf4j
public class SQLServerDBImpl implements DbInterface {
@Override
public String getDriver() {
return Constants.DbDriver.SQLSERVER;
}
@Override
public String getDBUrl(Db dataBase) {
return new StringBuilder("jdbc:sqlserver://")
.append(dataBase.getIp()).append(":")
.append(dataBase.getPort()).append(";DatabaseName=").append(dataBase.getName()).toString();
}
@Override
public String getInsertSQL(String tableName, List<Map<String, Object>> insertParams) {
// 拼接带有占位符的insertSql: insert into table (col1, col2...) values (val1, val2...)
StringBuilder columns = new StringBuilder("(");
StringBuilder values = new StringBuilder("(");
int paramSize = insertParams.size();
for (int i = 0; i < paramSize; i++) {
Map<String, Object> insertParam = insertParams.get(i);
String fieldName = insertParam.get(FIELD_NAME_EN).toString();
if (i == (paramSize - 1)) {
columns.append(fieldName).append(")");
values.append("?)");
} else {
columns.append(fieldName).append(",");
values.append("?,");
}
}
// 插入的sql语句
return new StringBuilder("INSERT INTO").append(BLANK)
.append(tableName).append(BLANK)
.append(columns).append(BLANK)
.append("VALUES").append(BLANK)
.append(values).toString();
}
@Override
public String getUpdateSQL(String tableName, List<Map<String, Object>> updateParams,
List<Map<String, Object>> whereParams) {
return new SQLServer.SqlBuilder()
.update(tableName)
.buildSet(updateParams)
.buildWhere(whereParams)
.build()
.toString();
}
@Override
public String getDeleteSQL(String tableName, List<Map<String, Object>> whereParams) {
return new SQLServer.SqlBuilder()
.delete()
.buildFrom(tableName)
.buildWhere(whereParams)
.build().toString();
}
@Override
public String getFindByIdSQL(String tableName, String id) {
return new SQLServer.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.build()
.toString() + " where " + id + " = ? ";
}
@Override
public String getFindByWhereSQL(String tableName,
List<Map<String, Object>> whereParams,
List<Map<String, String>> orderMap) {
return new SQLServer.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.buildWhere(whereParams)
.buildOrder(orderMap)
.build()
.toString();
}
@Override
public String getFindCountSQL(String tableName, List<Map<String, Object>> whereParams) {
return new SQLServer.SqlBuilder()
.select()
.buildCount()
.buildFrom(tableName)
.buildWhere(whereParams)
.build()
.toString();
}
@Override
public String getFindByPageSQL(String tableName, Page page,
List<Map<String, Object>> whereParams,
int startRowNum,
List<Map<String, String>> orderMap) {
return new SQLServer.SqlBuilder()
.select()
.buildAllColumns()
.buildFrom(tableName)
.buildWhere(whereParams)
.buildOrder(orderMap)
.buildOffset(startRowNum, page.getPageSize())
.build()
.toString();
}
@Override
public String getFindPageBySqlSQL(Page page, int startRowNum, String sql) {
String select = new SQLServer.SqlBuilder()
.select()
.buildAllColumns()
.build()
.toString();
String limit = new SQLServer.SqlBuilder()
.buildOffset(startRowNum, page.getPageSize())
.build()
.toString();
return select + " " + sql + " " + limit;
}
@Override
public String getFindCountBySqlSQL(String sql) {
String count = new SQLServer.SqlBuilder()
.select()
.buildCount()
.build()
.toString();
return count + " " + sql;
}
/**
* @Description: sqlServer类型转换器
**/
@Override
public Object typeHandler(String fieldType, String fieldValue) throws NodeException {
switch (fieldType) {
case VARCHAR:
case CHAR:
case TEXT:
return fieldValue;
case INT:
case TINYINT:
case SMALLINT:
case BIGINT:
return Integer.valueOf(fieldValue);
case FLOAT:
return Float.valueOf(fieldValue);
case DATETIME:
case DATETIME2:
return Timestamp.valueOf(fieldValue);
default:
throw new NodeException("SQLServer 未支持的类型" + fieldType);
}
}
}
package com.wanji.common.framework.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @Description: 数据库数据源
* @Author: xiaodong.zheng
* @Date: 2020/12/15 15:34
* @param
* @return
**/
@Data
@ApiModel(value = "DataBase", description = "数据库")
public class Db extends TrackableEntity {
@ApiModelProperty(value = "数据源名称")
private String name;
@ApiModelProperty(value = "数据源中文名称")
private String nameCn;
@ApiModelProperty(value = "数据源目录ID")
private String catalogId;
@ApiModelProperty(value = "数据源描述")
private String description;
@ApiModelProperty(value = "应用类型",example = "datasource,dataset")
private String appType;
@ApiModelProperty(value = "数据库类型", example = "mysql, oracle, sql server")
private String dbType;
@ApiModelProperty(value = "数据库ip")
private String ip;
@ApiModelProperty(value = "数据库端口")
private String port;
@ApiModelProperty(value = "数据库名称")
private String dbName;
@ApiModelProperty(value = "用户名")
private String user;
@ApiModelProperty(value = "密码")
private String pwd;
@ApiModelProperty(value = "Oracle数据库的模式")
private String schemaName;
}
package com.wanji.common.framework.domain;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Description:
* @Author mapabc4
* @Date 2019/12/16 15:13
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface FieldName {
/**
* 字段名
*/
String value() default "";
/**
* 是否忽略
*/
boolean Ignore() default false;
}
package com.wanji.common.framework.domain;
import com.alibaba.fastjson.annotation.JSONField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* 业务表模块操作日志实体类。
*
* @Author guoliang.dong@mapabc.com
* @Date 2021/12/22 17:30
*/
@Data
@ApiModel(description = "操作日志")
public class OperationLog extends TrackableEntity {
@ApiModelProperty("操作对象中文名)")
private String resName;
@ApiModelProperty("操作对象(类名)")
private String resType;
@ApiModelProperty("操作类型(方法)")
private String operationType;
@ApiModelProperty("操作人")
private String operationUser;
@ApiModelProperty("数据库id(有则记录)")
private String dbId;
@ApiModelProperty("操作描述信息(请求参数,json|多个参数都好分割)")
private String des;
@ApiModelProperty("操作状态")
private String status;
@ApiModelProperty("操作时长(结束-开始,单位毫秒)")
private Long operationTime;
@ApiModelProperty("开始时间")
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date startTime;
@ApiModelProperty("结束时间")
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date endTime;
@ApiModelProperty(value = "登录ip")
private String operationIp;
@ApiModelProperty(value = "请求参数详情")
private String clientParam;
@ApiModelProperty(value = "登录操作系统")
private String operationOS;
@ApiModelProperty(value = "登录浏览器")
private String operationBrowser;
}
package com.wanji.common.framework.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 导入表
*
* @author mapabc6
* @date 2020/3/18
*/
@Data
@ApiModel(value = "Table", description = "导入表")
public class Table extends TrackableEntity {
@ApiModelProperty(value = "中文表名")
private String nameCn;
@ApiModelProperty(value = "英文表名")
private String nameEn;
@ApiModelProperty(value = "oracle表所属模式名")
private String schemaName;
@ApiModelProperty(value = "表描述信息")
private String des;
}
package com.wanji.common.framework.domain;
import java.io.Serializable;
public class TileBox implements Serializable {
private static final long serialVersionUID = 1L;
private Double xmin;
private Double ymin;
private Double xmax;
private Double ymax;
public Double getXmin() {
return xmin;
}
public void setXmin(Double xmin) {
this.xmin = xmin;
}
public Double getYmin() {
return ymin;
}
public void setYmin(Double ymin) {
this.ymin = ymin;
}
public Double getXmax() {
return xmax;
}
public void setXmax(Double xmax) {
this.xmax = xmax;
}
public Double getYmax() {
return ymax;
}
public void setYmax(Double ymax) {
this.ymax = ymax;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(xmin);
sb.append(", ").append(ymin);
sb.append(", ").append(xmax);
sb.append(", ").append(ymax);
return sb.toString();
}
}
package com.wanji.common.framework.domain;
import com.alibaba.fastjson.annotation.JSONField;
import com.wanji.common.utils.tool.IDGenerator;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 继承自该类的entity表示是可被跟踪的,可以查询对应实体
*
* @author mapabc5
*/
@Getter
@Setter
@SuperBuilder
public class TrackableEntity implements Serializable {
private static final long serialVersionUID = -4052705808523280313L;
private static String ID = "id";
private static String CREATE_DATE = "createDate";
@QuerySqlField(index = true)
//update时需校验非空
// @NotBlank(groups = ValidationGroups.Update.class)
public String id;
@ApiModelProperty(value = "记录创建时间", example = "2016-08-01")
@JSONField(format = "yyyy-MM-dd")
@QuerySqlField(index = true)
private Date createDate;
@ApiModelProperty(value = "记录更新时间", example = "2016-08-01")
@JSONField(format = "yyyy-MM-dd")
private Date updateDate;
@ApiModelProperty(value = "扩展字段,例如:{\"key1\":\"value1\",\"key2\":\"value2\"}")
private Map<String, Object> expandMap;
@ApiModelProperty(value = "扩充字段")
private String expand;
protected TrackableEntity() {
}
/**
* 转换bean为map
*
* @param source 要转换的bean
* @param <T> bean类型
* @return 转换结果
*/
public static <T> Map<String, Object> bean2Map(T source) throws IllegalAccessException {
Map<String, Object> result = new HashMap<>();
Class<?> sourceClass = source.getClass();
//拿到所有的字段,不包括继承的字段
Field[] sourceFiled = sourceClass.getDeclaredFields();
for (Field field : sourceFiled) {
//设置可访问,不然拿不到private
field.setAccessible(true);
//配置了注解的话则使用注解名称,作为header字段
FieldName fieldName = field.getAnnotation(FieldName.class);
if (fieldName == null) {
result.put(field.getName(), getSource(field, source));
} else {
if (fieldName.Ignore()) {
continue;
}
result.put(fieldName.value(), field.get(source));
}
}
return result;
}
private static <T> Object getSource(Field field, T source) throws IllegalAccessException {
if (field.get(source) != null) {
return field.get(source);
}
if (ID.equals(field.getName())) {
return IDGenerator.getID();
}
if (CREATE_DATE.equals(field.getName())) {
return new Date();
}
return null;
}
}
package com.wanji.common.framework.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 封装D2A接口的执行结果。
* <p>
* 包括sql语句,查询参数和sql查询运行结果。
* 其中,前两者为了方便aop日志记录。
*
* @Author mapabc6
* @Date 2020/4/7 14:07
*/
@Data
@ApiModel(description = "执行结果")
public class View extends TrackableEntity {
@ApiModelProperty(notes = "生成的sql语句")
private String sql;
@ApiModelProperty(notes = "查询参数")
private Object[] queryParams;
@ApiModelProperty(notes = "sql执行结果")
private Object result;
}
package com.wanji.common.framework.dubbointerface;
import com.wanji.common.framework.domain.TrackableEntity;
import com.wanji.common.framework.exception.DubboProviderException;
import com.wanji.common.framework.rest.JsonViewObject;
import com.wanji.common.framework.rest.Page;
import java.util.List;
import java.util.Map;
/**
* dubbo抽象接口, 所有dubbo的接口都需要继承
*
* @param <Entity>
* @author mapabc
*/
public interface BaseDubboInterface<Entity extends TrackableEntity> {
/**
* 分页查询
*
* @param page
* @param map
* @return
* @throws DubboProviderException
*/
Page<Entity> findByPage(Page<Entity> page, Map<String, Object> map) throws DubboProviderException;
/**
* 持久化对象的信息
*
* @param entity
* @return
* @throws DubboProviderException
*/
JsonViewObject save(Entity entity) throws DubboProviderException;
/**
* 修改对象的信息
*
* @param entity
* @return
* @throws DubboProviderException
*/
JsonViewObject update(Entity entity) throws DubboProviderException;
/**
* 根据ID 删除指定的对象
*
* @param id
* @return
* @throws DubboProviderException
*/
JsonViewObject deleteById(String id) throws DubboProviderException;
/**
* 根据ID数组 删除指定的对象
*
* @param ids
* @return
* @throws DubboProviderException
*/
JsonViewObject deleteByIds(String[] ids) throws DubboProviderException;
/**
* 根据ID 查找指定的对象
*
* @param id
* @return
* @throws DubboProviderException
*/
Entity findById(String id) throws DubboProviderException;
/**
* 得到所有的对象
*
* @return
* @throws DubboProviderException
*/
List<Entity> findAll() throws DubboProviderException;
/**
* 用于多条件查询
*
* @param map
* @return
* @throws DubboProviderException
*/
List<Entity> findByMap(Map<String, Object> map) throws DubboProviderException;
/**
* 操作日志记录
* @param classNameCn
* @param className
* @param method
* @param username
* @param dbId
* @param lastTime
* @param jsonViewObject
*/
void sendOperationLog(String classNameCn, String className, String method, String username, String dbId, long lastTime, JsonViewObject jsonViewObject);
}
package com.wanji.common.framework.dubbointerface;
import com.wanji.common.framework.exception.DubboProviderException;
import com.wanji.common.framework.rest.JsonViewObject;
import org.elasticsearch.index.query.BoolQueryBuilder;
import java.util.Map;
// log 抽象接口, 所有 log 的接口都需要继承
public interface BaseLogInterface {
Boolean makeQueryBuilder(Map<String, Object> queryCondition, BoolQueryBuilder qb) throws Exception;
/**
* 查询接口
*
* @param params
* @return
*/
JsonViewObject logQuery(Map<String, Object> params) throws DubboProviderException;
/**
* 查询接口
*
* @param params
* @return
*/
JsonViewObject queryData(Map<String, Object> params) throws DubboProviderException;
/**
* 保存日志
*
* @param logData
* @return
*/
boolean saveServiceLog(String indexName, String typeName, Map<String, Object> logData) throws DubboProviderException;
}
package com.wanji.common.framework.dubbointerface.impl;
import com.alibaba.fastjson.JSONObject;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.domain.OperationLog;
import com.wanji.common.framework.domain.TrackableEntity;
import com.wanji.common.framework.dubbointerface.BaseDubboInterface;
import com.wanji.common.framework.exception.DubboProviderException;
import com.wanji.common.framework.mapper.BaseInterfaceMapper;
import com.wanji.common.framework.rest.JsonViewObject;
import com.wanji.common.framework.rest.Page;
import com.wanji.common.tool.mqtool.MqUtil;
import com.wanji.common.utils.tool.IDGenerator;
import com.wanji.common.utils.tool.StringUtils;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import static com.wanji.common.framework.Constants.LogType.OPERATION_LOG;
/**
* @author mapabc
*/
@Transactional(rollbackFor = Exception.class)
@Slf4j
public abstract class BaseDubboInterfaceImpl<Entity extends TrackableEntity> implements BaseDubboInterface<Entity> {
public static final String EXISTS = "exists";
public static final String TRUE = "true";
public static final String FALSE = "false";
@Override
public Page<Entity> findByPage(Page<Entity> page, Map<String, Object> map) throws DubboProviderException {
try {
if (map.get("keyword") == null || StringUtils.isBlank((String) map.get("keyword"))) {
map.put("keyword", (Object)null);
}
page.setTotal(this.getBaseInterfaceMapper().getCount(map));
page = Page.newInstance(page.getPageSize(), page.getTotal(), page.getPageNum());
map.put("startRowNum", page.getStartRowNum());
map.put("pageSize", page.getPageSize());
page.setRows(this.getBaseInterfaceMapper().findByPage(map));
} catch (Exception e) {
log.error("BaseDubboInterfaceImpl findByPage ", e);
throw new DubboProviderException(e.getMessage(), e);
}
return page;
}
@Override
public JsonViewObject save(Entity entity) throws DubboProviderException {
JsonViewObject jsonViewObject = JsonViewObject.newInstance();
try {
entity.setId(IDGenerator.getID());
entity.setCreateDate(new Date());
this.getBaseInterfaceMapper().save(entity);
jsonViewObject.success(entity.getId(), "数据保存成功!");
} catch (Exception e) {
jsonViewObject.fail("数据保存失败!");
log.error("BaseDubboInterfaceImpl save ", e);
throw new DubboProviderException(e.getMessage(), e);
}
return jsonViewObject;
}
@Override
public JsonViewObject update(Entity entity) throws DubboProviderException {
JsonViewObject jsonViewObject = JsonViewObject.newInstance();
try {
// entity.setCreateDate(new Date());
Integer updateCount = this.getBaseInterfaceMapper().update(entity);
jsonViewObject.success(updateCount, "数据修改成功!");
} catch (Exception e) {
jsonViewObject.fail("数据修改失败!");
log.error("BaseDubboInterfaceImpl update ", e);
throw new DubboProviderException(e.getMessage(), e);
}
return jsonViewObject;
}
@Override
public JsonViewObject deleteById(String id) throws DubboProviderException {
JsonViewObject jsonViewObject = JsonViewObject.newInstance();
try {
Integer deleteCount = this.getBaseInterfaceMapper().deleteById(id);
if (deleteCount < 1) {
jsonViewObject.fail(deleteCount, "删除数据不存在!");
} else {
jsonViewObject.success(deleteCount, "数据删除成功!");
}
} catch (Exception e) {
jsonViewObject.fail("数据删除失败!");
log.error("BaseDubboInterfaceImpl deleteById ", e);
throw new DubboProviderException(e.getMessage(), e);
}
return jsonViewObject;
}
@Override
public JsonViewObject deleteByIds(String[] ids) throws DubboProviderException {
JsonViewObject jsonViewObject = JsonViewObject.newInstance();
try {
Integer deleteCount = this.getBaseInterfaceMapper().deleteByIds(Arrays.asList(ids));
if (deleteCount < 1) {
jsonViewObject.fail(deleteCount, "删除数据不存在!");
} else {
jsonViewObject.success(deleteCount, "数据删除成功!");
}
} catch (Exception e) {
jsonViewObject.fail("数据删除失败!");
log.error("BaseDubboInterfaceImpl deleteById ", e);
throw new DubboProviderException(e.getMessage(), e);
}
return jsonViewObject;
}
@Override
public Entity findById(String id) throws DubboProviderException {
Entity entity;
try {
entity = this.getBaseInterfaceMapper().findById(id);
} catch (Exception e) {
log.error("BaseDubboInterfaceImpl findById ", e);
throw new DubboProviderException(e.getMessage(), e);
}
return entity;
}
@Override
public List<Entity> findAll() throws DubboProviderException {
List<Entity> list;
try {
list = this.getBaseInterfaceMapper().findAll();
} catch (Exception e) {
log.error("BaseDubboInterfaceImpl findAll ", e);
throw new DubboProviderException(e.getMessage(), e);
}
return list;
}
@Override
public List<Entity> findByMap(Map<String, Object> map) throws DubboProviderException {
List<Entity> list;
try {
list = this.getBaseInterfaceMapper().findByMap(map);
} catch (Exception e) {
log.error("BaseDubboInterfaceImpl findByMap", e);
throw new DubboProviderException(e.getMessage(), e);
}
return list;
}
@Override
public void sendOperationLog(String classNameCn,String className,String method,String username,String dbId,long lastTime,JsonViewObject jsonViewObject) {
OperationLog opLog = new OperationLog();
try {
opLog.setResName(classNameCn);
opLog.setResType(className);
opLog.setOperationType(method);
opLog.setOperationUser(username);
opLog.setDbId(dbId);
opLog.setDes(Objects.isNull(jsonViewObject) ? "" : JSONObject.toJSONString(jsonViewObject));
opLog.setOperationTime(lastTime);
opLog.setStartTime(new Date());
opLog.setEndTime(new Date());
opLog.setStatus(Objects.isNull(jsonViewObject) ? Constants.JsonView.STATUS_FAIL : jsonViewObject.getStatus());
try {
//用户客户端操作系统
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
if (Objects.nonNull(request)) {
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
//获取客户端操作系统
OperatingSystem agentOs = userAgent.getOperatingSystem();
//获取客户端浏览器
String agentBrowser = "";
if (null != userAgent.getBrowser() && null != userAgent.getBrowserVersion()) {
agentBrowser = userAgent.getBrowser().getName() + " " + userAgent.getBrowserVersion().getVersion();
}
opLog.setOperationOS(agentOs.getName());
opLog.setOperationBrowser(agentBrowser);
opLog.setClientParam(request.getHeader("User-Agent"));
String agentIp = request.getHeader("X-Real-IP");
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("X-Forwarded-For");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("Proxy-Client-IP");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("WL-Proxy-Client-IP");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getRemoteAddr();
}
opLog.setOperationIp("0:0:0:0:0:0:0:1".equals(agentIp) ? "127.0.0.1" : agentIp);
}
} catch (Exception ex) {
ex.printStackTrace();
}
MqUtil.sendLogMessage(OPERATION_LOG.toString(), OPERATION_LOG.toString(), TrackableEntity.bean2Map(opLog));
} catch (Exception e) {
log.error("SendOperationLog error", e);
}
}
/**
* 抽象方法需要实现,得到基础服务接口
*
* @return
*/
public abstract BaseInterfaceMapper<Entity> getBaseInterfaceMapper();
}
package com.wanji.common.framework.dubbointerface.impl;
import com.wanji.common.framework.dubbointerface.BaseLogInterface;
import com.wanji.common.framework.exception.DubboProviderException;
import com.wanji.common.framework.rest.JsonViewObject;
import com.wanji.common.framework.rest.Page;
import com.wanji.common.tool.estool.EsConfiguration;
import com.wanji.common.tool.estool.EsUtil;
import com.wanji.common.utils.tool.IDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
/**
* @author mapabc
*/
@Slf4j
public abstract class BaseLogInterfaceImpl implements BaseLogInterface {
public static final String PAGE_NUM = "pageNum";
public static final String TYPE = "type";
public static final String PAGE_SIZE = "pageSize";
public static final String CREATE_TIME = "createTime";
public static final String START_TIME = "startTime";
public static final String END_TIME = "endTime";
public static final String API_ID = "apiId";
public static final String API_ID_KEYWORD = "apiId.keyword";
public static final String STATUS = "status";
public static final String STATUS_KEYWORD = "status.keyword";
public static EsUtil esUtil = EsUtil.getInstance();
@Override
public JsonViewObject logQuery(Map<String, Object> queryCondition) {
JsonViewObject jsonViewObject = JsonViewObject.newInstance();
Page page = Page.newInstance();
BoolQueryBuilder qb = QueryBuilders.boolQuery();
if (queryCondition == null || queryCondition.isEmpty()) {
return jsonViewObject.success(page, "查询成功");
}
try {
String type = queryCondition.getOrDefault(TYPE, "").toString();
if (StringUtils.isBlank(type)) {
log.error("参数错误 type 为空");
return jsonViewObject.fail("参数错误");
}
// 分页
Page pageNumAndSize = getPageNumAndSize(queryCondition);
int startRow = pageNumAndSize.getPageSize() * (pageNumAndSize.getPageNum() - 1);
page.setPageNum(pageNumAndSize.getPageNum());
page.setPageSize(pageNumAndSize.getPageSize());
qb.must(QueryBuilders.rangeQuery(CREATE_TIME).from(queryCondition.get(START_TIME))
.to(queryCondition.get(END_TIME)));
this.makeQueryBuilder(queryCondition, qb);
// 排序
Queue<SortBuilder> queue = getSortQueue(CREATE_TIME, SortOrder.DESC);
page.setTotal(esUtil.searchDatasCount(EsConfiguration.getTransportClient(), type, type, qb).intValue());
page.setRows(esUtil.searchDatas(EsConfiguration.getTransportClient(), type, type, qb, startRow, pageNumAndSize.getPageSize(), queue));
jsonViewObject.success(page, "查询成功");
} catch (Exception e) {
log.error("logQuery error", e);
jsonViewObject.fail(false, "查询失败");
}
return jsonViewObject;
}
@Override
public JsonViewObject queryData(Map<String, Object> queryCondition) {
JsonViewObject jsonViewObject = JsonViewObject.newInstance();
BoolQueryBuilder qb = QueryBuilders.boolQuery();
try {
String type = queryCondition.getOrDefault(TYPE, "").toString();
if (StringUtils.isBlank(type)) {
return jsonViewObject.fail("参数错误");
}
qb.must(QueryBuilders.rangeQuery(CREATE_TIME).from(queryCondition.get(START_TIME))
.to(queryCondition.get(END_TIME)));
this.makeQueryBuilder(queryCondition, qb);
// 排序
Queue<SortBuilder> queue = getSortQueue(CREATE_TIME, SortOrder.DESC);
List<Map<String, Object>> result = esUtil.searchDatas(EsConfiguration.getTransportClient(), type, type, qb, queue);
jsonViewObject.success(result, "查询成功");
} catch (Exception e) {
log.error("queryData error", e);
jsonViewObject.fail(false, "查询失败");
}
return jsonViewObject;
}
@Override
public boolean saveServiceLog(String indexName, String typeName, Map<String, Object> logData) throws DubboProviderException {
return esUtil.putIndexData(EsConfiguration.getTransportClient(), indexName, typeName, IDGenerator.getID(), logData);
}
// 分页
public Page getPageNumAndSize(Map<String, Object> queryCondition) {
Page pageNumAndSize = Page.newInstance();
String s = queryCondition.getOrDefault(PAGE_NUM, 1).toString();
int pageNum = 1;
if (StringUtils.isNotBlank(s)) {
pageNum = Integer.valueOf(s);
}
pageNumAndSize.setPageNum(pageNum);
s = queryCondition.getOrDefault(PAGE_SIZE, 10).toString();
int pageSize = 10;
if (StringUtils.isNotBlank(s)) {
pageSize = Integer.valueOf(s);
}
pageNumAndSize.setPageSize(pageSize);
return pageNumAndSize;
}
// 排序
public Queue<SortBuilder> getSortQueue(String sort, SortOrder type) {
SortBuilder createTime = SortBuilders.fieldSort(sort).order(type);
Queue<SortBuilder> queue = new ArrayBlockingQueue<>(2);
queue.add(createTime);
return queue;
}
}
package com.wanji.common.framework.event;
import org.springframework.context.ApplicationEvent;
/**
* @Description: spring 事件驱动模型,定义事件源
* @Author mapabc
* @Date 2020/3/22 16:49
*/
public abstract class BaseEvent<T> extends ApplicationEvent {
private static final long serialVersionUID = 895628808370649881L;
protected T eventData;
public BaseEvent(Object source, T eventData) {
super(source);
this.eventData = eventData;
}
public BaseEvent(T eventData) {
super(eventData);
}
public T getEventData() {
return eventData;
}
public void setEventData(T eventData) {
this.eventData = eventData;
}
}
package com.wanji.common.framework.exception;
/**
* @author mapabc
* @date 2016/10/27
*/
public class DubboProviderException extends Exception {
private static final long serialVersionUID = 1L;
public DubboProviderException(Exception e) {
super(e);
}
public DubboProviderException(String msg, Exception e) {
super(msg, e);
}
public DubboProviderException(String msg) {
super(msg);
}
}
package com.wanji.common.framework.exception;
/**
* 类描述: bpmn20.xml写入异常
*
* @Author mapabc
* @Date 2019/8/5 19:25
*/
public class Json2BpmnXmlException extends Exception {
public Json2BpmnXmlException(Exception e) {
super(e);
}
public Json2BpmnXmlException(String msg, Exception e) {
super(msg, e);
}
public Json2BpmnXmlException(String msg) {
super(msg);
}
}
package com.wanji.common.framework.exception;
/**
* 节点异常处理
*
* @author mapabc4
*/
public class NodeException extends Exception {
public NodeException(Exception e) {
super(e);
}
public NodeException(String msg, Exception e) {
super(msg, e);
}
public NodeException(String msg) {
super(msg);
}
}
package com.wanji.common.framework.exception;
/**
* 类描述: 流程服务异常
*
* @Author mapabc
* @Date 2019/8/5 19:25
*/
public class ProcessServiceException extends Exception {
public ProcessServiceException(Exception e) {
super(e);
}
public ProcessServiceException(String msg, Exception e) {
super(msg, e);
}
public ProcessServiceException(String msg) {
super(msg);
}
}
package com.wanji.common.framework.exception;
import com.wanji.common.framework.rest.JsonViewObject;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Description:
* @Author Jack
* @Date 2020/8/25 14:33
*/
@RestControllerAdvice
public class RestArgumentsExceptionHandler {
//处理针对DTO的参数格式错误
@ExceptionHandler(MethodArgumentNotValidException.class)
public JsonViewObject handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
//一次性返回所有非法参数提示
List<String> errors = fieldErrors.stream()
.map(filedError -> String.format("参数【%s】不合法:%s",
filedError.getField(),
filedError.getDefaultMessage()))
.collect(Collectors.toList());
return JsonViewObject.newInstance().fail(errors, "请求参数格式错误!");
}
//处理RequestParam形式的参数校验错误
@ExceptionHandler(ConstraintViolationException.class)
public JsonViewObject handleMethodArgumentNotValidException(ConstraintViolationException e) {
List<String> errors = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
return JsonViewObject.newInstance().fail(String.join(",", errors), "请求参数格式错误!");
}
}
package com.wanji.common.framework.exception;
/**
* l流程异常处理
*
* @author mapabc4
*/
public class WorkFlowException extends Exception {
public WorkFlowException(Exception e) {
super(e);
}
public WorkFlowException(String msg, Exception e) {
super(msg, e);
}
public WorkFlowException(String msg) {
super(msg);
}
}
package com.wanji.common.framework.i18n;
/**
* @Description:国际化中,中文定义的词条
* @return
* @Author mapabc
* @Date 2019/11/30 11:19
**/
public final class Constants {
public static final String SAVE_SUCCESS_MSG = "数据保存成功!";
public static final String SAVE_FAILED_MSG = "数据保存失败!";
public static final String GET_FAILED_MSG = "获取数据失败!";
public static final String DELETE_FAILED_MSG = "删除数据失败!";
public static final String UPDATE_FAILED_MSG = "更新数据失败!";
public static final String BATCHSAVE_FAILED_MSG = "批量保存数据失败!";
public static final String BATCHUPDATE_FAILED_MSG = "批量更新数据失败!";
public static final String GET_CARD_ALLUSER_FAILED_MSG = "获取待生成名片的企业用户列表失败!";
public static final String PASSWORD_FALED = "您输入的密码不正确,请检查后重新提交!";
public static final String SAVE_CARD_FAILED_MSG = "保存名片失败!";
public static final String GET_CATALOG_FALED_MSG = "获取目录失败!";
public static final String PANEL_MENU_REST_SERVER_GET_TREEMENU_ERROR = "获取树形菜单列表失败!";
public static final String ENGINE_DEPLOY_REST_SERVER_OPTIONAL_SERVER_ERROR = "获取可部署的服务器失败!";
public static final String LACK_OF_PARAMETER = "缺失必要参数!";
public static final String USER_NAME_CANNOT_USERINFO = "根据用户名无法获取该用户信息!";
public static final String PASSWORD_ERROR = "密码错误!";
public static final String FAILED_TO_CANCEL_USER_ROLE_ASSIGNMENT = "取消用户角色分配失败!";
public static final String GET_ROLE_LIST_FAILED = "获取用户列表失败!";
public static final String USER_NAME_NO_EXIST = "用户名不存在!";
public static final String USER_DELETE = "此用户已删除!";
public static final String USER_OVERDUE = "用户过期!";
public static final String USER_NAME_NO_FIND_USER_INFO = "根据用户名无法获取该用户信息!";
public static final String AGAIN_LOGIN = "请重新登录!";
public static final String EXIT_LOGIN_SUCCESS = "退出登录成功!";
public static final String MESSAGE_FAIL = "操作失败!";
public static final String MESSAGE_SUCCESS = "操作成功!";
public static final String MESSAGE_PARAM_ERROR = "参数错误!";
public static final String MESSAGE_LOGIN_SUCCESS = "登录成功";
public static final String CREATE_SUCCESS = "创建成功";
public static final String CREATE_TABLE_FAILE = "创建表失败";
public static final String DELETE_SUCCESS = "删除成功";
public static final String DELETE_TABLE_FAILE = "删除表失败";
public static final String DELETE_TABLE_FIELD_FAILE = "删除表字段失败";
public static final String GET_LIST_IMPORT_TABLE_FAILE = "获取可导入列表失败";
public static final String DICTIONARY_NO_KEY_VALUE = "该字典下无此键值对";
public static final String CONFIGURATION_CONDITIONS_IS_NULL = "配置条件含空";
public static final String CONFIGURATION_VALUES_IS_NULL = "配置值含空";
public static final String CONFIGURATION_PARAMETER_FORMAT_FAILE = "配置参数格式错误";
public static final String CONFIGURATION_SUCCESS = "配置成功";
public static final String CONFIGURATION_FAILE = "配置失败";
public static final String SUCCESS_TABLE_FIELD_ARRAY_FAILE = "保存表字段数组失败";
public static final String CHOOSE_JAR_UPLOAD = "请选择一个jar包上传";
public static final String JAR_EXIST = "jar包已存在";
public static final String JAR_UPLOAD_SUCCESS = "jar包上传成功";
public static final String JAR_UPLOAD_FAILE = "jar包上传失败";
public static final String JAR_DELETE_FAILE = "jar包删除失败";
public static final String GET_JAR_SUCCESS = "获取jar包成功";
public static final String GET_JAR_FAILE = "获取jar包失败";
public static final String IO_CLOSE_FAILE = "流关闭失败";
public static final String GET_FILE_FUNCTION_FAILE = "获取json文件中函数失败";
public static final String GET_FILE_LIST_FAILE = "获取文件名列表失败";
public static final String GET_FILE_LOG_CONTENT = "获取日志文件内容";
public static final String DELETE_FILE_LOG_SUCCESS = "删除日志文件成功";
public static final String DELETE_FILE_LOG_FAILE = "删除日志文件失败";
public static final String FILE_NO_FIND = "文件不存在";
public static final String DOWLOAD_FAILE = "下载失败";
public static final String DOWLOAD_SUCCESS = "下载成功";
public static final String GET_DEPLOY_FAILE = "获取已部署服务器失败";
public static final String GET_LOG_FILE_LIST_FAILE = "日志文件列表获取失败";
public static final String READ_LOG_FILE_FAILE = "日志文件读取失败";
public static final String CLOSE_SERVER = "已关闭远程连接";
public static final String GET_LOWER_MENU_ERROR = "获取上级目录失败";
public static final String GET_ALL_TREE_MENU_ERROR = "获取树形菜单列表失败";
public static final String GET_TOP_TREE_MENU_ERROR = "获取顶级树形菜单列表失败";
public static final String BATCH_UPDATE_MENU_LIST_IS_NULL = "批量更改列表为空";
public static final String UPDATE_BATCH_MENU_LIST_ERROR = "更改菜单列表失败";
public static final String GET_VALUE_BY_KEY_ERROR = "获取失败";
public static final String DELETE_PLUGIN_ERROR = "删除插件失败";
public static final String GET_SERVICE_LIST_ERROR = "获取服务列表失败";
public static final String ADD_PARAMETER_ERROR = "添加参数失败";
public static final String PARAM_TABLE_ID_IS_NULL = "参数中未包含业务表id";
public static final String AUTO_CREATE_INTERFACE_ERROR = "自动生成业务表基础接口失败";
public static final String GET_PARAM_LIST_FAILE = "获取参数列表失败";
public static final String GET_INTERFACE_FIELD_LIST_FAILE = "获取接口字段列表失败";
public static final String PARAM_FORMAT_FAILE = "参数格式有误";
public static final String SERVICE_ID_IS_NULL = "服务id为空";
public static final String GET_SERVICE_BUILDER_ERROR = "生成接口信息失败";
public static final String GET_PLUGIN_SUCCESS = "获取插件成功";
public static final String GET_PLUGIN_FAILE = "获取插件失败";
public static final String GET_TEMPLATE_INTERFACE_SUCCESS = "获取模块接口成功";
public static final String SAVE_DATA_IS_NULL = "保存数据为空";
public static final String PARAM_IS_NULL = "传入参数为空";
public static final String IMPPORT_TABLE_FAILE = "导入表失败";
public static final String GET_IMPORT_SUCCESS = "获取可导入模式成功";
public static final String GET_IMPORT_FAILE = "获取可导入模式失败";
public static final String GET_IMPORT_TABLE_SUCCESS = "获取可导入表成功";
public static final String GET_IMPORT_TABLE_FAILE = "获取可导入表失败";
public static final String CREATE_PROXY_SUCCESS = "生成代理成功";
public static final String PARAM_DATABASE_ID_IS_NULL = "参数中未包含数据库id";
public static final String CERT_FILE_IS_NULL = "请选择证书文件";
public static final String CERT_UPLOAD_FAILE = "证书上传失败";
public static final String CHECK_CONFIG_IS_NULL = "未勾选配置";
public static final String TEST_INTERFACE_SERVICE_FAILE = "测试接口服务失败";
public static final String GET_LIST_ALL_SCHEDULE_MENU_ERROR = "获取所有调度任务目录失败";
public static final String START_SUCCESS = "启动成功";
public static final String START_FAIL = "启动失败";
public static final String STOP_SUCCESS = "停止成功";
public static final String STOP_FAILE = "停止失败";
public static final String GET_SCHEDULE_LIST_ERROR = "获取调度列表失败";
public static final String PAGE_UPLOAD_SUCCESS = "页面上传成功";
public static final String PAGE_UPLOAD_FAILE = "页面上传成功";
public static final String APPLICATION_CATEGORY_CONTAINS_APPLICATION_DELETE_FAILE = "该应用类别仍含有应用,无法删除";
public static final String GET_CARD_LIST_MENU_PERMISSION_FAILE = "获取名片列表时联查菜单权限失败";
public static final String DIRECTORY_TREE_IS_DIRTY_NULLPOINTEREXCEPTION = "装配目录树因脏数据导致空指针异常";
public static final String USER_NAME_IS_NULL = "用户姓名为空";
public static final String USER_PHONE_IS_NULL = "手机号为空";
public static final String GET_TREE_MENU_LIST_FAILE = "获取树形菜单列表失败";
public static final String GET_FILE_LIST_SUCCESS = "获取文件名列表成功";
public static final String GET_FILE_MESSAGE_SUCCESS = "获取文件内容成功";
public static final String GET_DEPLOY_SERVER_SUCCESS = "获取已部署服务器成功";
public static final String GET_STATUS_FAILE = "获取未读或已读消息失败";
public static final String GET_QUERY_HISTORY_MESSAGE_SUCCESS = "查询历史消息成功";
public static final String GET_MESSAGE_SUBSCRIBE_HAVE_DATA = "消息订阅有数据不能删除";
public static final String GET_MESSAGE_FILTER_HAVE_DATA = "消息过滤有数据,不能删除";
public static final String DELETE_DATA_SUCCESS = "数据删除成功";
public static final String DELETE_DATA_FAILE = "数据删除失败";
public static final String LOGIN_SERVES_SUCCESS = "登陆服务器成功";
public static final String GET_LOG_FAILE = "该目录下无指定日志级别文件";
public static final String GET_REMOTE_SERVICE_LOG_FAILE = "读取远程服务器日志失败";
public static final String GET_REMOTE_SERVICE_LOG_SUCCESS = "读取远程服务器日志成功";
public static final String DOWNLOAD_REMOTE_SERVICE_LOG_SUCCESS = "下载远程服务器日志成功";
public static final String DELETE_REMOTE_SERVICE_LOG_SUCCESS = "删除远程服务器日志成功";
public static final String GET_LOG_FILE_LIST_SUCCESS = "获取日志文件列表成功";
}
package com.wanji.common.framework.i18n;
/**
* @Description:国际化中,英文定义的词条
* @return
* @Author mapabc
* @Date 2019/11/30 11:19
**/
public final class Constants_en {
public static final String SAVE_SUCCESS_MSG = "Data saved success!";
public static final String SAVE_FAILED_MSG = "Data saved failed!";
public static final String GET_FAILED_MSG = "Get date failed!";
public static final String DELETE_FAILED_MSG = "Delete date failed!";
public static final String UPDATE_FAILED_MSG = "Update date failed!";
public static final String BATCHSAVE_FAILED_MSG = "Batch save date failed!";
public static final String BATCHUPDATE_FAILED_MSG = "Batch update date failed!";
public static final String GET_CARD_ALLUSER_FAILED_MSG = "Get list of business users to generate the business card";
public static final String PASSWORD_FALED = "The password you entered is not correct please check and resubmit";
public static final String SAVE_CARD_FAILED_MSG = "Save card failed!";
public static final String GET_CATALOG_FALED_MSG = "Get catalog failed!";
public static final String PANEL_MENU_REST_SERVER_GET_TREEMENU_ERROR = "PanelMenuRestServer getTreeMenu error!";
public static final String ENGINE_DEPLOY_REST_SERVER_OPTIONAL_SERVER_ERROR = "EngineDeployRestServer optionalServer error!";
public static final String LACK_OF_PARAMETER = "Lock of parameter !";
public static final String USER_NAME_CANNOT_USERINFO = "User name cannot retrieve user infomation !";
public static final String PASSWORD_ERROR = "Password error!";
public static final String FAILED_TO_CANCEL_USER_ROLE_ASSIGNMENT = "Failed to cancel user role assignment!";
public static final String GET_ROLE_LIST_FAILED = "Get user list failed!";
public static final String USER_NAME_NO_EXIST = "User name no exist !";
public static final String USER_DELETE = "User delete !";
public static final String USER_OVERDUE = "User overdue !";
public static final String USER_NAME_NO_FIND_USER_INFO = "user name did not find user info !";
public static final String AGAIN_LOGIN = "Again login please!";
public static final String EXIT_LOGIN_SUCCESS = "Exit login success!";
public static final String MESSAGE_FAIL= "Operation failure!";
public static final String MESSAGE_SUCCESS= "Operation success!";
public static final String MESSAGE_PARAM_ERROR= "Message param error!";
public static final String MESSAGE_LOGIN_SUCCESS = "Message login success";
public static final String CREATE_SUCCESS = "Create success";
public static final String CREATE_TABLE_FAILE = "Create table faile";
public static final String DELETE_SUCCESS = "Delete success";
public static final String DELETE_TABLE_FAILE = "Delete table faile";
public static final String DELETE_TABLE_FIELD_FAILE = "Delete table field faile";
public static final String GET_LIST_IMPORT_TABLE_FAILE = "BusinessTableRestServer listImportTable error";
public static final String DICTIONARY_NO_KEY_VALUE = "Dictionary no key value";
public static final String CONFIGURATION_CONDITIONS_IS_NULL = "Configuration conditions is null";
public static final String CONFIGURATION_VALUES_IS_NULL = "Configuration is null";
public static final String CONFIGURATION_PARAMETER_FORMAT_FAILE = "Configuration parameter format faile";
public static final String CONFIGURATION_SUCCESS = "Coiguration success";
public static final String CONFIGURATION_FAILE = "Coiguration faile";
public static final String SUCCESS_TABLE_FIELD_ARRAY_FAILE = "Success table field array failed!";
public static final String CHOOSE_JAR_UPLOAD = "Choose jar upload";
public static final String JAR_EXIST = "Jar exist";
public static final String JAR_UPLOAD_SUCCESS = "Jar upload success";
public static final String JAR_UPLOAD_FAILE = "Jar upload faile";
public static final String JAR_DELETE_FAILE = "Jar delete faile";
public static final String GET_JAR_SUCCESS = "Get jar success";
public static final String GET_JAR_FAILE = "Get jar faile";
public static final String IO_CLOSE_FAILE = "Io close faile";
public static final String GET_FILE_FUNCTION_FAILE = "Get file function faile";
public static final String GET_FILE_LIST_FAILE = "Get file list faile";
public static final String GET_FILE_LOG_CONTENT = "Get file log content";
public static final String DELETE_FILE_LOG_SUCCESS = "Delete file_log success";
public static final String DELETE_FILE_LOG_FAILE = "Delete file_log faile";
public static final String FILE_NO_FIND = "File no find";
public static final String DOWLOAD_FAILE = "Dowload faile";
public static final String DOWLOAD_SUCCESS = "Dowload success";
public static final String GET_DEPLOY_FAILE = "Get deploy faile";
public static final String GET_LOG_FILE_LIST_FAILE = "Get log file list faile";
public static final String READ_LOG_FILE_FAILE = "Read log file faile";
public static final String CLOSE_SERVER = "Close restful";
public static final String GET_LOWER_MENU_ERROR = "GetLowerMenu error";
public static final String GET_ALL_TREE_MENU_ERROR = "Get all tree menu error";
public static final String GET_TOP_TREE_MENU_ERROR = "Get top tree menu error";
public static final String BATCH_UPDATE_MENU_LIST_IS_NULL = "Batch update menu list is null";
public static final String UPDATE_BATCH_MENU_LIST_ERROR = "Batch update menu list error";
public static final String GET_VALUE_BY_KEY_ERROR = "Get value by key error";
public static final String DELETE_PLUGIN_ERROR = "Delete plugin error";
public static final String GET_SERVICE_LIST_ERROR = "Get service list error";
public static final String ADD_PARAMETER_ERROR = "Add parameter error";
public static final String PARAM_TABLE_ID_IS_NULL = "Param tableId is null";
public static final String AUTO_CREATE_INTERFACE_ERROR = "Auto create interface error";
public static final String GET_PARAM_LIST_FAILE = "Get param list faile";
public static final String GET_INTERFACE_FIELD_LIST_FAILE = "Get interface field list faile";
public static final String PARAM_FORMAT_FAILE = "Param format faile";
public static final String SERVICE_ID_IS_NULL = "Service id_is null";
public static final String GET_SERVICE_BUILDER_ERROR = "Get service builder error";
public static final String GET_PLUGIN_SUCCESS = "Get plugin success";
public static final String GET_PLUGIN_FAILE = "Get plugin faile";
public static final String GET_TEMPLATE_INTERFACE_SUCCESS = "Get template interface success";
public static final String SAVE_DATA_IS_NULL = "Save data is null";
public static final String PARAM_IS_NULL = "Param is null";
public static final String IMPPORT_TABLE_FAILE= "Impport table faile";
public static final String GET_IMPORT_SUCCESS = "Get import success";
public static final String GET_IMPORT_FAILE = "Get import faile";
public static final String GET_IMPORT_TABLE_SUCCESS= "Get import table success";
public static final String GET_IMPORT_TABLE_FAILE= "Get import table faile";
public static final String CREATE_PROXY_SUCCESS= "Create proxy success";
public static final String PARAM_DATABASE_ID_IS_NULL= "Param database id is null";
public static final String CERT_FILE_IS_NULL= "Cert file is null";
public static final String CERT_UPLOAD_FAILE= "Cert upload faile";
public static final String CHECK_CONFIG_IS_NULL= "Check config is null";
public static final String TEST_INTERFACE_SERVICE_FAILE= "Test interface service faile";
public static final String LIST_ALL_SCHEDULE_MENU_ERROR= "list_all_schedule_menu_error";
public static final String START_SUCCESS= "Start success";
public static final String START_FAIL = "Start fail";
public static final String STOP_SUCCESS= "Stop success";
public static final String STOP_FAILE= "Stop faile";
public static final String GET_SCHEDULE_LIST_ERROR= "Get schedule list error";
public static final String PAGE_UPLOAD_SUCCESS= "Page upload success";
public static final String PAGE_UPLOAD_FAILE= "Page upload faile";
public static final String APPLICATION_CATEGORY_CONTAINS_APPLICATION_DELETE_FAILE= "Application category contains application delete faile";
public static final String GET_CARD_LIST_MENU_PERMISSION_FAILE= "Get card list menu permission faile";
public static final String DIRECTORY_TREE_IS_DIRTY_NULLPOINTEREXCEPTION= "Directory tree is dirty NullPointerException";
public static final String USER_NAME_IS_NULL= "User name is null";
public static final String USER_PHONE_IS_NULL= "User phone is null";
public static final String GET_TREE_MENU_LIST_FAILE= "Get tree menu list faile";
public static final String GET_FILE_LIST_SUCCESS= "Get file list success";
public static final String GET_FILE_MESSAGE_SUCCESS= "Get file message success";
public static final String GET_DEPLOY_SERVER_SUCCESS= "Get deploy restful success";
public static final String GET_STATUS_FAILE = "Get status message faile";
public static final String GET_QUERY_HISTORY_MESSAGE_SUCCESS = "Query histoty message success";
public static final String GET_MESSAGE_SUBSCRIBE_HAVE_DATA = "Delete message topic faile message subscribe have data";
public static final String GET_MESSAGE_FILTER_HAVE_DATA = "Delete message topic faile message filter have data";
public static final String DELETE_DATA_SUCCESS = "Delete data success";
public static final String DELETE_DATA_FAILE = "Delete data faile";
public static final String LOGIN_SERVES_SUCCESS = "Login serves success";
public static final String GET_LOG_FAILE = "Gets no log level files speclified in the directory";
public static final String GET_REMOTE_SERVICE_LOG_FAILE = "Get remote service log faile";
public static final String GET_REMOTE_SERVICE_LOG_SUCCESS = "Get remote service log success";
public static final String DOWNLOAD_REMOTE_SERVICE_LOG_SUCCESS = "Download remote service log success";
public static final String DELETE_REMOTE_SERVICE_LOG_SUCCESS = "Delete remote service log success";
public static final String GET_LOG_FILE_LIST_SUCCESS = "Get log file success";
}
package com.wanji.common.framework.i18n;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
/**
* @Description: 国际化词条自动处理工具类
* @Author mapabc
* @Date 2019/11/30 11:20
**/
public final class I18nResourceBundle {
/**
* @Description: 当前国际化语言环境,默认中文,外部可以动态修改,直接通过赋值即可更新语言环境,
* 例:I18nResourceBundle.language = "en"
* 修改后在通过I18nResourceBundle.getConstants("key")获取的值即可动态改变
* @return
* @Author mapabc
* @Date 2019/11/30 11:20
**/
public static volatile String language = "zh";
/**
* @Description: 当前支持的国际化语言,后续补充直接扩充枚举常量即可
* @Author mapabc
* @Date 2019/11/30 11:21
**/
public enum LANGUAGE {
/*中文简体,默认值*/
ZH("zh"),
/*英文*/
EN("en");
LANGUAGE(String zh) {
}
}
/**
* @Description: 工具类私有化构造函数,安全性考虑,禁止通过外部实例化
* @Author mapabc
* @Date 2019/11/30 11:22
**/
private I18nResourceBundle() {
}
/**
* @Description: 根据词条在Constants中定义的成员变量名称,获取成员变量值
* 实现原理:通过Java反射,动态获取Constants中定义的成员变量值,
* 结合当前语言环境,判断从Constants(默认中文)或者Constants_en(英文)中加载对应值
* 后期扩展新语言,需要定义新Constants,并扩展LANGUAGE。
*
* @param key 词条键值
* @return java.lang.String 返回字符串,当前仅支持字符串定义
* @Author mapabc
* @Date 2019/11/29 22:12
**/
public static String getConstants(String key) {
String constant = "";
if (StringUtils.isEmpty(key)) {
return constant;
}
try {
Field filed;
if (StringUtils.equalsIgnoreCase(LANGUAGE.EN.name(), language)) {
filed = Constants_en.class.getDeclaredField(key);
} else {
filed = Constants.class.getDeclaredField(key);
}
//减少安全性检查,提高反射访问速度。Todo 性能对比
filed.setAccessible(false);
constant = String.valueOf(filed.get(key));
} catch (Exception e) {
return constant;
}
return constant;
}
/*
* Todo 测试 性能对比,直接访问成员变量 vs 通过反射获取 vs Spring boot自带resourceBundle
* Todo 测试 线程安全
*/
/**
* @Description:
*
* @param args Todo 测试 性能对比,直接访问成员变量 vs 通过反射获取 vs Spring boot自带resourceBundle
* Todo 测试 线程安全
* @return void
* @Author mapabc
* @Date 2019/11/30 13:43
**/
public static void main(String[] args) {
I18nResourceBundle.language = "en";
System.out.println(I18nResourceBundle.getConstants("SAVE_SUCCESS_MSG"));
I18nResourceBundle.language = "zh";
System.out.println(I18nResourceBundle.getConstants("SAVE_SUCCESS_MSG"));
}
}
package com.wanji.common.framework.log;
import com.alibaba.fastjson.JSONObject;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.domain.OperationLog;
import com.wanji.common.framework.domain.TrackableEntity;
import com.wanji.common.framework.rest.JsonViewObject;
import com.wanji.common.tool.mqtool.MqUtil;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import static com.wanji.common.framework.Constants.LogType.OPERATION_LOG;
@Slf4j
public abstract class AbstractLog {
@Context
protected HttpServletRequest request;
public void sendOperationLog(String classNameCn, String className, String method, String username, String dbId, long lastTime, JsonViewObject jsonViewObject) {
OperationLog opLog = new OperationLog();
try {
opLog.setResName(classNameCn);
opLog.setResType(className);
opLog.setOperationType(method);
opLog.setOperationUser(username);
opLog.setDbId(dbId);
opLog.setDes(Objects.isNull(jsonViewObject)?"": JSONObject.toJSONString(jsonViewObject));
opLog.setOperationTime(lastTime);
opLog.setStartTime(new Date());
opLog.setEndTime(new Date());
opLog.setStatus(Objects.isNull(jsonViewObject)? Constants.JsonView.STATUS_FAIL:jsonViewObject.getStatus());
try {
//用户客户端操作系统
if (request == null) {
request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
//获取客户端操作系统
OperatingSystem agentOs = userAgent.getOperatingSystem();
//获取客户端浏览器
String agentBrowser = "";
if (null != userAgent.getBrowser() && null != userAgent.getBrowserVersion()) {
agentBrowser = userAgent.getBrowser().getName() + " " + userAgent.getBrowserVersion().getVersion();
}
opLog.setOperationOS(agentOs.getName());
opLog.setOperationBrowser(agentBrowser);
opLog.setClientParam(request.getHeader("User-Agent"));
String agentIp = request.getHeader("X-Real-IP");
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("X-Forwarded-For");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("Proxy-Client-IP");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("WL-Proxy-Client-IP");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getRemoteAddr();
}
opLog.setOperationIp("0:0:0:0:0:0:0:1".equals(agentIp) ? "127.0.0.1" : agentIp);
}catch (Exception ex){
ex.printStackTrace();
}
MqUtil.sendLogMessage(OPERATION_LOG.toString(), OPERATION_LOG.toString(), TrackableEntity.bean2Map(opLog));
} catch (Exception e) {
log.error("SendOperationLog error", e);
}
}
public static void getApiRequestLog(long start, String adCode, String version, String name, Map<String, Object> logDetailMap, HttpServletRequest request, String username) {
long end = System.currentTimeMillis();
if (request == null) {
request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
logDetailMap.put("adCode", adCode);
logDetailMap.put("version", version);
logDetailMap.put("name", name);
logDetailMap.put("startTime", start);
logDetailMap.put("endTime", end);
logDetailMap.put("responseTime", String.valueOf(end - start));
logDetailMap.put("createTime", System.currentTimeMillis());
logDetailMap.put("queryParam", JSONObject.toJSONString(request.getParameterMap()));
//username
logDetailMap.put("username", username);
//ip
String agentIp="127.0.0.1";
try {
//用户客户端操作系统
if (request != null) {
agentIp = request.getHeader("X-Real-IP");
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("X-Forwarded-For");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("Proxy-Client-IP");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("WL-Proxy-Client-IP");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getRemoteAddr();
}
}
}catch (Exception ex){
ex.printStackTrace();
}
logDetailMap.put("ip","0:0:0:0:0:0:0:1".equals(agentIp) ? "127.0.0.1" : agentIp);
}
}
package com.wanji.common.framework.mapper;
import com.wanji.common.framework.domain.TrackableEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.cache.annotation.Cacheable;
import java.util.List;
import java.util.Map;
/**
* 持久化接口
*
* @param <Entity>
* @author mapabc
*/
public interface BaseInterfaceMapper<Entity extends TrackableEntity> {
void save(Entity entity);
Integer update(Entity entity);
Integer deleteById(String id);
Integer deleteByIds(@Param("idList") List<String> idList);
Entity findById(String id);
List<Entity> findAll();
List<Entity> findByMap(Map<String, Object> map);
Integer getCount(Map<String, Object> map);
List<Entity> findByPage(Map<String, Object> map);
List<Entity> findByName(Map<String, Object> map);
}
package com.wanji.common.framework.mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* @ClassName ExportImportMapper
* @Description
* @Author mapabc7
* @Date 2020/7/6 11:59
* @Version 1.0
*/
public interface ExportImportMapper {
void saveOrIgnoreAll(@Param("list") List<Map<String, Object>> list);
void saveOrReplaceAll(@Param("list") List<Map<String, Object>> list);
List<Map<String, Object>> newFindByMap(Map<String, Object> map);
}
package com.wanji.common.framework.rest;
import com.wanji.common.framework.domain.TrackableEntity;
import io.swagger.annotations.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @author mapabc
* 修改:新增请求参数校验内容
*/
@Api(value = "RESTful服务基础接口", description = "RESTful服务基础接口")
@Validated
public interface AbstractRestServer<Entity extends TrackableEntity> {
/**
* 获取所有记录
*
* @return JsonViewObject
*/
@ApiOperation(value = "获取所有记录", notes = "获取所有记录", response = JsonViewObject.class, produces = MediaType.APPLICATION_JSON)
@GetMapping(value = "/byAll", produces = MediaType.APPLICATION_JSON)
JsonViewObject getAll();
/**
* 根据条件分页查询记录
*
* @param page
* @return JsonViewObject
*/
@ApiOperation(value = "根据条件分页查询记录", notes = "根据条件分页查询记录", response = JsonViewObject.class, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
@PostMapping(value = "/byPage", produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
@ResponseBody
JsonViewObject getPage(@ApiParam(value = "查询条件和分页参数", required = true, example = "{\"pageSize\": 10, \"pageNum\": 1}") @RequestBody @Validated Page<Entity> page);
/**
* 根据条件查询记录
*
* @param entity 查询条件
* @return JsonViewObject
*/
@ApiOperation(value = "根据条件查询记录", notes = "根据条件查询记录", response = JsonViewObject.class, consumes = MediaType.APPLICATION_JSON)
@PostMapping(value = "/byCondition", produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
JsonViewObject getByWhere(@ApiParam(value = "查询条件", required = true) @RequestBody @Validated({ValidationGroups.Query.class}) Entity entity);
/**
* 根据id查询记录
*
* @param id
* @return JsonViewObject
*/
@ApiOperation(value = "根据id查询记录", notes = "根据id查询记录", response = JsonViewObject.class, produces = MediaType.APPLICATION_JSON)
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON)
JsonViewObject getById(@ApiParam(value = "记录的id", required = true, example = "1") @PathVariable("id") @NotBlank(message = "查询id不能为空") String id);
/**
* 根据id删除
*
* @param ids
* @return JsonViewObject
*/
@ApiOperation(value = "根据多个id删除记录", notes = "根据多个id删除记录", response = JsonViewObject.class, produces = MediaType.APPLICATION_JSON)
@ApiImplicitParams(value = {
@ApiImplicitParam(paramType = "query", name = "ids", dataType = "String", required = true, value = "多个记录id,用逗号分隔", example = "1,2")
})
@GetMapping(value = "/deleting", produces = MediaType.APPLICATION_JSON)
JsonViewObject deleteByIds(@QueryParam("ids") @NotBlank(message = "删除ids不能为空") String ids);
/**
* 新建记录
*
* @param entity
* @return JsonViewObject
*/
@ApiOperation(value = "新建记录", notes = "新建记录", response = JsonViewObject.class, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
@PostMapping(value = "/creating", produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
JsonViewObject save(@ApiParam(value = "记录的JSON格式字符串", required = true) @RequestBody @Validated({ValidationGroups.Create.class}) Entity entity);
/**
* 修改记录
*
* @param entity
* @return
*/
@ApiOperation(value = "修改记录", notes = "修改记录", response = JsonViewObject.class, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
@PostMapping(value = "/updating", produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
JsonViewObject update(@ApiParam(value = "记录的JSON格式字符串", required = true) @RequestBody @Validated({ValidationGroups.Update.class}) Entity entity);
/**
* 发送日志
*
* @param classNameCn 操作对象中文名
* @param className 操作对象英文名
* @param method 操作方法名
* @param username 操作人
* @param dbId 数据库id
* @param jsonViewObject 返回对象
* @param lastTime 操作时长
*/
void sendOperationLog(String classNameCn,String className,String method,String username,String dbId,long lastTime,JsonViewObject jsonViewObject) ;
}
package com.wanji.common.framework.rest;
/**
* bean验证分组
*
* @author mapabc
* @date 2017/6/28
*/
public class BeanValidationGroups {
/**
* 新建操作的bean验证分组
*/
public static interface CreateGroup {
}
/**
* 更新操作的bean验证分组
*/
public static interface UpdateGroup {
}
}
package com.wanji.common.framework.rest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;
/**
* @Description: servlet请求修改包装类
* @Author mapabc
* @Date 2020/6/23 15:05
*/
public class HeaderMapRequestWrapper extends HttpServletRequestWrapper {
/**
* construct a wrapper for this request
*
* @param request
*/
public HeaderMapRequestWrapper(HttpServletRequest request) {
super(request);
}
private Map<String, String> headerMap = new HashMap<>();
/**
* add a header with given name and value
*
* @param name
* @param value
*/
public void addHeader(String name, String value) {
headerMap.put(name, value);
}
/**
* remove a header with given name and value
*
* @param name
*/
public void removeHeader(String name) {
headerMap.remove(name);
}
@Override
public String getHeader(String name) {
String headerValue = super.getHeader(name);
if (headerMap.containsKey(name)) {
headerValue = headerMap.get(name);
}
return headerValue;
}
/**
* get the Header names
*/
@Override
public Enumeration<String> getHeaderNames() {
List<String> names = Collections.list(super.getHeaderNames());
for (String name : headerMap.keySet()) {
names.add(name);
}
return Collections.enumeration(names);
}
@Override
public Enumeration<String> getHeaders(String name) {
List<String> values = Collections.list(super.getHeaders(name));
if (headerMap.containsKey(name)) {
values = Arrays.asList(headerMap.get(name));
}
return Collections.enumeration(values);
}
}
package com.wanji.common.framework.rest;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.HttpCode;
import lombok.Data;
import java.io.Serializable;
/**
* restful对外的JSON 对象封装
*
* @author mapabc
*/
//没有get set方法会导致feign 接口调用时,无法使用JsonViewObject作为返回值
@Data
public class JsonViewObject implements Serializable {
private Object content;
private String message;
private String status;
private Integer code;
private Long timestamp;
public Object getContent() {
return content;
}
public String getMessage() {
return message;
}
public String getStatus() {
return status;
}
private JsonViewObject() {
}
public static JsonViewObject newInstance() {
return new JsonViewObject();
}
public JsonViewObject success() {
return success((Object) "");
}
public JsonViewObject success(Object content) {
return success(content, "");
}
public JsonViewObject success(String message) {
return success("", message);
}
public JsonViewObject success(Object content, String message) {
return pack(content, message, Constants.JsonView.STATUS_SUCCESS);
}
public JsonViewObject fail() {
return fail("", "");
}
public JsonViewObject fail(Exception e) {
String message = e.getMessage();
int index = message.indexOf(":");
return fail(index == -1 ? message : message.substring(index + 1));
}
public JsonViewObject fail(String errMsg) {
return fail("", errMsg);
}
public JsonViewObject fail(Object content, String message) {
return pack(content, message, Constants.JsonView.STATUS_FAIL);
}
private JsonViewObject pack(Object content, String message, String status) {
this.content = content;
this.message = message;
this.status = status;
//增加服务返回状态码,后期待完善
this.code=(status.equals(Constants.JsonView.STATUS_SUCCESS) ? HttpCode.SUCCESS.value():HttpCode.INTERNAL_SERVER_ERROR.value());
return this;
}
}
package com.wanji.common.framework.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @author mapabc7
*/
@Api(value = "log服务基础接口", description = "log服务基础接口")
public interface LogAbstractRestServer {
@ApiOperation(value = "查询所有消息记录-Todo各种条件", notes = "Todo各种条件",
response = JsonViewObject.class, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
@PostMapping(value = "/queryLog", produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
JsonViewObject queryLog(@ApiParam(value = "查询条件", required = true,
example = "{\"type\":\"job\",\"pageSize\":\"10\",\"pageNum\":\"1\",\"name\":\"张三\",\"startTime\":\"2018-10-10 11:12:00\",\"endTime\":\"2018-10-17 11:12:00\"}")
@RequestBody Map<String, Object> params);
@ApiOperation(value = "查询所有消息记录-Todo各种条件", notes = "Todo各种条件",
response = JsonViewObject.class, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
@PostMapping(value = "/queryData", produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
JsonViewObject queryData(@ApiParam(value = "查询条件", required = true,
example = "{\"type\":\"job\",\"pageSize\":\"10\",\"pageNum\":\"1\",\"name\":\"张三\",\"startTime\":\"2018-10-10 11:12:00\",\"endTime\":\"2018-10-17 11:12:00\"}")
@RequestBody Map<String, Object> params);
}
package com.wanji.common.framework.rest;
//import javax.validation.ConstraintViolation;
//import javax.validation.Validation;
//import javax.validation.Validator;
//import java.util.Set;
/**
* @author mapabc
* @date 2017/7/3
*/
public class MyValidator {
// /**
// * 手动调用bean验证,需要提供validation groups
// * 用于验证前段提交的参数 需要在bean的属性添加注解
// * @param entity
// * @param groups
// * @param <T>
// * @return
// */
// public static <T> Set<ConstraintViolation<T>> validate(T entity, Class... groups) {
// Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
// return validator.validate(entity, groups);
// }
//
// /**
// * 构造bean约束违反信息
// *
// * @param violations
// * @param <T>
// * @return
// */
// public static <T> String buildConstraintViolationMessage(Set<ConstraintViolation<T>> violations) {
// StringBuilder sb = new StringBuilder();
// for (ConstraintViolation<T> violation : violations) {
// sb.append("," + violation.getMessage());
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(0);
// }
// return sb.toString();
// }
}
package com.wanji.common.framework.rest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* @author
* @date 2018/1/18
*/
@Getter
@Setter
@ApiModel(value = "Node", description = "层级目录节点")
public class Node implements Serializable {
private static final long serialVersionUID = -3116372888315114025L;
@ApiModelProperty(value = "节点ID")
private String id;
@ApiModelProperty(value = "父节点ID")
private String pId;
@ApiModelProperty(value = "节点名称")
private String name;
@ApiModelProperty(value = "子节点")
private List<Node> children;
@ApiModelProperty(value = "节点扩展属性")
private Object data;
@ApiModelProperty(value = "是否默认选中")
private boolean checked;
@ApiModelProperty(value = "是否禁用节点选择框")
private boolean chkDisabled;
@ApiModelProperty(value = "扩展节点标记")
private boolean flag;
@ApiModelProperty(value = "节点是否可操作,根据页面扩展属性")
private boolean disabled;
@ApiModelProperty(value = "节点是否打开")
private boolean open;
/**
* 判断是否是其他节点,如是其他的为1,是树本身为0
* 目前用到这一判断的地方为主对象分类挂载主对象
*/
@ApiModelProperty(value = "判断是否是其他节点")
private Integer isOtherBean;
public Node(String id, String name, Object data, String pId) {
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
}
public Node(boolean checked, String id, String name, Object data, String pId) {
this.checked = checked;
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
}
public Node(boolean checked, String id, String name, Object data, String pId, List<Node> children) {
this.checked = checked;
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
this.children = children;
}
public Node(boolean checked, boolean chkDisabled, String id, String name, Object data, String pId) {
this.checked = checked;
this.chkDisabled = chkDisabled;
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
}
public Node(String id, String name, Object data, String pId, boolean disabled) {
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
this.disabled = disabled;
}
/**
* 将Node集合[{id:1,pid:0},{id:2,pid:0},{id:0,pid:-1}]
* 转换为[{id:0,pid:-1,children:[{id:1,pid:0},{id:2,pid:0}]}]
*
* @param nodeList node 集合
* @return
*/
public static List<Node> transformNodes(List<Node> nodeList) {
List<Node> result = Lists.newArrayList();
if (nodeList != null && !nodeList.isEmpty()) {
Map<String, Node> nodeMap = Maps.newHashMap();
nodeList.forEach(node -> nodeMap.put(node.getId(), node));
nodeList.forEach(node -> {
if (nodeMap.get(node.getPId()) != null) {
if (nodeMap.get(node.getPId()).getChildren() == null) {
nodeMap.get(node.getPId()).setChildren(Lists.newArrayList());
}
nodeMap.get(node.getPId()).getChildren().add(node);
} else {
result.add(node);
}
});
}
return result;
}
/**
* 将Node节点删去一个id=removeNodeId的子节点
*
* @param node
* @return
*/
public static Node removeNode(Node node, String removeNodeId) {
if (node == null || removeNodeId.equals(node.getId())) {
return null;
}
if (node.getChildren() == null || node.getChildren().isEmpty()) {
return node;
}
List<Node> children = node.getChildren();
node.setChildren(removeNode(children, removeNodeId));
return node;
}
/**
* 将Node集合删去一个id=removeNodeId的子节点
*
* @param nodeList
* @return
*/
public static List<Node> removeNode(List<Node> nodeList, String removeNodeId) {
if (nodeList == null || nodeList.isEmpty()) {
return Lists.newArrayList();
}
List<Node> result = Lists.newArrayList();
for (Node node : nodeList) {
if ((node = removeNode(node, removeNodeId)) != null) {
result.add(node);
}
}
return result;
}
/**
* 将已转化好的树形结构的节点集nodeList,展开为平铺结构
*
* @param nodeList
* @return List<Object>
*/
public static List flatTree(List<Node> nodeList) {
if (nodeList == null || nodeList.isEmpty()) {
return Lists.newArrayList();
}
List<Object> result = Lists.newArrayList();
for (Node node : nodeList) {
result.addAll(flatTreeNode(node));
}
return result;
}
/**
* 将单个节点,展开为平铺结构
*
* @param node
* @return
*/
public static List flatTreeNode(Node node) {
if (node == null) {
return Lists.newArrayList();
}
List<Object> result = Lists.newArrayList();
result.add(node.getData());
result.addAll(flatTree(node.getChildren()));
return result;
}
}
package com.wanji.common.framework.rest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* @author
* @date 2018/1/18
*/
@Getter
@Setter
public class NodeDTO implements Serializable {
private static final long serialVersionUID = -3116372888315114025L;
@ApiModelProperty(value = "节点ID")
private String id;
@ApiModelProperty(value = "父节点ID")
private String pId;
@ApiModelProperty(value = "节点名称")
private String name;
@ApiModelProperty(value = "子节点")
private List<NodeDTO> children;
@ApiModelProperty(value = "节点扩展属性")
private Object data;
@ApiModelProperty(value = "是否默认选中")
private boolean checked;
@ApiModelProperty(value = "是否禁用节点选择框")
private boolean chkDisabled;
@ApiModelProperty(value = "扩展节点标记")
private boolean flag;
@ApiModelProperty(value = "节点是否可操作,根据页面扩展属性")
private boolean disabled;
@ApiModelProperty(value = "节点是否打开")
private boolean open;
/**
* 判断是否是其他节点,如是其他的为1,是树本身为0
* 目前用到这一判断的地方为主对象分类挂载主对象
*/
@ApiModelProperty(value = "判断是否是其他节点")
private Integer isOtherBean;
@ApiModelProperty(value = "经度")
private Float lon;
@ApiModelProperty(value = "纬度")
private Float lat;
@ApiModelProperty(value = "范围坐标")
private String adrange;
public NodeDTO(String id, String name, Object data, String pId) {
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
}
public NodeDTO(String id, String name, Object data, String pId,Float lon,Float lat) {
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
this.lon=lon;
this.lat=lat;
}
public NodeDTO(boolean checked, String id, String name, Object data, String pId) {
this.checked = checked;
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
}
public NodeDTO(boolean checked, String id, String name, Object data, String pId, List<NodeDTO> children) {
this.checked = checked;
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
this.children = children;
}
public NodeDTO(boolean checked, boolean chkDisabled, String id, String name, Object data, String pId) {
this.checked = checked;
this.chkDisabled = chkDisabled;
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
}
public NodeDTO(String id, String name, Object data, String pId, boolean disabled) {
this.id = id;
this.name = name;
this.data = data;
this.pId = pId;
this.disabled = disabled;
}
/**
* 将Node集合[{id:1,pid:0},{id:2,pid:0},{id:0,pid:-1}]
* 转换为[{id:0,pid:-1,children:[{id:1,pid:0},{id:2,pid:0}]}]
*
* @param nodeList node 集合
* @return
*/
public static List<NodeDTO> transformNodes(List<NodeDTO> nodeList) {
List<NodeDTO> result = Lists.newArrayList();
if (nodeList != null && !nodeList.isEmpty()) {
Map<String, NodeDTO> nodeMap = Maps.newHashMap();
nodeList.forEach(node -> nodeMap.put(node.getId(), node));
nodeList.forEach(node -> {
if (nodeMap.get(node.getPId()) != null) {
if (nodeMap.get(node.getPId()).getChildren() == null) {
nodeMap.get(node.getPId()).setChildren(Lists.newArrayList());
}
nodeMap.get(node.getPId()).getChildren().add(node);
} else {
result.add(node);
}
});
}
return result;
}
/**
* 将Node节点删去一个id=removeNodeId的子节点
*
* @param node
* @return
*/
public static NodeDTO removeNode(NodeDTO node, String removeNodeId) {
if (node == null || removeNodeId.equals(node.getId())) {
return null;
}
if (node.getChildren() == null || node.getChildren().isEmpty()) {
return node;
}
List<NodeDTO> children = node.getChildren();
node.setChildren(removeNode(children, removeNodeId));
return node;
}
/**
* 将Node集合删去一个id=removeNodeId的子节点
*
* @param nodeList
* @return
*/
public static List<NodeDTO> removeNode(List<NodeDTO> nodeList, String removeNodeId) {
if (nodeList == null || nodeList.isEmpty()) {
return Lists.newArrayList();
}
List<NodeDTO> result = Lists.newArrayList();
for (NodeDTO node : nodeList) {
if ((node = removeNode(node, removeNodeId)) != null) {
result.add(node);
}
}
return result;
}
/**
* 将已转化好的树形结构的节点集nodeList,展开为平铺结构
*
* @param nodeList
* @return List<Object>
*/
public static List flatTree(List<NodeDTO> nodeList) {
if (nodeList == null || nodeList.isEmpty()) {
return Lists.newArrayList();
}
List<Object> result = Lists.newArrayList();
for (NodeDTO node : nodeList) {
result.addAll(flatTreeNode(node));
}
return result;
}
/**
* 将单个节点,展开为平铺结构
*
* @param node
* @return
*/
public static List flatTreeNode(NodeDTO node) {
if (node == null) {
return Lists.newArrayList();
}
List<Object> result = Lists.newArrayList();
result.add(node.getData());
result.addAll(flatTree(node.getChildren()));
return result;
}
}
package com.wanji.common.framework.rest;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.PositiveOrZero;
import java.io.Serializable;
import java.util.List;
/**
* {'total':64,'pageNum':1,'maxSize':10,'pageSize':10,'condition':''};
*
* @author mapabc
*/
@Getter
@Setter
@ApiModel
public class Page<T> implements Serializable {
/**
* 每页数据条数
*/
@ApiModelProperty(value = "每页显示的总条数", example = "10", dataType = "int")
@PositiveOrZero //校验必须为正数或0
private int pageSize = 10;
/**
* 总的数据数
*/
@ApiModelProperty(value = "总的数据数", example = "10", dataType = "int")
private int total = 0;
/**
* 起始页码
*/
@ApiModelProperty(value = "当前页", example = "1", dataType = "int")
@PositiveOrZero //校验必须为正数或0
private int pageNum = 1;
/**
* 起始行数
*/
private int startRowNum = 0;
@NotNull
private Object condition;
private List<T> rows;
public Page() {
}
public Page(int pageSize, int total, int pageNum) {
this.pageSize = pageSize;
this.total = total;
this.pageNum = pageNum;
this.startRowNum = pageSize * (pageNum - 1);
}
public int getTotalPageNum() {
return (total + pageSize - 1) / pageSize;
}
public static Page newInstance() { return new Page(); }
public static <T> Page<T> newInstance(int pageSize, int total, int pageNum) {
return new Page<>(pageSize, total, pageNum);
}
/**
* 开始内存分页
* @param list
* @param pageNum 页码
* @param pageSize 每页多少条数据
* @return
*/
public static List startPage(List list, Integer pageNum,
Integer pageSize) {
if (list == null) {
return null;
}
if (list.size() == 0) {
return null;
}
Integer count = list.size(); // 记录总数
Integer pageCount = 0; // 页数
if (count % pageSize == 0) {
pageCount = count / pageSize;
} else {
pageCount = count / pageSize + 1;
}
int fromIndex = 0; // 开始索引
int toIndex = 0; // 结束索引
if (pageNum != pageCount) {
fromIndex = (pageNum - 1) * pageSize;
toIndex = fromIndex + pageSize;
} else {
fromIndex = (pageNum - 1) * pageSize;
toIndex = count;
}
List pageList = list.subList(fromIndex, toIndex);
return pageList;
}
}
package com.wanji.common.framework.rest;
import com.wanji.common.framework.domain.TrackableEntity;
import javax.validation.groups.Default;
/**
* @Description: restful参数校验通用定义
* @Author mapabc
* @Date 2020/8/26 13:10
*/
public class ValidationGroups {
/**
* @Description: 通用保存接口校验组,继承Default,否则每个属性都得加上分组属性
*
* @see AbstractRestServer#save
* @Author mapabc
* @Date 2020/8/26 13:27
**/
public interface Create extends Default {}
/**
* @Description: 通用更新接口校验组,继承Default,否则每个属性都得加上分组属性
*
* @see AbstractRestServer#update
* @Author mapabc
* @Date 2020/8/26 13:27
**/
public interface Update extends Default {}
/**
* @Description: 通用查询接口校验组,继承Default,否则每个属性都得加上分组属性
*
* @see AbstractRestServer#getByWhere(TrackableEntity)
* @Author mapabc
* @Date 2020/8/26 13:27
**/
public interface Query extends Default {}
}
package com.wanji.common.framework.rest.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.domain.OperationLog;
import com.wanji.common.framework.domain.TrackableEntity;
import com.wanji.common.framework.dubbointerface.BaseDubboInterface;
import com.wanji.common.framework.exception.DubboProviderException;
import com.wanji.common.framework.i18n.I18nResourceBundle;
import com.wanji.common.framework.rest.AbstractRestServer;
import com.wanji.common.framework.rest.JsonViewObject;
import com.wanji.common.framework.rest.Page;
import com.google.common.collect.Maps;
import com.wanji.common.tool.mqtool.MqUtil;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static com.wanji.common.framework.Constants.LogType.OPERATION_LOG;
/**
* @author mapabc
*/
//@RequiresAuthentication
@Slf4j
public abstract class AbstractRestServerImpl<Entity extends TrackableEntity> implements AbstractRestServer<Entity> {
@Context
protected HttpServletResponse response;
@Context
protected HttpServletRequest request;
/**
* 抽象方法,子类需要实现,得到基础服务接口
*
* @return 各子类相对应的Provider接口
*/
public abstract BaseDubboInterface<Entity> getBaseDubboInterface();
/**
* {
* "content": "{"endRowNum":10,"objCondition":null,"pageNumber":1,"pageSize":10,"startRowNum":0,"total":2,"totalPageNum":1,
* "rows":[
* {"createDate":"2015-09-29 15:30:42","groupName":"test1","id":"C8879FFFB2064E66BB7A7D4ED052C9DE","username":null,"webPort":"5052"},
* {"createDate":"2015-09-29 14:51:46","groupName":"test2","id":"122830C1DC334517BC7BCE79F62D4FD5","username":null,"webPort":"5052"}
* ]}",
* "message": "",
* "status": "success"
* }
*
* @param page
* @return
*/
@Override
public JsonViewObject getPage(@RequestBody Page<Entity> page) {
JsonViewObject jsonView = JsonViewObject.newInstance();
long start=System.currentTimeMillis();
String jsonStr = JSON.toJSONString(page);
try {
Map<String, Object> mapBean = Maps.newHashMap();
if (page != null) {
if (page.getCondition() != null && page.getCondition() instanceof Map) {
mapBean = (Map<String, Object>) page.getCondition();
}
}
page = this.getBaseDubboInterface().findByPage(page, mapBean);
jsonView.success(page);
} catch (DubboProviderException e) {
jsonView.fail(e);
log.error("{} getPage error, jsonStr:{}", this.getClass().getSimpleName(), jsonStr, e);
}finally {
//this.sendOperationLog("根据条件分页查询记录->"+jsonStr,this.getClass().getSimpleName(),"resetPwd","","", System.currentTimeMillis()-start,jsonView);
}
return jsonView;
}
/**
* {
* "content": "[
* {"createDate":"2015-09-29 15:30:42","id":"C8879FFFB2064E66BB7A7D4ED052C9DE","name":"test1","status":"0"},
* {"createDate":"2015-09-29 14:51:46","id":"122830C1DC334517BC7BCE79F62D4FD5","name":"test2","status":"0"}
* ]",
* "message": "",
* "status": "success"
* }
*
* @return
*/
@Override
public JsonViewObject getAll() {
JsonViewObject jsonView = JsonViewObject.newInstance();
long start=System.currentTimeMillis();
try {
List<Entity> list = this.getBaseDubboInterface().findAll();
jsonView.success(list);
} catch (DubboProviderException e) {
jsonView.fail(I18nResourceBundle.getConstants("GET_FAILED_MSG"));
log.error("{} getAll error", this.getClass().getSimpleName(), e);
}finally {
//this.sendOperationLog("获取所有记录->",this.getClass().getSimpleName(),"resetPwd","","", System.currentTimeMillis()-start,jsonView);
}
return jsonView;
}
/**
* {
* "content": "[
* {"createDate":"2015-09-29 15:30:42","id":"C8879FFFB2064E66BB7A7D4ED052C9DE","name":"test1","status":"0"},
* {"createDate":"2015-09-29 14:51:46","id":"122830C1DC334517BC7BCE79F62D4FD5","name":"test2","status":"0"}
* ]",
* "message": "",
* "status": "success"
* }
*
* @param entity
* @return
*/
@Override
public JsonViewObject getByWhere(@RequestBody Entity entity) {
JsonViewObject jsonView = JsonViewObject.newInstance();
long start=System.currentTimeMillis();
String jsonStr = JSON.toJSONString(entity);
try {
//参数校验过程中修改,兼容实现,restful入参不用map,便于进行参数逐个校验
Map params = JSONObject.parseObject(JSONObject.toJSONString(entity), Map.class);
List list = this.getBaseDubboInterface().findByMap(params);
jsonView.success(list);
} catch (DubboProviderException e) {
jsonView.fail(I18nResourceBundle.getConstants("GET_FAILED_MSG"));
log.error("{} getByWhere error,jsonStr:{}", this.getClass().getSimpleName(), jsonStr, e);
}finally {
//this.sendOperationLog("根据条件查询记录->"+jsonStr,this.getClass().getSimpleName(),"resetPwd","","", System.currentTimeMillis()-start,jsonView);
}
return jsonView;
}
/**
* {
* "content": "{"groupId":"D54FAB067D6F47A99136210ED640368E","id":"C8879FFFB2064E66BB7A7D4ED052C9DE","status":"0","webPort":"5052"}",
* "message": "",
* "status": "success"
* }
*
* @param id
* @return JsonViewObject
*/
@Override
public JsonViewObject getById(@PathVariable String id) {
JsonViewObject jsonView = JsonViewObject.newInstance();
long start=System.currentTimeMillis();
try {
Entity entity = this.getBaseDubboInterface().findById(id);
jsonView.success(entity);
} catch (DubboProviderException e) {
jsonView.fail(I18nResourceBundle.getConstants("GET_FAILED_MSG"));
log.error("AbstractRestServerImpl getById error, id:{}", id, e);
}finally {
//this.sendOperationLog("根据id查询记录->"+id,this.getClass().getSimpleName(),"resetPwd","","", System.currentTimeMillis()-start,jsonView);
}
return jsonView;
}
@Override
public JsonViewObject deleteByIds(String ids) {
JsonViewObject jsonView = JsonViewObject.newInstance();
long start=System.currentTimeMillis();
String[] idArray = ids.split(",");
try {
if (idArray.length > 0) {
for (String id : idArray) {
jsonView = this.getBaseDubboInterface().deleteById(id);
}
}
} catch (DubboProviderException e) {
jsonView.fail(I18nResourceBundle.getConstants("DELETE_FAILED_MSG"));
log.error("AbstractRestServerImpl deleteByIds error, id:{}", ids, e);
}finally {
this.sendOperationLog("根据多个id删除记录->"+ids,this.getClass().getSimpleName(),"resetPwd","","", System.currentTimeMillis()-start,jsonView);
}
return jsonView;
}
@Override
public JsonViewObject save(@RequestBody Entity entity) {
JsonViewObject jsonView = JsonViewObject.newInstance();
long start=System.currentTimeMillis();
try {
if (entity != null) {
jsonView = this.getBaseDubboInterface().save(entity);
}
} catch (DubboProviderException e) {
jsonView.fail(I18nResourceBundle.getConstants("SAVE_FAILED_MSG"));
log.error("AbstractRestServerImpl save error, jsonStr:{}", JSON.toJSONString(entity), e);
}finally {
this.sendOperationLog("新增记录->"+entity,this.getClass().getSimpleName(),"resetPwd","","", System.currentTimeMillis()-start,jsonView);
}
return jsonView;
}
@Override
public JsonViewObject update(@RequestBody Entity entity) {
JsonViewObject jsonView = JsonViewObject.newInstance();
long start=System.currentTimeMillis();
try {
if (entity != null) {
jsonView = this.getBaseDubboInterface().update(entity);
}
} catch (DubboProviderException e) {
jsonView.fail(I18nResourceBundle.getConstants("UPDATE_FAILED_MSG"));
log.error("AbstractRestServerImpl update error, jsonStr:{}", JSON.toJSONString(entity), e);
}finally {
this.sendOperationLog("修改记录->"+entity,this.getClass().getSimpleName(),"resetPwd","","", System.currentTimeMillis()-start,jsonView);
}
return jsonView;
}
@Override
public void sendOperationLog(String classNameCn,String className,String method,String username,String dbId,long lastTime,JsonViewObject jsonViewObject) {
OperationLog opLog = new OperationLog();
try {
opLog.setResName(classNameCn);
opLog.setResType(className);
opLog.setOperationType(method);
opLog.setOperationUser(username);
opLog.setDbId(dbId);
opLog.setDes(Objects.isNull(jsonViewObject)?"":JSONObject.toJSONString(jsonViewObject));
opLog.setOperationTime(lastTime);
opLog.setStartTime(new Date());
opLog.setEndTime(new Date());
opLog.setStatus(Objects.isNull(jsonViewObject)? Constants.JsonView.STATUS_FAIL:jsonViewObject.getStatus());
try {
//用户客户端操作系统
if (request == null) {
request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
//获取客户端操作系统
OperatingSystem agentOs = userAgent.getOperatingSystem();
//获取客户端浏览器
String agentBrowser = "";
if (null != userAgent.getBrowser() && null != userAgent.getBrowserVersion()) {
agentBrowser = userAgent.getBrowser().getName() + " " + userAgent.getBrowserVersion().getVersion();
}
opLog.setOperationOS(agentOs.getName());
opLog.setOperationBrowser(agentBrowser);
opLog.setClientParam(request.getHeader("User-Agent"));
String agentIp = request.getHeader("X-Real-IP");
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("X-Forwarded-For");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("Proxy-Client-IP");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getHeader("WL-Proxy-Client-IP");
}
if (agentIp == null || agentIp.length() == 0 || "unknown".equalsIgnoreCase(agentIp)) {
agentIp = request.getRemoteAddr();
}
opLog.setOperationIp("0:0:0:0:0:0:0:1".equals(agentIp) ? "127.0.0.1" : agentIp);
}catch (Exception ex){
ex.printStackTrace();
}
MqUtil.sendLogMessage(OPERATION_LOG.toString(), OPERATION_LOG.toString(), TrackableEntity.bean2Map(opLog));
} catch (Exception e) {
log.error("SendOperationLog error", e);
}
}
}
package com.wanji.common.framework.rest.impl;
import com.alibaba.fastjson.JSONObject;
import com.wanji.common.framework.domain.OperationLog;
import com.wanji.common.framework.domain.TrackableEntity;
import com.wanji.common.framework.dubbointerface.BaseLogInterface;
import com.wanji.common.framework.rest.JsonViewObject;
import com.wanji.common.framework.rest.LogAbstractRestServer;
import com.wanji.common.tool.mqtool.MqUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import java.util.Date;
import java.util.Map;
import static com.wanji.common.framework.Constants.LogType.OPERATION_LOG;
@Slf4j
public abstract class LogAbstractRestServerImpl implements LogAbstractRestServer {
@Context
protected HttpServletResponse response;
@Context
protected HttpServletRequest request;
public abstract BaseLogInterface getBaseLogInterface();
@Override
public JsonViewObject queryLog(@RequestBody Map<String, Object> params) {
JsonViewObject jsonView = JsonViewObject.newInstance();
try {
jsonView = this.getBaseLogInterface().logQuery(params);
} catch (Exception e) {
jsonView.fail(e.getMessage());
log.error("queryLog error", e);
}
return jsonView;
}
@Override
public JsonViewObject queryData(@RequestBody Map<String, Object> params) {
JsonViewObject jsonView = JsonViewObject.newInstance();
try {
jsonView = this.getBaseLogInterface().queryData(params);
} catch (Exception e) {
jsonView.fail(e.getMessage());
log.error("queryData error", e);
}
return jsonView;
}
}
package com.wanji.common.framework.spring;
import org.springframework.context.ApplicationContext;
/**
* @author mapabc5
*/
public class ServiceBeanContext {
private static volatile ApplicationContext ctx = null;
private ServiceBeanContext() {
}
public static void loadContext(ApplicationContext context) {
ctx = context;
}
public static ApplicationContext getContext() {
return ctx;
}
public static <T> T getBean(String name) {
return (T) ctx.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return ctx.getBean(clazz);
}
}
package com.wanji.common.framework.thread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 使用线程池时,根据业务名称来给池中线程命名。
*
* @Author mapabc6
* @Date 2019/12/26 15:23
*/
public class NamedThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
private final boolean mDaemon;
public NamedThreadFactory() {
this("pool-" + poolNumber.getAndIncrement(), false);
}
public NamedThreadFactory(String threadName) {
this(threadName, false);
}
public NamedThreadFactory(String threadName, boolean daemon) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
mDaemon = daemon;
namePrefix = threadName + "-thread-";
}
@Override
public Thread newThread(Runnable r) {
String name = namePrefix + threadNumber.getAndIncrement();
Thread t = new Thread(group, r, name, 0);
t.setDaemon(mDaemon);
t.setUncaughtExceptionHandler(new MyUncatchExceptionHandler());
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
class MyUncatchExceptionHandler implements Thread.UncaughtExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(MyUncatchExceptionHandler.class);
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("捕获到了线程池中[ threadName:{}, threadId:{} ] 的异常", t.getName(), t.getId(), e);
}
}
package com.wanji.common.tool.dbtools;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.wanji.common.framework.exception.NodeException;
import org.apache.commons.lang.StringUtils;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.PostGreSqlColumn.*;
import static com.wanji.common.framework.Constants.PostGreSqlColumn.PATH;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.*;
/**
* 数据库相关处理帮助类
*
* @author guoliang.dong@mapabc.com
*
*/
public class DBUtils {
/**
* @param runtimeParams 运行时参数。对应占位符的实际值。
* @param pluginJson pluginJson。
* @return 替换为真实值的pluginJson的map格式。
*/
public static List<Map<String, Object>> tranAndGetPluginJsonMaps(Map<String, Object> runtimeParams,
JSONArray pluginJson) throws NodeException {
// 处理数据库字段
deleteNoParam(pluginJson, runtimeParams);
List<Map<String, Object>> result = new ArrayList<>();
try {
if (!pluginJson.isEmpty()) {
for (int i = 0; i < pluginJson.size(); i++) {
JSONObject map = pluginJson.getJSONObject(i);
String variable = map.getString(FIELD_VALUE);
Object value = runtimeParams.get(variable);
map.put(FIELD_VALUE, value);
result.add(map.toJavaObject(new TypeReference<Map<String, Object>>() {
}));
}
}
return result;
} catch (Exception e) {
throw new NodeException("处理数据库字段异常");
}
}
// 判断value是否为null。
private static boolean checkNull(Object value) {
return value == null || StringUtils.isBlank(String.valueOf(value));
}
/**
* @return void
* @throws
* @Author mapabc7
* @Description 删除无参字段
* @Date 11:53 2020/6/9
* @Param [typesAndValues, condColumns, operations]
*/
private static void deleteNoParam(JSONArray pluginJson, Map<String, Object> runtimeParams) throws NodeException {
for (int i = 0; i < pluginJson.size(); i++) {
JSONObject map = pluginJson.getJSONObject(i);
if (map == null) {
pluginJson.remove(i);
if (pluginJson.size() > 0) {
deleteNoParam(pluginJson, runtimeParams);
}
return;
} else {
String value = String.valueOf(map.get(FIELD_VALUE));
boolean flag = false;
if (map.get(FIELD_FLAG) != null) {
try {
flag = (boolean) map.get(FIELD_FLAG);
} catch (Exception e) {
throw new NodeException("flag格式转换错误");
}
}
if (StringUtils.isBlank(value) ||
runtimeParams == null ||
checkNull(runtimeParams.get(value))) {
if (flag) {
throw new NodeException("请填写必要的条件: " + value);
} else {
pluginJson.remove(i);
if (pluginJson.size() > 0) {
deleteNoParam(pluginJson, runtimeParams);
}
return;
}
}
}
}
}
private static Object typeHandler(String fieldType, String fieldValue) throws NodeException{
switch (fieldType) {
case FLOAT4:
return Float.valueOf(fieldValue);
case FLOAT8:
case MONEY:
return Double.valueOf(fieldValue);
case INT4:
case INT2:
return Integer.valueOf(fieldValue);
case BOOL:
case com.wanji.common.framework.Constants.PostGreSqlColumn.BIT:
return Boolean.valueOf(fieldValue);
case NUMERIC:
return new BigDecimal(fieldValue);
case INT8:
return Long.valueOf(fieldValue);
case TIMESTAMP:
return Timestamp.valueOf(fieldValue);
case TIME:
return Time.valueOf(fieldValue);
case DATE:
return Date.valueOf(fieldValue);
case BYTEA:
case TEXT:
case BPCHAR:
case com.wanji.common.framework.Constants.PostGreSqlColumn.VARCHAR:
case BOX:
case CIDR:
case INET:
case MACADDR:
case VARBIT:
case CIRCLE:
case INTERVAL:
case LINE:
case LSEG:
case POLYGON:
case POINT:
case PATH:
return fieldValue;
default:
throw new NodeException("[PostgresqlTypeHandler] 未支持的类型:" + fieldType);
}
}
public static Object[] typeHandler(List<Map<String, Object>> paramList) throws NodeException {
List<Object> list = new ArrayList<>();
for (Map<String, Object> paramMap : paramList) {
String fieldType = String.valueOf(paramMap.get(FIELD_TYPE));
String fieldValue = String.valueOf(paramMap.get(FIELD_VALUE));
if (com.wanji.common.utils.tool.StringUtils.equalsIgnoreCase(fieldValue, "null")) {
list.add(null);
} else {
list.add(typeHandler(fieldType, fieldValue));
}
}
return list.toArray();
}
}
package com.wanji.common.tool.dbtools;
import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.Properties;
/**
* @author mapabc
*/
@Slf4j
public class DSPool {
private static Map<String, DruidDataSource> dsPools;
private static final String MYSQL_QUERY_SQL = "SELECT 'X' ";
private static final String ORACLE_QUERY_SQL = "SELECT 'X' FROM DUAL";
private static final String MYSQL = "mysql";
private static final String ORACLE = "oracle";
static {
dsPools = Maps.newConcurrentMap();
}
public static DruidDataSource getDataSource(String driveName, String url, String userName, String password) {
String key = getKey(url, userName, password);
return getDataSource(key, driveName, url, userName, password);
}
private static String getKey(String url, String userName, String password) {
return url + "_" + userName + "_" + password;
}
private static DruidDataSource getDataSource(String id, String driveName, String url, String userName, String password) {
if (!dsPools.containsKey(id)) {
synchronized (DSPool.class) {
if (!dsPools.containsKey(id)) {
DruidDataSource dataSource = createDataSource(driveName, url, userName, password);
if (dataSource != null) {
dsPools.put(id, dataSource);
}
}
}
}
return dsPools.get(id);
}
public static DruidDataSource createDataSource(String driveName, String url, String userName, String password) {
DruidDataSource dataSource;
try {
dataSource = new DruidDataSource();
dataSource.setDriverClassName(driveName);
dataSource.setUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(password);
// 参数设置
// 初始化连接数量
dataSource.setInitialSize(10);
// 最大连接池数量
dataSource.setMaxActive(500);
// 获取连接时最大等待时间
dataSource.setMaxWait(600 * 1000);
dataSource.setTestWhileIdle(true);
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
dataSource.setRemoveAbandoned(true);
//关闭长时间不使用的连接超时时间,单位秒
dataSource.setRemoveAbandonedTimeout(1800);
//关闭abanded连接时输出错误日志
dataSource.setLogAbandoned(true);
//配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
dataSource.setTimeBetweenEvictionRunsMillis(600000);
// 设置失败尝试次数。
dataSource.setBreakAfterAcquireFailure(true); // true 中断失败连接
dataSource.setConnectionErrorRetryAttempts(0); // 失败重试次数
dataSource.setValidationQueryTimeout(20);
Properties properties = new Properties();
properties.setProperty("characterEncoding", "UTF-8");
// 连接超时时间 毫秒
// properties.setProperty("spring.datasource.connection-timeout", "10");
dataSource.setConnectProperties(properties);
if (driveName.contains(MYSQL)) {
dataSource.setValidationQuery(MYSQL_QUERY_SQL);
} else if (driveName.contains(ORACLE)) {
dataSource.setValidationQuery(ORACLE_QUERY_SQL);
}
//timeBetweenEvictionRunsMillis
//配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
dataSource.setTimeBetweenEvictionRunsMillis(10000 * 60 * 3);
//配置一个连接在池中最小生存的时间,单位是毫秒
dataSource.setMinEvictableIdleTimeMillis(10000 * 60 * 10);
dataSource.init();
log.info("init dataSource pool success,userName: {},password: {},url: {}", userName, password, url);
} catch (Exception e) {
log.error("init dataSource pool fail,userName: {},password: {},url: {}", userName, password, url, e);
dataSource = null;
}
return dataSource;
}
public static DruidDataSource removeDataSource(String url, String userName, String password) {
String key = getKey(url, userName, password);
return removeDataSource(key);
}
private static DruidDataSource removeDataSource(String id) {
return dsPools.remove(id);
}
}
package com.wanji.common.tool.dbtools;
import com.alibaba.druid.pool.DruidDataSource;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.domain.Table;
import com.wanji.common.framework.exception.NodeException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.commons.lang3.StringUtils;
import java.sql.*;
import java.util.*;
import static com.wanji.common.framework.Constants.DataBase.*;
import static com.wanji.common.framework.Constants.DbDriver.BEYONDB;
import static com.wanji.common.framework.Constants.DbDriver.MYSQL;
import static com.wanji.common.framework.Constants.DbDriver.ORACLE;
import static com.wanji.common.framework.Constants.DbDriver.SQLSERVER;
import static com.wanji.common.framework.Constants.MysqlColumn.BIT;
import static com.wanji.common.framework.Constants.MysqlColumn.FLOAT;
import static com.wanji.common.framework.Constants.MysqlColumn.VARCHAR;
import static com.wanji.common.framework.Constants.MysqlColumn.*;
import static com.wanji.common.framework.Constants.OracleColumn.*;
import static com.wanji.common.framework.Constants.PostGreSqlColumn.DATE;
import static com.wanji.common.framework.Constants.PostGreSqlColumn.TEXT;
import static com.wanji.common.framework.Constants.PostGreSqlColumn.TIMESTAMP;
import static com.wanji.common.framework.Constants.PostGreSqlColumn.*;
import static com.wanji.common.framework.Constants.ServiceGateWayConstants.D2ADataBase.*;
import static com.wanji.common.framework.Constants.TableInfo.*;
/**
* @author mapabc
*/
@Slf4j
public class DSUtils {
private static final String COLUMN_NAME = "column_name";
public static void createDatabase(Connection connection, String database) throws SQLException {
executeUpdateSql(connection, "create database " + database
+ " DEFAULT CHARSET utf8 COLLATE utf8_general_ci");
}
public static void deleteDatabase(Connection connection, String database) throws SQLException {
executeUpdateSql(connection, "drop database " + database);
}
/**
* get the connection
*/
public static Connection getConn(String driveName, String url, String userName, String password) throws Exception {
Connection con = null;
DruidDataSource dataSource = DSPool.getDataSource(driveName, url, userName, password);
if (dataSource != null) {
con = dataSource.getConnection();
}
return con;
}
/**
* close DB connection
*
* @param con DB connection
*/
public static void closeConn(Connection con) {
try {
if (con != null) {
con.close();
}
con = null;
} catch (Exception ignore) {
log.error("[DSUtils] 数据库关闭连接失败!");
}
}
/**
* 判断是否为主键
*
* @param conn
* @param tableName
* @param columnName
* @return
*/
public static boolean isPK(Connection conn, String tableName, String columnName) {
boolean isPK = false;
try {
DatabaseMetaData dsData = conn.getMetaData();
ResultSet rs = dsData.getPrimaryKeys(null, null, tableName);
try {
while (rs.next()) {
if (columnName.equals(rs.getString(COLUMN_NAME))) {
isPK = true;
break;
}
}
} catch (SQLException e) {
log.error("query table structure error,tableName:{}, columnName:{}", tableName, columnName, e);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return isPK;
}
/**
* 获取数据库中的所有表名
*
* @param conn
* @return
* @author cai_cf@126.com
*/
public static Set<String> getAllTableName(Connection conn) {
return getAllTableName(conn, null);
}
public static Set<String> getAllTableName(Connection conn, String schema) {
Set<String> tables = new HashSet<>();
try {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rsTables = meta.getTables(conn.getCatalog(), schema,
"%", new String[]{"TABLE"});
while (rsTables.next()) {
tables.add(rsTables.getString("TABLE_NAME"));
}
} catch (SQLException e) {
log.error("获取数据库中的所有表的表名", e);
}
return tables;
}
public static List<Table> getAllTableList(Connection conn, String schema) {
List<Table> tables = new ArrayList<>();
try {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rsTables = meta.getTables(conn.getCatalog(), schema,
"%", new String[]{"TABLE"});
while (rsTables.next()) {
Table table=new Table();
table.setNameEn(rsTables.getString("TABLE_NAME"));
table.setNameCn(rsTables.getString("TABLE_NAME"));
table.setDes(rsTables.getString("REMARKS"));
table.setSchemaName(rsTables.getString("TABLE_SCHEM"));
tables.add(table);
}
} catch (SQLException e) {
log.error("获取数据库中的所有表的表名", e);
} finally {
DSUtils.closeConn(conn);
}
return tables;
}
/**
* 判断数据库表是否存在
*
* @param conn
* @param schema
* @param tableName
* @return
*/
public static boolean existsTable(Connection conn, String schema, String tableName) {
boolean flag = false;
try {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rsTables = meta.getTables(null, schema, tableName, null);
if (rsTables.next()) {
flag = true;
log.info(tableName + "已经存在");
} else {
log.info(tableName + "不存在");
}
} catch (SQLException e) {
log.error("判断数据库表是否存在错误", e);
}
return flag;
}
private static String upperCaseTableNameForOracle(Connection conn, String tableName) throws SQLException {
if (ORACLE.equals(conn.getMetaData().getDatabaseProductName().toLowerCase())) {
tableName = tableName.toUpperCase();
}
return tableName;
}
/**
* 获取表字段属性
*
* @param conn
* @param tableName
* @return
* @throws NullPointerException
*/
public static List<Map<String, String>> findTableColumnList(Connection conn, String tableName) throws NullPointerException {
return findTableColumnList(conn, null, tableName);
}
public static List<Map<String, String>> findTableColumnList(Connection conn, String schema, String tableName) throws NullPointerException {
verify(tableName, conn);
List<Map<String, String>> columnsList = Lists.newArrayList();
try {
DatabaseMetaData dmd = conn.getMetaData();
if (dmd == null) {
log.error("The DatabaseMetaData Object was null.");
return columnsList;
}
ResultSet rs = dmd.getColumns(conn.getCatalog(), schema, tableName, "%");
rs2List(rs, columnsList, conn, tableName);
} catch (SQLException e) {
log.error("数据库连接失败!", e);
}
return columnsList;
}
/*public static void main(String[] arg) throws Exception {
String driveName = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@192.168.5.135:1521:orcl";
String userName = "AVPLAN";
String password = "123456";
Connection conn = getConn(driveName, url, userName, password);
System.out.println(getTableData(conn, "SELECT * FROM AVPLAN.\"test_\" WHERE \"test_\".ID = 1", new String[]{}));
}*/
public static void main(String[] arg) throws Exception {
String url = "jdbc:mysql://121.36.56.157:63306/uni_bp_dev_db_v1.0.0?useUnicode=true&characterEncoding=UTF-8&connectTimeout=1000";
String driveName = MYSQL;
String userName = "root";
String password = "123456";
Connection conn = getConn(driveName, url, userName, password);
System.out.println(getAllTableName(conn));
}
private static void verify(String tableName, Connection conn) throws NullPointerException {
if (StringUtils.isBlank(tableName)) {
throw new NullPointerException("the table name is null.");
}
if (conn == null) {
throw new NullPointerException("the connection is null");
}
}
private static void rs2List(ResultSet rs, List<Map<String, String>> columnsList, Connection conn, String tableName) {
try {
while (rs.next()) {
Map<String, String> map = Maps.newHashMap();
String type = rs.getString(TYPE_NAME);
String isNull = rs.getString(NULLABLE);
//因JDBC里面强制转换了类型,故特殊处理,by guoliang.dong@mapabc.com
map.put(Constants.TableInfo.COLUMN_NAME, rs.getString(Constants.TableInfo.COLUMN_NAME));
if("serial".equals(type)){
map.put(TYPE_NAME, "int4");
}else if("bigserial".equals(type)){
map.put(TYPE_NAME, "int8");
}else if("bpchar".equals(type)) {
map.put(TYPE_NAME, "char");
}else {
map.put(TYPE_NAME, type);
}
map.put(COLUMN_DEF, rs.getString(COLUMN_DEF));
String dataBaseType = conn.getMetaData().getDatabaseProductName().toLowerCase();
map.put(COLUMN_SIZE, getColumnSize(dataBaseType, rs));
map.put(ISNULL, isNull);
map.put(IS_PK, isPK(conn, tableName, rs.getString(Constants.TableInfo.COLUMN_NAME)) ? "1" : "0");
columnsList.add(map);
}
} catch (Exception e) {
log.error("query table structure error," + e.getMessage(), e);
}
}
private static String getColumnSize(String dataBaseType, ResultSet rs) {
String size = null;
try {
String type = rs.getString(TYPE_NAME);
if("serial".equals(type)){
type = "int4";
}else if("bigserial".equals(type)){
type = "int8";
}else if("bpchar".equals(type)) {
type = "char";
}
//判断数据库类型,来进行判断类型
switch (dataBaseType) {
case MYSQL:
switch (type) {
case YEAR:
case DATE:
case DATETIME:
case BINARY:
case VARBINARY:
case TINYINT:
case SMALLINT:
case MEDIUMINT:
case INT:
case BIGINT:
case BIT:
case CHAR:
case VARCHAR:
case Constants.MysqlColumn.TEXT:
case LONGTEXT:
size = rs.getString(COLUMN_SIZE);
break;
case DECIMAL:
case DOUBLE:
case FLOAT:
size = rs.getString(COLUMN_SIZE) + "," + rs.getString(DECIMAL_DIGITS);
break;
default:
break;
}
break;
case POSTGRESQL:
switch (type) {
case FLOAT4:
// size = rs.getFloat(COLUMN_SIZE)+"";
size = "24";
break;
case FLOAT8:
// size = rs.getFloat(COLUMN_SIZE)+"";
size = "53";
break;
case MONEY:
size = rs.getString(COLUMN_SIZE);
break;
case TEXT:
break;
case DATE:
size = rs.getString(COLUMN_SIZE);
break;
case BPCHAR:
case Constants.PostGreSqlColumn.VARCHAR:
size = rs.getString(COLUMN_SIZE);
break;
case INT4:
// size = rs.getInt(COLUMN_SIZE)+"";
size = "32";
break;
case INT2:
// size = rs.getInt(COLUMN_SIZE)+"";
size = "16";
break;
case Constants.PostGreSqlColumn.BIT:
case NUMERIC:
size = rs.getString(COLUMN_SIZE);
if(size.equals("131089")){
size = "0";
}
break;
case BOOL:
case INT8:
// size = rs.getInt(COLUMN_SIZE)+"";
size = "64";
break;
case TIMESTAMP:
size = rs.getString(COLUMN_SIZE);
break;
case TIME:
case BYTEA:
case BOX:
case CIDR:
case INET:
case MACADDR:
case VARBIT:
case CIRCLE:
case INTERVAL:
case LINE:
case LSEG:
case POLYGON:
case POINT:
case PATH:
size = rs.getString(COLUMN_SIZE);
break;
default:
break;
}
break;
case ORACLE:
switch (type) {
case VARCHAR2:
case ORACLE_CHAR:
case RAW:
case NVARCHAR2:
case Constants.OracleColumn.TIMESTAMP:
case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
case TIMESTAMP_WITH_TIME_ZONE:
size = rs.getString(COLUMN_SIZE);
break;
case INTERVAL_DAY_TO_SECOND:
case INTERVAL_YEAR_TO_MONTH:
case NUMBER:
size = "0".equals(rs.getString(DECIMAL_DIGITS))
? rs.getString(COLUMN_SIZE)
: rs.getString(COLUMN_SIZE) + "," + rs.getString(DECIMAL_DIGITS);
break;
default:
break;
}
break;
default:
throw new NodeException("not support type ");
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
public static List<Map<String, String>> findGPTableColumnList(Connection conn, String tableName) {
verify(tableName, conn);
List<Map<String, String>> columnsList = Lists.newArrayList();
try {
DatabaseMetaData dmd = conn.getMetaData();
if (dmd == null) {
log.error("The DatabaseMetaData Object was null .");
return columnsList;
}
ResultSet rs = dmd.getColumns(null, null, tableName, "%");
try {
while (rs.next()) {
Map<String, String> map = Maps.newHashMap();
String type = rs.getString(TYPE_NAME);
String name = rs.getString(Constants.TableInfo.COLUMN_NAME);
if ("UNKNOWN".equals(type)) {
type = getColumnType(tableName, name, conn);
}
String isNull = rs.getString(NULLABLE);
map.put(Constants.TableInfo.COLUMN_NAME, name);
map.put(TYPE_NAME, type);
map.put(COLUMN_DEF, rs.getString(COLUMN_DEF));
assert type != null;
if (!type.toLowerCase().contains("date") || !type.toLowerCase().contains("time")) {
map.put(COLUMN_SIZE, rs.getString(COLUMN_SIZE));
}
map.put(ISNULL, isNull);
map.put(IS_PK, isPK(conn, tableName, rs.getString(Constants.TableInfo.COLUMN_NAME)) ? "1" : "0");
columnsList.add(map);
}
} catch (Exception e) {
log.error("query table structure error," + e.getMessage(), e);
}
} catch (SQLException e) {
log.error("数据库连接失败!", e);
}
return columnsList;
}
private static String getColumnType(String table, String col, Connection con) throws SQLException {
ResultSet rs = null;
PreparedStatement pstmt = null;
String sql = "SELECT t.typname FROM pg_attribute a,pg_class c,pg_type t where a.attrelid=c.oid and t.oid=a.atttypid and c.relname=? and a.attname=?;";
try {
pstmt = con.prepareStatement(sql);
pstmt.setString(1, table);
pstmt.setString(2, col);
rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getString(1);
}
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
rs = null;
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (Exception e) {
pstmt = null;
}
}
}
return null;
}
/**
* 获取总条数
*
* @param conn
* @param sql
* @return
* @throws SQLException
*/
public static int getCount(Connection conn, String sql) throws SQLException {
int count;
try {
QueryRunner queryRunner = new QueryRunner();
count = Integer.valueOf(queryRunner.query(conn, sql, new ScalarHandler(1)).toString());
} catch (SQLException e) {
log.error("Count data of db fail.{sql:" + sql + "}", e);
throw e;
}
return count;
}
public static int getCount(Connection conn, String sql, Object[] params) throws SQLException {
int count;
try {
QueryRunner queryRunner = new QueryRunner();
count = Integer.valueOf(queryRunner.query(conn, sql, new ScalarHandler(1), params).toString());
} catch (SQLException e) {
log.error("Count data of db fail.{sql:" + sql + "}", e);
throw e;
}
return count;
}
/**
* execute sql to db (Create Table && Drop Table)
*
* @param conn connection of db
* @param sql sql to execute
* @return execute success?
* @author cai_cf@126.com
*/
public static boolean executeUpdateSql(Connection conn, String sql) throws SQLException {
boolean flag = true;
try {
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
// d2a外部事务实现,如果开启,将数据库连接自动提交关闭
if (!Constants.OPEN_GLOBAL_TRANSACTION.get()) {
conn.commit();
}
} catch (SQLException e) {
flag = false;
try {
conn.rollback();
} catch (SQLException e1) {
log.error("executeUpdateSql rollBack error", e1);
throw e1;
}
log.error("executeUpdateSql error sql:{}", sql, e);
throw e;
}
return flag;
}
/**
* execute sql to db (Create Table && Drop Table)
*
* @param conn connection of db
* @param sql sql to execute
* @return execute success?
* @author cai_cf@126.com
*/
public static int executeSqlReturnChangedRows(Connection conn, String sql) {
int result = 0;
try {
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
result = stmt.executeUpdate(sql);
// d2a外部事务实现,如果开启,将数据库连接自动提交关闭
if (!Constants.OPEN_GLOBAL_TRANSACTION.get()) {
conn.commit();
}
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("executeSqlReturnChangedRows rollBack error.", e1);
}
log.error("executeSqlReturnChangedRows error.{ sql:{}", sql, e);
}
return result;
}
public static int executeSqlReturnChangedRows(Connection conn, String sql,Object[] params) {
int result = 0;
QueryRunner queryRunner = new QueryRunner();
try {
conn.setAutoCommit(false);
//Statement stmt = conn.createStatement();
//result = stmt.executeUpdate(sql);
queryRunner.update(conn, sql, params);
// d2a外部事务实现,如果开启,将数据库连接自动提交关闭
if (!Constants.OPEN_GLOBAL_TRANSACTION.get()) {
conn.commit();
}
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("executeSqlReturnChangedRows rollBack error.", e1);
}
log.error("executeSqlReturnChangedRows error.{ sql:{}", sql, e);
}
return result;
}
/**
* 查询数据
*
* @param conn
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static List<Map<String, Object>> search(Connection conn, String sql, List<Object> params) throws SQLException {
List<Map<String, Object>> result;
QueryRunner runner = new QueryRunner();
try {
if (params != null && params.size() > 0) {
Object[] objects = params.toArray();
result = runner.query(conn, sql, new MapListHandler(), objects);
} else {
result = runner.query(conn, sql, new MapListHandler());
}
} catch (SQLException e) {
log.error("数据查询失败!", e);
throw e;
}
return result;
}
public static String searchOne(Connection conn, String sql) throws SQLException {
String result;
QueryRunner runner = new QueryRunner();
try {
result = runner.query(conn, sql, new ScalarHandler<String>());
} catch (SQLException e) {
log.error("数据查询失败!", e);
throw e;
}
return result;
}
/**
* 查所有数据 clob 和Blob需要单独处理
*/
public static List<Map<String, Object>> getTableData(Connection conn, String sql) throws SQLException {
List<Map<String, Object>> result;
QueryRunner runner = new QueryRunner();
try {
result = runner.query(conn, sql, new MapListHandler());
} catch (SQLException e) {
log.error("getTableData error", e);
throw e;
}
return result;
}
public static Map<String, Object> getTableDataObj(Connection conn, String sql) {
Map<String, Object> map = null;
QueryRunner runner = new QueryRunner();
try {
List<Map<String, Object>> result = runner.query(conn, sql, new MapListHandler());
if(result != null && result.size()>0){
map = result.get(0);
}
} catch (SQLException e) {
log.error("获取一条数据异常", e);
}
return map;
}
/**
* 获取表主键
*
* @param conn
* @param tableName
* @return
*/
public static String getPrimaryKey(Connection conn, String tableName) throws SQLException, ClassNotFoundException {
DatabaseMetaData metaData = conn.getMetaData();
ResultSet resultSet = metaData.getPrimaryKeys(conn.getCatalog(), null, tableName);
String pkName = "";
while (resultSet.next()) {
pkName = resultSet.getString("COLUMN_NAME");
}
return pkName;
}
/**
* 查询表中所有数据。
* <p>
* 使用Apache DbUtils中的QueryRunner。不会发生sql注入。
* 与search方法功能类似。
*
* @param conn 数据源连接。
* @param sql select sql语句。
* @return 查询结果。
* @throws SQLException 如果查询失败。
*/
public static List<Map<String, Object>> getTableData(Connection conn, String sql, Object[] params) throws SQLException {
List<Map<String, Object>> result;
QueryRunner runner = new QueryRunner();
try {
result = runner.query(conn, sql, new MapListHandler(), params);
} catch (SQLException e) {
throw new SQLException("[DSUtils] getTableData error. sql:{}", sql, e);
}
return result;
}
/**
* 执行update语句。
* <p>
* 此方法内含有事务。若update失败,则回滚。
* <p>
* 不抛出异常。
*
* @param conn 数据源连接。
* @param sql update sql语句。
* @return 是否执行成功。true:成功。false:失败。
* @throws NodeException 如果执行update sql失败。
*/
public static boolean executeUpdateSql(Connection conn, String sql, Object[] params) throws NodeException {
QueryRunner queryRunner = new QueryRunner();
try {
conn.setAutoCommit(false);
queryRunner.update(conn, sql, params);
// d2a外部事务实现,如果开启,将数据库连接自动提交关闭
if (!Constants.OPEN_GLOBAL_TRANSACTION.get()) {
conn.commit();
}
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("[DSUtils] executeUpdateSql rollBack error.", e1);
throw new NodeException("[DSUtils] executeUpdateSql rollBack error.", e);
}
log.error("[DSUtils] executeUpdateSql error. update sql:{}", sql, e);
throw new NodeException("[DSUtils] executeUpdateSql error.", e);
}
return true;
}
public static <T> List<T> queryList(Connection conn, String sql, Object[] params,Class clazz) throws SQLException {
QueryRunner queryRunner = new QueryRunner();
List<T> list = null;
try {
list = (List)queryRunner.query(conn, sql, new BeanListHandler(clazz),params);
} catch (SQLException e) {
throw new SQLException("[DSUtils] queryList error. sql:{}", sql, e);
}
return list;
}
}
package com.wanji.common.tool.dbtools;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.*;
/**
* MySQL sql构造器。
*
* @Author mapabc6
* @Date 2020/3/11 21:57
*/
public class MySQL {
private String select;
private String delete;
private String update;
private String set;
private String columns;
private String from;
private String where;
private String order;
private String limit;
private MySQL(SqlBuilder sqlBuilder) {
this.select = sqlBuilder.select;
this.delete = sqlBuilder.delete;
this.update = sqlBuilder.update;
this.set = sqlBuilder.set;
this.columns = sqlBuilder.columns;
this.from = sqlBuilder.from;
this.where = sqlBuilder.where;
this.order = sqlBuilder.order;
this.limit = sqlBuilder.limit;
}
public static class SqlBuilder {
private String select;
private String delete;
private String update;
private String set;
private String columns;
private String from;
private String where;
private String order;
private String limit;
public SqlBuilder select() {
this.select = "select ";
return this;
}
public SqlBuilder delete() {
this.delete = "delete ";
return this;
}
public SqlBuilder update(String tableName) {
this.update = "update " + "`" + tableName + "`";
return this;
}
// 构造update语句的set片段。
public SqlBuilder buildSet(List<Map<String, Object>> updateParams) {
StringBuilder setBuilder = new StringBuilder(" set ");
for (int i = 0; i < updateParams.size(); i++) {
if (updateParams.size() == (i + 1)) {
setBuilder.append(updateParams.get(i).get(FIELD_NAME_EN).toString()).append("=? ");
} else {
setBuilder.append(updateParams.get(i).get(FIELD_NAME_EN).toString()).append("=?, ");
}
}
this.set = setBuilder.toString();
return this;
}
public SqlBuilder buildAllColumns() {
this.columns = "* ";
return this;
}
public SqlBuilder buildCount() {
this.columns = "count(*) ";
return this;
}
public SqlBuilder buildFrom(String table) {
this.from = "from " + "`" + table + "`";
return this;
}
// 根据不同的操作符来拼接where片段
public SqlBuilder buildWhere(List<Map<String, Object>> whereParams) {
StringBuilder whereBuilder = new StringBuilder(" where 1=1 ");
for (Map<String, Object> map : whereParams) {
String operation = map.get(OPERATION).toString();
String fieldValue = map.get(FIELD_VALUE).toString();
String conditionCol = map.get(FIELD_NAME_EN).toString();
if (BETWEEN_OPERATION.equalsIgnoreCase(operation)) {
whereBuilder.append("and ").append(conditionCol).append(" ").append(operation)
.append(" ? and ").append("? ");
} else if (IN_OPERATION.equalsIgnoreCase(operation)) {
whereBuilder.append("and ").append(conditionCol).append(" ").append(operation);
String[] split = fieldValue.split(",");
int length = split.length;
for (int j = 0; j < length; j++) {
if (j == 0) {
whereBuilder.append(" (");
} else {
whereBuilder.append(",");
}
whereBuilder.append("?");
if (j == length - 1) {
whereBuilder.append(") ");
}
}
} else {
whereBuilder.append("and ").append(conditionCol).append(" ").append(operation)
.append(" ? ");
}
}
this.where = whereBuilder.toString();
return this;
}
// 根据不同的操作符来拼接 order 片段
public SqlBuilder buildOrder(List<Map<String, String>> orderParams) {
StringBuilder orderBuilder = new StringBuilder();
if (orderParams != null && !orderParams.isEmpty()) {
orderBuilder.append(" order by ");
for (Map<String, String> orderParam : orderParams) {
String operation = orderParam.get(OPERATION);
String fieldNameEn = orderParam.get(FIELD_NAME_EN);
if (DESC_OPERATION.equalsIgnoreCase(operation)) { // 降序
orderBuilder.append("`").append(fieldNameEn).append("`").append(" ")
.append(DESC_OPERATION).append(" ,");
} else { // 默认 升序排序
orderBuilder.append("`").append(fieldNameEn).append("`").append(" ")
.append(ASC_OPERATION).append(" ,");
}
}
orderBuilder = new StringBuilder(orderBuilder.toString().substring(0, orderBuilder.toString().length() - 1));
}
this.order = orderBuilder.toString();
return this;
}
public SqlBuilder buildLimit(int startRowNum, int pageSize) {
this.limit = new StringBuilder("limit ").append(startRowNum).append(", ").append(pageSize).toString();
return this;
}
public MySQL build() {
return new MySQL(this);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (select != null) {
builder.append(select);
}
if (delete != null) {
builder.append(delete);
}
if (update != null) {
builder.append(update);
}
if (set != null) {
builder.append(set);
}
if (columns != null) {
builder.append(columns);
}
if (from != null) {
builder.append(from);
}
if (where != null) {
builder.append(where);
}
if (order != null) {
builder.append(order);
}
if (limit != null) {
builder.append(limit);
}
return builder.toString();
}
}
package com.wanji.common.tool.dbtools;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.*;
/**
* Oracle sql 构造器。
*
* @Author mapabc6
* @Date 2020/3/13 11:48
*/
public class Oracle {
private String select;
private String delete;
private String update;
private String set;
private String columns;
private String from;
private String where;
private String order;
private Oracle(SqlBuilder sqlBuilder) {
this.select = sqlBuilder.select;
this.delete = sqlBuilder.delete;
this.update = sqlBuilder.update;
this.set = sqlBuilder.set;
this.columns = sqlBuilder.columns;
this.from = sqlBuilder.from;
this.where = sqlBuilder.where;
this.order = sqlBuilder.order;
}
public static class SqlBuilder {
private String select;
private String delete;
private String update;
private String set;
private String columns;
private String from;
private String where;
private String order;
public SqlBuilder select() {
this.select = "SELECT ";
return this;
}
public SqlBuilder delete() {
this.delete = "DELETE ";
return this;
}
public SqlBuilder update(String tableName) {
this.update = "UPDATE " + "`" + tableName + "`";
return this;
}
// 构造update中的set片段
public SqlBuilder buildSet(List<Map<String, Object>> updateParams) {
StringBuilder setBuilder = new StringBuilder(" SET ");
for (int i = 0; i < updateParams.size(); i++) {
if (updateParams.size() == (i + 1)) {
setBuilder.append("\"").append(updateParams.get(i).get(FIELD_NAME_EN).toString()).append("\"").append("=? ");
} else {
setBuilder.append("\"").append(updateParams.get(i).get(FIELD_NAME_EN).toString()).append("\"").append("=?, ");
}
}
this.set = setBuilder.toString();
return this;
}
public SqlBuilder buildAllColumns() {
this.columns = "* ";
return this;
}
public SqlBuilder buildCount() {
this.columns = "count(*) ";
return this;
}
public SqlBuilder buildFrom(String table) {
this.from = "FROM " + "`" + table + "`";
return this;
}
// 根据不同的操作符来拼接where片段
public SqlBuilder buildWhere(List<Map<String, Object>> whereParams) {
StringBuilder whereBuilder = new StringBuilder(" WHERE 1=1 ");
for (Map<String, Object> map : whereParams) {
String operation = map.get(OPERATION).toString().toUpperCase();
String fieldValue = map.get(FIELD_VALUE).toString();
String conditionCol = map.get(FIELD_NAME_EN).toString();
if (BETWEEN_OPERATION.equalsIgnoreCase(operation)) {
whereBuilder.append("AND ").append("\"").append(conditionCol).append("\"").append(" ")
.append(operation).append(" ? AND ").append("? ");
} else if (IN_OPERATION.equalsIgnoreCase(operation)) {
whereBuilder.append("AND ").append("\"").append(conditionCol).append("\"").append(" ")
.append(operation);
String[] split = fieldValue.split(",");
int length = split.length;
for (int j = 0; j < length; j++) {
if (j == 0) {
whereBuilder.append(" (");
} else {
whereBuilder.append(",");
}
whereBuilder.append("?");
if (j == length - 1) {
whereBuilder.append(") ");
}
}
} else {
whereBuilder.append("AND ").append("\"").append(conditionCol).append("\"").append(" ")
.append(operation).append(" ? ");
}
}
this.where = whereBuilder.toString();
return this;
}
// 根据不同的操作符来拼接 order 片段
public SqlBuilder buildOrder(List<Map<String, String>> orderParams) {
StringBuilder orderBuilder = new StringBuilder();
if (orderParams != null && !orderParams.isEmpty()) {
orderBuilder.append(" ORDER BY ");
for (Map<String, String> orderParam : orderParams) {
String operation = orderParam.get(OPERATION);
String fieldNameEn = orderParam.get(FIELD_NAME_EN);
if (DESC_OPERATION.equalsIgnoreCase(operation)) { // 降序
orderBuilder.append(fieldNameEn).append(" ").append(DESC_OPERATION).append(" ,");
} else { // 默认 升序排序
orderBuilder.append(fieldNameEn).append(" ").append(ASC_OPERATION).append(" ,");
}
}
orderBuilder = new StringBuilder(orderBuilder.toString().substring(0, orderBuilder.toString().length() - 1));
}
this.order = orderBuilder.toString();
return this;
}
public Oracle build() {
return new Oracle(this);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (select != null) {
builder.append(select);
}
if (delete != null) {
builder.append(delete);
}
if (update != null) {
builder.append(update);
}
if (set != null) {
builder.append(set);
}
if (columns != null) {
builder.append(columns);
}
if (from != null) {
builder.append(from);
}
if (where != null) {
builder.append(where);
}
if (order != null) {
builder.append(order);
}
return builder.toString();
}
}
package com.wanji.common.tool.dbtools;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.*;
/**
* MySQL sql构造器。
*
* @Author mapabc6
* @Date 2020/3/11 21:57
*/
public class PostgreSQL {
private String select;
private String delete;
private String update;
private String set;
private String columns;
private String from;
private String where;
private String order;
private String limit;
private PostgreSQL(SqlBuilder sqlBuilder) {
this.select = sqlBuilder.select;
this.delete = sqlBuilder.delete;
this.update = sqlBuilder.update;
this.set = sqlBuilder.set;
this.columns = sqlBuilder.columns;
this.from = sqlBuilder.from;
this.where = sqlBuilder.where;
this.order = sqlBuilder.order;
this.limit = sqlBuilder.limit;
}
public static class SqlBuilder {
private String select;
private String delete;
private String update;
private String set;
private String columns;
private String from;
private String where;
private String order;
private String limit;
public SqlBuilder select() {
this.select = "select ";
return this;
}
public SqlBuilder delete() {
this.delete = "delete ";
return this;
}
public SqlBuilder update(String tableName) {
this.update = "update " + "`" + tableName + "`";
return this;
}
// 构造update语句的set片段。
public SqlBuilder buildSet(List<Map<String, Object>> updateParams) {
StringBuilder setBuilder = new StringBuilder(" set ");
for (int i = 0; i < updateParams.size(); i++) {
if (updateParams.size() == (i + 1)) {
setBuilder.append(updateParams.get(i).get(FIELD_NAME_EN).toString()).append("=? ");
} else {
setBuilder.append(updateParams.get(i).get(FIELD_NAME_EN).toString()).append("=?, ");
}
}
this.set = setBuilder.toString();
return this;
}
public SqlBuilder buildAllColumns() {
this.columns = "* ";
return this;
}
public SqlBuilder buildCount() {
this.columns = "count(*) ";
return this;
}
public SqlBuilder buildFrom(String table) {
this.from = "from " + table;
return this;
}
// 根据不同的操作符来拼接where片段
public SqlBuilder buildWhere(List<Map<String, Object>> whereParams) {
StringBuilder whereBuilder = new StringBuilder(" where 1=1 ");
for (Map<String, Object> map : whereParams) {
String operation = map.get(OPERATION).toString();
String fieldValue = map.get(FIELD_VALUE).toString();
String conditionCol = map.get(FIELD_NAME_EN).toString();
if (BETWEEN_OPERATION.equalsIgnoreCase(operation)) {
whereBuilder.append("and ").append("\"").append(conditionCol).append("\"")
.append(" ").append(operation).append(" ? and ").append("? ");
} else if (IN_OPERATION.equalsIgnoreCase(operation)) {
whereBuilder.append("and ").append("\"").append(conditionCol).append("\"")
.append(" ").append(operation);
String[] split = fieldValue.split(",");
int length = split.length;
for (int j = 0; j < length; j++) {
if (j == 0) {
whereBuilder.append(" (");
} else {
whereBuilder.append(",");
}
whereBuilder.append("?");
if (j == length - 1) {
whereBuilder.append(") ");
}
}
} else {
whereBuilder.append("and ").append("\"").append(conditionCol).append("\"")
.append(" ").append(operation).append(" ? ");
}
}
this.where = whereBuilder.toString();
return this;
}
// 根据不同的操作符来拼接 order 片段
public SqlBuilder buildOrder(List<Map<String, String>> orderParams) {
StringBuilder orderBuilder = new StringBuilder();
if (orderParams != null && !orderParams.isEmpty()) {
String operation = orderParams.get(0).get(OPERATION);
orderBuilder.append(" order by ");
for (Map<String, String> orderParam : orderParams) {
String fieldNameEn = orderParam.get(FIELD_NAME_EN);
orderBuilder.append(" ").append("\"").append(fieldNameEn).append("\"").append(" ,");
}
orderBuilder = new StringBuilder(orderBuilder.toString().substring(0, orderBuilder.toString().length() - 1));
if (DESC_OPERATION.equalsIgnoreCase(operation)) {
orderBuilder.append(" ").append(DESC_OPERATION).append(" ");
} else {
orderBuilder.append(" ").append(ASC_OPERATION).append(" ");
}
}
this.order = orderBuilder.toString();
return this;
}
public SqlBuilder buildLimit(int startRowNum, int pageSize) {
this.limit = new StringBuilder("limit ").append(pageSize).append(" offset ").append(startRowNum).toString();
return this;
}
public PostgreSQL build() {
return new PostgreSQL(this);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (select != null) {
builder.append(select);
}
if (delete != null) {
builder.append(delete);
}
if (update != null) {
builder.append(update);
}
if (set != null) {
builder.append(set);
}
if (columns != null) {
builder.append(columns);
}
if (from != null) {
builder.append(from);
}
if (where != null) {
builder.append(where);
}
if (order != null) {
builder.append(order);
}
if (limit != null) {
builder.append(limit);
}
return builder.toString();
}
}
package com.wanji.common.tool.dbtools;
import java.util.List;
import java.util.Map;
import static com.wanji.common.framework.Constants.ServicePublishConstants.SqlConstants.*;
/**
* @Author mapabc6
* @Date 2020/3/13 16:22
*/
public class SQLServer {
private String select;
private String delete;
private String update;
private String set;
private String columns;
private String from;
private String where;
private String order;
private String limit;
private SQLServer(SqlBuilder sqlBuilder) {
this.select = sqlBuilder.select;
this.delete = sqlBuilder.delete;
this.update = sqlBuilder.update;
this.set = sqlBuilder.set;
this.columns = sqlBuilder.columns;
this.from = sqlBuilder.from;
this.where = sqlBuilder.where;
this.order = sqlBuilder.order;
this.limit = sqlBuilder.limit;
}
public static class SqlBuilder {
private String select;
private String delete;
private String update;
private String set;
private String columns;
private String from;
private String where;
private String order;
private String limit;
public SqlBuilder select() {
this.select = "select ";
return this;
}
public SqlBuilder delete() {
this.delete = "delete ";
return this;
}
public SqlBuilder update(String tableName) {
this.update = "update " + "`" + tableName + "`";
return this;
}
// 构造update中的set片段
public SqlBuilder buildSet(List<Map<String, Object>> updateParams) {
StringBuilder setBuilder = new StringBuilder(" set ");
for (int i = 0; i < updateParams.size(); i++) {
if (updateParams.size() == (i + 1)) {
setBuilder.append(updateParams.get(i).get(FIELD_NAME_EN).toString()).append("=? ");
} else {
setBuilder.append(updateParams.get(i).get(FIELD_NAME_EN).toString()).append("=?, ");
}
}
this.set = setBuilder.toString();
return this;
}
public SqlBuilder buildAllColumns() {
this.columns = "* ";
return this;
}
public SqlBuilder buildCount() {
this.columns = "count(*) ";
return this;
}
public SqlBuilder buildFrom(String table) {
this.from = "from " + "`" + table + "`";
return this;
}
// 根据不同的操作符来拼接where片段
public SqlBuilder buildWhere(List<Map<String, Object>> whereParams) {
StringBuilder whereBuilder = new StringBuilder(" where 1=1 ");
for (Map<String, Object> map : whereParams) {
String operation = map.get(OPERATION).toString();
String fieldValue = map.get(FIELD_VALUE).toString();
String conditionCol = map.get(FIELD_NAME_EN).toString();
if (BETWEEN_OPERATION.equalsIgnoreCase(operation)) {
whereBuilder.append("and ").append(conditionCol).append(" ").append(operation)
.append(" ? and ").append("? ");
} else if (IN_OPERATION.equalsIgnoreCase(operation)) {
whereBuilder.append("and ").append(conditionCol).append(" ").append(operation);
String[] split = fieldValue.split(",");
int length = split.length;
for (int j = 0; j < length; j++) {
if (j == 0) {
whereBuilder.append(" (");
} else {
whereBuilder.append(",");
}
whereBuilder.append("?");
if (j == length - 1) {
whereBuilder.append(") ");
}
}
} else {
whereBuilder.append("and ").append(conditionCol).append(" ").append(operation)
.append(" ? ");
}
}
this.where = whereBuilder.toString();
return this;
}
// 根据不同的操作符来拼接 order 片段
public SqlBuilder buildOrder(List<Map<String, String>> orderParams) {
StringBuilder orderBuilder = new StringBuilder();
if (orderParams != null && !orderParams.isEmpty()) {
orderBuilder.append(" order by ");
for (Map<String, String> orderParam : orderParams) {
String operation = orderParam.get(OPERATION);
String fieldNameEn = orderParam.get(FIELD_NAME_EN);
if (DESC_OPERATION.equalsIgnoreCase(operation)) { // 降序
orderBuilder.append(fieldNameEn).append(" ").append(DESC_OPERATION).append(" ,");
} else { // 默认 升序排序
orderBuilder.append(fieldNameEn).append(" ").append(ASC_OPERATION).append(" ,");
}
}
orderBuilder = new StringBuilder(orderBuilder.toString().substring(0, orderBuilder.toString().length() - 1));
}
this.order = orderBuilder.toString();
return this;
}
public SqlBuilder buildOffset(int startRowNum, int pageSize) {
this.limit = new StringBuilder("OFFSET ").append(startRowNum).append("ROWS ")
.append("FETCH NEXT ").append(pageSize).append(" ROWS ONLY").toString();
return this;
}
public SQLServer build() {
return new SQLServer(this);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (select != null) {
builder.append(select);
}
if (delete != null) {
builder.append(delete);
}
if (update != null) {
builder.append(update);
}
if (set != null) {
builder.append(set);
}
if (columns != null) {
builder.append(columns);
}
if (from != null) {
builder.append(from);
}
if (where != null) {
builder.append(where);
}
if (order != null) {
builder.append(order);
}
if (limit != null) {
builder.append(limit);
}
return builder.toString();
}
}
package com.wanji.common.tool.drools;
import com.alipay.jarslink.api.Module;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import java.util.Map;
/**
* @ClassName AddFunction
* @Description
* @Author mapabc7
* @Date 2020/8/6 15:10
* @Version 1.0
*/
public class AddFunction extends AbstractFunction {
private String actionName;
private Module module;
public AddFunction(String actionName, Module module) {
this.actionName = actionName;
this.module = module;
}
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject args) {
return module.doAction(actionName, FunctionUtils.getJavaObject(args, env));
}
@Override
public String getName() {
return actionName;
}
}
package com.wanji.common.tool.drools;
import com.wanji.common.action.BuiltInActionLibraryUtils;
import com.wanji.common.action.SpringBean;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map;
/**
* <>
*
* @author wanji
* 2020/6/23 15:26
*/
@Slf4j
public class AviatorTool {
private static Map<String, Map<String, String>> jarBeanMap = Maps.newHashMap();
static {
}
/**
* 准备动作库的数据
*
* @param moduleName
* @param beanMap {"beanName":id}
*/
public static void readyActionLibrary(String moduleName, Map<String, String> beanMap) {
if (StringUtils.isBlank(moduleName) || MapUtils.isEmpty(beanMap)) {
return;
}
jarBeanMap.put(moduleName, beanMap);
}
public static void init() {
try {
registerCommonAction();
// registerJarAction();
} catch (Exception e) {
log.info("******注册Aviator方法异常************");
} finally {
//卸载jar
jarBeanMap.clear();
AviatorUtils.registerStaticFunctions();
}
}
/**
* 注册jar里的action
*/
/*private static void registerJarAction() {
jarBeanMap.forEach((moduleName, v) -> {
//获取扩展点
ModuleManager moduleManager = ServiceBeanContext.getBean("moduleManager");
Module module = moduleManager.find(moduleName);
//添加方法到Aviator中
Map<String, Action> actions = module.getActions();
for (Map.Entry<String, Action> entry : actions.entrySet()) {
// actionId actionName action
AviatorUtils.addStaticFunctions(v.get(entry.getKey()), entry.getKey(), entry.getValue().);
}
for (Class<? extends CustomFunction> extensionClass : extensionClasses) {
Integer actionId = v.get(extensionClass.getSimpleName());
AviatorUtils.addStaticFunctions(actionId, extensionClass.getSimpleName(), extensionClass);
}
});
}*/
/**
* 注册内置公共的action
*/
private static void registerCommonAction() {
BuiltInActionLibraryUtils.init();
List<SpringBean> builtInActions = BuiltInActionLibraryUtils.getBuiltInActions();
if (CollectionUtils.isEmpty(builtInActions)) {
return;
}
for (SpringBean builtInAction : builtInActions) {
AviatorUtils.addStaticFunctions(null, builtInAction.getName(), builtInAction.getPath());
}
}
}
package com.wanji.common.tool.drools;
import com.wanji.common.utils.tool.MD5Util;
import com.google.common.collect.Maps;
import com.googlecode.aviator.AviatorEvaluator;
import org.apache.commons.collections4.MapUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Map;
import java.util.Objects;
/**
* <>
*
* @author wanji
* 2020/6/13 9:01
*/
public class AviatorUtils {
private static final Logger log = LogManager.getLogger(AviatorUtils.class);
private static final ThreadLocal<Map<String, Class<?>>> THREAD_LOCAL_FUNCTION = new ThreadLocal<>();
private static final ThreadLocal<String> THREAD_LOCAL_AVIATOR_MAP = new ThreadLocal<>();
public static boolean test() {
return true;
}
public static boolean assertor(String exp, Object... args) {
Map<String, Object> map = AviatorEvaluator.newEnv(args);
Object object;
if (Objects.isNull(map)) {
object = AviatorEvaluator.getInstance().compile(Objects.requireNonNull(MD5Util.md5(exp)), exp, true);
} else {
object = AviatorEvaluator.getInstance().compile(Objects.requireNonNull(MD5Util.md5(exp)), exp, true).execute(map);
}
if (Objects.isNull(object)) {
return true;
}
Class<?> clazz = object.getClass();
if (clazz.isAssignableFrom(Boolean.class) || clazz.isAssignableFrom(boolean.class)) {
return (Boolean) object;
} else {
return false;
}
}
public static Object execute(String exp, Object... args) {
Map<String, Object> map = AviatorEvaluator.newEnv(args);
return AviatorEvaluator.getInstance().compile(Objects.requireNonNull(MD5Util.md5(exp)), exp, true).execute(map);
}
public static String genNamespace(String actionId, String beanName) {
String action = Objects.isNull(actionId) ? "Drools" : actionId;
return beanName + action;
}
public static String addStaticFunctions(String actionId, String beanName, String path) {
try {
Class<?> clazz = Class.forName(path);
return addStaticFunctions(actionId, beanName, clazz);
} catch (Exception e) {
log.error("AviatorEvaluator addStaticFunctions error!", e);
return "";
}
}
public static void addAviatorMap(String aviatorMap) {
THREAD_LOCAL_AVIATOR_MAP.set(aviatorMap);
}
public static String getAviatorMap() {
return THREAD_LOCAL_AVIATOR_MAP.get();
}
public static void removeAviatorMap() {
THREAD_LOCAL_AVIATOR_MAP.remove();
}
public static String addStaticFunctions(String actionId, String beanName, Class<?> clazz) {
String namespace = genNamespace(actionId, beanName);
Map<String, Class<?>> map = THREAD_LOCAL_FUNCTION.get();
if (MapUtils.isEmpty(map)) {
map = Maps.newHashMap();
}
map.put(namespace, clazz);
THREAD_LOCAL_FUNCTION.set(map);
return namespace;
}
public static void registerStaticFunctions() {
try {
Map<String, Class<?>> map = THREAD_LOCAL_FUNCTION.get();
if (MapUtils.isEmpty(map)) {
return;
}
for (Map.Entry<String, Class<?>> entry : map.entrySet()) {
try {
AviatorEvaluator.getInstance().addStaticFunctions(entry.getKey(), entry.getValue());
} catch (Exception e) {
log.error("AviatorEvaluator addStaticFunctions error!", e);
}
}
} catch (Exception e) {
log.error("AviatorEvaluator addStaticFunctions error!", e);
throw new RuntimeException(e);
} finally {
THREAD_LOCAL_FUNCTION.remove();
}
}
}
package com.wanji.common.tool.drools;
import com.alipay.jarslink.api.ModuleManager;
import com.wanji.common.framework.rest.JsonViewObject;
import com.wanji.common.framework.spring.ServiceBeanContext;
import com.wanji.common.utils.tool.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.drools.core.base.RuleNameStartsWithAgendaFilter;
import org.kie.api.KieServices;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.ReleaseId;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.AgendaFilter;
import java.util.*;
/**
* <>
*
* @author wanji
* 2020/6/20 22:39
*/
@Slf4j
public class DroolsTool {
/**
* 标识符
*/
private static final String GROUP_NAME = "com.unis.drools";
/**
* 版本
*/
private static final String VERSION = "1.0.0";
/**
* 存放session 避免重复编译KieContainer
*/
private static Map<String, KieContainer> kieContainers;
/**
* kie入口
*/
private static KieServices kieServices;
/**
* KieModule仓库
*/
private static KieRepository repository;
static {
kieServices = KieServices.Factory.get();
repository = kieServices.getRepository();
kieContainers = Maps.newConcurrentMap();
System.setProperty("drools.dateformat", "yyyy-MM-dd");
}
/**
* 初始化
*
* @param ruleCategoryId 规则目录id
* @param scriptMap 规则脚本Map{ruleScriptId:script}
*/
public static void init(String ruleCategoryId, Map<String, String> scriptMap) {
if (StringUtils.isBlank(ruleCategoryId) || MapUtils.isEmpty(scriptMap)) {
log.info("初始化规则参数不合法【ruleCategoryId:{}】", ruleCategoryId);
return;
}
scriptMap.forEach((k, v) -> {
loadRule(ruleCategoryId, k, v);
});
}
/**
* 初始化
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
* @param script 规则脚本
*/
public static void init(String ruleCategoryId, String ruleScriptId, String script) {
if (StringUtils.isBlank(ruleCategoryId) || StringUtils.isBlank(ruleScriptId) || StringUtils.isBlank(script)) {
log.info("初始化规则参数为空");
return;
}
loadRule(ruleCategoryId, ruleScriptId, script);
}
/**
* 销毁session
*
* @param scriptMap 规则脚本Map{ruleScriptId:script}
*/
public static void destroy(String ruleCategoryId, Map<String, String> scriptMap) {
scriptMap.forEach((k, v) -> {
if (StringUtils.isBlank(ruleCategoryId) || StringUtils.isBlank(k)) {
log.info("销毁参数为空");
return;
}
kieContainers.remove(genKey(ruleCategoryId, k));
});
}
/**
* 销毁session
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
*/
public static void destroy(String ruleCategoryId, String ruleScriptId) {
if (StringUtils.isBlank(ruleCategoryId) || StringUtils.isBlank(ruleScriptId)) {
log.info("销毁参数为空");
return;
}
kieContainers.remove(genKey(ruleCategoryId, ruleScriptId));
}
/**
* 执行单条
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
* @param fact fact
* @return List
*/
/* public static List<Map<String, Object>> batchExecute(String ruleCategoryId, String ruleScriptId, Map<String, Object> fact) {
return fireRules(ruleCategoryId, ruleScriptId, null, genRuleNameStartsWithAgendaFilter(ruleCategoryId, ruleScriptId), Collections.singletonList(fact));
}*/
public static JsonViewObject batchExecute(String ruleCategoryId, String ruleScriptId, Map<String, Object> fact) {
return null;
}
/**
* 执行多条(返回值过滤)
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
* @param facts facts
* @return List
*/
/*public static List<Map<String, Object>> batchExecute(String ruleCategoryId, String ruleScriptId, List<Map<String, Object>> facts) {
return fireRules(ruleCategoryId, ruleScriptId, null, genRuleNameStartsWithAgendaFilter(ruleCategoryId, ruleScriptId), facts);
}*/
public static JsonViewObject batchExecute(String ruleCategoryId, String ruleScriptId, List<Map<String, Object>> facts) {
return null;
}
/**
* 按规则流-执行多条(返回值过滤)
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptIdList 规则脚本id
* @param facts facts
* @return List
*/
public static List<Map<String, Object>> batchExecute(String ruleCategoryId, List<String> ruleScriptIdList, List<Map<String, Object>> facts) {
List<Map<String, Object>> list = Lists.newArrayList();
list.addAll(facts);
for (String ruleScriptId : ruleScriptIdList) {
List<Map<String, Object>> maps = fireRules(ruleCategoryId, ruleScriptId, null, genRuleNameStartsWithAgendaFilter(ruleCategoryId, ruleScriptId), list);
list.addAll(maps);
}
return list;
}
/**
* 生成议程组
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
* @return String
*/
private static String genAgendaGroup(String ruleCategoryId, String ruleScriptId) {
return String.format("agendaGroup%s%s", ruleCategoryId, ruleScriptId);
}
/**
* 获取规则前缀过滤
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
* @return AgendaFilter 议程组过滤
*/
public static AgendaFilter genRuleNameStartsWithAgendaFilter(String ruleCategoryId, String ruleScriptId) {
return new RuleNameStartsWithAgendaFilter(DroolsTool.genRuleName(ruleCategoryId, ruleScriptId));
}
/**
* 规则名
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
* @return String
*/
public static String genRuleName(String ruleCategoryId, String ruleScriptId) {
return genRuleName(ruleCategoryId, ruleScriptId, "");
}
/**
* 规则名
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
* @param suffix 后缀
* @return String
*/
public static String genRuleName(String ruleCategoryId, String ruleScriptId, String suffix) {
return String.format("rule%s%s%s", ruleCategoryId, ruleScriptId, suffix);
}
/**
* 执行指定数据集下的所有AgendaGroup指定议程组和“MAIN”议程组(使用agenda-group定义,默认是MAIN)的并且
* 经过AgendaFilter过滤的规则
*
* @param ruleCategoryId 规则所在的目录
* @param agendaGroup 规则所在议程组名称,如果不定义默认:MAIN
* @param filter 规则过滤器
* @param facts 事实
*/
private static List<Map<String, Object>> fireRules(String ruleCategoryId, String ruleScriptId, String agendaGroup, AgendaFilter filter, List<Map<String, Object>> facts) {
KieSession session = null;
try {
session = newKieSession(ruleCategoryId, ruleScriptId);
session.setGlobal("moduleManager", ServiceBeanContext.getBean(ModuleManager.class));
// 新增 fact
for (Object fact : facts) {
session.insert(fact);
}
Set<Map<String, Object>> set = Sets.newConcurrentHashSet();
session.insert(set);
//focus agenda group
if (agendaGroup != null && !agendaGroup.isEmpty()) {
//执行分组
session.getAgenda().getAgendaGroup(agendaGroup).setFocus();
}
// 执行
int count;
if (filter != null) {
count = session.fireAllRules(filter);
} else {
count = session.fireAllRules();
}
log.info("执行并匹配到的规则数量:{}", count);
return new ArrayList<>(new HashSet<>(set));
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
if (session != null) {
session.dispose();
}
}
}
/**
* 加载规则
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
*/
private static void loadRule(String ruleCategoryId, String ruleScriptId, String script) {
String artifactId = String.format("unis-%s", ruleCategoryId);
ReleaseId releaseId = kieServices.newReleaseId(GROUP_NAME, artifactId, VERSION);
InternalKieModule kieModule = DroolsUtils.createKieModule(kieServices, releaseId, ruleCategoryId, ruleScriptId, script);
repository.addKieModule(kieModule);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
kieContainer.updateToVersion(releaseId);
kieContainers.put(genKey(ruleCategoryId, ruleScriptId), kieContainer);
}
/**
* 创建指定数据集下的KieSession
*
* @param ruleCategoryId 规则目录主键
* @return KieSession
*/
private static KieSession newKieSession(String ruleCategoryId, String ruleScriptId) {
String key = genKey(ruleCategoryId, ruleScriptId);
KieContainer kieContainer = kieContainers.get(key);
if (kieContainer == null) {
throw new RuntimeException("无法获取KieContainer:" + key);
}
return kieContainer.newKieSession();
}
/**
* 获取容器Map的key
*
* @param ruleCategoryId 规则目录id
* @return String
*/
private static String genKey(String ruleCategoryId, String ruleScriptId) {
return String.format("kie-rule-category-%s-%s", ruleCategoryId, ruleScriptId);
}
/**
* 判断key是否存在
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
* @return boolean
*/
public static boolean exists(String ruleCategoryId, String ruleScriptId) {
return kieContainers.containsKey(genKey(ruleCategoryId, ruleScriptId));
}
}
package com.wanji.common.tool.drools;
import com.wanji.common.utils.tool.StringUtils;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
/**
* <>
*
* @author wanji
* 2020/6/4 13:42
*/
public class DroolsUtils {
private static final String ROOT = "src/main/resources/";
/**
* 创建kieModule
*
* @param kieServices
* @param releaseId
* @param ruleScriptId
* @param script
* @return
*/
public static InternalKieModule createKieModule(KieServices kieServices, ReleaseId releaseId, String ruleCategoryId, String ruleScriptId, String script) {
KieFileSystem kfs = createKieFileSystemWithKProject(kieServices, true);
kfs.writePomXML(genPom(releaseId));
if (StringUtils.isNotBlank(script)) {
kfs.write(genDrlPath(ruleCategoryId, ruleScriptId), script);
}
KieBuilder kieBuilder = kieServices.newKieBuilder(kfs);
kieBuilder.buildAll();
if (!kieBuilder.getResults().getMessages().isEmpty()) {
throw new IllegalStateException(
"Error creating KieBuilder. errorMsg:" + kieBuilder.getResults().getMessages());
}
return (InternalKieModule) kieBuilder.getKieModule();
}
/**
* 生成drl虚拟路径
*
* @param ruleCategoryId 规则目录id
* @param ruleScriptId 规则脚本id
* @return String
*/
private static String genDrlPath(String ruleCategoryId, String ruleScriptId) {
return String.format("%s%s/%s.drl", ROOT, ruleCategoryId, ruleScriptId);
}
/**
* 创建默认的kbase和stateful的kiesession
*
* @param kieServices
* @param isdefault 是否默认
* @return KieFileSystem
*/
private static KieFileSystem createKieFileSystemWithKProject(KieServices kieServices, boolean isdefault) {
//对应kmodule节点
KieModuleModel kieModuleModel = kieServices.newKieModuleModel();
//对应kbase节点
KieBaseModel kieBaseModel = kieModuleModel
.newKieBaseModel("KBase")
.setDefault(isdefault)
.setEqualsBehavior(EqualityBehaviorOption.EQUALITY)
.setEventProcessingMode(EventProcessingOption.STREAM);
// Configure the KieSession.
kieBaseModel.newKieSessionModel("KSession")
.setDefault(isdefault)
.setType(KieSessionModel.KieSessionType.STATEFUL);
KieFileSystem kfs = kieServices.newKieFileSystem();
kfs.writeKModuleXML(kieModuleModel.toXML());
return kfs;
}
/**
* 生成pom.xml
*
* @param releaseId 发布id
* @param dependencies 依赖
* @return String
*/
private static String genPom(ReleaseId releaseId, ReleaseId... dependencies) {
String pom = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n"
+ " <modelVersion>4.0.0</modelVersion>\n" + "\n" + " <groupId>" + releaseId.getGroupId()
+ "</groupId>\n" + " <artifactId>" + releaseId.getArtifactId() + "</artifactId>\n" + " <version>"
+ releaseId.getVersion() + "</version>\n" + "\n";
if (dependencies != null && dependencies.length > 0) {
pom += "<dependencies>\n";
for (ReleaseId dep : dependencies) {
pom += "<dependency>\n";
pom += " <groupId>" + dep.getGroupId() + "</groupId>\n";
pom += " <artifactId>" + dep.getArtifactId() + "</artifactId>\n";
pom += " <version>" + dep.getVersion() + "</version>\n";
pom += "</dependency>\n";
}
pom += "</dependencies>\n";
}
pom += "</project>";
return pom;
}
}
package com.wanji.common.tool.estool;
import com.wanji.common.framework.spring.ServiceBeanContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: es client bean管理
* @Author mapabc
* @Date 2019/12/10 10:01
*/
@Configuration
@AutoConfigureAfter
@Slf4j
public class EsConfiguration {
private static TransportClient transportClient = null;
public static TransportClient getTransportClient() {
if (transportClient == null) {
transportClient = getEsClient();
}
return transportClient;
}
/**
* @Description: es获取配置文件中的name和url
* @Author mapabc9
* @Date 2019/12/13 11:02
*/
private static TransportClient getEsClient() {
EsProperties esProperties = ServiceBeanContext.getBean(EsProperties.class);
if (StringUtils.isEmpty(esProperties.getUrl()) || StringUtils.isEmpty(esProperties.getName())) {
log.error("es consumer start error: esProperties config error");
return null;
}
Map address = new HashMap();
//按照逗号切分不同的url
String[] esUrlArray = StringUtils.split(esProperties.getUrl(), ",");
if (null == esUrlArray || esUrlArray.length == 0) {
log.error("es consumer start error: esProperties config error");
return null;
}
for (String esUrl : esUrlArray) {
if (esUrl.contains(":")) {
//按照冒号切分不同的url
String[] esUrlItem = StringUtils.split(esUrl, "\\:");
address.put(String.valueOf(esUrlItem[0]), Integer.valueOf(esUrlItem[1]));
}
}
return EsUtil.getInstance().esClient(esProperties.getName(), address);
}
@Bean(value = "esUtil")
public EsUtil getEsUtil() {
return EsUtil.getInstance();
}
}
package com.wanji.common.tool.estool;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Description:
* @Author mapabc9
* @Date 2019/12/12 17:07
*/
@Getter
@Setter
@Component(value = "esProperties")
@ConfigurationProperties(prefix = EsProperties.ES_PREFIX)
@ConditionalOnProperty(value = "es.cluster.name")
public class EsProperties {
static final String ES_PREFIX = "es.cluster";
@Value("${es.cluster.name}")
private String name;
@Value("${es.cluster.url}")
private String url;
}
package com.wanji.common.tool.estool;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.net.InetAddress;
import java.util.*;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
/**
* 对ES操作的工具类
*
* @author mapabc
* @date 2016/11/23
*/
@Slf4j
public class EsUtil {
private static EsUtil esUtil = null;
public static EsUtil getInstance() {
if (esUtil == null) {
esUtil = new EsUtil();
}
return esUtil;
}
/**
* 测试连接是否存在
*
* @param clusterName
* @param address
* @return
*/
public boolean checkConn(String clusterName, Map<String, Integer> address) {
boolean flag = false;
TransportClient client = null;
try {
Settings settings = Settings.builder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", false)
.build();
client = new PreBuiltTransportClient(settings);
for (Map.Entry<String, Integer> map : address.entrySet()) {
client.addTransportAddress(new TransportAddress(InetAddress.getByName(map.getKey()), map.getValue()));
}
if (client.connectedNodes().size() > 0) {
flag = true;
}
} catch (Exception e) {
log.error("ES-Server Connection is error!", e);
} finally {
if (null != client) {
client.close();
}
}
return flag;
}
/**
* 得到ES连接
*
* @return
*/
public TransportClient esClient(String clusterName, Map<String, Integer> address) {
TransportClient client = null;
try {
Settings settings = Settings.builder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", false)
.build();
client = new PreBuiltTransportClient(settings);
for (Map.Entry<String, Integer> map : address.entrySet()) {
client.addTransportAddress(new TransportAddress(InetAddress.getByName(map.getKey()), map.getValue()));
}
} catch (Exception e) {
log.error("ES-Server Connection is error!", e);
}
return client;
}
/**
* 关闭连接
*
* @param client
*/
public void closeConn(TransportClient client) {
if (null != client) {
client.close();
}
}
/**
* 创建索引
*
* @param client
* @param indexName
* @param indexNumberShards
* @param indexNumberReplicas
*/
public boolean createIndex(TransportClient client, String indexName, Long indexNumberShards, Long indexNumberReplicas) {
boolean flag = true;
try {
client.admin().indices().prepareCreate(indexName)
.setSettings(Settings.builder()
.put("index.number_of_shards", indexNumberShards)
.put("index.number_of_replicas", indexNumberReplicas)
)
.get();
} catch (Exception e) {
flag = false;
log.error("[indexName:" + indexName + "],[indexNumberShards:" + indexNumberShards + "],[indexNumberReplicas:" + indexNumberReplicas + "] EsUtil createIndex is error! ", e);
}
return flag;
}
/**
* 删除索引
*
* @param client
* @param indexName
* @return
*/
public boolean deleteIndex(TransportClient client, String indexName) {
boolean flag = true;
try {
client.admin().indices().prepareDelete(indexName).execute().actionGet();
} catch (Exception e) {
flag = false;
log.error("[indexName:" + indexName + "] EsUtil createIndex is error! ", e);
}
return flag;
}
/**
* 创建Mapping
*
* @param client
* @param indexName
* @param typeName
* @param map
* @return
*/
public boolean createMapping(TransportClient client, String indexName, String typeName, Map<String, String> map) {
boolean flag = true;
Map<String, Map<String, Map<String, String>>> properMap = Maps.newHashMap();
try {
Map<String, Map<String, String>> propMap = Maps.newHashMap();
for (Map.Entry<String, String> entry : map.entrySet()) {
Map<String, String> typeMap = Maps.newHashMap();
typeMap.put("type", entry.getValue());
propMap.put(entry.getKey(), typeMap);
}
properMap.put("properties", propMap);
String json = JSON.toJSONString(properMap);
client.admin().indices().preparePutMapping(indexName)
.setType(typeName)
.setSource(json)
.get();
} catch (Exception e) {
flag = false;
log.error("EsUtil createMapping is error!", e);
}
return flag;
}
/**
* 删除mapping
*
* @param client
* @param index
* @param typeName
* @return
* @throws Exception
*/
public boolean deleteMapping(TransportClient client, String index, String typeName) throws Exception {
return true;
}
/**
* 向指定的索引库中添加数据
*
* @param client
* @param indexName
* @param typeName
* @param map
* @return
*/
public boolean putIndexData(TransportClient client, String indexName, String typeName, String id, Map<String, Object> map) {
boolean flag = true;
XContentBuilder builder;
try {
builder = jsonBuilder().startObject();
for (Map.Entry<String, Object> mapData : map.entrySet()) {
builder.field(mapData.getKey(), mapData.getValue());
}
builder.endObject();
client.prepareIndex(indexName, typeName, id)
.setSource(builder)
.get();
log.info("[indexName:" + indexName + "],[typeName:" + typeName + "],[id:" + id + "] put succeed!");
} catch (Exception e) {
flag = false;
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[id:" + id + "] EsUtil findDataById is error! ", e);
}
return flag;
}
/**
* 批量添加数据
*
* @param client
* @param indexName
* @param typeName
* @param datas
* @return
*/
public boolean putIndexDatas(TransportClient client, String indexName, String typeName, List<Map<String, Object>> datas) {
boolean flag = true;
BulkResponse bulkResponse = null;
try {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (Map<String, Object> data : datas) {
data.remove("id");
bulkRequest.add(client.prepareIndex(indexName, typeName, (String) data.get("id"))
.setSource(data)
);
}
bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[Item:" + bulkResponse.getItems() + "] put fail!");
}
log.debug("[indexName:" + indexName + "],[typeName:" + typeName + "],[Item:" + bulkResponse.getItems() + "] put succeed!");
} catch (Exception e) {
flag = false;
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[Item:" + bulkResponse.getItems() + "] EsUtil putIndexDatas is error! ", e);
}
return flag;
}
/**
* 根据索引的Id查找索引的数据
*
* @param client
* @param indexName
* @param typeName
* @param id
*/
public Map<String, Object> findDataById(TransportClient client, String indexName, String typeName, String id) {
Map<String, Object> map = new HashMap<>();
try {
GetResponse res = client.prepareGet(indexName, typeName, id).get();
map = res.getSourceAsMap();
} catch (Exception e) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[id:" + id + "] EsUtil findDataById is error! ", e);
}
return map;
}
/**
* 根据多个Id查询多条数据
*
* @param client
* @param indexName
* @param typeName
* @param ids
* @return
*/
public String findDataByIds(TransportClient client, String indexName, String typeName, String... ids) {
String json = "";
try {
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add(indexName, typeName, ids)
.get();
for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
GetResponse response = itemResponse.getResponse();
if (response.isExists()) {
json = response.getSourceAsString();
}
}
} catch (Exception e) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[ids:" + ids + "] EsUtil findDataByIds is error! ", e);
}
return json;
}
/**
* 根据关键字进行查询
*
* @param client
* @return
*/
public List<Map<String, Object>> searchDatas(TransportClient client, String indexName, String typeName, String key, String value) {
List<Map<String, Object>> list = Lists.newArrayList();
try {
SearchResponse response = client.prepareSearch(indexName).setTypes(typeName)
.setQuery(QueryBuilders.matchQuery(key, value))
.execute()
.actionGet();
for (SearchHit hit : response.getHits().getHits()) {
hit.getSourceAsMap().put("id", hit.getId());
list.add(hit.getSourceAsMap());
}
} catch (Exception e) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[name:" + typeName + "],[value:" + value + "] EsUtil searchDatas is error! ", e);
}
return list;
}
/**
* 组合查询
* QueryBuilders
* .boolQuery()
* .must(QueryBuilders.matchQuery("name", "value"))
* .must(QueryBuilders.matchQuery("home", "value"))
* .mustNot(QueryBuilders.matchQuery("isRealMen", false))
* .should(QueryBuilders.matchQuery("now_home", "value"));
*
* @param client
* @param indexName
* @param typeName
* @param qb
* @return
*/
public List<Map<String, Object>> searchDatas(TransportClient client, String indexName, String typeName, QueryBuilder qb) {
List<Map<String, Object>> list = Lists.newArrayList();
try {
SearchResponse response = client.prepareSearch(indexName).setTypes(typeName)
.setQuery(qb)
.setExplain(true)
.execute()
.actionGet();
for (SearchHit hit : response.getHits().getHits()) {
hit.getSourceAsMap().put("id", hit.getId());
list.add(hit.getSourceAsMap());
}
} catch (Exception e) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[name:" + typeName + "], EsUtil searchDatas is error! ", e);
}
return list;
}
/**
* 分页查询
*
* @param client
* @param indexName
* @param typeName
* @param qb 可以为null 表示没有条件
* @param startRow
* @param pageSize
* @return
*/
public List<Map<String, Object>> searchDatas(TransportClient client, String indexName, String typeName, QueryBuilder qb, int startRow, int pageSize) {
List<Map<String, Object>> list = Lists.newArrayList();
try {
SearchResponse response = client.prepareSearch(indexName).setTypes(typeName)
.setQuery(qb)
.setFrom(startRow).setSize(pageSize)
.setExplain(true)
.execute()
.actionGet();
for (SearchHit hit : response.getHits().getHits()) {
hit.getSourceAsMap().put("id", hit.getId());
list.add(hit.getSourceAsMap());
}
} catch (Exception e) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[name:" + typeName + "], EsUtil searchDatas is error! ", e);
}
return list;
}
public List<Map<String, Object>> searchDatas(TransportClient client, String indexName, String typeName, QueryBuilder qb, Queue<SortBuilder> sortBuilders) {
List<Map<String, Object>> list = Lists.newArrayList();
try {
SearchRequestBuilder request = client.prepareSearch(indexName).setTypes(typeName)
.setQuery(qb)
.setExplain(true);
for (SortBuilder sort : sortBuilders) {
request.addSort(sort);
}
SearchResponse response = request.execute().actionGet();
for (SearchHit hit : response.getHits().getHits()) {
hit.getSourceAsMap().put("id", hit.getId());
list.add(hit.getSourceAsMap());
}
} catch (Exception e) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[name:" + typeName + "], EsUtil searchDatas is error! ", e);
}
return list;
}
public List<Map<String, Object>> searchDatas(TransportClient client, String indexName, String typeName, QueryBuilder qb, int startRow, int pageSize, Queue<SortBuilder> sortBuilders) {
List<Map<String, Object>> list = Lists.newArrayList();
try {
SearchRequestBuilder request = client.prepareSearch(indexName).setTypes(typeName)
.setQuery(qb)
.setFrom(startRow).setSize(pageSize)
.setExplain(true);
for (SortBuilder sort : sortBuilders) {
request.addSort(sort);
}
SearchResponse response = request.execute().actionGet();
for (SearchHit hit : response.getHits().getHits()) {
hit.getSourceAsMap().put("id", hit.getId());
list.add(hit.getSourceAsMap());
}
} catch (Exception e) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[name:" + typeName + "], EsUtil searchDatas is error! ", e);
}
return list;
}
/**
* @param client
* @param indexName 索引名称
* @param typeName 类型名称
* @param qb 查询条件
* @param startRow 分页起始行
* @param pageSize 分页终止行
* @param fileds 需要返回的字段
* @return java.util.List<java.util.Map < java.lang.String , java.lang.Object>>
* @Description: 分页查询,并返回指定字段
* @Author mapabc
* @Date 2019/12/16 16:34
**/
public List<Map<String, Object>> searchDatas(TransportClient client, String indexName, String typeName, QueryBuilder qb, int startRow, int pageSize, Set<String> fileds) {
List<Map<String, Object>> list = Lists.newArrayList();
if (null == fileds || fileds.isEmpty()) {
return list;
}
try {
SearchResponse response = client.prepareSearch(indexName).setTypes(typeName)
.setQuery(qb)
.setFrom(startRow).setSize(pageSize)
.setExplain(true)
.execute()
.actionGet();
for (SearchHit hit : response.getHits().getHits()) {
Map<String, Object> result = new HashMap<>(response.getHits().getHits().length);
fileds.retainAll(hit.getSourceAsMap().keySet());
if (fileds.isEmpty()) {
return list;
}
result.put("id", hit.getId());
for (String field : fileds) {
result.put(field, hit.getSourceAsMap().get(field));
}
list.add(result);
}
} catch (Exception e) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[name:" + typeName + "], EsUtil searchDatas is error! ", e);
}
return list;
}
/**
* 获取符合条件的数据总数
*
* @param client
* @param indexName
* @param typeName
* @param qb
* @return
*/
public Long searchDatasCount(TransportClient client, String indexName, String typeName, QueryBuilder qb) {
long count = 0L;
try {
SearchResponse response = client.prepareSearch(indexName).setTypes(typeName)
.setQuery(qb)
.setExplain(true)
.execute()
.actionGet();
count = response.getHits().getTotalHits();
} catch (Exception e) {
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[name:" + typeName + "], EsUtil searchDatasCount is error! ", e);
}
return count;
}
/**
* 根据索引的Id删除数据
*
* @param client
* @param indexName
* @param typeName
* @param id
* @return
*/
public boolean deleteDataById(TransportClient client, String indexName, String typeName, String id) {
boolean flag = true;
try {
DeleteResponse response = client.prepareDelete(indexName, typeName, id).get();
log.info("[indexName:" + indexName + "],[typeName:" + typeName + "],[id:" + id + "],[status:" + response.status() + "] delete succeed!");
} catch (Exception e) {
flag = false;
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[id:" + id + "] EsUtil deleteDataById is error! ", e);
}
return flag;
}
/**
* 根据Id修改索引的数据
*
* @param client
* @param indexName
* @param typeName
* @param id
* @param map
* @return
*/
public boolean updateDataById(TransportClient client, String indexName, String typeName, String id, Map<String, Object> map) {
boolean flag = true;
try {
XContentBuilder builder = jsonBuilder().startObject();
for (Map.Entry<String, Object> mapData : map.entrySet()) {
builder.field(mapData.getKey(), mapData.getValue());
}
builder.endObject();
UpdateRequest updateRequest = new UpdateRequest(indexName, typeName, id).doc(builder);
client.update(updateRequest).get();
log.info("[indexName:" + indexName + "],[typeName:" + typeName + "],[id:" + id + "],[map:" + map + "] update succeed!");
} catch (Exception e) {
flag = false;
log.error("[indexName:" + indexName + "],[typeName:" + typeName + "],[id:" + id + "],[map:" + map + "] EsUtil updateDataById is error! ", e);
}
return flag;
}
public static void main(String[] arg) {
EsUtil esUtil = new EsUtil();
try {
Map<String, Integer> map = new HashedMap();
map.put("219.142.87.89", 9300);
// map.put("192.168.5.10",9300);
TransportClient client = EsUtil.getInstance().esClient("business-platform", map);
Map<String, Object> dataMap = Maps.newHashMap();
dataMap.put("filed1", "name");
dataMap.put("filed2", 10);
dataMap.put("filed3", 1);
dataMap.put("filed4", 1.1);
dataMap.put("filed5", 1.001);
dataMap.put("filed6", true);
dataMap.put("filed7", new Date());
Map<String, String> mapping = Maps.newHashMap();
mapping.put("filed1", "string");
mapping.put("filed2", "integer");
mapping.put("filed3", "long");
mapping.put("filed4", "float");
mapping.put("filed5", "double");
mapping.put("filed6", "boolean");
mapping.put("filed7", "date");
esUtil.deleteIndex(client, "dev_service_plugin_log");
esUtil.deleteMapping(client, "dev_service_plugin_log", "dev_service_plugin_log");
// esUtil.searchDatas(client,"vim","employee","name","hudw");
// esUtil.createMapping(client,"vim","mapping",mapping);
//
//esUtil.putIndexData(client,"test2","delet_test1","2",data_map);
// System.out.println(esUtil.findDataById(client,"test2","delet_test1","2"));
// esUtil.updateDataById(client,"test_index","test1","2",data_map);
// System.out.println(esUtil.findDataById(client,"test_index","test1","2"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.wanji.common.tool.http;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
/**
*
* HTTPS 双向认证 - direct into cacerts
* Created by mapabc4 on 2019/7/10.
*/
@Slf4j
public class HttpsClient {
private static String KEY_TOOL = "${JAVA_HOME}/jre/bin/keytool";
private static String KEY_STORE = "\"${JAVA_HOME}/jre/lib/security/cacerts\"";
public static void importCrt(String path, String keyPass, String aliasName) {
//"/bin/sh","-c" / "cmd", "c"
String[] shell = {"/bin/sh","/-c",KEY_TOOL+" -import -keystore "+KEY_STORE+" -storepass changeit -keypass "+keyPass+" -alias "+aliasName+" -file "+path+" -noprompt"};
try {
Runtime.getRuntime().exec(shell);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* HTTPS协议GET调用
*
* @param url
* @param clientCertPath
* @param secretKey
* @param headers
* @return
* @throws Exception
*/
public static String sslRequestGet(String url, String clientCertPath, String secretKey, Header[] headers) throws Exception {
CloseableHttpClient httpclient = getHttpClient(clientCertPath, secretKey);
try {
HttpGet httpget = new HttpGet(url);
// 设置heander等
headers = judgeHeaders(headers);
httpget.setHeaders(headers);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
// 返回结果
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return jsonStr;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/**
* HTTPS协议DELETE调用
*
* @param url
* @param clientCertPath
* @param secretKey
* @param headers
* @return
* @throws Exception
*/
public static String sslRequestDelete(String url, String clientCertPath, String secretKey, Header[] headers) throws Exception {
CloseableHttpClient httpclient = getHttpClient(clientCertPath, secretKey);
try {
HttpDelete httpDelete = new HttpDelete(url);
// 设置heander等
headers = judgeHeaders(headers);
httpDelete.setHeaders(headers);
CloseableHttpResponse response = httpclient.execute(httpDelete);
try {
HttpEntity entity = response.getEntity();
// 返回结果
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return jsonStr;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
private static CloseableHttpClient getHttpClient(String clientCertPath, String secretKey) throws Exception {
if (clientCertPath == null || "null".equals(clientCertPath) || "".equals(clientCertPath)) {
return HttpClients.custom().build();
}
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream instream = new FileInputStream(new File(clientCertPath));
try {
// 这里就指的是KeyStore库的密码
keyStore.load(instream, secretKey.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, secretKey.toCharArray())
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext
// supportedProtocols ,这里可以按需要设置
, new String[] { "TLSv1" }
, null
, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
/**
* HTTPS协议POST调用
*
* @param url
* @param clientCertPath
* @param secretKey
* @param headers
* @param bodyStr
* @return
* @throws Exception
*/
public static String sslRequestPost(String url, String clientCertPath, String secretKey, Header[] headers, String bodyStr) throws Exception {
CloseableHttpClient httpclient = getHttpClient(clientCertPath, secretKey);
try {
HttpPost httpPost = new HttpPost(url);
// 设置一些heander等
headers = judgeHeaders(headers);
httpPost.setHeaders(headers);
httpPost.setEntity(new StringEntity(bodyStr, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
// 返回结果
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return jsonStr;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/**
* HTTPS协议PUT调用
*
* @param url
* @param clientCertPath
* @param secretKey
* @param headers
* @param bodyStr
* @return
* @throws Exception
*/
public static String sslRequestPut(String url, String clientCertPath, String secretKey, Header[] headers, String bodyStr) throws Exception {
CloseableHttpClient httpclient = getHttpClient(clientCertPath, secretKey);
try {
HttpPut httpPut = new HttpPut(url);
// 设置一些heander等
headers = judgeHeaders(headers);
httpPut.setHeaders(headers);
httpPut.setEntity(new StringEntity(bodyStr, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpPut);
try {
HttpEntity entity = response.getEntity();
// 返回结果
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return jsonStr;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/**
* 如果header为空,初始化一些必要的参数
*
* @param headers
*/
private static Header[] judgeHeaders(Header[] headers) {
if (headers == null || headers.length == 0) {
headers = new Header[1];
headers[0] = new BasicHeader("Content-Type", "application/json;chartset=UTF-8");
}
return headers;
}
}
package com.wanji.common.tool.jobtool;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.Trigger.TriggerState;
import org.quartz.impl.StdSchedulerFactory;
import java.util.Date;
import java.util.Map;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
/**
* 通用的任务调度管理工具类
*
* @author vain@ccuu.me
* @date 14-10-30
*/
@Slf4j
public class JobTool {
private static class JobToolHelper {
private static final JobTool INSTANCE = new JobTool();
}
public static JobTool getInstance() {
return JobToolHelper.INSTANCE;
}
public Scheduler getScheduler() {
return scheduler;
}
private Scheduler scheduler;
JobTool() {
//Scheduler quartzScheduler = ServiceBeanContext.getInstance().getBean("quartzScheduler");
try {
if (scheduler == null) {
scheduler = StdSchedulerFactory.getDefaultScheduler();
}
scheduler.start();
log.info("scheduler init success.");
} catch (SchedulerException e) {
log.error("scheduler 初始化失败.", e);
}
}
/**
* 使用cron表达式增加一个调度任务
*
* @param jobName 任务名称
* @param cron cron表达式
* @param clazz Job
* @throws Exception
*/
public void addJob(String jobName, String jonGroup, String cron, Class<? extends Job> clazz) throws Exception {
JobDetail job;
CronTrigger trigger;
try {
job = newJob(clazz).withIdentity(jobName, jonGroup).build();
trigger = newTrigger().withIdentity(jobName, jonGroup).withSchedule(cronSchedule(cron)).build();
} catch (Exception e) {
throw new Exception("build JobDetail or CronTrigger exception," + e.getMessage(), e);
}
scheduleJob(jobName, job, trigger);
}
/**
* 使用cron表达式增加一个调度任务,并携带任务执行参数
*
* @param jobName 任务名称
* @param jonGroup 任务名称
* @param cron cron表达式
* @param clazz Job
* @param params 任务执行参数
* @throws Exception
*/
public void addJob(String jobName, String jonGroup, String cron, Class<? extends Job> clazz, Map<String, String> params) throws Exception {
JobDetail job;
CronTrigger trigger;
try {
job = newJob(clazz)
.withIdentity(jobName, jonGroup)
.usingJobData(new JobDataMap(params))
.build();
trigger = newTrigger()
.withIdentity(jobName, jobName)
.withSchedule(cronSchedule(cron))
.build();
} catch (Exception e) {
throw new Exception("build JobDetail or CronTrigger exception," + e.getMessage(), e);
}
scheduleJob(jobName, job, trigger);
}
/**
* 使用cron表达式增加一个调度任务,设置任务的开始执行时间和结束执行时间,并携带任务执行参数
*
* @param jobName 任务名称
* @param jobGroup 任务组
* @param cron cron表达式
* @param startTime 任务起始时间
* @param finishTime 任务结束时间
* @param clazz Job
* @param params 任务执行参数
* @throws Exception
*/
public void addJob(String jobName, String jobGroup, String cron, Date startTime, Date finishTime, Class<? extends Job> clazz, Map<String, String> params) throws Exception {
JobDetail job;
CronTrigger trigger;
try {
job = newJob(clazz).withIdentity(jobName, jobGroup).build();
job.getJobDataMap().putAll(params);
trigger = newTrigger().withIdentity(jobName, jobGroup)
.startAt(startTime)
.withSchedule(cronSchedule(cron))
.endAt(finishTime)
.build();
} catch (Exception e) {
throw new Exception("build JobDetail or CronTrigger exception," + e.getMessage(), e);
}
scheduleJob(jobName, job, trigger);
}
/**
* 使用cron表达式增加一个调度任务,设置任务的结束执行时间,并携带任务执行参数
* 注意: 该方法没有设置任务执行的开始时间,可保证任务开始执行时不会立即执行一次,只会按照设定的Cron表达式执行
*
* @param jobName 任务名称
* @param jobGroup 任务组
* @param cron cron表达式
* @param finishTime 任务结束时间
* @param clazz Job
* @param params 任务执行参数
* @throws Exception 定时任务异常
*/
public void addJob(String jobName, String jobGroup, String cron, Date finishTime, Class<? extends Job> clazz, Map<String, Object> params) throws Exception {
JobDetail job;
CronTrigger trigger;
try {
job = newJob(clazz).withIdentity(jobName, jobGroup).build();
job.getJobDataMap().putAll(params);
trigger = newTrigger().withIdentity(jobName, jobGroup)
.withSchedule(cronSchedule(cron))
.endAt(finishTime)
.build();
} catch (Exception e) {
log.error("[JobTool] jobName: {} build JobDetail or CronTrigger exception", jobName, e);
throw new Exception("Cron表达式填写不符合规范", e);
}
scheduleJob(jobName, job, trigger);
}
/**
* 使用任务间隔毫秒数增加一个调度任务
*
* @param jobName 任务名称
* @param jobGroup 任务组
* @param interval 任务执行间隔
* @param clazz Job
* @throws Exception
*/
public void addJob(String jobName, String jobGroup, long interval, Class<? extends Job> clazz) throws Exception {
JobDetail job;
SimpleTrigger trigger;
try {
job = newJob(clazz).withIdentity(jobName, jobGroup).build();
trigger = newTrigger().withIdentity(jobName, jobGroup)
.withSchedule(simpleSchedule().withIntervalInMilliseconds(interval).repeatForever())
.build();
} catch (Exception e) {
throw new Exception("build JobDetail or SimpleTrigger exception," + e.getMessage(), e);
}
scheduleJob(jobName, job, trigger);
}
/**
* 使用任务间隔毫秒数增加一个调度任务,并携带任务执行参数
*
* @param jobName 任务名称
* @param jobGroup 任务组
* @param interval 任务执行间隔
* @param clazz Job
* @param params 任务执行参数
* @throws Exception
*/
public void addJob(String jobName, String jobGroup, long interval, Class<? extends Job> clazz, Map<String, String> params) throws Exception {
JobDetail job;
SimpleTrigger trigger;
try {
job = newJob(clazz).withIdentity(jobName, jobGroup).build();
job.getJobDataMap().putAll(params);
trigger = newTrigger().withIdentity(jobName, jobGroup)
.withSchedule(simpleSchedule().withIntervalInMilliseconds(interval).repeatForever())
.build();
} catch (Exception e) {
throw new Exception("build JobDetail or SimpleTrigger exception," + e.getMessage(), e);
}
scheduleJob(jobName, job, trigger);
}
/**
* 使用任务间隔毫秒数增加一个调度任务,设置任务的开始执行时间和结束执行时间,并携带任务执行参数
*
* @param jobName 任务名称
* @param jobGroup 任务组
* @param interval 任务执行间隔
* @param startTime 任务起始时间
* @param finishTime 任务结束时间
* @param clazz Job
* @param params 任务执行参数
* @throws Exception
*/
public void addJob(String jobName, String jobGroup, long interval, Date startTime, Date finishTime, Class<? extends Job> clazz, Map<String, String> params) throws Exception {
JobDetail job;
SimpleTrigger trigger;
try {
job = newJob(clazz).withIdentity(jobName, jobGroup).build();
job.getJobDataMap().putAll(params);
trigger = newTrigger().withIdentity(jobName, jobGroup)
.startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInMilliseconds(interval).repeatForever())
.endAt(finishTime)
.build();
} catch (Exception e) {
throw new Exception("build JobDetail or SimpleTrigger exception," + e.getMessage(), e);
}
scheduleJob(jobName, job, trigger);
}
/**
* 对任务进行调度
*
* @param jobName 任务名称
* @param job 任务内容
* @param trigger 调度方案
* @throws Exception 可能出现的异常
*/
public void scheduleJob(String jobName, JobDetail job, Trigger trigger) throws Exception {
try {
if (scheduler.isShutdown()) {
scheduler.start();
}
try {
if (!scheduler.checkExists(job.getKey())) {
scheduler.scheduleJob(job, trigger);
log.info("The " + jobName + " job has been started.{jobName:" + jobName + "}");
}
} catch (SchedulerException e) {
throw new Exception("Add new job scheduler exception,{jobCode:" + jobName + "}," + e.getMessage(), e);
}
} catch (SchedulerException e) {
throw new Exception("Restart scheduler exception," + e.getMessage(), e);
}
}
/**
* 删除一个job
*
* @param jobName
* @param jobGroup
* @throws Exception
*/
public void deleteJob(String jobName, String jobGroup) throws Exception {
try {
if (scheduler.isShutdown()) {
scheduler.start();
}
JobKey key = new JobKey(jobName, jobGroup);
if (scheduler.checkExists(key)) {
scheduler.deleteJob(key);
log.info("the " + jobName + " job has been removed.");
}
} catch (SchedulerException e) {
throw new Exception("Delete job by jobCode failed,{jobName: " + jobName + ",jobGroup: " + jobGroup + "}", e);
}
}
/**
* 暂停一个job
*
* @param jobName
* @param jobGroup
* @throws Exception
*/
public void pauseJob(String jobName, String jobGroup) throws Exception {
try {
if (scheduler.isShutdown()) {
scheduler.start();
}
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
if (scheduler.checkExists(jobKey)) {
scheduler.pauseJob(jobKey);
log.info("the " + jobName + " job has been paused.");
}
} catch (SchedulerException e) {
throw new Exception("Pause job by jobCode failed, {jobName: " + jobName + ",jobGroup: " + jobGroup + "}", e);
}
}
/**
* 恢复一个job
*
* @param jobName
* @param jobGroup
* @throws Exception
*/
public void resumeJob(String jobName, String jobGroup) throws Exception {
try {
if (scheduler.isShutdown()) {
scheduler.start();
}
JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
if (scheduler.checkExists(jobKey)) {
scheduler.resumeJob(jobKey);
log.info("the " + jobName + " job has been resumed.");
}
} catch (SchedulerException e) {
throw new Exception("Resume job by jobCode failed, {jobName: " + jobName + ",jobGroup: " + jobGroup + "}", e);
}
}
/**
* 获取指定任务的状态
*
* @param jobName
* @param jobGroup
* @return
* @throws Exception
*/
public TriggerState getJobState(String jobName, String jobGroup) throws Exception {
TriggerState state;
try {
if (scheduler.isShutdown()) {
scheduler.start();
}
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
state = scheduler.getTriggerState(triggerKey);
} catch (SchedulerException e) {
throw new Exception("getJobState failed, {jobName: " + jobName + ",jobGroup: " + jobGroup + "}", e);
}
return state;
}
}
package com.wanji.common.tool.jobtool;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
/**
* @ClassName RetryTemplate
* @Description
* @Author mapabc7
* @Date 2020/7/13 10:00
* @Version 1.0
*/
@Slf4j
public abstract class RetryTemplate {
private static final int DEFAULT_RETRY_TIME = 1;
private int retryTime = DEFAULT_RETRY_TIME;
// 重试的睡眠时间
private int sleepTime = 0;
public int getSleepTime() {
return sleepTime;
}
public RetryTemplate setSleepTime(int sleepTime) {
if (sleepTime < 0) {
throw new IllegalArgumentException("sleepTime should equal or bigger than 0");
}
this.sleepTime = sleepTime;
return this;
}
public int getRetryTime() {
return retryTime;
}
public RetryTemplate setRetryTime(int retryTime) {
if (retryTime <= 0) {
throw new IllegalArgumentException("retryTime should bigger than 0");
}
this.retryTime = retryTime;
return this;
}
/**
* 重试的业务执行代码
* 失败时请抛出一个异常
*/
protected abstract Object doBiz() throws Exception;
public Object execute() throws InterruptedException {
for (int i = 0; i < retryTime; i++) {
try {
return doBiz();
} catch (Exception e) {
log.error("业务执行出现异常,e: {}", e);
Thread.sleep(sleepTime);
}
}
return null;
}
public Object submit(ExecutorService executorService) {
if (executorService == null) {
throw new IllegalArgumentException("please choose executorService!");
}
return executorService.submit((Callable) () -> execute());
}
public static void main(String[] args) {
Object ans = null;
try {
ans = new RetryTemplate() {
@Override
protected Object doBiz() throws Exception {
int temp = (int) (Math.random() * 10);
System.out.println(temp);
if (temp > 3) {
throw new Exception("generate value bigger then 3! need retry");
}
return temp;
}
}.setRetryTime(10).setSleepTime(10000).execute();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ans);
}
}
package com.wanji.common.tool.kafkatool;
import com.google.common.collect.Maps;
import org.apache.kafka.clients.KafkaClient;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.common.PartitionInfo;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class KafkaUtil {
//public static Producer<String,String> producer=null;
public static KafkaConsumer<String, String> consumer=null;
public static Properties properties;
public static KafkaClient kafkaClient;
public static void connect(Map<String,String> map) throws Exception{
properties=new Properties();
properties.put("bootstrap.servers", map.get("servers"));
properties.put("group.id", map.get("groupId"));
properties.put("enable.auto.commit", "false");
properties.put("auto.commit.interval.ms", "1000");
properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
/*properties.put("retries",map.get("retries"));
properties.put("batch.size",map.get("batch.size"));
properties.put("linger.ms",map.get("linger.ms"));
properties.put("max.request.size",map.get("request.size"));
properties.put("compression.type",map.get("compression.type"));
properties.put("buffer.memory",map.get("buffer.memory"));*/
//producer=new KafkaProducer<String,String>(properties);
consumer=new KafkaConsumer<String, String>(properties);
}
@SuppressWarnings("resource")
public static boolean comsumeTopic(String topicName) {
return consumer.listTopics().containsKey(topicName);
}
public static void main(String []arags){
Map<String,String> param= Maps.newHashMap();
param.put("servers","121.36.56.157:9092");
param.put("groupId","gis-t");
try {
KafkaUtil.connect(param);
System.out.println(KafkaUtil.comsumeTopic("gis-t"));
}catch (Exception ex){
ex.printStackTrace();
}
}
}
package com.wanji.common.tool.mqtool;
import com.alibaba.fastjson.JSONObject;
import com.wanji.common.framework.Constants;
import com.wanji.common.framework.spring.ServiceBeanContext;
import com.wanji.common.framework.thread.NamedThreadFactory;
import com.wanji.common.utils.tool.StringUtils;
import com.rabbitmq.client.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
/**
* RabbitMQ 收发消息统一帮助类
*
* @author gl.dong
* @date 2020/7/1
*/
@Slf4j
@Data
public class MqUtil {
/**
* 消息发送线程池
*/
private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(
new NamedThreadFactory("gisc-message-thread", true));
/**
* RabbitMq连接工厂对象
**/
private volatile static ConnectionFactory factory = null;
/**
* 默认的队列名
*/
private final static String DEFAULT_QUEUE_NAME = "GISC-TOPIC-LOG";
public MqUtil() {
}
/**
* 获取RabbitMQ的连接
*
* @return
*/
public static ConnectionFactory getInstance() throws Exception {
if (factory == null) {
/**
* 服务器域名或IP
*/
String host = ServiceBeanContext.getContext().getEnvironment().getProperty("rabbitmq.host");
/**
* 端口,默认5672
*/
String port = ServiceBeanContext.getContext().getEnvironment().getProperty("rabbitmq.port");
/**
* 用户名,默认guest
*/
String username = ServiceBeanContext.getContext().getEnvironment().getProperty("rabbitmq.username");
/**
* 用户密码,默认guest
*/
String password = ServiceBeanContext.getContext().getEnvironment().getProperty("rabbitmq.password");
/**
* 虚拟目录,默认/
*/
String virtualHost = ConnectionFactory.DEFAULT_VHOST;
if (!StringUtils.isNotBlank(host, username, password, virtualHost)) {
log.error("MQ初始配置参数错误[host:{},virtualHost:{}]", host, virtualHost);
throw new Exception("rabbitMQ初始化参数异常");
}
if (StringUtils.isBlank(port)) {
port = ConnectionFactory.DEFAULT_AMQP_PORT + "";
log.info("MQ初始配置参数启用默认端口");
}
factory = new ConnectionFactory();
//设置服务地址
factory.setHost(host);
//端口
factory.setPort(Integer.parseInt(port));
//设置账号信息,用户名、密码、vhost
//test 设置虚拟机,一个mq服务可以设置多个虚拟机,每个虚拟机就相当于一个独立的mq
factory.setVirtualHost(virtualHost);
factory.setUsername(username);
factory.setPassword(password);
}
return factory;
}
/**
* 创建交换机
* <p>
* exchange 交换器名称
* type 交换器类型 DIRECT("direct"), FANOUT("fanout"), TOPIC("topic"), HEADERS("headers");
* durable 是否持久化,durable设置为true表示持久化,反之是非持久化,持久化的可以将交换器存盘,在服务器重启的时候不会丢失信息.
* autoDelete 是否自动删除,设置为TRUE则表是自动删除,自删除的前提是至少有一个队列或者交换器与这交换器绑定,之后所有与这个交换器绑定的队列或者交换器都与此解绑,一般都设置为false
* internal 是否内置,如果设置 为true,则表示是内置的交换器,客户端程序无法直接发送消息到这个交换器中,只能通过交换器路由到交换器的方式
* arguments 其它一些结构化参数比如:alternate-exchange
*/
private static void exchangeDeclare(String exchangeName, String type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments) {
Connection connection = null;
Channel channel = null;
try {
if (StringUtils.isNotBlank(exchangeName)) {
// 1、通过工厂获取连接
connection = MqUtil.getInstance().newConnection();
// 2、从连接中创建通道,使用通道才能完成消息相关的操作
channel = connection.createChannel();
// 3、 创建 exchange
channel.exchangeDeclare(exchangeName, type, durable, autoDelete, internal, arguments);
}
} catch (Exception e) {
log.error("交换机创建失败 exchangeName:{} , error:{}", exchangeName, e.getMessage());
} finally {
close(connection, channel);
}
}
/**
* internal : false
*/
private static void exchangeDeclare(String exchangeName, String type, boolean durable, boolean autoDelete, Map<String, Object> arguments) {
exchangeDeclare(exchangeName, type, durable, autoDelete, false, arguments);
}
/**
* durable : false
* autoDelete : false
* internal : false
* arguments : null
*/
private static void exchangeDeclare(String exchangeName, String type) {
exchangeDeclare(exchangeName, type, false, false, null);
}
/**
* type : topic
* durable : false
* autoDelete : false
* internal : false
* arguments : null
*/
private static void exchangeDeclare(String exchangeName) {
exchangeDeclare(exchangeName, "topic");
}
/**
* 异步发送消息
*
* @param exchangeName 交换机名
* @param topicName 消息队列名key
* @param content 消息体
*/
public static void sendMessage(String exchangeName, String topicName, String content) {
EXECUTOR.execute(() -> {
Connection connection = null;
Channel channel = null;
try {
// 1、通过工厂获取连接
connection = MqUtil.getInstance().newConnection();
// 2、从连接中创建通道,使用通道才能完成消息相关的操作
channel = connection.createChannel();
// 3、 创建 exchange
exchangeDeclare(exchangeName);
commonSendMessage(channel, exchangeName, topicName, content);
} catch (Exception e) {
log.error("{} sendMessage is error", MqUtil.class.getSimpleName(), e);
} finally {
close(connection, channel);
}
});
}
public static boolean sendTopicMessage(String exchangeName, String topicName, String content) {
Connection connection = null;
Channel channel = null;
try {
// 1、通过工厂获取连接
connection = MqUtil.getInstance().newConnection();
// 2、从连接中创建通道,使用通道才能完成消息相关的操作
channel = connection.createChannel();
// 3、 创建 exchange
exchangeDeclare(exchangeName);
commonSendMessage(channel, exchangeName, topicName, content);
return true;
} catch (Exception e) {
log.error("{} sendLogMessage is error", MqUtil.class.getSimpleName(), e);
return false;
} finally {
close(connection, channel);
}
}
public static void receiveTopicMessage(String queueName,String keyName, MessageHandler handler, boolean isAutoAck) throws Exception {
Connection connection = null;
Channel channel = null;
try {
// 1.获取到连接
connection = MqUtil.getInstance().newConnection();
// 2. 创建会话通道,生产者和mq服务所有通信都在channel通道中完成
channel = connection.createChannel();
/**
* 3. 声明队列
* 参数:String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
* 参数明细
* 1、queue 队列名称
* 2、durable 是否持久化,如果持久化,mq重启后队列还在
* 3、exclusive 是否独占连接,队列只允许在该连接中访问,如果connection连接关闭队列则自动删除,如果将此参数设置true可用于临时队列的创建
* 4、autoDelete 自动删除,队列不再使用时是否自动删除此队列,如果将此参数和exclusive参数设置为true就可以实现临时队列(队列不用了就自动删除)
* 5、arguments 参数,可以设置一个队列的扩展参数,比如:可设置存活时间
*/
channel.queueDeclare(queueName, false, false, false, null);
// 4. 实现消费方法
commonReceive(channel, queueName, handler, isAutoAck);
} catch (Exception e) {
log.error("MQ 消费者启动失败 :{}", e);
}
}
public static void receiveTopicMessage(String queueName, MessageHandler handler, boolean isAutoAck) throws Exception {
Connection connection = null;
Channel channel = null;
try {
// 1.获取到连接
connection = MqUtil.getInstance().newConnection();
// 2. 创建会话通道,生产者和mq服务所有通信都在channel通道中完成
channel = connection.createChannel();
/**
* 3. 声明队列
* 参数:String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
* 参数明细
* 1、queue 队列名称
* 2、durable 是否持久化,如果持久化,mq重启后队列还在
* 3、exclusive 是否独占连接,队列只允许在该连接中访问,如果connection连接关闭队列则自动删除,如果将此参数设置true可用于临时队列的创建
* 4、autoDelete 自动删除,队列不再使用时是否自动删除此队列,如果将此参数和exclusive参数设置为true就可以实现临时队列(队列不用了就自动删除)
* 5、arguments 参数,可以设置一个队列的扩展参数,比如:可设置存活时间
*/
channel.queueDeclare(queueName, false, false, false, null);
// 4. 实现消费方法
commonReceive(channel, queueName, handler, isAutoAck);
} catch (Exception e) {
log.error("MQ 消费者启动失败 :{}", e);
}
}
/**
* 同步发送消息
*
* @param exchangeName 交换机名
* @param topicName 消息队列名key
* @param content 消息体
*/
public static boolean sendSyncMessage(String exchangeName, String topicName, String content) {
Connection connection = null;
Channel channel = null;
try {
// 1、通过工厂获取连接
connection = MqUtil.getInstance().newConnection();
// 2、从连接中创建通道,使用通道才能完成消息相关的操作
channel = connection.createChannel();
// 3、 创建 exchange
exchangeDeclare(exchangeName);
commonSendMessage(channel, exchangeName, topicName, content);
return true;
} catch (Exception e) {
log.error("{} sendLogMessage is error", MqUtil.class.getSimpleName(), e);
return false;
} finally {
close(connection, channel);
}
}
private static void commonSendMessage(Channel channel, String exchangeName, String topicName, String content) throws Exception {
/**
* 4、声明(创建)队列
* 参数:String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
* 参数明细
* 1、queue 队列名称
* 2、durable 是否持久化,如果持久化,mq重启后队列还在
* 3、exclusive 是否独占连接,队列只允许在该连接中访问,如果connection连接关闭队列则自动删除,如果将此参数设置true可用于临时队列的创建
* 4、autoDelete 自动删除,队列不再使用时是否自动删除此队列,如果将此参数和exclusive参数设置为true就可以实现临时队列(队列不用了就自动删除)
* 5、arguments 参数,可以设置一个队列的扩展参数,比如:可设置存活时间
*/
channel.queueDeclare(topicName, false, false, false, null);
/**
* 5、向指定的队列中发送消息
*
* 参数:String exchange, String routingKey, BasicProperties props, byte[] body
* 参数明细:
* 1、exchange,交换机,如果不指定将使用mq的默认交换机(设置为"")
* 2、routingKey,路由key,交换机根据路由key来将消息转发到指定的队列,如果使用默认交换机,routingKey设置为队列的名称
* 3、props,消息的属性
* 4、body,消息内容
*/
channel.basicPublish(exchangeName, topicName, null, content.getBytes());
log.info(" MQ Send {}", content);
}
/**
* 广播模式
*
* @param exchangeName 交换机名
* @param topicName 消息队列名key
* @param content 消息体
*/
public static boolean sendFanoutMessage(String exchangeName, String content) {
Connection connection = null;
Channel channel = null;
try {
// 1、通过工厂获取连接
connection = MqUtil.getInstance().newConnection();
// 2、从连接中创建通道,使用通道才能完成消息相关的操作
channel = connection.createChannel();
// 3、 创建 exchange
exchangeDeclare(exchangeName, "fanout");
channel.basicPublish(exchangeName, exchangeName, null, content.getBytes());
log.info(" MQ Send {}", content);
return true;
} catch (Exception e) {
log.error("{} sendLogMessage is error", MqUtil.class.getSimpleName(), e);
return false;
} finally {
close(connection, channel);
}
}
public static void sendLogMessage(String indexName, String typeName, Map<String, Object> logData) {
// 封装消息内容结
Map<String, Object> map = new HashMap<>();
map.put("type", Constants.BP_LOG);
Map<String, Object> contentMap = new HashMap<>();
contentMap.put("indexName", indexName);
contentMap.put("typeName", typeName);
contentMap.put("logData", logData);
map.put("content", contentMap);
String message = JSONObject.toJSONString(map);
sendMessage("", Constants.BP_LOG, message);
}
/**
* 接收处理消息
*
* @param queueName 消息队列名key
* @param handler 消息处理类
* @param isAutoAck 是否自动ACK
* @throws Exception
*/
public static void receiveMessage(String queueName, MessageHandler handler, boolean isAutoAck) throws Exception {
Connection connection = null;
Channel channel = null;
try {
// 1.获取到连接
connection = MqUtil.getInstance().newConnection();
// 2. 创建会话通道,生产者和mq服务所有通信都在channel通道中完成
channel = connection.createChannel();
/**
* 3. 声明队列
* 参数:String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
* 参数明细
* 1、queue 队列名称
* 2、durable 是否持久化,如果持久化,mq重启后队列还在
* 3、exclusive 是否独占连接,队列只允许在该连接中访问,如果connection连接关闭队列则自动删除,如果将此参数设置true可用于临时队列的创建
* 4、autoDelete 自动删除,队列不再使用时是否自动删除此队列,如果将此参数和exclusive参数设置为true就可以实现临时队列(队列不用了就自动删除)
* 5、arguments 参数,可以设置一个队列的扩展参数,比如:可设置存活时间
*/
channel.queueDeclare(queueName, false, false, false, null);
// 4. 实现消费方法
commonReceive(channel, queueName, handler, isAutoAck);
} catch (Exception e) {
log.error("MQ 消费者启动失败 :{}", e);
}
}
/**
* 接收处理消息
*
* @param exchangeName 消息队列topic
* @param handler 消息处理类
* @param isAutoAck 是否自动ACK
* @throws Exception
*/
public static void receiveMessageBus(String exchangeName, MessageHandler handler, boolean isAutoAck) throws Exception {
Connection connection = null;
Channel channel = null;
try {
// 1.获取到连接
connection = MqUtil.getInstance().newConnection();
// 2. 创建会话通道,生产者和mq服务所有通信都在channel通道中完成
channel = connection.createChannel();
String queueName = UUID.randomUUID().toString();
// 3、 创建 exchange
exchangeDeclare(exchangeName);
/**
* 3. 声明队列
* 参数:String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
* 参数明细
* 1、queue 队列名称
* 2、durable 是否持久化,如果持久化,mq重启后队列还在
* 3、exclusive 是否独占连接,队列只允许在该连接中访问,如果connection连接关闭队列则自动删除,如果将此参数设置true可用于临时队列的创建
* 4、autoDelete 自动删除,队列不再使用时是否自动删除此队列,如果将此参数和exclusive参数设置为true就可以实现临时队列(队列不用了就自动删除)
* 5、arguments 参数,可以设置一个队列的扩展参数,比如:可设置存活时间
*/
channel.queueDeclare(queueName, false, false, false, null);
// 队列绑定到交换机,key,固定匹配
channel.queueBind(queueName, exchangeName, exchangeName + ".#");
// 4. 实现消费方法
commonReceive(channel, queueName, handler, isAutoAck);
} catch (Exception e) {
log.error("MQ 消费者启动失败 {}", exchangeName, e);
}
}
private static void commonReceive(Channel channel, String queueName, MessageHandler handler, boolean isAutoAck) throws IOException {
// 获取消息,并且处理,这个方法类似事件监听,如果有消息的时候,会被自动调用
DefaultConsumer consumer = new DefaultConsumer(channel) {
/**
* 当接收到消息后此方法将被调用
*
* @param consumerTag 消费者标签,用来标识消费者的,在监听队列时设置channel.basicConsume
* @param envelope 信封,通过envelope
* @param properties 消息属性
* @param body 消息内容
* @throws IOException
*/
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//交换机
String exchange = envelope.getExchange();
//消息id,mq在channel中用来标识消息的id,可用于确认消息已接收
long deliveryTag = envelope.getDeliveryTag();
// body 即消息体
String message = new String(body, StandardCharsets.UTF_8);
try {
handler.handle(this.getChannel(), message, envelope, isAutoAck);
} catch (RejectedExecutionException e) {
if (!isAutoAck) {
channel.basicAck(envelope.getDeliveryTag(), false);
}
log.info("Mq message handle queue full");
} catch (Exception e) {
log.error("mq consume message error", e);
}
}
@Override
public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {
log.error("mq consumer:" + consumerTag + "被关闭", sig);
}
};
/**
* 监听队列,第二个参数:是否自动进行消息确认。
* 参数明细:
* 1、queue 队列名称
* 2、autoAck 自动回复,当消费者接收到消息后要告诉mq消息已接收,如果将此参数设置为tru表示会自动回复mq,如果设置为false要通过编程实现回复
* 3、callback,消费方法,当消费者接收到消息要执行的方法
*/
channel.basicConsume(queueName, isAutoAck, consumer);
}
public static void receiveFanoutMessage(String exchangeName, MessageHandler handler, boolean isAutoAck) throws Exception {
Connection connection = null;
Channel channel = null;
try {
connection = MqUtil.getInstance().newConnection();
channel = connection.createChannel();
String queueName = UUID.randomUUID().toString();
// 3、 创建 exchange
exchangeDeclare(exchangeName, "fanout");
channel.queueDeclare(queueName, false, false, false, null);
channel.queueBind(queueName, exchangeName, exchangeName + ".#");
// 4. 实现消费方法
commonReceive(channel, queueName, handler, isAutoAck);
} catch (Exception e) {
log.error("MQ 消费者启动失败 {}", exchangeName, e);
}
}
public static void close(Connection connection, Channel channel) {
if (channel != null) {
try {
channel.close();
} catch (Exception e) {
log.error("关闭channel失败", e.getMessage());
}
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
log.error("关闭connection失败", e.getMessage());
}
}
}
/**
* 定义消息处理类接口
*/
public static interface MessageHandler {
void handle(Channel channel, String message, Envelope envelope, boolean autoAck);
}
public static void main(String[] args) throws Exception {
// 4、消息内容
String message = "Hello World!" + System.currentTimeMillis();
// MqUtil.sendMessage("receive-test-20", "666", message);
//MqUtil.receiveMessage();
}
}
package com.wanji.common.tool.nginxtool;
import com.wanji.common.framework.exception.DubboProviderException;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Properties;
/**
* @Author mapabc8
* @Date 2020/2/11 15:47
**/
@Slf4j
public class OperationMonitorUtil {
/**
* @param ipAddress
* @return boolean
* @Description: 测试指定的ip是否能ping通
* @Author mapabc8
* @Date 2020/2/12 9:23
**/
public static boolean ping(String ipAddress) throws Exception {
int timeOut = 3000;
boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut);
return status;
}
/**
* @param processName
* @return boolean
* @Description:
* @Author mapabc8
* @Date 2020/2/11 18:28
**/
static boolean findProcess(String processName) {
BufferedReader bufferedReader = null;
try {
Properties prop = System.getProperties();
Process proc = null;
// 获取操作系统名称
String os = prop.getProperty("os.name");
if (os != null && os.toLowerCase().startsWith("lin")) {
proc = Runtime.getRuntime().exec("ps -ef");
} else {
proc = Runtime.getRuntime().exec("tasklist");
}
bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains(processName)) {
return true;
}
}
return false;
} catch (Exception ex) {
log.error("get procedure whetherRunning failed!");
return false;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (Exception ex) {
log.error("bufferedReader close failed!");
}
}
}
}
/**
* @param
* @return java.lang.String
* @Description:
* @Author mapabc8
* @Date 2020/2/11 18:29
**/
public static String getSystemLocalIp() throws Exception {
String ip = null;
String osname = System.getProperties().getProperty("os.name");
try {
// 针对window系统
if (osname.startsWith("Windows")) {
ip = InetAddress.getLocalHost().getHostAddress();
// 针对linux系统
} else {
ip = getUnixLocalIp();
}
if (null == ip) {
throw new DubboProviderException("主机的ip地址未知");
}
} catch (SocketException e) {
log.error("获取本机ip错误" + e.getMessage());
throw new DubboProviderException("获取本机ip错误" + e.getMessage());
}
return ip;
}
/**
* @param
* @return java.net.InetAddress
* @Description: 获取Linux系统下本机ip地址
* @Author mapabc8
* @Date 2020/2/11 18:08
**/
private static String getUnixLocalIp() throws SocketException {
String ip = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
ip = ipaddress;
log.info(ipaddress);
}
}
}
}
}
} catch (SocketException ex) {
log.error("获取IP失败");
ip = "127.0.0.1";
ex.printStackTrace();
}
return ip;
}
}
package com.wanji.common.tool.redistool;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
public static JedisPool jedisPool=null;
public static Jedis getInstance(String server,int port,int database,String password) {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(100); //最大可用连接数
jedisPoolConfig.setBlockWhenExhausted(true); //连接耗尽后是否等待
jedisPoolConfig.setMaxWaitMillis(2000); //等待时间
jedisPoolConfig.setMaxIdle(5); //最大闲置连接数
jedisPoolConfig.setMinIdle(5); //最小闲置连接数
jedisPoolConfig.setTestOnBorrow(true); //连接的时候测试一下ping pong
jedisPool = new JedisPool(jedisPoolConfig, server, port, 1000, password, database);
System.out.println("开辟连接池");
return jedisPool.getResource();
}
public static boolean checkConn(){
if(jedisPool!=null&&jedisPool.getResource().isConnected()){
jedisPool.close();
return true;
}
return false;
}
public static void main(String []args){
RedisUtil.getInstance("115.28.212.232",6379,14,"Mapabc@2020");
System.out.println(RedisUtil.checkConn());
}
}
package com.wanji.common.tool.resttool;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import java.net.URI;
/**
* @ClassName HttpComponentsClientRestfulHttpRequestFactory
* @Description
* @Author mapabc7
* @Date 2020/8/14 13:53
* @Version 1.0
*/
public class HttpComponentsClientRestfulHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
@Override
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
if (httpMethod == HttpMethod.GET) {
return new HttpGetRequestWithEntity(uri);
}
return super.createHttpUriRequest(httpMethod, uri);
}
private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetRequestWithEntity(final URI uri) {
super.setURI(uri);
}
@Override
public String getMethod() {
return HttpMethod.GET.name();
}
}
}
package com.wanji.common.tool.resttool;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* @author mapabc4
* @date 2019-04-11
*/
@Configuration
@ConditionalOnClass(value = {RestTemplate.class, HttpClient.class})
public class RestTemplateConfiguration {
//连接池的最大连接数默认0
@Value("${remote.maxTotalConnect:0}")
private int maxTotalConnect;
//单个主机的最大连接数
@Value("${remote.maxConnectPerRoute:200}")
private int maxConnectPerRoute;
//连接超时默认2s
@Value("${remote.connectTimeout:2000}")
private int connectTimeout;
//读取超时默认30s
@Value("${remote.readTimeout:30000}")
private int readTimeout;
//创建HTTP客户端工厂
private ClientHttpRequestFactory createFactory() {
if (this.maxTotalConnect <= 0) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
HttpClient httpClient = (HttpClient) HttpClientBuilder.create().setMaxConnTotal(this.maxTotalConnect)
.setMaxConnPerRoute(this.maxConnectPerRoute).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
httpClient);
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
//初始化RestTemplate,并加入spring的Bean工厂
@Bean
@ConditionalOnMissingBean(RestTemplate.class)
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate(this.createFactory());
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
//重新设置StringHttpMessageConverter字符集为UTF-8,解决中文乱码问题
HttpMessageConverter<?> converterTarget = null;
for (HttpMessageConverter<?> item : converterList) {
if (StringHttpMessageConverter.class == item.getClass()) {
converterTarget = item;
break;
}
}
if (null != converterTarget) {
converterList.remove(converterTarget);
}
converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//加入FastJson转换器
converterList.add(new FastJsonHttpMessageConverter4());
restTemplate.setRequestFactory(new HttpComponentsClientRestfulHttpRequestFactory());
return restTemplate;
}
public static RestTemplateConfiguration newInstance() {
return new RestTemplateConfiguration();
}
}
package com.wanji.common.tool.resttool;
import com.alibaba.fastjson.JSON;
import com.wanji.common.utils.tool.StringUtils;
import lombok.Getter;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import static org.apache.http.HttpStatus.SC_OK;
/**
* @author mapabc4
* todo spring框架默认处理MimeType方式过于严格,存在兼容性问题,需要使用原生重新封装
* todo 不支持的接口示例: @RequestMapping(value = "/zmove_material")
* public void save(@QueryParam("sap-client") String sap_client, @RequestBody User entity, HttpServletResponse response) {
* User user = User.newInstance();
* user.setName("name2");
* user.setId("id_1");
* user.setUsername(sap_client);
* response.setContentType("TEXT;charset=utf-8");
* try(OutputStream ros = response.getOutputStream()) {
* IOUtils.write("xxx", ros);
* ros.flush();
* } catch (IOException e) {
* }
* }
* todo 参见 org.springframework.util.MimeTypeUtils#parseMimeTypeInternal(java.lang.String)
*
*/
public class RestTemplateTool {
@Getter
private static RestTemplate restTemplate = RestTemplateConfiguration.newInstance().getRestTemplate();
private RestTemplateTool() {
}
/**
* get
*
* @param url
* @return
*/
public static String get(String url) throws Exception {
if (StringUtils.isBlank(url)) {
return null;
}
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
if (200 != responseEntity.getStatusCode().value()) {
throw new Exception(responseEntity.toString());
}
return responseEntity.getBody();
}
/**
* delete
*
* @param url
* @return
*/
public static void delete(String url) {
if (!StringUtils.isNotBlank(url)) {
return;
}
restTemplate.delete(url, String.class);
}
/**
* post
*
* @param url
* @param requestEntity
* @return
*/
public static String post(String url, HttpEntity requestEntity) throws Exception {
if (StringUtils.isBlank(url)) {
return null;
}
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
if (200 != responseEntity.getStatusCode().value()) {
throw new Exception(responseEntity.toString());
}
return responseEntity.getBody();
}
/**
* post
*
* @param url
* @param param
* @return
*/
public static String post(String url, String param) throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity requestEntity = new HttpEntity<>(JSON.parseObject(param), requestHeaders);
return post(url, requestEntity);
}
/**
* post
*
* @param url
* @param param
* @param requestHeaders
* @return
*/
public static String post(String url, String param, HttpHeaders requestHeaders) throws Exception {
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(JSON.parseObject(param), requestHeaders);
return post(url, requestEntity);
}
/**
* post
*
* @param url
* @param param
* @param headerStr
* @return
*/
public static String post(String url, String param, String headerStr) throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
String[] headers = headerStr.split("\n");
for (String h : headers) {
String[] headerEntry = h.split(":");
requestHeaders.add(headerEntry[0], headerEntry[1]);
}
return post(url, param, requestHeaders);
}
/**
* put
*
* @param url
* @param requestEntity
*/
public static void put(String url, HttpEntity<String> requestEntity) {
if (!StringUtils.isNotBlank(url)) {
return;
}
restTemplate.put(url, requestEntity, String.class);
}
/**
* put
*
* @param url
* @param param
*/
public static void put(String url, String param) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<String> requestEntity = new HttpEntity<>(param, requestHeaders);
put(url, requestEntity);
}
/**
* put
*
* @param url
* @param param
* @param requestHeaders
*/
public static void put(String url, String param, HttpHeaders requestHeaders) {
HttpEntity<String> requestEntity = new HttpEntity<>(param, requestHeaders);
put(url, requestEntity);
}
/**
* put
*
* @param url
* @param param
* @param headerStr
*/
public static void put(String url, String param, String headerStr) {
HttpHeaders requestHeaders = new HttpHeaders();
String[] headers = headerStr.split("\n");
for (String h : headers) {
String[] headerEntry = h.split(":");
requestHeaders.add(headerEntry[0], headerEntry[1]);
}
put(url, param, requestHeaders);
}
/**
* get请求,可添加header和request params。
* <p>
* url类型:http://127.0.0.1:15020/deleting?ids={ids}
*
* @param url request地址。
* @param headers 请求头。
* @param params 请求参数。
* @return 响应对象。
* @throws Exception 如果请求异常。
*/
public static ResponseEntity get(String url, Map<String, Object> headers, Map<String, Object> params) throws Exception {
// 添加header
HttpHeaders httpHeaders = new HttpHeaders();
for (Map.Entry<String, Object> header : headers.entrySet()) {
httpHeaders.add(header.getKey(), (String) header.getValue());
}
//HttpEntity
HttpEntity<Object> httpEntity = new HttpEntity<>(params, httpHeaders);
ResponseEntity<?> responseEntity = null;
if (params == null) {
responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
} else {
responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, params);
}
if (SC_OK != responseEntity.getStatusCode().value()) {
throw new Exception(responseEntity.toString());
}
return responseEntity;
}
/**
* post请求,可添加header和json字符串格式的body。
*
* @param url 请求路径。
* @param headers 请求头。
* @param body 请求体。
* @return 响应参数。
* @throws Exception 如果请求异常。
*/
public static ResponseEntity post(String url, Map<String, Object> headers, Map<String, Object> body) throws Exception {
// 添加header
HttpHeaders httpHeaders = new HttpHeaders();
if (!headers.containsKey("Content-Type")) {
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
}
if (!headers.containsKey("Accept")) {
httpHeaders.add("Accept", "*/*");
}
//设置返回媒体数据类型
if (!headers.isEmpty()) {
for (Map.Entry<String, Object> header : headers.entrySet()) {
httpHeaders.add(header.getKey(), (String) header.getValue());
}
}
HttpEntity<Object> request = new HttpEntity<>(body, httpHeaders);
ResponseEntity<String> responseEntity;
if (body == null || body.isEmpty()) {
responseEntity = restTemplate.postForEntity(url, request, String.class);
} else {
responseEntity = restTemplate.postForEntity(url, request, String.class, body);
}
if (SC_OK != responseEntity.getStatusCode().value()) {
throw new Exception(responseEntity.toString());
}
return responseEntity;
}
}
package com.wanji.common.tool.wsdltool;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
/**
* @ClassName DoSoapTool
* @Description
* @Author mapabc7
* @Date 2020/7/28 10:30
* @Version 1.0
*/
public class DoSoapTool {
public final static String charset = "UTF-8";
/**
* @param address
* @param charset
* @param requestXml
* @throws MalformedURLException
* @throws IOException
*/
@Deprecated
private static String doPostSoap_(String address, String charset, String requestXml) throws MalformedURLException, IOException {
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(address).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Content-Type", "text/xml;charset=" + charset);
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(requestXml.getBytes(charset));
int responseCode = httpURLConnection.getResponseCode();
StringBuilder stringBuffer = new StringBuilder();
if (HttpStatus.SC_OK == responseCode) {
InputStream inputStream = httpURLConnection.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
stringBuffer.append(new String(buffer, 0, len));
}
}
return stringBuffer.toString();
} finally {
if (null != httpURLConnection) httpURLConnection.disconnect();
}
}
public static String doPostSoap(String address, String requestXml) throws ParseException, IOException {
return doPostSoap(address, requestXml, charset);
}
public static String doPostSoap(String address, String requestXml, String charset) throws ParseException, IOException {
return doPostSoap(address, charset, requestXml, null, null, false);
}
public static String doPostSoap(String address, String requestXml, String charset, String username, String password) throws ParseException, IOException {
return doPostSoap(address, charset, requestXml, username, password, true);
}
public static String doPostSoap(String address, String requestXml, String username, String password) throws ParseException, IOException {
return doPostSoap(address, requestXml, charset, username, password);
}
/**
* @param url
* @param charset
* @param requestXml
* @param username
* @param password
* @param auth
* @return
* @throws ParseException
* @throws IOException
*/
public static String doPostSoap(String url, String charset, String requestXml, String username,
String password, boolean auth) throws ParseException, IOException {
CloseableHttpClient httpClient = null;
try {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60 * 1000)
.setConnectTimeout(60 * 1000).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "text/xml;charset=" + charset);
//httpPost.setHeader("SOAPAction", methodName);
if (auth)
httpPost.setHeader("Authorization", authHeader(username, password, charset));
StringEntity data = new StringEntity(requestXml, Charset.forName(charset));
httpPost.setEntity(data);
CloseableHttpResponse response = httpClient.execute(httpPost);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
return EntityUtils.toString(httpEntity, charset);
}
}
} finally {
// 释放资源
if (httpClient != null) httpClient.close();
}
return null;
}
private static String authHeader(String userName, String password, String charset) {
String auth = userName + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName(charset)));
return "Basic " + new String(encodedAuth);
}
public static void main(String[] args) throws IOException {
String reqXML = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:web=\"http://WebXml.com.cn/\">\n" +
" <soap:Header/>\n" +
" <soap:Body>\n" +
" <web:getSupportCity>\n" +
" <!--Optional:-->\n" +
" <web:byProvinceName>河北</web:byProvinceName>\n" +
" </web:getSupportCity>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
String result = DoSoapTool.doPostSoap("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx", reqXML);
System.out.println(result);
}
}
package com.wanji.common.tool.wstool;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
@Slf4j
public class WebSocketUtil {
public static boolean connect(String ws) {
WebSocketClient client = null;
try {
URI uri = new URI(ws);
client = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
}
@Override
public void onMessage(String s) {
log.info("返回的数据:" + s);
JSONObject jo = JSONObject.parseObject(s);
String dynamicdata = jo.getString("dynamicdata");
if (dynamicdata != null) {
JSONObject jo_dynamicdata = JSONObject.parseObject(dynamicdata);
String realtimestate = jo_dynamicdata.getString("realtimestate");
if (realtimestate.equals("outconnected")) {
send("{\"command\":\"closeheadsettochannel\"}");
}
}
}
@Override
public void onClose(int i, String s, boolean b) {
}
@Override
public void onError(Exception e) {
log.error(e.getMessage());
}
};
//建立连接
client.connect();
long start=System.currentTimeMillis();
while(!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)){
System.out.println("正在连接....");
if(System.currentTimeMillis()-start>2000){
return false;
}
}
return true;
} catch (URISyntaxException e) {
log.info(e.getMessage());
return false;
} finally {
client.close();
}
}
public static void main(String []args){
String socketUrl = "ws://121.40.165.18:8800";
System.out.println(WebSocketUtil.connect(socketUrl));
}
}
package com.wanji.common.utils;
import com.alibaba.fastjson.JSONObject;
import com.wanji.common.utils.geo.GeometryUtils;
import org.locationtech.jts.geom.Geometry;
import org.geotools.geojson.GeoJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.List;
public class FittingFunctionUntils {
private static final GeometryFactory geometryFactory = new GeometryFactory();
public static LineString calculateLineString(String wkt, int precision)
{
WKTReader reader = new WKTReader(geometryFactory);
LineString line = null;
try {
line = (LineString)reader.read(wkt);
} catch (ParseException e) {
e.printStackTrace();
}
//LineString lineByWKT = GeometryUtils.createLineByWKT(wkt);
return calculateLineString(line,precision);
}
public static LineString calculateLineString(LineString lineString, int precision) {
double[][] points = new double[lineString.getNumPoints()][2];
Coordinate[] coordinates = lineString.getCoordinates();
for (int i = 0; i < coordinates.length; i++) {
Coordinate coordinate = coordinates[i];
points[i][0] = coordinate.x;
points[i][1] = coordinate.y;
}
double[][] calculate = calculate(points, precision);
Coordinate[] coordinatesNew = new Coordinate[calculate.length + 1];
for (int i = 0; i < calculate.length; i++) {
coordinatesNew[i] = new Coordinate(calculate[i][0], calculate[i][1]);
}
coordinatesNew[calculate.length] = lineString.getEndPoint().getCoordinate();
return geometryFactory.createLineString(coordinatesNew);
}
public static double[][] calculate(List<String> list, int precision) {
double[][] points = new double[list.size()][2];
for (int i = 0; i < list.size(); i++) {
String point = (String)list.get(i);
String[] split = point.split(",");
points[i][0] = Double.parseDouble(split[0]);
points[i][1] = Double.parseDouble(split[1]);
}
return calculate(points, precision);
}
public static double[][] calculate(double[][] poss, int precision)
{
int dimersion = poss[0].length;
int number = poss.length;
if ((number < 2) || (dimersion < 2)) {
return (double[][])null;
}
double[][] result = new double[precision][dimersion];
int[] mi = new int[number];
int tmp43_42 = 1; mi[1] = tmp43_42; mi[0] = tmp43_42;
for (int i = 3; i <= number; i++)
{
int[] t = new int[i - 1];
for (int j = 0; j < t.length; j++)
t[j] = mi[j];
int tmp100_99 = 1; mi[(i - 1)] = tmp100_99; mi[0] = tmp100_99;
for (int j = 0; j < i - 2; j++) {
mi[(j + 1)] = (t[j] + t[(j + 1)]);
}
}
for (int i = 0; i < precision; i++) {
double t = new BigDecimal(i + "").divide(new BigDecimal(precision + ""), 80, 0).doubleValue();
for (int j = 0; j < dimersion; j++) {
double temp = 0.0D;
for (int k = 0; k < number; k++) {
temp += Math.pow(1.0D - t, number - k - 1) * poss[k][j] * Math.pow(t, k) * mi[k];
}
result[i][j] = temp;
}
}
return result;
}
public static void main(String []args){
LineString lineString = FittingFunctionUntils.calculateLineString("LINESTRING(118.700421223022 37.4278045360367,118.700798456007 37.4278045360367,118.700798456007 37.4276183268811)", 10);
String json = null;
try {
org.locationtech.jts.io.WKTReader reader = new org.locationtech.jts.io.WKTReader();
Geometry geometry = reader.read(lineString.toText());
StringWriter writer = new StringWriter();
GeometryJSON g = new GeometryJSON(20);
g.write(geometry, writer);
json = writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println( json);
}
}
package com.wanji.common.utils.cache;
import com.wanji.common.utils.tool.StringUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import java.util.List;
import static com.wanji.common.framework.Constants.igniteCacheName.BP_DESIGN_CACHE;
/**
* EHCache工具类
*
* @author wanshan.hu
*/
@Slf4j
public class EHCacheUtil {
/**
* 元素最大数量
*/
private static final int MAX_ELEMENTS_IN_MEMORY = 50000;
/**
* 是否把溢出数据持久化到硬盘
*/
private static final boolean OVERFLOW_TO_DISK = false;
/**
* 是否会死亡
*/
private static final boolean ETERNAL = false;
/**
* 缓存的间歇时间
*/
private static final int TIME_TO_IDLE_SECONDS = 0;
/**
* 存活时间(默认一天86400)
*/
private static final int TIME_TO_LIVE_SECONDS = 0;
/**
* 需要持久化到硬盘否
*/
public static final boolean DISK_PERSISTENT = false;
/**
* 内存存取策略
*/
public static final String MEMORY_STORE_EVICTION_POLICY = "LFU";
private static CacheManager cacheManager = null;
static {
EHCacheUtil.initCacheManager();
}
/**
* 初始化缓存管理容器
*/
private static void initCacheManager() {
try {
if (cacheManager == null) {
cacheManager = CacheManager.getInstance();
}
} catch (Exception e) {
log.error("EHCacheUtil initCacheManager error.", e);
}
}
/**
* 初始化cache
*/
public static Cache initCache(String cacheName) throws Exception {
return initCache(cacheName, 0);
}
/**
* 初始化cache
*
* @param cacheName cache的名字
* @param timeToLiveSeconds 有效时间
* @return cache 缓存
* @throws Exception
*/
public static Cache initCache(String cacheName, long timeToLiveSeconds) throws Exception {
return initCache(cacheName, MAX_ELEMENTS_IN_MEMORY, OVERFLOW_TO_DISK, ETERNAL, timeToLiveSeconds, TIME_TO_IDLE_SECONDS);
}
/**
* 初始化缓存
*
* @param cacheName 缓存名称
* @param maxElementsInMemory 元素最大数量
* @param overflowToDisk 是否持久化到硬盘
* @param eternal 是否会死亡
* @param timeToLiveSeconds 缓存存活时间
* @param timeToIdleSeconds 缓存的间隔时间
* @return 缓存
* @throws Exception
*/
private static Cache initCache(String cacheName, int maxElementsInMemory, boolean overflowToDisk, boolean eternal,
long timeToLiveSeconds, long timeToIdleSeconds) throws Exception {
checkCacheManager();
Cache cache;
try {
cache = getCache(cacheName);
if (cache == null) {
Cache memoryOnlyCache = new Cache(cacheName, maxElementsInMemory, overflowToDisk, eternal, timeToLiveSeconds, timeToIdleSeconds);
cacheManager.addCache(memoryOnlyCache);
cache = getCache(cacheName);
} else {
CacheConfiguration config = cache.getCacheConfiguration();
config.setTimeToLiveSeconds(timeToLiveSeconds);
config.setMaxEntriesLocalHeap(maxElementsInMemory);
config.setOverflowToDisk(overflowToDisk);
config.setEternal(eternal);
config.setTimeToIdleSeconds(timeToIdleSeconds);
}
} catch (Exception e) {
log.error("EHCacheUtil initCache {} error.", cacheName, e);
throw new Exception("CacheName:" + cacheName + "创建失败!");
}
return cache;
}
/**
* 释放CacheManager
*/
public static void shutdown() {
cacheManager.shutdown();
}
/**
* 修改缓存容器配置
*
* @param cacheName 缓存名
* @param timeToLiveSeconds 有效时间
* @param maxElementsInMemory 最大数量
* @throws Exception
*/
public static boolean modifyCache(String cacheName, long timeToLiveSeconds, int maxElementsInMemory) throws Exception {
try {
if (StringUtils.isNotBlank(cacheName) && timeToLiveSeconds != 0L && maxElementsInMemory != 0) {
CacheManager myManager = CacheManager.create();
Cache myCache = myManager.getCache(cacheName);
CacheConfiguration config = myCache.getCacheConfiguration();
config.setTimeToLiveSeconds(timeToLiveSeconds);
config.setMaxEntriesLocalHeap(maxElementsInMemory);
return true;
} else {
return false;
}
} catch (Exception e) {
log.error("EHCacheUtil modifyCache {} error.", cacheName, e);
throw new Exception("modify cache " + cacheName + " failed!!!");
}
}
/**
* 向指定容器中设置值
*
* @param cacheName 容器名
* @param key 键
* @param value 值
* @return 返回真
* @throws Exception 异常
*/
public static boolean setValue(String cacheName, String key, Object value) throws Exception {
checkCacheManager();
try {
Cache cache = getCache(cacheName);
if (cache == null) {
cache = initCache(cacheName);
}
cache.put(new Element(key, value));
return true;
} catch (Exception e) {
log.error("EHCacheUtil setValue error, cacheName = {}, key = {}, value = {}.", cacheName, key, value, e);
throw new Exception("set cache " + cacheName + " failed!!!");
}
}
/**
* 向指定容器中设置值
*
* @param cacheName 容器名
* @param key 键
* @param value 值
* @param timeToLiveSeconds 存活时间
* @return 真
* @throws Exception 抛出异常
*/
public static boolean setValue(String cacheName, String key, Object value, Integer timeToLiveSeconds) throws Exception {
checkCacheManager();
try {
Cache cache = getCache(cacheName);
if (cache == null) {
cache = initCache(cacheName);
}
cache.put(new Element(key, value, TIME_TO_IDLE_SECONDS, timeToLiveSeconds));
return true;
} catch (Exception e) {
log.error("EHCacheUtil setValue error, cacheName = {}, key = {}, value = {}.", cacheName, key, value, e);
throw new Exception("EHCacheUtil setValue error, cacheName = " + cacheName + ", key = " + key + ", value = " + value, e);
}
}
/**
* 从ehcache的指定容器中取值
*
* @param key 键
* @return 返回Object类型的值
*/
public static Object getValue(String cacheName, String key) {
checkCacheManager();
Object object = null;
try {
Cache cache = getCache(cacheName);
if (cache == null) {
cache = initMyCache(cacheName);
}
if (cache.get(key) != null) {
object = cache.get(key).getObjectValue();
}
} catch (Exception e) {
log.error("EHCacheUtil setValue error, cacheName = {}, key = {}.", cacheName, key, e);
//throw new Exception("EHCacheUtil setValue error, cacheName = " + cacheName + ", key = " + key, e);
}
return object;
}
private static Cache getCache(String cacheName) {
checkCacheManager();
return cacheManager.getCache(cacheName);
}
private static Cache initMyCache(String cacheName) throws Exception {
return EHCacheUtil.initCache(cacheName, TIME_TO_LIVE_SECONDS);
}
/**
* 删除EHCache容器中的元素
*
* @param cacheName 容器名
* @param key 键
* @return 真
* @throws Exception 失败抛出异常
*/
public static boolean removeElement(String cacheName, String key) throws Exception {
checkCacheManager();
try {
Cache cache = getCache(cacheName);
cache.remove(key);
return true;
} catch (Exception e) {
log.error("EHCacheUtil removeElement error, cacheName = {}, key = {}.", cacheName, key, e);
throw new Exception("remove cache " + cacheName + " failed!!!");
}
}
/**
* 删除指定容器中的所有元素
*
* @param cacheName 容器名
* @return 真
* @throws Exception 失败抛出异常
*/
public static boolean removeAllElement(String cacheName) throws Exception {
checkCacheManager();
try {
Cache cache = getCache(cacheName);
cache.removeAll();
return true;
} catch (Exception e) {
log.error("EHCacheUtil removeAllElement error, cacheName = {}.", cacheName, e);
throw new Exception("remove cache " + cacheName + " failed!!!");
}
}
/**
* 移除cache
*
* @param cacheName
*/
public static void removeCache(String cacheName) {
checkCacheManager();
Cache cache = getCache(cacheName);
if (null != cache) {
cacheManager.removeCache(cacheName);
}
}
/**
* 移除所有cache
*/
public static void removeAllCache() {
checkCacheManager();
cacheManager.removeAllCaches();
}
public static void removeValue(String cacheName, String key) {
Cache cache = getCache(cacheName);
checkCache(cache);
cache.remove(key);
}
public static void removeAllValue(String cacheName) {
removeAllValue(getCache(cacheName));
}
/**
* 移除所有Element
*/
private static void removeAllValue(Cache cache) {
checkCache(cache);
cache.removeAll();
}
/**
* 获取所有的cache名称
*
* @return
*/
public static String[] getAllCaches() {
checkCacheManager();
return cacheManager.getCacheNames();
}
/**
* 获取Cache所有的Keys
*
* @param cacheName
* @return
*/
public static List getKeys(String cacheName) {
return getKeys(getCache(cacheName));
}
private static List getKeys(Cache cache) {
checkCache(cache);
return cache.getKeys();
}
/**
* 检测cacheManager
*/
private static void checkCacheManager() {
if (null == cacheManager) {
throw new IllegalArgumentException("调用前请先初始化CacheManager值:EHCacheUtil.initCacheManager");
}
}
private static void checkCache(Cache cache) {
if (null == cache) {
throw new IllegalArgumentException("调用前请先初始化Cache值:EHCacheUtil.initCache(参数)");
}
}
/**
* @return void
* @throws
* @Author mapabc7
* @Description 更新缓存
* @Date 16:41 2020/7/3
* @Param [id, obj]
*/
public static void saveCache(String id, Object obj) throws Exception {
EHCacheUtil.setValue(
BP_DESIGN_CACHE,
id,
obj
);
}
/*public static void main(String[] arg) {
// 初始化--必须
*//*try {
EHCacheUtil.setValue("dataAccessCahe", "name", "12121");
String nn = EHCacheUtil.getValue("dataAccessCahe", "name").toString();
System.out.println(nn);
} catch (Exception e) {
e.printStackTrace();
}*//*
System.out.println(new Date().getTime());
initCacheManager();
String cacheName = "testCache";
System.out.println(new Date().getTime()); // 1594290889200 1594290962412
for (int i = 0; i < 100000; i++) { // 1594715074241
try {
setValue(cacheName, String.valueOf(i), i);
} catch (Exception e) {
log.error("setValue error" + i, e);
}
}
System.out.println(new Date().getTime()); // 1594290891526 1594290964803
for (int i = 0; i < 100000; i++) { // 1594715074382
try {
getValue(cacheName, String.valueOf(i));
// Object value = getValue(cacheName, String.valueOf(i));
// System.out.println(value);
} catch (Exception e) {
log.error("getValue error" + i, e);
}
}
System.out.println(new Date().getTime()); // 1594290894087 1594290967215
} // 1594715074432*/
}
package com.wanji.common.utils.cache;
import com.wanji.common.framework.spring.ServiceBeanContext;
import com.wanji.common.utils.tool.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.PartitionLossPolicy;
import org.apache.ignite.cache.query.ScanQuery;
import org.apache.ignite.client.ClientCache;
import org.apache.ignite.client.ClientCacheConfiguration;
import org.apache.ignite.client.ClientException;
import org.apache.ignite.client.IgniteClient;
import org.apache.ignite.configuration.ClientConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.wanji.common.framework.Constants.igniteCacheName.BP_DESIGN_CACHE;
/**
* @ClassName IgniteClientCacheUtil
* @Description ignite 缓存 工具类
* @Author mapabc7
* @Date 2020/7/9 15:15
* @Version 1.0
*/
@Slf4j
public class IgniteClientCacheUtil {
private static String addresses = ServiceBeanContext.getContext().getEnvironment().getProperty("ignite-client.address");
//private static String addresses = "121.36.56.157:10800";
private static IgniteClient igniteClient = null;
static {
IgniteClientCacheUtil.initIgniteClient();
}
/**
* 初始化缓存管理容器
*/
private static void initIgniteClient() {
try {
if (igniteClient == null) {
igniteClient = Ignition.startClient(getClientConfiguration());
log.info("IgniteClientCacheUtil initIgniteClient success");
}
} catch (Exception e) {
log.error("IgniteClientCacheUtil initIgniteClient error.", e);
}
}
/**
* 初始化缓存
*/
public static ClientCache<String, Object> initCache(String cacheName) throws Exception {
log.info("IgniteClientCacheUtil initCache , cacheName : {}", cacheName);
return IgniteClientCacheUtil.getCache(cacheName);
}
/**
* 初始化缓存
*/
public static ClientCache<String, Object> initCache(String cacheName, Long expireTime) throws Exception {
log.info("IgniteClientCacheUtil initCache , cacheName : {} ,expire :{} ", cacheName, expireTime);
return IgniteClientCacheUtil.getCache(cacheName, expireTime);
}
private static ClientConfiguration getClientConfiguration() {
log.info("IgniteClientCacheUtil getClientConfiguration , addresses : {}", addresses);
ClientConfiguration configuration = new ClientConfiguration();
configuration.setAddresses(addresses);
return configuration;
}
/**
* 检测 igniteClient
*/
private static void checkIgniteClient() {
if (null == igniteClient) {
throw new IllegalArgumentException("调用前请先初始化 IgniteClient 值:IgniteClientCacheUtil.checkIgniteClient");
}
}
/**
* 向指定容器中设置值
*
* @param cacheName 容器名
* @param key 键
* @param value 值
* @return 返回真
* @throws Exception 异常
*/
public static boolean setValue(String cacheName, String key, Object value) throws Exception {
checkIgniteClient();
try {
log.info("IgniteClientCacheUtil setValue , cacheName : {} , key : {} , value : {}", cacheName, key, value);
ClientCache<String, Object> cache = getCache(cacheName);
if (StringUtils.isBlank(key)) {
throw new Exception("IgniteClientCacheUtil setValue , key == null");
}
cache.put(key, value);
return true;
} catch (Exception e) {
log.error("IgniteClientCacheUtil setValue error, cacheName = {}, key = {}, value = {}.", cacheName, key, value, e);
throw new Exception("set cache " + cacheName + " failed!!!");
}
}
/**
* 从ehcache的指定容器中取值
*
* @param key 键
* @return 返回Object类型的值
*/
public static Object getValue(String cacheName, String key) throws Exception {
checkIgniteClient();
Object object = null;
try {
ClientCache<String, Object> cache = getCache(cacheName);
if (StringUtils.isNotBlank(key)) {
object = cache.get(key);
}
} catch (Exception e) {
log.error("IgniteClientCacheUtil getValue error, cacheName = {}, key = {}.", cacheName, key, e);
throw new Exception("IgniteClientCacheUtil getValue error, cacheName = " + cacheName + ", key = " + key, e);
}
return object;
}
/**
* 获取Cache所有的Keys
*
* @param cacheName
* @return
*/
public static List<String> getKeys(String cacheName) throws Exception {
log.info("IgniteClientCacheUtil getKeys , cacheName : {}", cacheName);
return getKeys(getCache(cacheName));
}
/**
* 获取Keys下的所有值
*
* @param cacheName
* @param keys
* @return
* @throws Exception
*/
public static List<Object> getValues(String cacheName, List<String> keys) throws Exception {
log.info("IgniteClientCacheUtil getValues ,keys :{} ", keys.toArray());
checkIgniteClient();
List<Object> values = new ArrayList<>();
keys.forEach(key -> {
try {
ClientCache<String, Object> cache = getCache(cacheName);
if (StringUtils.isNotBlank(key)) {
values.add(cache.get(key));
}
} catch (Exception e) {
log.error("IgniteClientCacheUtil getValue error, cacheName = {}, key = {}.", cacheName, key, e);
}
});
return values;
}
private static List<String> getKeys(ClientCache<String, Object> cache) {
checkIgniteClient();
List<String> keys = new ArrayList<>();
cache.query(new ScanQuery<>(null)).forEach(entry -> keys.add((String) entry.getKey()));
return keys;
}
private static ClientCache<String, Object> getCache(String cacheName) throws Exception {
checkIgniteClient();
if (StringUtils.isBlank(cacheName)) {
throw new Exception("IgniteClientCacheUtil getCache , cacheName == null");
}
ClientCacheConfiguration configuration = new ClientCacheConfiguration();
configuration.setName(cacheName);
configuration.setCacheMode(CacheMode.REPLICATED);
configuration.setPartitionLossPolicy(PartitionLossPolicy.READ_ONLY_SAFE);
configuration.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
return igniteClient.getOrCreateCache(configuration);
}
private static ClientCache<String, Object> getCache(String cacheName, Long expireTime) throws Exception {
checkIgniteClient();
if (StringUtils.isBlank(cacheName)) {
throw new Exception("IgniteClientCacheUtil getCache , cacheName == null");
}
ClientCacheConfiguration configuration = new ClientCacheConfiguration();
configuration.setName(cacheName);
configuration.setCacheMode(CacheMode.REPLICATED);
configuration.setExpiryPolicy(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, expireTime)).create());
configuration.setPartitionLossPolicy(PartitionLossPolicy.READ_ONLY_SAFE);
configuration.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
return igniteClient.getOrCreateCache(configuration);
}
/**
* 删除 ignite client cache 中的 key
*
* @param cacheName 容器名
* @param key 键
* @return 真
* @throws Exception 失败抛出异常
*/
public static boolean removeKey(String cacheName, String key) throws Exception {
checkIgniteClient();
try {
log.info("IgniteClientCacheUtil removeKey , cacheName : {} , key : {}", cacheName, key);
ClientCache<String, Object> cache = getCache(cacheName);
cache.remove(key);
return true;
} catch (Exception e) {
log.error("IgniteClientCacheUtil removeKey error, cacheName = {}, key = {}.", cacheName, key, e);
throw new Exception("remove cache " + cacheName + " failed!!!");
}
}
/**
* 删除 ignite client cache 中 包含 containsKey 的 key
*
* @param cacheName 容器名
* @param containsKey 键
* @return 真
* @throws Exception 失败抛出异常
*/
public static boolean removeContainsKey(String cacheName, String containsKey) throws Exception {
checkIgniteClient();
try {
ClientCache<String, Object> cache = getCache(cacheName);
List<String> keys = IgniteClientCacheUtil.getKeys(cache);
for (String key : keys) {
if (key.contains(containsKey)) {
cache.remove(key);
log.info("IgniteClientCacheUtil removeKey , cacheName : {} , key : {}", cacheName, key);
}
}
return true;
} catch (Exception e) {
log.error("IgniteClientCacheUtil removeKey error, cacheName = {}, containsKey = {}.", cacheName, containsKey, e);
throw new Exception("remove cache " + cacheName + " failed!!!");
}
}
/**
* 删除 ignite client cache 中所有的 key
*
* @param cacheName 容器名
* @return 真
* @throws Exception 失败抛出异常
*/
public static boolean removeAllKey(String cacheName) throws Exception {
checkIgniteClient();
try {
log.info("IgniteClientCacheUtil removeAllKey , cacheName : {}", cacheName);
ClientCache<String, Object> cache = getCache(cacheName);
cache.removeAll();
return true;
} catch (Exception e) {
log.error("IgniteClientCacheUtil removeAllKey error, cacheName = {}.", cacheName, e);
throw new Exception("remove cache " + cacheName + " failed!!!");
}
}
/**
* 移除cache
*
* @param cacheName
*/
public static void removeCache(String cacheName) {
checkIgniteClient();
log.info("IgniteClientCacheUtil removeCache , cacheName : {}", cacheName);
try {
igniteClient.destroyCache(cacheName);
} catch (ClientException e) {
log.info("IgniteClientCacheUtil removeCache , cacheName : {} Cache does not exist ", cacheName);
}
}
public static void main(String[] args) throws Exception {
String cacheName = "VECTOR_TILE";
IgniteClientCacheUtil.initCache(cacheName);
IgniteClientCacheUtil.removeAllKey(cacheName);
// removeKey(cacheName, "92460E87D880442E951A95026856590F");
/*try {
setValue(cacheName, "test", "test");
} catch (Exception e) {
log.error("setValue error", e);
}
try {
System.out.println(getValue(cacheName, "test"));
} catch (Exception e) {
log.error("getValue error", e);
}
System.out.println(new Date().getTime()); // 1594290889200 1594290962412
for (int i = 0; i < 10000; i++) {
try {
setValue(cacheName, String.valueOf(i), i);
} catch (Exception e) {
log.error("setValue error" + i, e);
}
}
System.out.println(new Date().getTime()); // 1594290891526 1594290964803
for (int i = 0; i < 10000; i++) {
try {
getValue(cacheName, String.valueOf(i));
// Object value = getValue(cacheName, String.valueOf(i));
// System.out.println(value);
} catch (Exception e) {
log.error("getValue error" + i, e);
}
}
System.out.println(new Date().getTime()); // 1594290894087 1594290967215*/
}
/*
* CacheMode 缓存操作模式
* PARTITIONED 分区模式:所有数据均匀分布在每个节点上,默认的模式
* REPLICATED 复制模式:所有数据复制到每个节点上,每一个节点都保存其他节点的备份
* LOCAL 本地模式
*
* PartitionLossPolicy 分区丢失策略
* READ_ONLY_SAFE:所有缓存/表的写操作都会抛出异常,在线分区的读操作是可以的,丢失分区的读操作会抛出异常;
READ_ONLY_ALL:包括丢失分区在内的所有分区都是可以读的,所有分区的写操作都会抛出异常,从丢失的分区读取数据的结果是未定义的,而且不同的节点返回结果可能不同;
READ_WRITE_SAFE:在线分区的读写都是可以的,丢失分区的读写操作都会抛出异常;
READ_WRITE_ALL:所有的读写都会继续进行,就像所有分区都处于一致状态那样(就像没有分区丢失),从丢失分区的读操作是未定义的,并且不同节点返回结果可能不同;
IGNORE:该模式不会标记丢失的分区为丢失状态,假定没有发生分区丢失,并且立即清除分区丢失状态。从技术上来说,分区不会被加入lostPartitions列表,这是与READ_WRITE_ALL模式的主要区别。从丢失的分区读取数据的结果是未定义的,而且不同的节点返回结果可能不同,IGNORE模式为默认模式。
*
* writeSynchronizationMode 写同步模式
* FULL_SYNC 客户端节点要等待所有相关远程节点的写入或者提交完成(主和备)。
FULL_ASYNC 客户端不需要等待参与节点的响应。这时远程节点可能会在任何缓存写入方法完成或Transaction.commit()方法完成后稍微更新其状态。
PRIMARY_SYNC 这是默认模式,客户端节点会等待主节点的写或者提交完成,但不会等待备份节点的更新完成。
*
* 主备副本 backups
* 在PARTITIONED模式下,数据的主键归属的节点叫做这些主键的主节点,对于缓存的数据,也可以可选地配置任意多个备份节点。如果副本数量大于0,那么Ignite会自动地为每个独立的键赋予备份节点,比如,如果副本数量为1,那么数据网格内缓存的每个键都会有2个备份,一主一备。
*
* 原子化模式 CacheAtomicityMode
* TRANSACTIONAL和TRANSACTIONAL_SNAPSHOT模式支持完全兼容ACID的事务,TRANSACTIONAL模式只支持基于Java API的键-值事务,这个模式的事务有不同的并发模型和隔离级别。
* ATOMIC模式因为避免了事务锁,所以性能更好,但是仍然提供了单个数据的原子性和一致性。ATOMIC模式的另一个不同是批量写,比如putAll(...)和removeAll(...)方法不在一个事务中执行,因此可能部分失败并抛出CachePartialUpdateException,它里面包含了更新失败的键列表。
* */
}
package com.wanji.common.utils.cookie;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Description:
* @Author mapabc
* @Date 2020/6/23 14:35
*/
public class CookieUtil {
private CookieUtil() {
}
/**
* 添加cookie
*
* @param response
* @param name
* @param value
* @param maxAge
*/
public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
if (maxAge >= 0) {
cookie.setMaxAge(maxAge);
}
response.addCookie(cookie);
}
/**
* 删除cookie
*
* @param response
* @param name
*/
public static void removeCookie(HttpServletResponse response, String name) {
Cookie uid = new Cookie(name, null);
uid.setPath("/");
uid.setMaxAge(0);
response.addCookie(uid);
}
/**
* 获取cookie值
*
* @param request
* @return
*/
public static String getUid(HttpServletRequest request, String cookieName) {
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName)) {
return cookie.getValue();
}
}
}
return null;
}
}
package com.wanji.common.utils.file;
import com.github.tobato.fastdfs.domain.fdfs.FileInfo;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.io.*;
/**
* 使用FastDFS访问和存储文件
*
* @author gl.dong
* @date 2020/5/26
*/
@Slf4j
@Component("fastDfsUtils")
@ConditionalOnProperty(value = "fdfs.groupName") //判断fastdfs的配置是否存在
public class FastDfsUtils {
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private ThumbImageConfig thumbImageConfig;
@Value("${fdfs.groupName}")
private String groupName;
@Value("${fdfs.serverUrl}")
public String serverUrl;
@Value("${fdfs.fileDownUrl}")
public String fileDownUrl;
/**
* 判断文件或目录是否存在
*
* @param filePath
* @return
* @throws Exception
*/
public boolean exists(String filePath) throws Exception {
if (filePath.contains(groupName)) {
filePath = filePath.replace(groupName + "/", "");
}
FileInfo fileInfo;
try {
fileInfo = storageClient.queryFileInfo(groupName, filePath);
} catch (Exception e) {
return false;
}
return fileInfo != null;
}
/**
* 删除文件
*
* @param fullRemoteFileName
* @return
* @throws Exception
*/
public boolean delFile(String fullRemoteFileName) throws Exception {
boolean flag = false;
try {
if (fullRemoteFileName.contains(groupName)) {
fullRemoteFileName = fullRemoteFileName.replace(groupName + "/", "");
}
if (exists(fullRemoteFileName)) {
//删除文件服务器的文件信息
storageClient.deleteFile(groupName, fullRemoteFileName);
flag = true;
}
} catch (Exception e) {
throw new Exception("deleted remote exception by fileName(" + fullRemoteFileName + ")", e);
}
return flag;
}
/**
* @return boolean
* @throws
* @Author mapabc7
* @Description 删除本地文件
* @Date 9:26 2020/6/1
* @Param [fullRemoteFileName]
*/
public boolean delLocalFile(String fullRemoteFileName) throws Exception {
try {
if (!fullRemoteFileName.contains(fileDownUrl)) {
fullRemoteFileName = fileDownUrl + "/" + fullRemoteFileName;
}
File file = new File(fullRemoteFileName);
// 是文件
if (file.exists() && file.isFile()) {
file.delete();
} else {
// 是文件夹
delTempChild(file);
}
return true;
} catch (Exception e) {
throw new Exception("deleted local file exception by fileName(" + fullRemoteFileName + ")," + e.getMessage(), e);
}
}
private void delTempChild(File file) {
if (file.isDirectory()) {
String[] children = file.list();//获取文件夹下所有子文件夹
//递归删除目录中的子目录下
if (children != null) {
for (String child : children) {
delTempChild(new File(file, child));
}
}
} else {
// 目录空了,进行删除
file.delete();
}
}
/**
* 将数据流写入到远程文件系统中
*
* @return
* @throws Exception
*/
public String writeInputStreamToFile(File file) throws Exception {
try (FileInputStream in = new FileInputStream(file)) {
StorePath storePath = storageClient.uploadFile(in, file.length(), FilenameUtils.getExtension(file.getName()), null);
return storePath.getFullPath();
} catch (Exception e) {
throw new Exception("upload remote path exception," + e.getMessage(), e);
}
}
/**
* 将数据流写入到远程文件系统中
*
* @return
* @throws Exception
*/
public String writeInputStreamToFile(InputStream inputStream, long fileSize, String remoteFilename) throws Exception {
try {
StorePath storePath = storageClient.uploadFile(inputStream, fileSize, FilenameUtils.getExtension(remoteFilename), null);
return storePath.getFullPath();
} catch (Exception e) {
throw new Exception("upload remote path exception," + e.getMessage(), e);
} finally {
inputStream.close();
}
}
public boolean downloadToLocal(String localFilePath, String remoteDir) {
File file = new File(localFilePath);
return downloadToLocal(file, remoteDir);
}
public boolean downloadToLocal(File file, String remoteDir) {
// 先删 后下载
FileUtil.delFile(file);
byte[] bytes = null;
boolean flag = false;
OutputStream outputStream = null;
try {
if (remoteDir.contains(groupName)) {
remoteDir = remoteDir.replace(groupName + "/", "");
}
if (storageClient.queryFileInfo(groupName, remoteDir) != null) {
bytes = storageClient.downloadFile(groupName, remoteDir, new DownloadByteArray());
}
// 创建目录
FileUtil.newFolder(file.getParentFile());
outputStream = new FileOutputStream(file);
if (bytes == null || bytes.length <= 0) {
log.error("download remote(" + remoteDir + ") to local exception, 文件系统无此文件");
return false;
}
outputStream.write(bytes);
flag = true;
} catch (Exception e) {
log.error("download remote:{} to local:{} path exception error:{}", remoteDir, file.getPath(), e.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.error("文件流关闭失败:{}", e.getMessage());
}
}
}
return flag;
}
/**
* 根据当前图片地址返回缩略图图片地址
*
* @param url 当前图片地址
* @return 缩略图图片地址
* @throws Exception
* @Author gl.dong
*/
public String getThumbFromUrl(String url) throws Exception {
String thumbUrl = "";
if (url.contains(groupName)) {
url = url.replace(groupName + "/", "");
}
try {
if (exists(url)) {
thumbUrl = thumbImageConfig.getThumbImagePath(url);
}
} catch (Exception e) {
throw new Exception(" get thumb url fail", e);
}
return thumbUrl;
}
/**
* 将流转为字节
*
* @param inStream
* @return
* @throws Exception
*/
public static byte[] inputStreamToBytes(InputStream inStream) throws Exception {
byte[] bytes = null;
try (ByteArrayOutputStream swapStream = new ByteArrayOutputStream()) {
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
bytes = swapStream.toByteArray();
} catch (Exception e) {
log.error("将流转为字节失败", e);
throw new Exception("将流转为字节失败", e);
}
return bytes;
}
/**
* 传入文件路径 将文件转为字节
*
* @param filePath
* @return
* @throws Exception
*/
public byte[] readFileToBytes(String filePath) throws Exception {
byte[] bytes = null;
String group = "group1";
try {
if (storageClient.queryFileInfo(group, filePath) != null) {
bytes = storageClient.downloadFile(group, filePath, new DownloadByteArray());
}
} catch (Exception e) {
throw new Exception("download remote(" + filePath + ") path exception", e);
}
return bytes;
}
/**
* 将字节流数据写入到远程文件系统中
*
* @param bytes
* @return 远程文件路径
* @throws Exception
*/
public String writeByteArrayToFile(byte[] bytes, String remoteDir, String remoteName) throws Exception {
InputStream in = byteToInputStream(bytes);
return writeInputStreamToFile(in, bytes.length, remoteName);
}
/**
* 字节转换InputStream
*
* @param in
* @return
*/
public static InputStream byteToInputStream(byte[] in) throws Exception {
ByteArrayInputStream is = new ByteArrayInputStream(in);
return is;
}
public static void main(String[] args) {
String a = "http://219.142.87.76:8080/" + "group1/M00/00/19/wKgFwF7QpByAGClYAAA6xbqsNdg30.docx";
String b = a.replace("http://219.142.87.76:8080/", "");
System.out.println(a.lastIndexOf(")"));
System.out.println(a.substring(a.lastIndexOf(".")));
}
}
package com.wanji.common.utils.file;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.URL;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
/**
* 文件操作帮助类
*
* @author yanglei
*/
@Slf4j
public class FileUtil {
/**
* 创建文件
*
* @param pathStr 路径
* @param fileName 文件名字
* @return File实例
*/
public static File createFile(String pathStr, String fileName) {
File path = new File(pathStr);
if (!path.exists()) {
path.mkdirs();
}
File file = new File(pathStr + "/" + fileName);
if (file.exists()) {
int dotIndex = fileName.lastIndexOf(".");
if (dotIndex != -1) {
file = new File(pathStr + "/" + fileName.substring(0, dotIndex) + System.currentTimeMillis()
+ fileName.substring(dotIndex, fileName.length()));
} else {
file = new File(pathStr + "/" + fileName + System.currentTimeMillis());
}
}
return file;
}
/**
* 创建目录
* 支持创建多级目录
*
* @param folderPath
*/
public static void newFolder(String folderPath) {
File myFilePath = new File(folderPath);
newFolder(myFilePath);
}
/**
* 创建目录
* 支持创建多级目录
*/
public static void newFolder(File myFilePath) {
try {
if (!myFilePath.exists()) {
myFilePath.mkdirs();
}
} catch (Exception e) {
log.error("新建目录操作出错", e);
}
}
/**
* 删除文件夹
*
* @return boolean
*/
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
File myFilePath = new File(folderPath);
myFilePath.delete(); //删除空文件夹
} catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}
}
/**
* 删除文件夹里面的所有文件
*
* @param path String 文件夹路径 如 c:/fqf
*/
public static void delAllFile(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
File temp = null;
for (String aTempList : tempList) {
if (path.endsWith(File.separator)) {
temp = new File(path + aTempList);
} else {
temp = new File(path + File.separator + aTempList);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + aTempList);//先删除文件夹里面的文件
delFolder(path + "/" + aTempList);//再删除空文件夹
}
}
}
/**
* 复制单个文件
*
* @param oldPath String 原文件路径 如:c:/fqf.txt
* @param newPath String 复制后路径 如:f:/fqf.txt
* @return boolean
*/
public static boolean copyFile(String oldPath, String newPath) {
boolean flag = false;
try {
int byteSum = 0;
int byteRead = 0;
File oldFile = new File(oldPath);
if (oldFile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteRead = inStream.read(buffer)) != -1) {
byteSum += byteRead; //字节数 文件大小
System.out.println(byteSum);
fs.write(buffer, 0, byteRead);
}
inStream.close();
flag = true;
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
return flag;
}
/**
* 复制整个文件夹内容
*
* @param oldPath String 原文件路径 如:c:/fqf
* @param newPath String 复制后路径 如:f:/fqf/ff
* @return boolean
*/
public static boolean copyFolder(String oldPath, String newPath) {
boolean flag = false;
try {
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (String aFile : file) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + aFile);
} else {
temp = new File(oldPath + File.separator + aFile);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()));
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {//如果是子文件夹
copyFolder(oldPath + "/" + aFile, newPath + "/" + aFile);
}
}
flag = true;
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
return flag;
}
/**
* 复制整个文件夹内容
*
* @param oldPath String 原文件路径 如:c:/fqf
* @param newPath String 复制后路径 如:f:/fqf/ff
* @param filterDir String 过滤目录名称
* @return boolean
*/
public static boolean copyFolder(String oldPath, String newPath, String filterDir) {
boolean flag = false;
try {
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (String aFile : file) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + aFile);
} else {
temp = new File(oldPath + File.separator + aFile);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()));
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {//如果是子文件夹
if (!aFile.equals(filterDir)) {
copyFolder(oldPath + "/" + aFile, newPath + "/" + aFile, filterDir);
}
}
}
flag = true;
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
return flag;
}
/**
* 移动文件到指定目录
*
* @param oldPath String 如:c:/fqf.txt
* @param newPath String 如:d:/fqf.txt
*/
public static boolean moveFile(String oldPath, String newPath) {
boolean flag = copyFile(oldPath, newPath);
if (flag) {
delFile(oldPath);
}
return flag;
}
/**
* 移动文件到指定目录
*
* @param oldPath String 如:c:/fqf.txt
* @param newPath String 如:d:/fqf.txt
*/
public static void moveFolder(String oldPath, String newPath) {
copyFolder(oldPath, newPath, null);
delFolder(oldPath);
}
public static void delFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else {
File[] files = file.listFiles();
for (File f : files) {
delFile(f);
}
file.delete();
}
}
}
public static void delFile(String path) {
delFile(new File(path));
}
/**
* copy 文件
*
* @param sourceFile
* @param targetFile
* @throws IOException
*/
public static void copyFile(File sourceFile, File targetFile) throws IOException {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
try {
// 新建文件输入流并对它进行缓冲
inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
// 新建文件输出流并对它进行缓冲
outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
} finally {
// 关闭流
if (inBuff != null) {
inBuff.close();
}
if (outBuff != null) {
outBuff.close();
}
}
}
/**
* @return
* @throws Exception
*/
public static File getFile(String fileName, String propertyName) throws Exception {
String filePath = null;
if (propertyName != null && !"".equals(propertyName)) {
filePath = System.getProperty(propertyName);
}
File file = null;
if (filePath == null || "".equals(filePath)) {
URL url = FileUtil.class.getClassLoader().getResource(propertyName + fileName);
if (url == null) {
throw new FileNotFoundException(fileName + " not found!");
}
file = new File(url.getPath());
} else {
filePath = filePath.endsWith("/") ? filePath.concat(fileName)
: filePath.concat("/").concat(fileName);
file = new File(filePath);
}
return file;
}
public static String getFilePath(String fileName, String propertyName) throws Exception {
String filePath = null;
if (propertyName != null && !"".equals(propertyName)) {
filePath = System.getProperty(propertyName);
}
if (filePath == null || "".equals(filePath)) {
URL url = FileUtil.class.getClassLoader().getResource(propertyName + fileName);
if (url == null) {
throw new FileNotFoundException(fileName + " not found!");
}
filePath = url.getPath();
} else {
filePath = filePath.endsWith("/") ? filePath.concat(fileName)
: filePath.concat("/").concat(fileName);
}
return filePath;
}
public static String getFileDir(String fileName, String propertyName) throws Exception {
String filePath = null;
if (propertyName != null && !"".equals(propertyName)) {
filePath = System.getProperty(propertyName);
}
if (filePath == null || "".equals(filePath)) {
URL url = FileUtil.class.getClassLoader().getResource(propertyName + fileName);
if (url == null) {
throw new FileNotFoundException(fileName + " not found!");
}
filePath = url.getPath();
filePath = filePath.replace(fileName, "");
} else {
filePath = filePath.endsWith("/") ? filePath.concat(fileName)
: filePath.concat("/").concat(fileName);
}
return filePath;
}
/**
* @param file
*/
public static String read(File file, String charset) {
final byte[] content = read(file);
return content == null ? "" : new String(content);
}
public static byte[] read(File file) {
if (!(file.exists() && file.isFile())) {
throw new IllegalArgumentException("The remote not exist or not a remote");
}
FileInputStream fis = null;
byte[] content = null;
try {
fis = new FileInputStream(file);
content = new byte[fis.available()];
fis.read(content);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
fis = null;
}
}
return content;
}
public static void write(String txtPath,String content){
FileOutputStream fileOutputStream=null;
File file=new File(txtPath);
try{
if(!file.exists()){
if(file.createNewFile()){
fileOutputStream=new FileOutputStream(file);
}
}else {
fileOutputStream = new FileOutputStream(file,true);
}
fileOutputStream.write(content.getBytes());
fileOutputStream.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if(fileOutputStream!=null) {
try {
fileOutputStream.close();
}catch (Exception e){}
}
}
}
/**
* 将saveProperties保存为文件
*
* @param filePath
* @param parameterName
* @param parameterValue
*/
public static void saveProperties(String filePath, String parameterName, String parameterValue) {
Properties prop = new Properties();
try {
InputStream fis = new FileInputStream(filePath);
prop.load(fis);
OutputStream fos = new FileOutputStream(filePath);
prop.setProperty(parameterName, parameterValue);
prop.store(fos, "Update '" + parameterName + "' value");
fis.close();
} catch (IOException e) {
System.err.println("Visit " + filePath + " for updating " + parameterName + " value error");
}
}
/**
*    * 删除单个文件
*    * @param filePath
*    * 文件目录路径
*    * @param fileName
*    * 文件名称
*    
*/
public static void deleteFile(String filePath, String fileName) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
for (File file1 : files) {
if (file1.isFile()) {
if (file1.getName().equals(fileName)) {
file1.delete();
return;
}
}
}
}
}
/**
* 流转byte数组
*
* @param input
* @return
* @throws IOException
*/
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
public static void main(String[] arr) {
// FileUtil.copyFolder("C:\\test\\source_data\\ptgui\\0100002\\2015\\10-02\\ptgui_project", "E:\\outputfile\\result_data\\ptgui\\0100002\\2015\\10-02\\ptgui_project", "task");
// String[] arr_ = new String[1];
// arr_[0] = "exe";
// String path = "D:\\opt\\share";
// List<Map<String,String>> mapList = FileUtil.listFileAll(path, null);
// for(Map<String,String> one:mapList){
// System.out.println(one.get("fileName") + "--" + one.get("path") + "---" + one.get("size")+ "---" + one.get("count")+ "---" + one.get("modified")+ "---" + one.get("fileDir"));
//
// }
//
// FileUtil.newFolder("e:/rr1/ee/qw/www/wwq/qqq");
// FileUtil.moveFile("e:/rr1/1111.txt","e:/rr1/ee/qw/www/wwq/qqq/1111.txt");
//
// String shareDir = "e:/ed/ed/r/d/";
// String filepath = "e:/ed/ed/r/d//frfr";
//
// shareDir = shareDir.replace("\\","/");
// filepath = filepath.replace("\\","/");
// StringBuffer tmp = new StringBuffer(filepath);
// tmp.insert(shareDir.length(),"/backupDir");
// String backupDir=tmp.toString();
// backupDir = backupDir.replace("//","/");
// System.out.println(backupDir);
FileUtil.write("d://1111.txt","wode\n");
FileUtil.write("d://1111.txt","wode\n");
FileUtil.write("d://1111.txt","wode\n");
FileUtil.write("d://1111.txt","wode\n");
}
/**
* 数据文件,返回文件内容
*
* @param path
* @return
*/
public static String readFile(String path) {
BufferedReader reader = null;
StringBuilder lastStr = new StringBuilder();
try {
FileInputStream fileInputStream = new FileInputStream(path);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
reader = new BufferedReader(inputStreamReader);
String tempString = null;
while ((tempString = reader.readLine()) != null) {
lastStr.append(tempString);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return lastStr.toString();
}
public static List<File> listFiles(File path) {
List<File> result = Lists.newLinkedList();
List<File> root = Lists.newLinkedList();
if (path.isDirectory()) {
root.addAll(Arrays.asList(path.listFiles()));
}
while (root.size() > 0) {
File file = root.remove(0);
if (file.isFile()) {
result.add(file);
} else {
root.addAll(Arrays.asList(file.listFiles()));
}
}
return result;
}
/**
* 获取某个文件总行数
*
* @param file
* @return
* @throws Exception
*/
public static int getFileLineNumber(File file) throws Exception {
int lineNumber;
try (LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(file))) {
lineNumberReader.skip(Long.MAX_VALUE);
lineNumber = lineNumberReader.getLineNumber();
lineNumber++;
} catch (Exception e) {
throw new Exception("getFileLineNumber has error");
}
return lineNumber;
}
/**
* 从文本末尾分页读取内容。
*
* @param file 一个文件对象。
* @param curPage 当前读取内容的页码号,文件从末尾开始读取,末尾所在页码为1。
* @param row 每次读取内容的行数。
* @return list 读取的文本内容集合。
* @throws IOException
*/
public static List<String> backwardReadLineByRange(File file, int curPage, int row) throws IOException {
LinkedList<String> list = null;
if (file == null) {
return list;
}
RandomAccessFile rafile = new RandomAccessFile(file, "r");
// 计算要读取的行号,从末行读取,所以起始行号为0。
int startRow = (curPage - 1) * row;
int endRow = curPage * row - 1;
// 当前行号。
int curRow = 0;
String line = null;
long length = rafile.length();
try {
if (length > 0) {
long p = length;
list = Lists.newLinkedList();
while (p-- > 0) {
// 定位指针
rafile.seek(p);
// 如果已经读取到文本末尾,则不再读取。
if (curRow > endRow) {
break;
}
if (rafile.readByte() == '\n') {
if (curRow >= startRow && curRow <= endRow) {
// 读取到换行符,这里是上一行的换行符,所以这用永远不会打印第一行内的内容。
line = rafile.readLine();
line = (line == null) ? "" : new String(line.getBytes("ISO-8859-1"), "UTF-8");
// 让末行添加至链表的
list.addFirst(line);
}
curRow++;
}
}
}
} catch (IOException e) {
throw new IOException(e);
} finally {
rafile.close();
}
return list;
}
}
package com.wanji.common.utils.file;
import com.sun.xfile.XFile;
import com.sun.xfile.XFileInputStream;
import com.sun.xfile.XFileOutputStream;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* 使用xfile访问nfs文件系统
*
* @author
* @date 2019/2/17
*/
@Slf4j
public class XFileUtils {
/**
* 主机ip
*/
private String ip;
/**
* 共享目录
*/
private String share;
public XFileUtils(String ip, String share) {
this.ip = ip;
this.share = share;
}
private String getBaseSharePath() {
String path = (ip + "/" + share + "/").replace("\\\\", "/").replace("//", "/");
return "nfs://" + path;
}
public String getRemoteDir(String relativePath) {
String dirPath = "";
String remoteRoot = this.getBaseSharePath();
relativePath = relativePath.replace("\\\\", "/");
if (relativePath.startsWith("/")) {
dirPath = remoteRoot + relativePath.substring(1);
} else {
dirPath = remoteRoot + relativePath;
}
return dirPath;
}
/**
* 在远程共享文件系统中创建文件夹(支持多级目录创建)
*
* @param filePath
* @throws Exception
*/
public boolean mkdirs(String filePath) throws Exception {
boolean flag = true;
try {
XFile xFile = new XFile(getRemoteDir(filePath));
if (!xFile.exists()) {
xFile.mkdirs();
log.error("创建成功!");
}
} catch (Exception e) {
flag = false;
log.error("创建目录失败!", e);
throw e;
}
return flag;
}
/**
* 判断文件或目录是否存在
*
* @param filePath
* @return
* @throws Exception
*/
public boolean exists(String filePath) throws Exception {
boolean flag = false;
try {
XFile xFile = new XFile(getRemoteDir(filePath));
if (xFile.exists()) {
flag = true;
}
} catch (Exception e) {
flag = false;
log.error("exists fails!", e);
throw e;
}
return flag;
}
/**
* 读取远程文件
*
* @param remoteFileName
* @return
* @throws Exception
*/
public InputStream readFileToInputStream(String remoteFileName) throws Exception {
try {
XFile file = new XFile(remoteFileName);
if (file.exists()) {
return new XFileInputStream(file);
} else {
log.debug("文件" + remoteFileName + "不存在");
return null;
}
} catch (Exception e) {
throw new Exception("create xFile Object exception by remoteFileName(" + remoteFileName + ")", e);
}
}
/**
* 读取远程文件
*
* @param remoteFileName
* @return
* @throws Exception
*/
public InputStream readFileToConvertInputStream(String remoteFileName) throws Exception {
try {
XFile file = new XFile(remoteFileName);
if (file.exists()) {
return new XFileInputStream(file);
} else {
log.debug("文件" + remoteFileName + "不存在");
return null;
}
} catch (Exception e) {
throw new Exception("create xFile Object exception by remoteFileName(" + remoteFileName + ")", e);
}
}
/**
* 将数据流写入到远程文件系统中
*
* @return
* @throws Exception
*/
public boolean writeInputStreamToFile(InputStream inputStream, String remotedir, String remoteFilename) throws Exception {
boolean isWriteSuccess = false;
String fileFullName = remotedir + "/" + remoteFilename;
XFileOutputStream xFileOutputStream = null;
try {
XFile file = new XFile(fileFullName);
if (file.exists()) {
file.delete();
} else {
XFile parent = new XFile(file.getParent());
if (!parent.exists()) {
parent.mkdirs();
}
}
xFileOutputStream = new XFileOutputStream(file);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
xFileOutputStream.write(buffer, 0, len);
}
isWriteSuccess = true;
} catch (Exception e) {
throw new Exception("create xFile exception,{fileFullName:" + fileFullName + "}," + e.getMessage(), e);
} finally {
if (inputStream != null) {
inputStream.close();
}
if (xFileOutputStream != null) {
xFileOutputStream.flush();
xFileOutputStream.close();
}
}
return isWriteSuccess;
}
/**
* 删除文件夹
*
* @param folderPath
* @throws Exception
*/
public boolean delFolder(String folderPath) throws Exception {
boolean flag = false;
try {
if (!folderPath.endsWith("/")) {
folderPath = folderPath + "/";
}
XFile xFile = new XFile(folderPath);
if (xFile.exists()) {
if (xFile.isDirectory()) {
String[] paths = xFile.list();
for (String path : paths) {
String childPath = folderPath + path;
this.delFolder(childPath);
}
}
xFile.delete();
}
flag = true;
} catch (Exception e) {
throw new Exception("delete directory exception," + e.getMessage(), e);
}
return flag;
}
/**
* 删除文件
*
* @param fullRemoteFileName
* @return
* @throws Exception
*/
public boolean delRemoteFile(String fullRemoteFileName) throws Exception {
boolean flag = false;
try {
XFile file = new XFile(fullRemoteFileName);
if (file.exists()) {
file.delete();
}
flag = true;
} catch (Exception e) {
throw new Exception("deleted remote exception by fileName(" + fullRemoteFileName + ")," + e.getMessage(), e);
}
return flag;
}
public boolean delFile(String fullRemoteFileName) throws Exception {
boolean flag = false;
try {
XFile file = new XFile(fullRemoteFileName);
flag = file.delete();
} catch (Exception e) {
throw new Exception("deleted remote exception by fileName(" + fullRemoteFileName + ")," + e.getMessage(), e);
}
return flag;
}
/**
* 下载远程文件至本地
*
* @param localFilePath
* @param remoteDir
* @return
* @throws Exception
*/
public boolean downloadToLocal(String localFilePath, String remoteDir) throws Exception {
boolean flag = true;
try {
XFile xFile = new XFile(remoteDir);
if (!xFile.exists()) {
flag = false;
throw new Exception("remote file[" + remoteDir + "] does't exist");
}
XFileInputStream inputStream = new XFileInputStream(xFile);
File file=new File(localFilePath);
if(!file.exists()){
file.getParentFile().mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(file);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
flag = false;
throw new Exception("download remote(" + remoteDir + ") to local" + localFilePath + " path exception," + e.getMessage(), e);
}
return flag;
}
public boolean renameName(String oldName, String newName) {
XFile xFile = new XFile(getRemoteDir(oldName));
XFile newFile = new XFile(getRemoteDir(newName));
boolean b = xFile.renameTo(newFile);
return b;
}
/**
* 传入文件路径 将文件转为字节
*
* @param filePath
* @return
* @throws Exception
*/
public byte[] readFileToBytes(String filePath) throws Exception {
byte[] bytes = null;
try {
XFile file = new XFile(filePath);
if (file.exists()) {
XFileInputStream xFileInputStream = new XFileInputStream(file);
bytes = inputStreamToBytes(xFileInputStream);
} else {
log.debug("文件" + filePath + "不存在");
return null;
}
} catch (Exception e) {
throw new Exception("create xFile Object exception by remoteFileName(" + filePath + ")", e);
}
return bytes;
}
/**
* 将流转为字节
*
* @param inStream
* @return
* @throws Exception
*/
public static byte[] inputStreamToBytes(InputStream inStream) throws Exception {
byte[] bytes = null;
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
bytes = swapStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage(), e);
}
return bytes;
}
/**
* 将字节流数据写入到远程文件系统中
*
* @param bytes
* @return
* @throws Exception
*/
public boolean writeByteArrayToFile(byte[] bytes, String remoteDir, String remoteName) throws Exception {
InputStream in = byteToInputStream(bytes);
return writeInputStreamToFile(in, remoteDir, remoteName);
}
/**
* 字节转换InputStream
*
* @param in
* @return
*/
public static InputStream byteToInputStream(byte[] in) throws Exception {
ByteArrayInputStream is = new ByteArrayInputStream(in);
return is;
}
public static void main(String[] args) throws Exception {
XFileUtils xFileUtils = new XFileUtils("10.10.1.86", "/data/share/business/actionA/");
boolean b = xFileUtils.downloadToLocal("/opt/bussinsess/ActionA-1.0.0.jar", xFileUtils.getRemoteDir("ActionA-1.0.0.jar"));
System.out.println(b);
}
}
package com.wanji.common.utils.geo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wanji.common.tool.estool.EsUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.toilelibre.libe.curl.Curl.curl;
import static org.toilelibre.libe.curl.Curl.$;
/**
* GeoWebCache帮助类
* @author guoliang.dong@mapabc.com
*/
@Slf4j
public class GeoWebCacheUtils {
private String geoUrl;
private String geoUsername;
private String geoPassword;
private static GeoWebCacheUtils geoWebCacheUtils = null;
public static GeoWebCacheUtils getGeoServerRESTManager(String url,String username,String password) {
if (geoWebCacheUtils == null) {
geoWebCacheUtils = new GeoWebCacheUtils(url,username,password);
}
return geoWebCacheUtils;
}
public GeoWebCacheUtils(String url,String username,String password){
geoUrl=url;
geoUsername=username;
geoPassword=password;
}
/**
* 新增工作空间
*
* @param workspace 工作空间名
* @return boolean
*/
public boolean addWorkspace(String workspace) {
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -XPOST -H \"Content-type: text/xml\"\n" +
" -d \"<workspace><name>" + workspace + "</name></workspace>\"\n" +
" " + geoUrl + "/rest/workspaces";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==201;
}
/**
* 创建外存储geotiff
*
* @param workspace
* @param store
* @return
*/
public boolean addExternalGeotiffStore(String workspace ,String store,String fileurl){
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -XPUT -H \"Content-type: text/plain\"\n" +
" -d \"file://"+fileurl+"\"\n" +
" " + geoUrl + "/rest/workspaces/" + workspace + "/coveragestores/"+store+"/external.geotiff?configure=first&coverageName="+store;
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==201;
}
/**
* 获取geoWebCache中的图层
*
* @return Map
*/
public Map<String, Object> getLayers() {
Map<String, Object> map = new HashMap();
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " \"" + geoUrl + "/gwc/rest/layers\"";
List<String> shp = new ArrayList<>();
List<String> image = new ArrayList<>();
HttpResponse curl = curl(cmd);
HttpEntity entity = curl.getEntity();
if (entity != null) {
String result = null;
try {
result = EntityUtils.toString(entity, "UTF-8");
JSONArray jsonArray = JSONArray.parseArray(result);
for (Object o : jsonArray) {
String str = o.toString();
map.put(str,o);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
/**
*
*
* @param layer
* @param zoomStart
* @param zoomStop
* @return boolean
*/
/**
* 指定图层进行切片操作
* @param layer 指定图层 shp:test
* @param type * seed (add tiles) * reseed (replace tiles) * truncate (remove tiles)
* @param srs 坐标系srid
* @param zoomStart 1 切片开始层级
* @param zoomStop 15 切片结束层级
* @return
*/
public boolean slice(String layer, String type,int srs,int zoomStart, int zoomStop,String gridSetId) {
int threadCount = 2;
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " \"" + geoUrl + "/gwc/rest/seed/"+layer+".xml\""+ " -XPOST -H \"Content-type: text/xml\" -d '<seedRequest><name>" + layer +
"</name><srs><number>"+srs+"</number></srs><zoomStart>" + zoomStart + "</zoomStart><zoomStop>" + zoomStop + "</zoomStop><format>image/png</format><type>"+type+"</type><threadCount>" + threadCount + "</threadCount><gridSetId>"+gridSetId+"</gridSetId></seedRequest>' \""
+ geoUrl + "/gwc/rest/seed/" + layer + ".xml\"";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==200;
}
/**
* 获取切片的情况
*
* @param layer 指定图层
* @return Map
*/
public Map getSliceType(String layer) {
Map map = new HashMap();
//返回所有图层切片情况 curl -u <user>:<password> -XGET http://localhost:8080/geoserver/gwc/rest/seed.json
//返回指定图层的切片情况
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -XGET " + geoUrl + "/gwc/rest/seed/" + layer + ".json";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
if (statusLine.getStatusCode()==200) {
HttpEntity entity = curl.getEntity();
try {
String result = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonArray = JSONObject.parseObject(result);
map.put("res", jsonArray.getJSONArray("long-array-array"));
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
/**
* 停止所有正在进行的切片任务
*
* @return boolean
*/
public boolean stopAllSlice() {
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -d \"kill_all=all\" \"" + geoUrl + "/gwc/rest/seed\"";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==200;
}
/**
* 停止指定图层的切片任务
*
* @return boolean
*/
public boolean stopSliceByLayer(String layer) {
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -d \"kill_all=all\" \"" + geoUrl + "/gwc/rest/seed/" + layer + "\"";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==200;
}
public static void main(String[]args){
GeoWebCacheUtils geoServerRESTManager=GeoWebCacheUtils.getGeoServerRESTManager("http://127.0.0.1:8080/geoserver","admin","geoserver");
//System.out.println(geoServerRESTManager.addWorkspace("zhangwei"));
//Map<String, Object> layers=geoServerRESTManager.getLayers();
//System.out.println("图层数:"+layers.size());
//System.out.println(layers);
System.out.println(geoServerRESTManager.slice("sf:result8","seed",4326,14,14,"My_EPSG:4326"));
//System.out.println(geoServerRESTManager.stopSliceByLayer("gisc_3f0786e36794%3Apoi"));
//System.out.println(geoServerRESTManager.getSliceType("gisc_3f0786e36794%3Apoi"));
//System.out.println(geoServerRESTManager.getSliceType("gisc_3f0786e36794%3Apoi"));
//System.out.println(geoServerRESTManager.stopAllSlice());
//System.out.println(geoServerRESTManager.addExternalGeotiffStore("sf","result8","D:/ProgramData/GeoServer/data/sf/result8/result.tif"));
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
package com.wanji.common.utils.licenseUtils;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class AESUtils {
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
private static final String ALGORITHM_AES = "AES";
private static final int DIGIT_AES = 128; // AES加密位数
private static final String ENCONDING_TAG = "UTF-8";
private static KeyGenerator keyGen;
private static Cipher cipher;
static boolean isInited = false;
private static void init() {
try {
/**
* 为指定算法生成一个 KeyGenerator 对象。 此类提供(对称)密钥生成器的功能。 密钥生成器是使用此类的某个 getInstance 类方法构造的。
* KeyGenerator 对象可重复使用,也就是说,在生成密钥后, 可以重复使用同一 KeyGenerator 对象来生成进一步的密钥。
* 生成密钥的方式有两种:与算法无关的方式,以及特定于算法的方式。 两者之间的惟一不同是对象的初始化: 与算法无关的初始化 所有密钥生成器都具有密钥长度 和随机源 的概念。
* 此 KeyGenerator 类中有一个 init 方法,它可采用这两个通用概念的参数。 还有一个只带 keysize 参数的 init 方法,
* 它使用具有最高优先级的提供程序的 SecureRandom 实现作为随机源 (如果安装的提供程序都不提供 SecureRandom 实现,则使用系统提供的随机源)。 此
* KeyGenerator 类还提供一个只带随机源参数的 inti 方法。 因为调用上述与算法无关的 init 方法时未指定其他参数,
* 所以由提供程序决定如何处理将与每个密钥相关的特定于算法的参数(如果有)。 特定于算法的初始化 在已经存在特定于算法的参数集的情况下, 有两个具有
* AlgorithmParameterSpec 参数的 init 方法。 其中一个方法还有一个 SecureRandom 参数, 而另一个方法将已安装的高优先级提供程序的
* SecureRandom 实现用作随机源 (或者作为系统提供的随机源,如果安装的提供程序都不提供 SecureRandom 实现)。 如果客户端没有显式地初始化
* KeyGenerator(通过调用 init 方法), 每个提供程序必须提供(和记录)默认初始化。
*/
keyGen = KeyGenerator.getInstance(ALGORITHM_AES);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 初始化此密钥生成器,使其具有确定的密钥长度。
keyGen.init(DIGIT_AES); // 128位的AES加密
try {
// 生成一个实现指定转换的 Cipher 对象。
cipher = Cipher.getInstance(ALGORITHM_STR);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
// 标识已经初始化过了的字段
isInited = true;
}
private static byte[] genKey() {
if (!isInited) {
init();
}
// 首先 生成一个密钥(SecretKey),
// 然后,通过这个秘钥,返回基本编码格式的密钥,如果此密钥不支持编码,则返回 null。
return keyGen.generateKey().getEncoded();
}
private static byte[] encrypt(byte[] content, byte[] keyBytes) {
byte[] encryptedText = null;
if (!isInited) {
init();
}
/**
* 类 SecretKeySpec 可以使用此类来根据一个字节数组构造一个 SecretKey, 而无须通过一个(基于 provider 的)SecretKeyFactory。
* 此类仅对能表示为一个字节数组并且没有任何与之相关联的钥参数的原始密钥有用 构造方法根据给定的字节数组构造一个密钥。 此构造方法不检查给定的字节数组是否指定了一个算法的密钥。
*/
Key key = new SecretKeySpec(keyBytes, ALGORITHM_AES);
try {
// 用密钥初始化此 cipher。
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
try {
// 按单部分操作加密或解密数据,或者结束一个多部分操作。(不知道神马意思)
encryptedText = cipher.doFinal(content);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return encryptedText;
}
private static byte[] encrypt(String content, String password) {
try {
byte[] keyStr = getKey(password);
SecretKeySpec key = new SecretKeySpec(keyStr, ALGORITHM_AES);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // algorithmStr
byte[] byteContent = content.getBytes(ENCONDING_TAG);
cipher.init(Cipher.ENCRYPT_MODE, key); // ʼ
byte[] result = cipher.doFinal(byteContent);
return result; //
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
private static byte[] decrypt(byte[] content, String password) {
try {
byte[] keyStr = getKey(password);
SecretKeySpec key = new SecretKeySpec(keyStr, ALGORITHM_AES);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // algorithmStr
cipher.init(Cipher.DECRYPT_MODE, key); // ʼ
byte[] result = cipher.doFinal(content);
return result; //
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
private static byte[] getKey(String password) {
byte[] rByte = null;
if (password != null) {
rByte = password.getBytes();
} else {
rByte = new byte[24];
}
return rByte;
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
// 注意: 这里的password(秘钥必须是16位的)
private static final String keyBytes = "vpa003icoreaims#";
/** 加密 */
public static String encode(String content, String key) {
// 加密之后的字节数组,转成16进制的字符串形式输出
return parseByte2HexStr(encrypt(content, key));
}
/** 解密 */
public static byte[] decode(String content, String key) {
// String decryptCode = null;
// 解密之前,先将输入的字符串按照16进制转成二进制的字节数组,作为待解密的内容输入
return decrypt(parseHexStr2Byte(content), key);
// try {
// decryptCode= new String(res, Constants.UTF8_ENCODING);
// } catch (UnsupportedEncodingException e) { }
// return decryptCode;
}
public static void main(String[] args) {
String content = "Y" + "," + "420FC7FC-1616-3382-0D20-664AE5A7CDD3" + "," + "20301218";
String encodeStr = encode("X,bill,2020-08-07", keyBytes);
System.out.print(encodeStr);
}
}
package com.wanji.common.utils.licenseUtils;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
/**
* 授权加密解密工具类,做成授权工具的话,主要就是用的这个类
*/
public class DESUtils {
/**
* 密钥
*/
public static final String DEFAULT_KEY = "BOTWAVEE";
public static String decrypt(String message) throws Exception {
return java.net.URLDecoder.decode(decrypt(message, DEFAULT_KEY), "utf-8");
}
/**
* 解密
* @param message 加密后的内容
* @param key 密钥
* @return
* @throws Exception
*/
public static String decrypt(String message, String key) throws Exception {
byte[] bytesrc = convertHexString(message);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte);
}
public static String encrypt(String message) throws Exception{
return toHexString(encrypt(message, DEFAULT_KEY)).toUpperCase();
}
/**
* 加密
*
* @param message
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(String message, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return cipher.doFinal(message.getBytes("UTF-8"));
}
public static byte[] convertHexString(String ss) {
byte digest[] = new byte[ss.length() / 2];
for (int i = 0; i < digest.length; i++) {
String byteString = ss.substring(2 * i, 2 * i + 2);
int byteValue = Integer.parseInt(byteString, 16);
digest[i] = (byte) byteValue;
}
return digest;
}
public static void main(String[] args) throws Exception {
String key = "BOTWAVEE";
String jiami = "znxd,000000,7005-459C,2018-07-27,2022-02-02";
System.out.println("加密数据:" + jiami);
// Byte a = encrypt(jiami,key);
System.out.println("加密后的数据为:" + encrypt(jiami,key));
String b =decrypt(new String(encrypt(jiami,key)));
System.out.println("解密后的数据:" + b);
}
public static String toHexString(byte b[]) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String plainText = Integer.toHexString(0xff & b[i]);
if (plainText.length() < 2)
plainText = "0" + plainText;
hexString.append(plainText);
}
return hexString.toString();
}
}
package com.wanji.common.utils.licenseUtils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/** Created by JAVA on 2018/7/24. */
public class DateUtils {
public static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
public static boolean authorize_date(String date) {
TimeZone tz = TimeZone.getTimeZone("ETC/GMT-8");
TimeZone.setDefault(tz);
String currentTime = DateUtils.formatter.format(new Date());
if (compare_date(currentTime, date) >= 0) {
return true;
}
return false;
}
public static int compare_date(String date1, String date2) {
DateFormat df = new SimpleDateFormat("yyyyMMdd");
try {
Date dt1 = df.parse(date1);
Date dt2 = df.parse(date2);
if (dt1.getTime() < dt2.getTime()) {
// System.out.println("dt1 在dt2前");
return 1;
} else if (dt1.getTime() > dt2.getTime()) {
// System.out.println("dt1在dt2后");
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static void main(String[] args) {
System.out.println(authorize_date("20200807"));;
}
}
package com.wanji.common.utils.licenseUtils;
import java.io.*;
/**
* Created by JAVA on 2018/7/24.
*/
public class EncoderFile {
// public static void main(String[] args) throws FileNotFoundException {
// File cfgFile =new File("d:/license/encoder.txt");
// if(!cfgFile.exists()){
// cfgFile.getParentFile().mkdirs();
// try {
// cfgFile.createNewFile();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// String string = "znxd,100000,PF0AQGM7,"+ DateUtils.currenttime+",2022-02-02";
// System.out.println(string);
// try {
// string = DESUtils.encrypt(string);
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// write(cfgFile,string);
//
// String line = read(cfgFile);
//
// System.out.println(line);
//
// try {
// System.out.println(DESUtils.decrypt(line));
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
// public static void write(File cfgFile ,String write){
// File file = cfgFile; //1、建立连接
// OutputStream os = null;
// try {
// //2、选择输出流,以追加形式(在原有内容上追加) 写出文件 必须为true 否则为覆盖
// os = new FileOutputStream(file);
//// //和上一句功能一样,BufferedInputStream是增强流,加上之后能提高输出效率,建议
//// os = new BufferedOutputStream(new FileOutputStream(file,true));
//
// byte[] data = write.getBytes(); //将字符串转换为字节数组,方便下面写入
//
// os.write(data, 0, data.length); //3、写入文件
// os.flush(); //将存储在管道中的数据强制刷新出去
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// System.out.println("文件没有找到!");
// } catch (IOException e) {
// e.printStackTrace();
// System.out.println("写入文件失败!");
// }finally {
// if (os != null) {
// try {
// os.close();
// } catch (IOException e) {
// e.printStackTrace();
// System.out.println("关闭输出流失败!");
// }
// }
// }
// }
public static String read(File cfgFile ){
StringBuilder sb = new StringBuilder();
try {
// 读取字符文件
BufferedReader in = new BufferedReader(new FileReader(cfgFile));
// 为什么单独在这里加上try块而不是直接使用外边的try块?
// 需要考虑这么一种情况,如果文件没有成功打开,则finally关闭文件会出问题
try {
String s;
while ((s = in.readLine()) != null) {
sb.append(s + "\n");
}
}finally{
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
package com.wanji.common.utils.licenseUtils;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
@Slf4j
public class HardWareUtils {
//安全性考虑,构造方法私有化
private HardWareUtils() {}
/**
* @Description: 获取当前操作系统名称
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 17:45
**/
public static String getOSName() {
return System.getProperty("os.name").toLowerCase();
}
/**
* @Description: 判断当前操作系统
*
* @return boolean,true-unix系统,false,其他,本工具类内其他会按照windows系统处理
* @Author mapabc
* @Date 2020/7/28 17:47
**/
public static boolean isUnixOs() {
System.out.println(getOSName());
return getOSName().contains("linux")||getOSName().contains("mac")||getOSName().contains("unix");
}
/**
* @Description: 获取主板序列号,windows实现
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 17:53
**/
public static String getDosMotherboardSN() throws IOException {
StringBuffer result = new StringBuffer();
String vbs =
"Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
exeDosCmd(vbs).forEach(item -> {
if (Objects.nonNull(item) && StringUtils.isNotBlank(item.toString()))
result.append(item.toString().trim());
});
return result.toString();
}
/**
* @Description: 获取unix系统 主板序列号
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 20:26
**/
public static String getUnixMotherboardSN() throws IOException {
StringBuffer stringBuffer = new StringBuffer();
String maniBordCmd = "dmidecode | grep 'Serial Number' | awk '{print $3}' | tail -1";
exeShellCmd(maniBordCmd).forEach(item -> {
if (Objects.nonNull(item) && StringUtils.isNotBlank(item.toString())) {
stringBuffer.append(item.toString());
}
});
return stringBuffer.toString();
}
/**
* @Description: 获取unix系统 cpu序列号
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 19:41
**/
public static String getUnixCPUSerial() throws IOException {
StringBuffer result = new StringBuffer();
exeShellCmd("dmidecode").forEach(item -> {
if (Objects.nonNull(item) &&
StringUtils.isNotBlank(item.toString()) &&
StringUtils.containsIgnoreCase(item.toString(), "uuid")) {
result.append(StringUtils.substringAfter(item.toString(), "uuid").trim());
}
});
return result.toString();
}
/**
* @Description: 执行unix shell脚本
*
* @param cmd 命令
* @return java.util.List<java.lang.Object>
* @Author mapabc
* @Date 2020/7/28 20:30
**/
private static List<Object> exeShellCmd(String cmd) throws IOException {
List<Object> result;
Process p;
p = Runtime.getRuntime().exec(new String[] { "sh", "-c", cmd }); //管道
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
result = Arrays.asList(bufferedReader.lines().toArray());
bufferedReader.close();
return result;
}
/**
* @Description: 执行dos脚本
*
* @param cmd 命令
* @return java.util.List<java.lang.Object>
* @Author mapabc
* @Date 2020/7/28 20:25
**/
private static List<Object> exeDosCmd(String cmd) throws IOException {
List<Object> result;
File file = File.createTempFile("tmp", ".vbs");
file.deleteOnExit();
FileWriter fw = new FileWriter(file);
fw.write(cmd);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
result = Arrays.asList(input.lines().toArray());
input.close();
file.delete();
return result;
}
/**
* @Description: 获取CPU序列号
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 17:53
**/
public static String getDosCPUSerial() throws IOException {
StringBuffer result = new StringBuffer();
String vbs =
"Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_Processor\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.ProcessorId \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
exeDosCmd(vbs).forEach(item -> {
if (Objects.nonNull(item) && StringUtils.isNotBlank(item.toString()))
result.append(item.toString().trim());
});
return result.toString();
}
/**
* @Description: 获取MAC地址,多网卡环境存在计算不准的问题
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 19:46
**/
public static String getMac() {
try {
byte[] mac =
NetworkInterface.getByInetAddress(InetAddress.getLocalHost())
.getHardwareAddress();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mac.length; i++) {
if (i != 0) {
sb.append("-");
}
String s = Integer.toHexString(mac[i] & 0xFF);
sb.append(s.length() == 1 ? 0 + s : s);
}
return sb.toString().toUpperCase();
} catch (Exception e) {
return "";
}
}
/**
* @Description: 获取主板序列号,支持unix和dos系统
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 20:25
**/
public static String getMotherboardSN() throws IOException {
return isUnixOs() ? getUnixMotherboardSN() : getDosMotherboardSN();
}
/**
* @Description: 获取cpu序列号,支持unix和dos系统
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 20:24
**/
public static String getCPUSerial() throws IOException {
return isUnixOs() ? getUnixCPUSerial() : getDosCPUSerial();
}
public static void main(String[] args) throws IOException {
System.out.println("CPU SN: " + HardWareUtils.getCPUSerial());
System.out.println("主板 SN: " + HardWareUtils.getMotherboardSN());
System.out.println("MAC SN: " + HardWareUtils.getMac());
try {
System.out.println(DESUtils.encrypt(HardWareUtils.getCPUSerial() + "," + HardWareUtils.getMotherboardSN() +","+ HardWareUtils.getMac() +","+ "2020-08-05 23:59:59"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Author mapabc
* @Description 获取机器码
* @Date 18:49 2020/8/3
* @Param []
* @return java.lang.String
* @throws
*/
public static String getMachineCode() throws IOException{
return getCPUSerial() + "-" + getMotherboardSN() ;
}
}
package com.wanji.common.utils.mail;
import com.wanji.common.framework.rest.JsonViewObject;
import com.wanji.common.utils.tool.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.mail.Session;
import java.util.Map;
import java.util.Properties;
/**
* @ClassName MailUtils
* @Description 邮件工具类
* @Author mapabc7
* @Date 2020/5/29 13:44
* @Version 1.0
*/
@Slf4j
public class MailUtils {
/**
* @return void
* @throws
* @Author mapabc7
* @Description 邮件发送
* @Date 13:57 2020/5/29
* @Param [m2AMail, map]
*/
public static JsonViewObject sendSimpleMail(Map<String, Object> map) {
JsonViewObject jsonViewObject = JsonViewObject.newInstance();
// 发送器
JavaMailSenderImpl sender = new JavaMailSenderImpl();
try {
sender.setHost((String) map.get("server"));
sender.setPort(Integer.parseInt(map.get("port").toString()));
sender.setUsername((String) map.get("user"));
sender.setPassword((String) map.get("pwd"));
} catch (Exception e) {
log.error("邮件发送器装配异常", e);
return jsonViewObject.fail("邮件发送器装配异常");
}
// 配置文件对象
try {
Properties props = new Properties();
props.put("mail.smtp.auth", map.get("ssl")); // 是否进行验证
Session session = Session.getInstance(props);
sender.setSession(session); // 为发送器指定会话
} catch (Exception e) {
log.error("文件对象装配异常", e);
return jsonViewObject.fail("文件对象装配异常");
}
SimpleMailMessage mail = new SimpleMailMessage();
try {
String addressee = String.valueOf(map.get("addressee")); // 收件人
String[] split = addressee.split(";");
mail.setTo(split);
//todo 完善抄送,密送
mail.setSubject(String.valueOf(map.get("title"))); // 标题
String senderMailAddr = (String) map.get("defaultSender");
if (map.containsKey("sender") && StringUtils.isNotBlank((String) map.get("sender"))) {
senderMailAddr = String.valueOf(map.get("sender"));
}
mail.setFrom(senderMailAddr); // 发件人
mail.setText(String.valueOf(map.get("message"))); // 邮件内容
} catch (Exception e) {
log.error("邮件信息装配异常", e);
return jsonViewObject.fail("邮件信息装配异常");
}
try {
sender.send(mail); // 发送
log.info("邮件发送成功");
jsonViewObject.success("邮件发送成功");
} catch (Exception e) {
log.error("邮件发送异常", e);
jsonViewObject.fail("邮件发送异常");
}
return jsonViewObject;
}
}
package com.wanji.common.utils.tool;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName BeanListUtils
* @Description
* @Author mapabc7
* @Date 2020/6/30 17:54
* @Version 1.0
*/
public class BeanListUtils {
public static <T> ArrayList beanToList(T bean) throws NoSuchFieldException, IllegalAccessException {
ArrayList<String> list = new ArrayList<String>();
if (bean == null)
return null;
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
Field f = bean.getClass().getDeclaredField(field.getName());
f.setAccessible(true);
Object o = f.get(bean);
list.add(o.toString());
}
return list;
}
/**
*
* 将dto和entity之间的属性互相转换,dto中属性一般为String等基本类型,
* 但是entity中可能有复合主键等复杂类型,需要注意同名问题
* @param src
* @param target
*/
public static Object populate(Object src, Object target) {
Method[] srcMethods = src.getClass().getMethods();
Method[] targetMethods = target.getClass().getMethods();
for (Method m : srcMethods) {
String srcName = m.getName();
if (srcName.startsWith("get")) {
try {
Object result = m.invoke(src);
for (Method mm : targetMethods) {
String targetName = mm.getName();
if (targetName.startsWith("set")
&& targetName.substring(3, targetName.length())
.equals(srcName.substring(3, srcName.length()))) {
mm.invoke(target, result);
}
}
} catch (Exception e) {
}
}
}
return target;
}
/**
*
* dto集合和实体类集合间的互相属性映射
*
* @param src
* @param target
* @param targetClass
* @return
*/
@SuppressWarnings("unchecked")
public static <S, T> List<T> populateList(List<S> src, List<T> target, Class<?> targetClass) {
for (int i = 0; i < src.size(); i++) {
try {
Object object = targetClass.newInstance();
target.add((T) object);
populate(src.get(i), object);
} catch (Exception e) {
continue;// 某个方法反射异常
}
}
return target;
}
}
package com.wanji.common.utils.tool;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.cglib.beans.BeanMap;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @ClassName BeanMapUtils
* @Description 用于Map和domain类的相互转换,比fastjson效率高
* @Author ${mapabc}
* @Date 2020/6/19 13:42
* @Version 1.0
*/
public class BeanMapUtils {
private static Pattern linePattern = Pattern.compile("_(\\w)");
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/** 下划线转驼峰 */
public static String lineToHump(String str) {
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/** 驼峰转下划线 */
public static String humpToLine(String str) {
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 将对象装换为map
* @param bean
* @return
*/
public static <T> Map<String, Object> beanToMap(T bean) {
Map<String, Object> map = Maps.newHashMap();
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key+"", beanMap.get(key));
}
}
return map;
}
/**
* 将map装换为javabean对象 TODO bug 待处理,将map对象转换为bean时,如果属性中首字母为大写会转换不过去,待处理
* @param map
* @param clazz
* @return
*/
/*public static <T> T mapToBean(Map<String, Object> map,T bean) {
BeanMap beanMap = BeanMap.create(bean);
beanMap.putAll(map);
return bean;
}*/
public static <T> T mapToBean(Map<String, Object> map,Class<T> clazz) throws Exception {
T bean = null;
try {
bean = clazz.newInstance();
for (Field field : getAllFields(clazz)) {
if (map.containsKey(humpToLine(field.getName()))) {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object object = map.get(humpToLine(field.getName()));
if (object != null) {
if (field.getType().isAssignableFrom(object.getClass())) {
field.set(bean, object);
} else {
//判断属性类型 进行转换,map中存放的是Object对象需要转换 实体类中有多少类型就加多少类型,实体类属性用包装类;
if (field.getType().toString().contains("Long")) {
field.set(bean, Long.parseLong(object.toString()));
}
if (field.getType().toString().contains("String")) {
field.set(bean, object.toString());
}
if (field.getType().toString().contains("Integer")) {
field.set(bean, Integer.parseInt(object.toString()));
}
if (field.getType().toString().contains("Float")) {
field.set(bean, Float.valueOf(object.toString()));
}
//处理LocalDateTime类型
/*if (field.getType().toString().contains("LocalDateTime")) {
field.set(bean, stringConvertLocalDateTime(object.toString()));
}*/
}
}
field.setAccessible(flag);
}
}
return bean;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return bean;
}
/**
* 获取自身和上一级父类属性
* @param clazz
* @param <T>
* @return
*/
public static <T> Field[] getAllFields(Class<T> clazz){
List<Field> fieldList = new ArrayList<>();
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
if(clazz.getSuperclass()!=null){
//写死的 取一层父类 TODO 没有好的解决方案
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getSuperclass().getDeclaredFields())));
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
public static void main(String[] args) {
Map map = new HashMap();
map.put("resName","1111");
map.put("resType","123");
// mapToBean(map,new OperationLog)
//// String indexName = map.get("indexName").toString();
//// String typeName = map.get("typeName").toString();
}
/**
* 将List<T>转换为List<Map<String, Object>>
* @param objList
* @return
*
*/
public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
List<Map<String, Object>> list = Lists.newArrayList();
if (objList != null && objList.size() > 0) {
Map<String, Object> map = null;
T bean = null;
for (int i = 0,size = objList.size(); i < size; i++) {
bean = objList.get(i);
map = beanToMap(bean);
list.add(map);
}
}
return list;
}
/**
* 将List<Map<String,Object>>转换为List<T>
* @param maps
* @param clazz
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps,Class<T> clazz) throws Exception {
List<T> list = Lists.newArrayList();
if (maps != null && maps.size() > 0) {
Map<String, Object> map = null;
T bean = null;
for (int i = 0,size = maps.size(); i < size; i++) {
map = maps.get(i);
bean = mapToBean(map, clazz);
list.add(bean);
}
}
return list;
}
}
package com.wanji.common.utils.tool;
import org.apache.commons.lang3.StringUtils;
public class CamelUnderlineUtil {
private static final char UNDERLINE ='_';
public static String camelToUnderline(String param) {
if (StringUtils.isEmpty(param)) {
return "";
}
StringBuilder sb = new StringBuilder();
int len = param.length();
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(UNDERLINE);
sb.append(Character.toLowerCase(c));
} else {
sb.append(c);
}
}
return sb.toString();
}
public static String underlineToCamel(String param){
if (StringUtils.isEmpty(param)) {
return "";
}
StringBuilder sb = new StringBuilder();
int len = param.length();
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (c==UNDERLINE) {
if(++i<len){
sb.append(Character.toUpperCase(param.charAt(i)));
}
} else {
sb.append(c);
}
}
return sb.toString();
}
}
\ No newline at end of file
package com.wanji.common.utils.tool;
import java.math.BigInteger;
import java.util.Stack;
/**
* @author hfx
* @date 2023/1/16 15:45
* @desc ConvertBaseUtils
*/
public class ConvertBaseUtils {
private static final String TARGET_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final char[] chs = TARGET_STR.toCharArray();
private static final BigInteger INTEGER0 = new BigInteger("0");
private static final Integer SHIFT = 5;
private static final Integer RADIX32 = 32;
/**
* 基数转换32进制,不足五位,补齐五位字符
* @param number
* @return
*/
public static String numToRadix32(long number) {
String buf = numToRadix(number +"", RADIX32);
if(buf.length() < SHIFT) {
int num = SHIFT - buf.length();
for(int i = 0; i < num; i++) {
buf = "0" + buf;
}
}
return buf;
}
/**
* 10进制转任意进制
* @param number
* @param radix
* @return
*/
public static String numToRadix(String number, int radix) {
if (radix < 0 || radix > TARGET_STR.length()) {
radix = TARGET_STR.length();
}
BigInteger bigNumber = new BigInteger(number);
BigInteger bigRadix = new BigInteger(radix + "");
Stack<Character> stack = new Stack<>();
StringBuilder result = new StringBuilder(0);
while (!bigNumber.equals(INTEGER0)) {
stack.add(chs[bigNumber.remainder(bigRadix).intValue()]);
bigNumber = bigNumber.divide(bigRadix);
}
for (; !stack.isEmpty(); ) {
result.append(stack.pop());
}
return result.length() == 0 ? "0" : result.toString();
}
}
package com.wanji.common.utils.tool;
import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @ClassName CsvUtils
* @Description
* @Author mapabc7
* @Date 2020/7/15 11:44
* @Version 1.0
*/
@Slf4j
public class CsvUtils {
private static String split = ",";
/**
* @return void
* @throws
* @Author mapabc7
* @Description 写入标题
* @Date 15:01 2020/7/15
* @Param [header, file]
*/
public static void writeTitle(List<String> header, File file) throws Exception {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
// 填充对象属性值
if (!CollectionUtils.isEmpty(header)) {
// 添加头部(首行)
for (int i = 0; i < header.size(); i++) {
bw.append(header.get(i));
if (i != header.size() - 1) {
bw.append(split);
}
}
bw.newLine();
}
} catch (Exception e) {
log.error("Write CSV exception------", e);
throw e;
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
log.error("Close OutputStream exception------", e);
}
}
}
}
/**
* @return void
* @throws
* @Author mapabc7
* @Description 填充数据
* @Date 15:01 2020/7/15
* @Param [data, header, file]
*/
public static void writeCSV(List<Map<String, Object>> data, List<String> header, File file) throws Exception {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8));
// 填充数据
if (!CollectionUtils.isEmpty(data)) {
for (Map<String, Object> map : data) {
for (int j = 0; j < header.size(); j++) {
String str = StringEscapeUtils.escapeCsv(String.valueOf(map.get(header.get(j))));
bw.append(str == null ? "" : str);
if (j != header.size() - 1) {
bw.append(split);
}
}
bw.newLine();
}
}
} catch (Exception e) {
log.error("Write CSV exception------", e);
throw e;
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
log.error("Close OutputStream exception------", e);
}
}
}
}
public static List<Map<String, Object>> readCSV(File file) throws Exception {
List<Map<String, Object>> list = new ArrayList<>();
try {
CsvReader reader = new CsvReader(file.getPath(), ',', StandardCharsets.UTF_8);
//关闭安全性校验,否则大字段读取会失败,http://javacsv.sourceforge.net/com/csvreader/CsvReader.html
reader.setSafetySwitch(false);
// 跳过表头 如果需要表头的话,不要写这句
reader.readHeaders();
String[] title = reader.getHeaders();
while (reader.readRecord()) {
String[] values = reader.getValues();
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < title.length; i++) {
String s = StringEscapeUtils.unescapeCsv(values[i]);
if (StringUtils.isBlank(s) || StringUtils.equalsIgnoreCase(s, "null")) {
s = null;
}
map.put(title[i], s);
}
list.add(map);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
log.error("read csv file error. : {}", e.getLocalizedMessage());
}
return list;
}
}
package com.wanji.common.utils.tool;
import com.wanji.common.framework.Constants;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import static com.wanji.common.framework.Constants.DATE_FORMAT.*;
/**
* 对日期的处理
*
* @author mapabc
*/
public class DateUtil {
public static Date parse(String text, String pattern) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(text);
}
/**
* long转换为时间
*
* @param millSec
* @return
*/
public static String longToDate(Long millSec) {
SimpleDateFormat sdf = new SimpleDateFormat(E_DATE_FORMAT_SECOND.getStrFormat());
Date date = new Date(millSec);
return sdf.format(date);
}
public static void main(String[] args) throws ParseException {
// DateToString(new Date());
// System.out.println(longToDate(1566144240000L));
Random r = new Random();
for(int i=0;i<10;i++){
System.out.println(getId());
}
}
public static String getRandom(int i) {
Random jjj = new Random();
// int suiJiShu = jjj.nextInt(9);
if (i == 0) {
return "";
}
String jj = "";
for (int k = 0; k < i; k++) {
jj = jj + jjj.nextInt(9);
}
return jj;
}
public static String getId(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String format = sdf.format(new Date());
return format+getRandom(4);
}
public static String StringToDate(Date date) throws ParseException {
if (date == null) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(date);
return dateString;
}
public static String DateToString(Date date) throws ParseException {
if (date == null) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = formatter.format(date);
return dateString;
}
/**
* @Author mapabc
* @Description 比较两个日期的大小,默认before小于after,如果不符合预置条件,则返回false
* @Date 16:02 2020/8/3
* @Param [before, after]
* @return boolean
* @throws
*/
public static boolean compare_date(String before, String after) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date dt1 = df.parse(before);
Date dt2 = df.parse(after);
if (dt1.getTime() > dt2.getTime()) {
return false;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return true ;
}
/**
* 时间转换为long时间戳
*
* @param date
* @return
*/
public static long dateToLong(Date date) {
return date.getTime();
}
/**
* 将代表时间格式的文本转换为日期类型;
*
* @param text 待解析的文本,如"2017-12-08 13:48:29.123"
* @param dateFormat 时间戳格式
*/
public static Date parse(String text, Constants.DATE_FORMAT dateFormat) throws ParseException {
return parse(text, dateFormat.getStrFormat());
}
public static String format(Date date, Constants.DATE_FORMAT dateFormat) {
return new SimpleDateFormat(dateFormat.getStrFormat()).format(date);
}
/**
* 将指定的时间戳转换为代表时间格式的文本;
*
* @param unixTime unix时间戳,单位为ms;
* @param dateFormat 时间戳格式,需要为DATE_FORMAT枚举
*/
public static String format(long unixTime, Constants.DATE_FORMAT dateFormat) {
return format(new Date(unixTime), dateFormat);
}
/**
* 判断给定时间是否位于指定区间内
*
* @param baseDate 待判断的时间点
* @param startDate 时间区间的开始时间点
* @param endDate 时间区间的结束时间点
* @return 如果给定的时间点位于区间内,则返回true,否则返回false.
*/
public static boolean isBetween(Date baseDate, Date startDate, Date endDate) {
if (startDate.after(endDate)) {
throw new RuntimeException("Datetime exception: 结束时间不能早于开始时间!");
}
if (baseDate.before(startDate)) {
return false;
}
if (baseDate.after(endDate)) {
return false;
}
return true;
}
// --------------------------
// 以下为过时方法,不建议使用
// --------------------------
/**
* @param millSec 单位为毫秒
* @return
* @deprecated 将unix时间戳转换为单位到秒的时间
*/
public static String format(long millSec) {
return format(millSec, E_DATE_FORMAT_SECOND);
}
/**
* 判断给定时间点是否处于指定区间内
*
* @param startTime
* @param endTime
* @return [-1: 给定时间点早于开始时间点, 0: 给定时间点处于区间内, 1: 给定时间点晚于结束时间点]
*/
private static int timeLocation(long baseTime, long startTime, long endTime) {
return baseTime < startTime ? -1 : (baseTime > endTime ? 1 : 0);
}
/**
* 计算两个日期之间相差的天数
*
* @param startDate 较小的时间
* @param endDate 较大的时间
* @return 相差天数
* @throws ParseException
*/
private static int daysBetween(Date startDate, Date endDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
startDate = sdf.parse(sdf.format(startDate));
endDate = sdf.parse(sdf.format(endDate));
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
long time1 = cal.getTimeInMillis();
cal.setTime(endDate);
long time2 = cal.getTimeInMillis();
long betweenDays = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(betweenDays));
}
/**
* 获得当前系统日期
*
* @return
* @author mapabc Sep 29, 2006 10:43:22 AM
*/
public static String getDate() {
return new SimpleDateFormat(E_DATE_FORMAT_DAY.getStrFormat()).format(new Date());
}
/**
* 得到当前系统时间和日期
*
* @return
* @author mapabc 2006-10-13 上午09:55:24
*/
public static String getDateTimeInSecond() {
return new SimpleDateFormat(E_DATE_FORMAT_SECOND.getStrFormat()).format(new Date());
}
/**
* 将当前系统时间转换成 Millisecond 的样式
*/
public static String getDateTimeInMillis() {
return new SimpleDateFormat(E_DATE_FORMAT_MILLIS.getStrFormat()).format(new Date());
}
/**
* 获得当前系统时间
*
* @return
* @author mapabc Sep 29, 2006 11:06:57 AM
*/
public static String getTime() {
return new SimpleDateFormat(E_DATE_FORMAT_TIME.getStrFormat()).format(new Date());
}
/**
* 将给定日期转换为至秒的时间
*/
public static String getDate(Date dDate) {
return new SimpleDateFormat(E_DATE_FORMAT_DAY.getStrFormat()).format(dDate);
}
/**
* 将给定日期转换为至秒的时间
*
* @param date
* @return
*/
public static String getDateTimeInSecond(Date date) {
return new SimpleDateFormat(E_DATE_FORMAT_SECOND.getStrFormat()).format(date);
}
/**
* 将给定日期转换为至毫秒的时间
*
* @param date
* @return
*/
public static String getDateTimeInMillis(Date date) {
return new SimpleDateFormat(E_DATE_FORMAT_MILLIS.getStrFormat()).format(date);
}
/**
* 根据指定的日期格式显示日期
*
* @param date
* @param format
* @return
* @author mapabc Sep 29, 2006 10:21:46 AM
*/
public static String formatDate(Date date, String format) {
return new SimpleDateFormat(format).format(date);
}
/**
* 添加秒
*/
public static Date addSecond(String date, long amount) throws ParseException {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date, E_DATE_FORMAT_MINUTE.getStrFormat()));
cal.add(Calendar.SECOND, (int) amount);
return cal.getTime();
}
/**
* 添加分
*/
public static Date addMinute(String date, long amount) throws ParseException {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date, E_DATE_FORMAT_MINUTE.getStrFormat()));
cal.add(Calendar.MINUTE, (int) amount);
return cal.getTime();
}
/**
* 添加小时
*
* @param date
* @param amount
* @return
* @throws ParseException
*/
public static Date addHour(String date, long amount) throws ParseException {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date, E_DATE_FORMAT_MINUTE.getStrFormat()));
cal.add(Calendar.HOUR_OF_DAY, (int) amount);
return cal.getTime();
}
/**
* 添加天数
*/
public static Date addDay(String date, long amount) throws ParseException {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date, E_DATE_FORMAT_MINUTE.getStrFormat()));
cal.add(Calendar.DAY_OF_MONTH, (int) amount);
return cal.getTime();
}
/**
* 添加 周
*/
public static Date addWeek(String date, long amount) throws ParseException {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date, E_DATE_FORMAT_MINUTE.getStrFormat()));
cal.add(Calendar.WEEK_OF_YEAR, (int) amount);
return cal.getTime();
}
/**
* 添加 月
*/
public static Date addMonth(String date, int amount) throws ParseException {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date, E_DATE_FORMAT_MINUTE.getStrFormat()));
int month = cal.get(Calendar.MONTH);
month += amount;
int year = month / 12;
month %= 12;
cal.set(Calendar.MONTH, month);
if (year != 0) {
int oldYear = cal.get(Calendar.YEAR);
cal.set(Calendar.YEAR, year + oldYear);
}
return cal.getTime();
}
/**
* 添加 年
*
* @param date
* @param amount
* @return
* @author mapabc Sep 29, 2006 10:17:14 AM
*/
public static Date addYear(String date, int amount) throws ParseException {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date, E_DATE_FORMAT_MINUTE.getStrFormat()));
int oldYear = cal.get(Calendar.YEAR);
cal.set(Calendar.YEAR, amount + oldYear);
return cal.getTime();
}
/**
* 得到当前年
*
* @author liuxd
* @date 2011-04-20
*/
public static int getYear(Date dDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(dDate);
return cal.get(Calendar.YEAR);
}
/**
* 得到当前月
*
* @param dDate
* @return
*/
public static int getMonth(Date dDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(dDate);
return cal.get(Calendar.MONTH);
}
/**
* 得到当前日期是星期几
*
* @param dDate
* @return
* @author mapabc 2006-10-27 下午01:26:32
*/
public static int getWeek(Date dDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(dDate);
return cal.get(Calendar.DAY_OF_WEEK) - 1;
}
/**
* 根据一个日期,返回是星期几的字符串
*
* @param date 指定的日期
* @return ["星期一","星期二",...]
*/
public static String getWeekInChn(Date date) {
return new SimpleDateFormat(E_DATE_FORMAT_WEEKDAY.getStrFormat()).format(date);
}
/**
* 得到当前日期
*
* @param dDate
* @return
* @author mapabc 2006-10-27 下午01:34:37
*/
public static int getDayOfMonth(Date dDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(dDate);
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 得到当前小时
*
* @param timeStamp
* @return
*/
public static int getHourOfDay(Date timeStamp) {
if (timeStamp == null) {
return 0;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(timeStamp);
return calendar.get(Calendar.HOUR_OF_DAY);
}
/**
* 得到当前时间的分钟
*
* @param timeStamp
* @return
*/
public static int getMinuteOfHour(Date timeStamp) {
if (timeStamp == null) {
return 0;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(timeStamp);
return calendar.get(Calendar.MINUTE);
}
/**
* 得到当前季度 1 第一季度 2 第二季度 3 第三季度 4 第四季度
*
* @author liuxd
* @date 2011-04-20
*/
public static int getSeason() {
int month = Calendar.getInstance().get(Calendar.MONTH);
switch (month) {
case Calendar.JANUARY:
case Calendar.FEBRUARY:
case Calendar.MARCH:
return 1;
case Calendar.APRIL:
case Calendar.MAY:
case Calendar.JUNE:
return 2;
case Calendar.JULY:
case Calendar.AUGUST:
case Calendar.SEPTEMBER:
return 3;
case Calendar.OCTOBER:
case Calendar.NOVEMBER:
case Calendar.DECEMBER:
return 4;
default:
return 0;
}
}
/**
* Data类型转LocalDataTime类型
*
* @param date
* @return
*/
public static LocalDateTime toLocalDate(Date date) {
//获取时间实例
Instant instant = date.toInstant();
//获取时间地区ID
ZoneId zoneId = ZoneId.systemDefault();
//转换为LocalDate
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
//获得LocalDateTime时间戳(东八区)
localDateTime.toEpochSecond(ZoneOffset.of("+8"));
return localDateTime;
}
}
package com.wanji.common.utils.tool;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
/**
* 类描述: encrypt加密,解密工具类
*
* @Author mapabc
* @Date 2019/10/8 11:15
*/
public class EncryptUtil {
// 密钥是16位长度的byte[]进行Base64转换后得到的字符串
public static String key = "LmMGStGtOpF4xNyvYt54EQ==";
/**
* 描述: 加密方法
*
* @param xmlStr 需要加密的消息字符串
* @return java.lang.String 加密后的字符串
* @Author mapabc
* @Date 2019/10/8 11:16
**/
public static String encrypt(String xmlStr) {
byte[] encrypt = null;
try {
// 取需要加密内容的utf-8编码。
encrypt = xmlStr.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 取MD5Hash码,并组合加密数组
byte[] md5Hasn = null;
try {
md5Hasn = EncryptUtil.MD5Hash(encrypt, 0, encrypt.length);
} catch (Exception e) {
e.printStackTrace();
}
// 组合消息体
byte[] totalByte = EncryptUtil.addMD5(md5Hasn, encrypt);
// 取密钥和偏转向量
byte[] key = new byte[8];
byte[] iv = new byte[8];
getKeyIV(EncryptUtil.key, key, iv);
SecretKeySpec deskey = new SecretKeySpec(key, "DES");
IvParameterSpec ivParam = new IvParameterSpec(iv);
// 使用DES算法使用加密消息体
byte[] temp = null;
try {
temp = EncryptUtil.DES_CBC_Encrypt(totalByte, deskey, ivParam);
} catch (Exception e) {
e.printStackTrace();
}
// 使用Base64加密后返回
return new BASE64Encoder().encode(temp);
}
/**
* 描述: 解密方法
*
* @param xmlStr 需要解密的消息字符串
* @return java.lang.String 解密后的字符串
* @Author mapabc
* @Date 2019/10/8 11:16
**/
public static String decrypt(String xmlStr) throws Exception {
// base64解码
BASE64Decoder decoder = new BASE64Decoder();
byte[] encBuf = null;
try {
encBuf = decoder.decodeBuffer(xmlStr);
} catch (IOException e) {
e.printStackTrace();
}
// 取密钥和偏转向量
byte[] key = new byte[8];
byte[] iv = new byte[8];
getKeyIV(EncryptUtil.key, key, iv);
SecretKeySpec deskey = new SecretKeySpec(key, "DES");
IvParameterSpec ivParam = new IvParameterSpec(iv);
// 使用DES算法解密
byte[] temp = null;
try {
temp = EncryptUtil.DES_CBC_Decrypt(encBuf, deskey, ivParam);
} catch (Exception e) {
e.printStackTrace();
}
// 进行解密后的md5Hash校验
byte[] md5Hash = null;
try {
md5Hash = EncryptUtil.MD5Hash(temp, 16, temp.length - 16);
} catch (Exception e) {
e.printStackTrace();
}
// 进行解密校检
for (int i = 0; i < md5Hash.length; i++) {
if (md5Hash[i] != temp[i]) {
// System.out.println(md5Hash[i] + "MD5校验错误。" + temp[i]);
throw new Exception("MD5校验错误。");
}
}
// 返回解密后的数组,其中前16位MD5Hash码要除去。
return new String(temp, 16, temp.length - 16, "utf-8");
}
/**
* 描述: 经过封装的DES/CBC加密算法,如果包含中文,请注意编码。
*
* @param sourceBuf 需要加密内容的字节数组。
* @param deskey KEY 由8位字节数组通过SecretKeySpec类转换而成。
* @param ivParam IV偏转向量,由8位字节数组通过IvParameterSpec类转换而成。
* @return byte[] 加密后的字节数组
* @Author mapabc
* @Date 2019/10/8 11:17
**/
public static byte[] DES_CBC_Encrypt(byte[] sourceBuf,
SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
byte[] cipherByte;
// 使用DES对称加密算法的CBC模式加密
Cipher encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);
cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);
// 返回加密后的字节数组
return cipherByte;
}
/**
* 描述: 经过封装的DES/CBC解密算法。
*
* @param sourceBuf 需要解密内容的字节数组
* @param deskey KEY 由8位字节数组通过SecretKeySpec类转换而成。
* @param ivParam IV偏转向量,由6位字节数组通过IvParameterSpec类转换而成。
* @return byte[] 解密后的字节数组
* @Author mapabc
* @Date 2019/10/8 11:18
**/
public static byte[] DES_CBC_Decrypt(byte[] sourceBuf,
SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
byte[] cipherByte;
// 获得Cipher实例,使用CBC模式。
Cipher decrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
// 初始化加密实例,定义为解密功能,并传入密钥,偏转向量
decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);
cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);
// 返回解密后的字节数组
return cipherByte;
}
/**
* 描述: MD5,进行了简单的封装,以适用于加,解密字符串的校验。
*
* @param buf 需要MD5加密字节数组
* @param offset 加密数据起始位置
* @param length 需要加密的数组长度
* @return byte[]
* @Author mapabc
* @Date 2019/10/8 11:18
**/
public static byte[] MD5Hash(byte[] buf, int offset, int length)
throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(buf, offset, length);
return md.digest();
}
/**
* 描述: MD校验码 组合方法,前16位放MD5Hash码。 把MD5验证码byte[],加密内容byte[]组合的方法。
*
* @param md5Byte 加密内容的MD5Hash字节数组
* @param bodyByte 加密内容字节数组
* @return byte[] 组合后的字节数组,比加密内容长16个字节。
* @Author mapabc
* @Date 2019/10/8 11:19
**/
public static byte[] addMD5(byte[] md5Byte, byte[] bodyByte) {
int length = bodyByte.length + md5Byte.length;
byte[] resutlByte = new byte[length];
// 前16位放MD5Hash码
for (int i = 0; i < length; i++) {
if (i < md5Byte.length) {
resutlByte[i] = md5Byte[i];
} else {
resutlByte[i] = bodyByte[i - md5Byte.length];
}
}
return resutlByte;
}
/**
* 方法名称:getKeyIV
* 功能描述:
*
* @param encryptKey
* @param key
* @param iv
*/
public static void getKeyIV(String encryptKey, byte[] key, byte[] iv) {
// 密钥Base64解密
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = null;
try {
buf = decoder.decodeBuffer(encryptKey);
} catch (IOException e) {
e.printStackTrace();
}
// 前8位为key
int i;
for (i = 0; i < key.length; i++) {
key[i] = buf[i];
}
// 后8位为iv向量
for (i = 0; i < iv.length; i++) {
iv[i] = buf[i + 8];
}
}
public static void main(String[] args) throws Exception {
System.out.println(encrypt("123456"));
System.out.println(decrypt("oqGiG3w2C/s4l945xI++My4Wpv2cCyLi"));
}
}
package com.wanji.common.utils.tool;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @ClassName ExcelUtils
* @Description
* @Author mapabc7
* @Date 2020/6/30 13:22
* @Version 1.0
*/
public class ExcelUtils {
private static final String XLS = "xls";
private static final String XLSX = "xlsx";
private static final DateFormat FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
/**
* 输出数据到自定义模版的Excel输出流
*
* @param excelTemplate 自定义模版文件
* @param data 数据
* @param outputStream Excel输出流
* @param sheetName sheet 名称
* @param title 标题
* @throws IOException 错误时抛出异常,由调用者处理
*/
public static void writeDataToTemplateOutputStream(File excelTemplate,
List<Map<String, Object>> data,
OutputStream outputStream,
String sheetName,
List<String> title) throws IOException {
Workbook book = ExcelUtils.getWorkbookFromExcel(excelTemplate);
ExcelUtils.writeDataToWorkbook(title, data, book, sheetName);
ExcelUtils.writeWorkbookToOutputStream(book, outputStream);
}
/**
* 输出数据到自定义模版的Excel file
*
* @param excelTemplate 自定义模版文件
* @param data 数据
* @param sheetName sheet 名称
* @param title 标题
* @throws IOException 错误时抛出异常,由调用者处理
*/
public static void writeDataToTemplateFile(File excelTemplate,
List<Map<String, Object>> data,
String sheetName,
List<String> title) throws IOException {
Workbook book = ExcelUtils.getWorkbookFromExcel(excelTemplate);
ExcelUtils.writeDataToWorkbook(title, data, book, sheetName);
ExcelUtils.writeWorkbookToFile(book, excelTemplate);
}
/**
* 从Excel文件获取Workbook对象
*
* @param excelFile Excel文件
* @return Workbook对象
* @throws IOException 错误时抛出异常,由调用者处理
*/
public static Workbook getWorkbookFromExcel(File excelFile) throws IOException {
try (
InputStream inputStream = new FileInputStream(excelFile);
) {
if (excelFile.getName().endsWith(XLS)) {
return new HSSFWorkbook(inputStream);
} else if (excelFile.getName().endsWith(XLSX)) {
return new XSSFWorkbook(inputStream);
} else {
throw new IOException("文件类型错误");
}
}
}
/**
* @return org.apache.poi.ss.usermodel.Sheet
* @throws
* @Author mapabc7
* @Description 根据 workbook 和 sheetName 获取 sheet
* @Date 14:10 2020/7/1
* @Param [book, sheetName, title]
*/
public static Sheet getSheet(Workbook book, String sheetName, List<String> title) {
Sheet sheet = book.getSheet(sheetName);
if (sheet == null) {
sheet = book.createSheet(sheetName);
Row row = sheet.createRow(0);
// 设置表头
for (int i = 0; i < title.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellValue(title.get(i));
}
}
return sheet;
}
/**
* 输出数据到Workbook对象中指定 sheet
*
* @param title 标题,写在第一行,可传null
* @param data 数据
* @param book Workbook对象
* @param sheetName sheet页名称
*/
public static void writeDataToWorkbook(List<String> title, List<Map<String, Object>> data, Workbook book, String sheetName) {
Sheet sheet = ExcelUtils.getSheet(book, sheetName, title);
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i < data.size(); i++) {
Map<String, Object> rowData = data.get(i);
if (null == rowData) {
continue;
}
ExcelUtils.makeRowAndCell(sheet, i, lastRowNum, title, rowData);
}
}
/**
* @return void
* @throws
* @Author mapabc7
* @Description 组装 row 和 cell
* @Date 14:22 2020/7/1
* @Param [sheet, i, lastRowNum, title, rowData]
*/
public static void makeRowAndCell(Sheet sheet, int i, int lastRowNum, List<String> title, Map<String, Object> rowData) {
Row row = sheet.createRow(i + 1 + lastRowNum);
for (int k = 0; k < title.size(); k++) {
Cell cell = row.createCell(k);
setValue(cell, rowData.get(title.get(k)));
}
}
/**
* 把Workbook对象内容输出到Excel文件
*
* @param book Workbook对象
* @param file Excel文件
* @throws FileNotFoundException 找不到文件异常,文件已创建,实际不存在该异常
* @throws IOException 输入输出异常
*/
public static void writeWorkbookToFile(Workbook book, File file) throws FileNotFoundException, IOException {
/*if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}*/
try (
OutputStream outputStream = new FileOutputStream(file);
) {
writeWorkbookToOutputStream(book, outputStream);
}
}
/**
* 把Workbook对象输出到Excel输出流
*
* @param book Workbook对象
* @param outputStream Excel输出流
* @throws IOException 错误时抛出异常,由调用者处理
*/
public static void writeWorkbookToOutputStream(Workbook book, OutputStream outputStream) throws IOException {
book.write(outputStream);
}
/**
* 设置单元格值
*
* @param cell 单元格
* @param value 值
*/
public static void setValue(Cell cell, Object value) {
if (null == cell) {
return;
}
if (null == value) {
cell.setCellValue((String) null);
} else if (value instanceof Boolean) {
cell.setCellValue((Boolean) value);
} else if (value instanceof Date) {
cell.setCellValue(FORMAT.format((Date) value));
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
} else {
cell.setCellValue(value.toString());
}
}
/**
* 读取Excel
*
* @param pathname 文件路径名
* @return 数据集合
* @throws IOException 错误时抛出异常,由调用者处理
*/
public static List<Map<String, Object>> readExcelWithSheet(String pathname, String sheetName) throws IOException {
File file = new File(pathname);
return readExcelWithSheet(file, sheetName);
}
/**
* 读取Excel文件
*
* @param file Excel文件
* @return 数据集合
* @throws IOException 错误时抛出异常,由调用者处理
*/
public static List<Map<String, Object>> readExcelWithSheet(File file, String sheetName) throws IOException {
try (
InputStream inputStream = new FileInputStream(file);
) {
if (file.getName().endsWith(XLS)) {
return readXlsWithSheet(inputStream, sheetName);
} else if (file.getName().endsWith(XLSX)) {
return readXlsxWithSheet(inputStream, sheetName);
} else {
throw new IOException("文件类型错误");
}
}
}
/**
* 读取xls格式Excel文件
*
* @param inputStream Excel文件输入流
* @return 数据集合
* @throws IOException 错误时抛出异常,由调用者处理
*/
public static List<Map<String, Object>> readXlsWithSheet(InputStream inputStream, String sheetName) throws IOException {
Workbook workbook = new HSSFWorkbook(inputStream);
return readExcelWithSheet(workbook, sheetName);
}
/**
* @param inputStream 输入流
* @param sheetName sheet页名称
* @return java.util.List<java.util.Map < java.lang.String , java.lang.Object>> map中key为表头,value为值
* @Description: 根据sheetname 读取excel内容,默认按照xlsx格式读取,失败后读取xls
* @Author Jack
* @Date 2020/7/1 12:27
**/
public static List<Map<String, Object>> readXlsOrXlsxWithSheet(InputStream inputStream, String sheetName) throws IOException {
try {
return readXlsxWithSheet(inputStream, sheetName);
} catch (Exception e) {
return readXlsWithSheet(inputStream, sheetName);
}
}
public static Workbook readXlsOrXlsx(InputStream inputStream) throws IOException {
try {
return new XSSFWorkbook(inputStream);
} catch (Exception e) {
return new HSSFWorkbook(inputStream);
}
}
public static Workbook readXlsOrXlsx(File file) throws IOException {
InputStream inputStream = new FileInputStream(file);
try {
return new XSSFWorkbook(inputStream);
} catch (Exception e) {
return new HSSFWorkbook(inputStream);
} finally {
inputStream.close();
}
}
/**
* 读取xlsx格式Excel文件
*
* @param inputStream Excel文件输入流
* @return 数据集合
* @throws IOException 错误时抛出异常,由调用者处理
*/
public static List<Map<String, Object>> readXlsxWithSheet(InputStream inputStream, String sheetName) throws IOException {
Workbook workbook = new XSSFWorkbook(inputStream);
return readExcelWithSheet(workbook, sheetName);
}
/**
* 读取Workbook
*
* @param book Workbook对象
* @return 数据集合
*/
public static List<Map<String, Object>> readExcelWithSheet(Workbook book, String sheetName) {
return readExcelContent(book, sheetName);
}
/**
* 读取指定页面的Excel
*
* @param book Workbook对象
* @param sheetName sheet 名称
* @return 指定页面数据集合
*/
public static List<Map<String, Object>> readExcelContent(Workbook book, String sheetName) {
Sheet sheet = book.getSheet(sheetName);
return readExcelContentBySheet(sheet);
}
/**
* 读取指定页面的Excel
*
* @param sheet Sheet 对象
* @return 指定页面数据集合
*/
public static List<Map<String, Object>> readExcelContentBySheet(Sheet sheet) {
List<Map<String, Object>> list = new ArrayList<>();
// 标题
Row row = sheet.getRow(0);
List<String> title = new ArrayList<>();
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
title.add((String) getValue(cell));
}
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
// 如果当前行为空,则加入空,保持行号一致
if (null == row) {
list.add(null);
continue;
}
Map<String, Object> columns = new HashMap<>();
for (int j = 0; j < title.size(); j++) {
Cell cell = row.getCell(j);
columns.put(title.get(j), getValue(cell));
}
list.add(columns);
}
return list;
}
/**
* 读取指定页面的Excel Header
*
* @param sheetName sheetName
* @return 指定页面Header
*/
public static List<String> readExcelHeaderBySheet(Workbook book,String sheetName) {
List<String> list = new ArrayList<>();
Sheet sheet = book.getSheet(sheetName);
// Header
Row row = sheet.getRow(0);
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
list.add((String) getValue(cell));
}
return list;
}
/**
* 解析单元格中的值
*
* @param cell 单元格
* @return 单元格内的值
*/
private static Object getValue(Cell cell) {
if (null == cell) {
return null;
}
Object value = null;
switch (cell.getCellType()) {
case BOOLEAN:
value = cell.getBooleanCellValue();
break;
case NUMERIC:
// 日期类型,转换为日期
if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
value = cell.getDateCellValue();
} else { // 数值类型
// 默认返回double,创建BigDecimal返回准确值
value = new BigDecimal(cell.getNumericCellValue());
}
break;
default:
value = cell.toString();
break;
}
return value;
}
public static void main(String[] args) {
// Excel 文件
File file = new File("D:\\test.xlsx");
String sheetName = "测试";
// 测试 写入
// writeDataToTemplateFileDemo(file, sheetName);
// 测试 读取
List<Map<String, Object>> maps = readExcelWithSheetDemo(file, sheetName);
System.out.println(maps);
}
private static List<Map<String, Object>> readExcelWithSheetDemo(File file, String sheetName) {
List<Map<String, Object>> maps = null;
try {
maps = ExcelUtils.readExcelWithSheet(file, sheetName);
} catch (IOException e) {
e.printStackTrace();
}
return maps;
}
private static void writeDataToTemplateFileDemo(File file, String sheetName) {
// 数据
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>() {{
add(new HashMap<String, Object>() {{
put("id", 1);
put("name", "张三");
}});
add(new HashMap<String, Object>() {{
put("id", 2);
put("name", "lisi");
}});
add(new HashMap<String, Object>() {{
put("id", 3);
put("name", 111);
}});
}};
List<String> title = new ArrayList<String>() {{
add("id");
add("name");
}};
try {
ExcelUtils.writeDataToTemplateFile(file, data, sheetName, title);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.wanji.common.utils.tool;
import com.google.common.collect.Maps;
import groovy.lang.GroovyClassLoader;
import lombok.extern.slf4j.Slf4j;
import javax.script.*;
import java.io.*;
import java.util.Map;
/**
* @author mapabc
* @date 2018-04-11
*/
@Slf4j
public class GroovyUtil {
private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
private static Map<Object, CompiledScript> compiledScriptMap = Maps.newHashMap();
private static Map<Object, Invocable> invocableMap = Maps.newHashMap();
/**
* 执行一段文本表示的脚本片段,得到返回值
*
* @param script 脚本片段,如:return "hello $name!"
* @param params 脚本中使用的变量名称和值的映射,如:{"name":"Jack"}
* @return
*/
public static Object evalScript(String script, Map<String, Object> params) throws ScriptException {
Bindings bindings = new SimpleBindings(params);
CompiledScript cs = compiledScriptMap.get(script);
if (cs == null) {
cs = ((Compilable) engine).compile(script);
compiledScriptMap.put(script, cs);
}
return cs.eval(bindings);
}
/**
* 执行一个脚本文件,得到返回值
*
* @param file 脚本文件路径
* @param params 脚本中使用的变量名称和值的映射
* @return
*/
public static Object runScriptFile(String file, Map<String, Object> params) throws ScriptException, FileNotFoundException {
log.debug("run script file: " + file);
Reader reader = new FileReader(new File(file));
Bindings bindings = new SimpleBindings(params);
CompiledScript cs = compiledScriptMap.get(file);
if (cs == null) {
cs = ((Compilable) engine).compile(reader);
compiledScriptMap.put(file, cs);
}
return cs.eval(bindings);
}
/**
* 调用脚本片段中的一个函数
*
* @param script 脚本片段
* @param fn 函数名称
* @param params 脚本中使用的变量名称和值的映射
* @param args 函数需要的参数
* @return
*/
public static Object invokeFnInScript(String script, String fn, Map<String, Object> params, Object... args) throws ScriptException, NoSuchMethodException {
Bindings bindings = new SimpleBindings(params);
engine.eval(script, bindings);
Invocable invocable = invocableMap.get(script);
if (invocable == null) {
invocable = (Invocable) engine;
}
return invocable.invokeFunction(fn, args);
}
/**
* 调用一个脚本文件中定义的函数
*
* @param file 脚本文件
* @param fn 函数名称
* @param params 脚本中使用的变量名称和值的映射
* @param args 函数需要的参数
* @return
*/
public static Object invokeFnInFile(String file, String fn, Map<String, Object> params, Object... args) throws ScriptException, NoSuchMethodException, FileNotFoundException {
Bindings bindings = new SimpleBindings(params);
engine.eval(new FileReader(new File(file)), bindings);
Invocable invocable = invocableMap.get(file);
if (invocable == null) {
invocable = (Invocable) engine;
}
return invocable.invokeFunction(fn, args);
}
/**
* 从文件中加载groovy class
*
* @param file 脚本文件
* @return
*/
public static Class loadClassFromFile(String file) {
GroovyClassLoader cl = new GroovyClassLoader(GroovyUtil.class.getClassLoader());
try {
return cl.parseClass(new File(file));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 从文本中加载groovy class
*
* @param text 脚本片段
* @return
*/
public static Class loadClassFromText(String text) {
GroovyClassLoader cl = new GroovyClassLoader(GroovyUtil.class.getClassLoader());
return cl.parseClass(text);
}
/**
* 删除已编译脚本
*
* @param script
*/
public static void removeCache(String script) {
compiledScriptMap.remove(script);
invocableMap.remove(script);
}
}
package com.wanji.common.utils.tool;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
/**
* @author mapabc
*/
public class IDGenerator {
private static int COUNT = 0;
public static String getID() {
UUID uid = UUID.randomUUID();
String id = uid.toString();
id = id.toUpperCase();
id = id.replace("-", "");
return id;
}
public static String get12UUID() {
UUID uid = UUID.randomUUID();
String id = uid.toString();
id = id.toUpperCase();
id = id.replace("-", "");
return id.substring(0, 12);
}
public static void main(String[] args) {
System.out.println(getRandomWorkflowId());
}
/**
* 生成随机字母
*/
public static String getRandomChar() {
int randomInt;
int pwdLength = 0;
char[] str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z'};
final int maxNum = str.length;
StringBuilder pwd = new StringBuilder();
Random rand = new Random();
while (pwdLength < 32) {
randomInt = Math.abs(rand.nextInt(maxNum));
if (randomInt >= 0 && randomInt < str.length) {
pwd.append(str[randomInt]);
pwdLength++;
}
}
return pwd.toString();
}
/**
* 获取26位唯一字符串,前15位距离19700101的时间毫秒数,后11单独计数值
*
* @return
*/
public static synchronized String getUniqueID() {
long millis = System.currentTimeMillis();
return num2Str(millis, 15) + num2Str(++COUNT, 11);
}
/**
* 数字按照指定长度
*
* @param number
* @param width
* @return
*/
private static String num2Str(long number, int width) {
String numStr = String.valueOf(number);
int len = numStr.length() - width;
if (len > 0) {
numStr = numStr.substring(len);
}
width -= numStr.length();
StringBuilder zeroBuff = new StringBuilder();
while (zeroBuff.length() < width) {
zeroBuff.append("0");
}
return zeroBuff.toString() + numStr;
}
public static synchronized String getDateUniqueID() {
return num2Str(17) + num2Str(++COUNT, 2);
}
/**
* 当前时间制定长度
*
* @param width
* @return
*/
public static String num2Str(int width) {
String numStr = DateFormatUtils.format(new Date(), "HHmmssS");
width -= numStr.length();
StringBuilder zeroBuff = new StringBuilder();
while (zeroBuff.length() < width) {
zeroBuff.append("0");
}
return zeroBuff.toString() + numStr;
}
/**
* 生成流程id,克隆时不能用getID,部署不成功
*/
public static String getRandomWorkflowId() {
int randomInt;
int pwdLength = 0;
char[] str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z'};
char[] numStr={'1','2','3','4','5','6','7','8','9','0'};
final int maxNum = str.length;
final int num=numStr.length;
StringBuilder pwd = new StringBuilder();
Random rand = new Random();
while (pwdLength < 10) {
randomInt = Math.abs(rand.nextInt(maxNum));
if (randomInt >= 0 && randomInt < str.length) {
pwd.append(str[randomInt]);
pwdLength++;
}
}while (pwdLength <20) {
randomInt = Math.abs(rand.nextInt(num));
if (randomInt >= 0 && randomInt < numStr.length) {
pwd.append(numStr[randomInt]);
pwdLength++;
}
}
return pwd.toString();
}
}
package com.wanji.common.utils.tool;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wanji.common.framework.exception.DubboProviderException;
import com.wanji.common.utils.webservice.SoapUtils;
import com.wanji.common.utils.webservice.WebServiceUtils;
import org.dom4j.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.commons.lang3.StringUtils.isEmpty;
/**
* @ClassName JsonUtil
* @Description
* @Author mapabc7
* @Date 2020/6/3 11:15
* @Version 1.0
*/
public class JsonUtil {
/**
* xml转json
*
* @param element
* @param json
*/
public static void dom4j2Json(Element element, JSONObject json) {
//如果是属性
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
List<Element> chdEl = element.elements();
if (chdEl.isEmpty() && !isEmpty(element.getText())) {//如果没有子元素,只有一个值
json.put(element.getName(), element.getText());
}
for (Element e : chdEl) {//有子元素
if (!e.elements().isEmpty()) {//子元素也有子元素
JSONObject chdjson = new JSONObject();
dom4j2Json(e, chdjson);
Object o = json.get(e.getName());
if (o != null) {
JSONArray jsona = null;
if (o instanceof JSONObject) {//如果此元素已存在,则转为jsonArray
JSONObject jsono = (JSONObject) o;
json.remove(e.getName());
jsona = new JSONArray();
jsona.add(jsono);
jsona.add(chdjson);
}
if (o instanceof JSONArray) {
jsona = (JSONArray) o;
jsona.add(chdjson);
}
json.put(e.getName(), jsona);
} else {
if (!chdjson.isEmpty()) {
json.put(e.getName(), chdjson);
}
}
} else {//子元素没有子元素
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
if (!e.getText().isEmpty()) {
Object o = json.get(e.getName());
if (o != null) {
List list = null;
if (o instanceof String) {//如果此元素已存在,则转为jsonArray
list = new ArrayList<>();
list.add(o);
}
if (o instanceof ArrayList) {
list = (List) o;
}
String name = e.getName();
String text = e.getText();
list.add(text);
json.put(name, list);
} else {
json.put(e.getName(), e.getText());
}
}
}
}
}
public static void main(String[] args) {
Map headerMap = new HashMap() {{
put("Content-Type", "text/xml; charset=utf-8");
}};
String targetUrl = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
String targetNamespace = "http://WebXml.com.cn/";
String funName = "getSupportCity";
Map bodyMap = new HashMap() {{
put("byProvinceName", "河北");
}};
String soapXml = SoapUtils.buildSoapXml(targetNamespace, funName, bodyMap);
String xml = null;
try {
xml = WebServiceUtils.doPostSoap1_1(targetUrl, soapXml, headerMap);
System.out.println(xml);
} catch (DubboProviderException e) {
e.printStackTrace();
}
JSONObject jsonObject = new JSONObject();
Document doc = null;
try {
doc = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
e.printStackTrace();
}
JsonUtil.dom4j2Json(doc.getRootElement(), jsonObject);
Object result = jsonObject.get("Body");
System.out.println(String.valueOf(result));
}
}
package com.wanji.common.utils.tool;
import com.wanji.common.tool.wsdltool.DoSoapTool;
import org.dom4j.DocumentException;
import org.json.JSONObject;
import org.json.XML;
import java.io.IOException;
/**
* @ClassName JsonXmlUtils
* @Description
* @Author mapabc7
* @Date 2020/7/28 10:34
* @Version 1.0
*/
public class JsonXmlUtils {
private static JSONObject xmlToJson(String xml, boolean keepStrings) {
if (StringUtils.isNotBlank(xml)) {
JSONObject jsonObject = XML.toJSONObject(xml, keepStrings);
StringBuilder stringBuilder = new StringBuilder();
JSONObject json = new JSONObject();
String envelope = null;
for (String s : jsonObject.keySet()) {
if (StringUtils.containsIgnoreCase(s, "Envelope")) {
envelope = s;
break;
}
}
stringBuilder.append(envelope);
JSONObject envelopeValue = jsonObject.getJSONObject(envelope);
// 组装重构生成的json
packageJson(stringBuilder, envelopeValue);
json.put(stringBuilder.toString(), envelopeValue);
return json;
}
return null;
}
public static String xmlToJsonString(String xml) {
return xmlToJsonString(xml, true);
}
public static String soapXmlToJsonString(String xml) {
return xmlToJsonString(xml, true);
}
public static String xmlToJsonString(String xml, boolean keepStrings) {
if (StringUtils.isNotBlank(xml)) {
JSONObject jsonObject = xmlToJson(xml, keepStrings);
if (jsonObject != null) {
return jsonObject.toString();
}
}
return null;
}
public static String jsonToXml(Object json) {
if (json != null) {
String s = XML.toString(new JSONObject(json + ";"));
return s.substring(0, s.lastIndexOf(":Envelope")) + ":Envelope>";
}
return null;
}
public static String jsonToSoapXml(Object json) {
if (json != null) {
String s = XML.toString(new JSONObject(json + ";"));
return s.substring(0, s.lastIndexOf(":Envelope")) + ":Envelope>";
}
return null;
}
private static void packageJson(StringBuilder stringBuilder, JSONObject envelopeValue) {
for (String s : envelopeValue.keySet()) {
if (s.startsWith("xmlns:")) {
stringBuilder.append(" ").append(s).append("=").append("\"").append(envelopeValue.getString(s)).append("\"");
envelopeValue.remove(s);
if (envelopeValue.length() > 0) {
packageJson(stringBuilder, envelopeValue);
}
return;
}
}
}
public static void main(String[] args) throws DocumentException, IOException {
String xml = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:web=\"http://WebXml.com.cn/\">\n" +
" <soap:Header/>\n" +
" <soap:Body>\n" +
" <web:getSupportCity>\n" +
" <!--Optional:-->\n" +
" <web:byProvinceName>河北</web:byProvinceName>\n" +
" </web:getSupportCity>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
String s2 = DoSoapTool.doPostSoap("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl", xml);
System.out.println(s2);
}
}
package com.wanji.common.utils.tool;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String md5(String str) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (md5 != null) {
md5.update(str.getBytes());
byte[] encodeBytes = md5.digest();
char[] encodeStr = new char[encodeBytes.length * 2];
int k = 0;
for (byte encodeByte : encodeBytes) {
encodeStr[k++] = hexDigits[encodeByte >> 4 & 0xf];
encodeStr[k++] = hexDigits[encodeByte & 0xf];
}
return new String(encodeStr);
}
return null;
}
public static void main(String[] args) {
String str = "1115240";
System.out.println(str);
System.out.println(MD5Util.md5(str));
//58ce73cce2c01d8ef87016c274cb593b
}
}
package com.wanji.common.utils.tool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class PageUtil {
/**
* <p>Description: 内存分页 </p>
*
* @param records 待分页的数据
* @param pageNum 当前页码
* @param pageSize 每页显示的条数
* @return 分页之后的数据
*/
public static <T> List<T> pagination(List<T> records, int pageNum, int pageSize) {
if (CollectionUtils.isEmpty(records)) {
return Collections.emptyList();
}
if (pageNum < 0 || pageSize < 0) {
return Collections.emptyList();
}
int totalCount = records.size();
int pageCount;
int remainder = totalCount % pageSize;
if (remainder > 0) {
pageCount = totalCount / pageSize + 1;
} else {
pageCount = totalCount / pageSize;
}
log.info("总记录数为: [{}], 当前页码为: [{}], 每页显示的条数为: [{}]", totalCount, pageNum, pageSize);
if (remainder == 0) {
records = records.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
return records;
} else {
if (pageNum == pageCount) {
records = records.stream().skip((pageNum - 1) * pageSize).limit(totalCount).collect(Collectors.toList());
return records;
} else {
records = records.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
return records;
}
}
}
}
package com.wanji.common.utils.tool;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 对字符处理的公共类
*
* @author mapabc
*/
@Slf4j
public class StringUtils {
public static String GBKToUTF(String str) {
String utfStr = null;
try {
utfStr = new String(str.getBytes("GBK"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return utfStr;
}
public static String UTFToGBK(String str) {
String utfStr = null;
try {
utfStr = new String(str.getBytes("UTF-8"), "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return utfStr;
}
public static String ISOToGBK(String str) {
String utfStr = null;
try {
utfStr = new String(str.getBytes("ISO8859_1"), "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return utfStr;
}
/**
* 将字符转换成map
* {row:20000,pageno:1,startdate:2008-9-10,enddate:2008-10-1}
* 注意:要求在字符串的key和value中不可以包含“,”、“:”,否则会出现分割错误
*
* @return
* @author mapabc
* @date Nov 3, 2008 10:03:26 AM
*/
public static Map<String, String> strToMap(String str) {
Map<String, String> map = Maps.newHashMap();
if (!isBlank(str)) {
String strObj = str.substring(1, str.length() - 1);
String[] obj = strObj.split(",");
for (String value : obj) {
String[] key = value.split(":");
map.put(key[0], key[1]);
}
}
return map;
}
/**
* 将map转换成字符
*
* @param map
* @return
* @author mapabc
* @date Nov 3, 2008 10:21:31 AM
*/
public static String mapToStr(Map<String, String> map) {
StringBuilder str = new StringBuilder();
if (map != null) {
for (Map.Entry<String, String> obj : map.entrySet()) {
String key = obj.getKey();
String value = obj.getValue();
str.append(key).append(":").append(value).append(",");
}
}
if (str.length() > 0) {
str = new StringBuilder("{" + str.substring(0, str.length() - 1) + "}");
}
return str.toString();
}
/**
* @param str
* @return 如果<tt>str</tt>为<tt>null</tt>或空白字符串返回<tt>true</tt>
*/
public static boolean isBlank(String str) {
return str == null || "".equals(str.trim());
}
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
public static boolean isNotBlank(String... strs) {
boolean isNotNull = true;
if (strs == null || strs.length == 0) {
return false;
}
for (String str : strs) {
if (StringUtils.isBlank(str)) {
isNotNull = false;
break;
}
}
return isNotNull;
}
/**
* 用<tt>separator</tt>连接字符串,例如将数组{"a","b","c"}使用';'连接,得到"a;b;c",忽略<tt>null<tt>和空白字符串
*
* @param s 需要连接的字符串数组
* @param separator 分隔符
* @return 连接好的字符串或""
* @throws NullPointerException 如果<tt>s</tt>或<tt>separator</tt>为<tt>null</tt>
* @see #join(String[], String, boolean, boolean)
*/
public static String join(String[] s, String separator) {
return join(s, separator, true, true);
}
/**
* 用<tt>separator</tt>连接字符串,例如将数组{"a","b","c"}使用';'连接,得到"a;b;c"
*
* @param strList 需要连接的字符串数组
* @param separator 分隔符
* @param ignoreBlank 是否忽略空字符串,通过<tt>String.trim().length() == 0</tt>判断空字符串
* @param ignoreNull 是否忽略<tt>null</tt>
* @return 连接好的字符串或""
* @throws NullPointerException 如果<tt>strList</tt>或<tt>separator</tt>为<tt>null</tt>
*/
public static String join(String[] strList, String separator,
boolean ignoreBlank, boolean ignoreNull) {
if (strList == null || separator == null) {
throw new NullPointerException();
}
StringBuilder result = new StringBuilder(256);
for (String str : strList) {
if (ignoreNull && str == null) {
continue;
} else if (ignoreBlank && str.trim().length() == 0) {
continue;
}
result.append(str);
result.append(separator);
}
int i = result.length();
if (i > 0) {
return result.substring(0, i - separator.length());
} else {
return "";
}
}
/**
* 将CamelCase转换成大写字母,以“_”为间隔,例如abcFoo转换成ABC_FOO
*
* @param s
* @return
*/
public static String camelToCapital(String s) {
final String pattern = "[A-Z]*[a-z0-9]+|[A-Z0-9]+";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(s);
String r = null;
while (m.find()) {
if (r != null) {
r = r + "_" + m.group().toUpperCase();
} else {
r = m.group().toUpperCase();
}
}
return r;
}
/**
* 将大写字母转换成CamelCase,以“_”为间隔,例如ABC_FOO转换成abcFoo
*
* @param s
* @return
*/
public static String capitalToCamel(String s) {
String[] tokens = s.split("_");
StringBuilder r = new StringBuilder(tokens[0].toLowerCase());
for (int i = 1; i < tokens.length; i++) {
r.append(tokens[i].substring(0, 1)).append(tokens[i].substring(1)
.toLowerCase());
}
return r.toString();
}
/**
* 截取字符串,按照系统默认的字符集,截取后的后缀为“...”
*
* @param target 被截取的原字符串,此方法执行前会先<tt>trim</tt>
* @param maxBytes 截取后字符串的最大<tt>byte</tt>数,包括截取后的字符串的后缀
* @return
* @see #substring(String, String, int, String)
*/
public static String substring(String target, int maxBytes) {
return substring(target.trim(), Charset.defaultCharset().name(),
maxBytes, "...");
}
/**
* 截取字符串
*
* @param target 被截取的原字符串
* @param charset 字符串的字符集
* @param maxBytes 截取后字符串的最大<tt>byte</tt>数,包括截取后的字符串的后缀
* @param append 字符串被截去后的后缀
* @return
*/
public static String substring(String target, String charset, int maxBytes,
String append) {
try {
int count = getBytes(target, charset).length;
if (count <= maxBytes) {
return target;
} else {
int bytesCount = 0;
char[] replace = new char[getBytes(append, charset).length];
int j = 0;
int bound = maxBytes - getBytes(append, charset).length;
for (int i = 0; i < target.length(); i++) {
char c = target.charAt(i);
bytesCount = c > 255 ? bytesCount + 2 : bytesCount + 1;
if (bytesCount > maxBytes) {
return target.substring(0, i - j).concat(append);
}
if (bytesCount > bound) {
replace[j++] = c;
}
}
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
throw new RuntimeException("Unreachable!");
}
private static byte[] getBytes(String s, String charset)
throws UnsupportedEncodingException {
return s.getBytes(charset);
}
public static String substringAfterLast(String str, String separator) {
if (!isNotBlank(str, separator)) {
return "";
} else {
int pos = str.lastIndexOf(separator);
return pos != -1 && pos != str.length() - separator.length() ? str.substring(pos + separator.length()) : "";
}
}
public static String trim(String str) {
str = str.replace(' ', ' ');
return str.trim();
}
public static boolean containsIgnoreCase(String orig, String targ) {
return orig.toLowerCase().contains(targ.toLowerCase());
}
public static boolean equalsIgnoreCase(String str, String tar) {
return isNotBlank(str, tar) && str.toLowerCase().equals(tar.toLowerCase());
}
public static String joinPath(String str1, String str2) {
if (str1.endsWith("/") && str2.startsWith("/")) {
str2 = str1 + str2.substring(1);
} else if (str1.endsWith("/") || str2.startsWith("/")) {
str2 = str1 + str2;
} else {
str2 = str1 + "/" + str2;
}
return str2;
}
}
package com.wanji.common.utils.tool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Calendar;
/**
* Web上下文
*
* @author peiyuan.cai
*/
@Slf4j
public class WebCxt {
private static final String CONTENT_TYPE = "application/json; charset=utf-8";
private static final String CONTENT_TYPE_FOR_IE = "text/html; charset=utf-8";
private static Calendar calendar = Calendar.getInstance();
static {
calendar.set(2099, 11, 31);
}
private static final long DATE = System.currentTimeMillis();
public static final String TILE_CONTENT_TYPE = "application/x-protobuf";
public static final long CACHE_TIME = 2592000L;
public static final long MODIFY_DATE = System.currentTimeMillis();
public static final String TILE_HEADER_ETAG = String.valueOf(MODIFY_DATE);
public static final long EXPIRES_TIME = calendar.getTimeInMillis();
public static final String CHECK_SQL = "^(.+)\\sand\\s(.+)|(.+)\\sor(.+)\\s$";
public static final String CHECK_Q = "^.*'.*$";
/**
* 向response对象输出原始byte数据
*
* @param response
* @param data
*/
public static void renderRaw(HttpServletResponse response, byte[] data) {
renderRaw(response, data, TILE_CONTENT_TYPE);
}
public static void renderRaw(HttpServletResponse response, byte[] data, String contentType) {
ServletOutputStream out = null;
try {
setCacheHeader(response, String.valueOf(data.length));
response.setContentType(contentType);
response.setContentLength(data.length);
out = response.getOutputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(data);
byte[] buffer = new byte[1024];
for (int len = -1; (len = bais.read(buffer)) != -1; ) {
out.write(buffer, 0, len);
}
out.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* 向response输出json字符串
*
* @param response
* @param jsonText
* @param forIE
*/
public static void renderJson(HttpServletResponse response, String jsonText, boolean forIE) {
PrintWriter writer = null;
try {
setCacheHeader(response, String.valueOf(jsonText.length()));
response.setContentType(forIE ? CONTENT_TYPE_FOR_IE : CONTENT_TYPE);
writer = response.getWriter();
writer.write(jsonText);
writer.flush();
} catch (IOException e) {
}
}
/**
* 输出图片资源到response
*
* @param response
* @param data
*/
public static void renderImg(HttpServletResponse response, byte[] data) {
ServletOutputStream out = null;
try {
setCacheHeader(response, String.valueOf(data.length));
response.setContentType("image/png");
out = response.getOutputStream();
out.write(data);
out.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* 输出文本到response
*
* @param response
* @param text
*/
public static void renderText(HttpServletResponse response, String text, String contentType) {
try {
setCacheHeader(response, String.valueOf(text.length()));
response.setContentType(contentType);
PrintWriter writer = response.getWriter();
writer.print(text);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* 设置response缓存头标识
*
* @param response
*/
public static void setCorsHeader(HttpServletRequest request, HttpServletResponse response) {
String url = request.getHeader("Origin");
String Credentials = request.getHeader("Access-Control-Allow-Credentials");
// log.debug("Access-Control-Allow-Origin:" + url);
if (!StringUtils.isEmpty(url)) {
// String val = response.getHeader("Access-Control-Allow-Origin");
response.addHeader("Access-Control-Allow-Origin", url);
response.addHeader("Access-Control-Allow-Credentials", "true");
/* if (StringUtils.isEmpty(val)) {
}*/
} else {
response.setHeader("Access-Control-Allow-Origin", "*");
}
}
/**
* 设置response缓存头标识
*
* @param response
*/
public static void setCacheHeader(HttpServletResponse response, String etag) {
//response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control", "max-age=690000");
response.setHeader("Connection", "keep-alive");
response.setHeader("ETag", etag);
response.setDateHeader("Expires", System.currentTimeMillis());
response.setDateHeader("Last-Modified", System.currentTimeMillis());
response.setDateHeader("Date", System.currentTimeMillis());
}
// 字符串读取
// 方法一
public static String ReadAsChars(HttpServletRequest request) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder("");
try {
br = request.getReader();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
br.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return sb.toString();
}
// 方法二
public static void ReadAsChars2(HttpServletRequest request) {
InputStream is = null;
try {
is = request.getInputStream();
StringBuilder sb = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = is.read(b)) != -1; ) {
sb.append(new String(b, 0, n));
}
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
// 二进制读取
public static byte[] readAsBytes(HttpServletRequest request) {
int len = request.getContentLength();
byte[] buffer = new byte[len];
ServletInputStream in = null;
try {
in = request.getInputStream();
in.read(buffer, 0, len);
in.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return buffer;
}
/**
* 将文件以字节码方式返回到客户端
*
* @param response
* @param cacheFile
* @param s
*/
public static void renderFileToRaw(HttpServletResponse response, File cacheFile, String s) {
try (
OutputStream bos = response.getOutputStream();
FileInputStream fis = new FileInputStream(cacheFile);
) {
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
} finally {
}
}
}
package com.wanji.common.utils.webservice;
import com.alibaba.fastjson.JSON;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName SoapUtils
* @Description
* @Author mapabc7
* @Date 2020/6/1 18:20
* @Version 1.0
*/
public class SoapUtils {
/**
* 生成soapxml
*
* @param targetNamespace
* @param functionName
* @param bodyMap
* @return
*/
public static String buildSoapXml(String targetNamespace, String functionName, Map<String, Object> bodyMap) {
StringBuilder stringBuilder = new StringBuilder("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n")
.append("\t<soap:Body>\n")
.append("\t\t<" + functionName + " xmlns=\"" + targetNamespace + "\">\n")
.append(paramTransformSoapXml(bodyMap))
.append("\t\t</" + functionName + ">\n")
.append("\t</soap:Body>\n")
.append("</soap:Envelope>");
return String.valueOf(stringBuilder);
}
/**
* 将参数转化为soapXml中的一部分
*
* @param paramMap
* @return
*/
private static String paramTransformSoapXml(Map<String, Object> paramMap) {
if (paramMap.isEmpty()) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
stringBuilder.append(paramTransformSoapXml(entry));
}
return String.valueOf(stringBuilder);
}
private static String paramTransformSoapXml(Map.Entry<String, Object> entry) {
StringBuilder stringBuilder = new StringBuilder();
String entryKey = entry.getKey();
Object entryValue = entry.getValue();
if (entryValue instanceof Map) {
stringBuilder.append("\t\t\t").append("<" + entryKey + ">\n");
stringBuilder.append(paramTransformSoapXml(JSON.parseObject(JSON.toJSONString(entryValue))));
stringBuilder.append("\t\t\t").append("</" + entryKey + ">\n");
} else {
stringBuilder.append("\t\t\t").append("<" + entryKey + ">").append(entryValue).append("</" + entryKey + ">\n");
}
return String.valueOf(stringBuilder);
}
public static void main(String[] args) {
String targetNamespace = "http://WebXml.com.cn/";
String funName = "getSupportCity";
Map bodyMap = new HashMap() {{
put("byProvinceName", "河北");
}};
String soapXml = SoapUtils.buildSoapXml(targetNamespace, funName, bodyMap);
System.out.println(soapXml);
}
}
package com.wanji.common.utils.webservice;
import com.wanji.common.framework.exception.DubboProviderException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/**
* Created by mapabc4 on 2019/5/22.
*/
@Slf4j
public class WebServiceUtils {
// 请求超时时间
static int socketTimeout = 30000;
// 传输超时时间
static int connectTimeout = 30000;
/**
* 使用SOAP1.1发送消息
*
* @param postUrl
* @param soapXml
* @return
*/
public static String doPostSoap1_1(String postUrl, String soapXml, Map<String, Object> headerMap) throws DubboProviderException {
String retStr = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(postUrl);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
try {
// httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("Content-Type", String.valueOf(headerMap.get("Content-Type")));
StringEntity data = new StringEntity(soapXml,
Charset.forName("UTF-8"));
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印响应内容
retStr = EntityUtils.toString(httpEntity, "UTF-8");
log.info("response:" + retStr);
}
// 释放资源
closeableHttpClient.close();
} catch (Exception e) {
log.error("exception in doPostSoap1_1", e);
throw new DubboProviderException(e);
}
return retStr;
}
/**
* 使用SOAP1.2发送消息
*
* @param postUrl
* @param soapXml
* @param soapAction
* @return
*/
public static String doPostSoap1_2(String postUrl, String soapXml,
String soapAction, Map<String, Object> headerMap) {
String retStr = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(postUrl);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
try {
// httpPost.setHeader("Content-Type",
// "application/soap+xml;charset=UTF-8");
httpPost.setHeader("Content-Type", String.valueOf(headerMap.get("Content-Type")));
httpPost.setHeader("SOAPAction", soapAction);
StringEntity data = new StringEntity(soapXml,
Charset.forName("UTF-8"));
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印响应内容
retStr = EntityUtils.toString(httpEntity, "UTF-8");
log.info("response:" + retStr);
}
// 释放资源
closeableHttpClient.close();
} catch (Exception e) {
log.error("exception in doPostSoap1_2", e);
}
return retStr;
}
public static void main(String[] args) {
String url = "http://192.168.10.179:8080/helloService?wsdl";
String targetNamespace = "http://webservice.restful.design.bp.com/";
String funName = "sayHello";
Map bodyMap = new HashMap() {{
put("message", "你好");
}};
String xml = SoapUtils.buildSoapXml(targetNamespace, funName, bodyMap);
System.out.println(xml);
try {
System.out.println(doPostSoap1_1(url, xml, new HashMap<String, Object>() {{
put("Content-Type", "text/xml; charset=utf-8");
}}));
} catch (DubboProviderException e) {
e.printStackTrace();
}
}
}
package com.wanji.structure;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
/**
* 所有模型类继承此抽象类方便打印输出
* @Author:
* @Description:
* @Date: 2018/3/4 上午11:32
*/
public abstract class BaseModel implements Serializable {
/** 路口编号 */
String crossId;
/** 行驶方向:0、正向;1、逆向 */
String direction;
/** 创建时间 */
String gmtCreate;
/** 修改时间 */
String gmtModified;
/** 当前页 */
Integer currentPage;
/** 每页大小 */
Integer pageSize;
String objectString;
@Override
public String toString() {
String result = this.objectString;
if(result != null){
return result;
}
try {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
} catch (Exception e) {
return super.toString();
}
}
public String getCrossId() {
return crossId;
}
public void setCrossId(String crossId) {
this.crossId = crossId;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public String getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(String gmtCreate) {
this.gmtCreate = gmtCreate;
}
public String getGmtModified() {
return gmtModified;
}
public void setGmtModified(String gmtModified) {
this.gmtModified = gmtModified;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
}
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