Commit 75761ba1 authored by 竹天卫's avatar 竹天卫

富平数据采集项目 后台代码 start。。。。。。。。。。。

parents
Pipeline #279 failed with stages
# Created by .ignore support plugin (hsz.mobi)
### Example user template template
### Example user template
# IntelliJ project files
.idea
.idea/*
*.iml
out
gen
/rebel.xml
/logs/*
/target
### Java template
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
/mybatis-generator/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst
/mybatis-generator/target/maven-archiver/pom.properties
/cement-common/common-swagger/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst
/cement-common/common-swagger/target/maven-archiver/pom.properties
/cement-common/common-swagger/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst
/cement-common/common-swagger/target/maven-archiver/pom.properties
/cement-common/common-swagger/target/
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.wise.sc.acquisition</groupId>
<artifactId>data-acquisition</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>acquisition-business</artifactId>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<version>5.1.45</version>-->
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>cn.wise.sc.tjcement</groupId>
<artifactId>common-swagger</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<!-- JwtUtil类需要jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.oschina.zcx7878/fastdfs-client-java -->
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aspose/aspose-slides -->
<dependency>
<groupId>com.aspose</groupId> <!--自定义-->
<artifactId>cells</artifactId> <!--自定义-->
<version>1.0</version> <!--自定义-->
<scope>system</scope> <!--system,类似provided,需要显式提供依赖的jar以后,Maven就不会在Repository中查找它-->
<systemPath>${basedir}/lib/aspose-cells-8.5.2.jar</systemPath> <!--项目根目录下的lib文件夹下-->
</dependency>
<dependency>
<groupId>com.aspose</groupId> <!--自定义-->
<artifactId>words</artifactId> <!--自定义-->
<version>1.0</version> <!--自定义-->
<scope>system</scope> <!--system,类似provided,需要显式提供依赖的jar以后,Maven就不会在Repository中查找它-->
<systemPath>${basedir}/lib/words.jar</systemPath> <!--项目根目录下的lib文件夹下-->
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.0</version>
<exclusions>
<exclusion>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jcommon</artifactId>
<version>1.0.24</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.0</version>
</dependency>
<!-- lombok start -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
<!-- lombok end -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
</dependencies>
<profiles>
<profile>
<!-- 开发环境 -->
<id>dev</id>
<properties>
<env>dev</env><!-- 节点名字environment是自己随意取的 -->
</properties>
<activation>
<activeByDefault>true</activeByDefault><!-- 默认激活该profile节点-->
</activation>
</profile>
<profile>
<!-- 生产环境 -->
<id>prod</id>
<properties>
<env>prod</env>
</properties>
<!--<activation>
<activeByDefault>true</activeByDefault>&lt;!&ndash; 默认激活该profile节点&ndash;&gt;
</activation>-->
</profile>
<profile>
<!-- 演示环境 -->
<id>show</id>
<properties>
<env>show</env>
</properties>
<!-- <activation>
<activeByDefault>true</activeByDefault>&lt;!&ndash; 默认激活该profile节点&ndash;&gt;
</activation>-->
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>zip</nonFilteredFileExtension>
<nonFilteredFileExtension>cer</nonFilteredFileExtension>
<nonFilteredFileExtension>pfx</nonFilteredFileExtension>
<nonFilteredFileExtension>py</nonFilteredFileExtension>
<nonFilteredFileExtension>keystore</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory> <!--指定文件下-->
<filtering>true</filtering> <!--动态配置-->
<excludes> <!--去除多余的文件-->
<exclude>application-dev.yml</exclude>
<exclude>application-prod.yml</exclude>
<exclude>application-show.yml</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering> <!--动态配置 ${env}-->
<includes> <!--包含加载的文件(env 默认加载uat 具体看配置)-->
<include>application-${env}.yml</include>
</includes>
</resource>
<resource>
<directory>src/main/java/cn/wise/sc/cement/business/mapper/xml</directory>
<filtering>true</filtering>
<includes>
<include>*.xml</include>
</includes>
<targetPath>cn/wise/sc/cement/business/mapper</targetPath>
</resource>
</resources>
</build>
</project>
\ No newline at end of file
package cn.wise.sc.cement.business;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
import java.util.TimeZone;
/**
* 启动类
*
* @author zhutianwei
*/
@SpringBootApplication
@EnableScheduling
@MapperScan("cn.wise.sc.cement.business.mapper")
public class AcquisitionApplication {
public static void main(String[] args) {
// 系统默认的时区
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
SpringApplication.run(AcquisitionApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package cn.wise.sc.cement.business.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
@Configuration
public class DateConfig {
/**
* 默认日期时间格式
*/
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 默认日期格式
*/
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/**
* 默认时间格式
*/
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
/**
* LocalDate转换器,用于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, LocalDate> localDateConverter() {
return new Converter<String, LocalDate>() {
@Override
public LocalDate convert(String source) {
return LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
}
};
}
/**
* LocalDateTime转换器,用于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, LocalDateTime> localDateTimeConverter() {
return new Converter<String, LocalDateTime>() {
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
}
};
}
/**
* LocalTime转换器,用于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, LocalTime> localTimeConverter() {
return new Converter<String, LocalTime>() {
@Override
public LocalTime convert(String source) {
return LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
}
};
}
/**
* Date转换器,用于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, Date> dateConverter() {
return new Converter<String, Date>() {
@Override
public Date convert(String source) {
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
try {
return format.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
};
}
/**
* Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
*/
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
//ObjectMapper忽略多余字段
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//LocalDateTime系列序列化和反序列化模块,继承自jsr310,我们在这里修改了日期格式
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//Date序列化和反序列化
javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
String formattedDate = formatter.format(date);
jsonGenerator.writeString(formattedDate);
}
});
javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
});
// 注册新的模块到objectMapper
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
/**
* @date :Created in 2019-03-21 10:21
* @description:用途:
*/
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private ObjectMapper objectMapper = new ObjectMapper();
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
static {
//解决fastJson autoType is not support错误
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.defaultInstance().constructType(clazz);
}
}
package cn.wise.sc.cement.business.config;
import cn.wise.sc.cement.business.exception.BusinessOldException;
import cn.wise.sc.cement.business.wrapper.WrapMapper;
import cn.wise.sc.cement.business.wrapper.Wrapper;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
@ControllerAdvice
@RestController
public class GlobalDefaultExceptionHandler extends AbstractErrorController {
@ExceptionHandler(value = RuntimeException.class)
@ResponseBody
public Wrapper defaultErrorHandler(HttpServletResponse response, BusinessOldException e) {
response.setStatus(e.getStatusCode().value());
return WrapMapper.error(e.getMessage());
}
public GlobalDefaultExceptionHandler(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
private static final String ERROR_PATH = "/error";
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public Wrapper error(HttpServletRequest request) {
WebRequest webRequest = new ServletWebRequest(request);
Throwable e = getError(webRequest);
if (e == null) {
Map<String, Object> attributes = getErrorAttributes(request, false);
Object timestamp = attributes.get("timestamp");
Object status = attributes.get("status");
String error = attributes.get("error").toString();
String message = attributes.get("message").toString();
Object path = attributes.get("path");
//todo 上线后更改为error
return WrapMapper.wrap(Integer.parseInt(status.toString()), message);
} else {
return WrapMapper.error(e.getMessage());
}
}
private Throwable getError(WebRequest webRequest) {
return (Throwable) this.getAttribute(webRequest, "javax.servlet.error.exception");
}
private Object getAttribute(RequestAttributes requestAttributes, String name) {
return requestAttributes.getAttribute(name, 0);
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class MapStringTypeHandler<T> extends BaseTypeHandler<Map<String, T>> {
private Class<T> clazz;
//private static final TypeReference<HashMap<String, String>> mapStrStrTypeRef = new TypeReference<HashMap<String, String>>(){};
private final TypeReference<HashMap<String, T>> typeRef = new TypeReference<HashMap<String, T>>() {
};
public MapStringTypeHandler(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Map<String, T> parameter, JdbcType jdbcType) throws SQLException {
String json = JSON.toJSONString(parameter);
ps.setString(i, json);
}
@Override
public Map<String, T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parseJson(rs.getString(columnName));
}
@Override
public Map<String, T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parseJson(rs.getString(columnIndex));
}
@Override
public Map<String, T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parseJson(cs.getString(columnIndex));
}
private Map<String, T> parseJson(String json) {
if (String.class == clazz || Integer.class == clazz || Boolean.class == clazz) {
return JSON.parseObject(json, typeRef);
}
Map<String, T> result = new HashMap<>();
JSON.parseObject(json).forEach((k, v) -> result.put(k, JSON.parseObject(JSON.toJSONString(v), clazz)));
return result;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author miemie
* @since 2018-08-10
*/
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
// 开启 count 的 join 优化,只针对 left join !!!
return new PaginationInterceptor().setCountSqlParser(new JsqlParserCountOptimize(true));
}
}
package cn.wise.sc.cement.business.config;
import com.alibaba.fastjson.parser.ParserConfig;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.config.TransportMode;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* @description:用途: @EnableCaching 开启声明式缓存支持. 之后就可以使用 @Cacheable/@CachePut/@CacheEvict 注解缓存数据.
*/
@Configuration
@EnableCaching
public class RedisCacheConfig {
private RedisConnectionFactory redisConnectionFactory;
public RedisCacheConfig(RedisConnectionFactory redisConnectionFactory) {
this.redisConnectionFactory = redisConnectionFactory;
}
// @Bean
// public Jedis jedis() {
// JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// jedisPoolConfig.setMaxTotal(80);
// jedisPoolConfig.setMinIdle(20);
// jedisPoolConfig.setMaxIdle(80);
// JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);
// return jedisPool.getResource();
// }
/**
* 覆盖默认的配置
*
* @return RedisTemplate
*/
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
// 设置value的序列化规则和key的序列化规则
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
template.setDefaultSerializer(fastJsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
/**
* 解决注解方式存放到redis中的值是乱码的情况
*
* @param factory
* @return CacheManager
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
// 配置注解方式的序列化
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
RedisCacheConfiguration redisCacheConfiguration =
config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer))
//配置注解默认的过期时间
.entryTtl(Duration.ofDays(1));
// 加入白名单 https://github.com/alibaba/fastjson/wiki/enable_autotype
ParserConfig.getGlobalInstance().addAccept("cn.wise");
return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
}
// @Bean
// public RedissonClient redissonClient() {
// Config config = new Config();
// config.useSingleServer()
// .setAddress("redis://127.0.0.1:6379")
// .setConnectionMinimumIdleSize(10)
// .setConnectionPoolSize(50)
// .setPingConnectionInterval(60)
// .setIdleConnectionTimeout(6000)
// .setConnectTimeout(10000)
// .setTimeout(3000);
// return Redisson.create(config);
// }
}
package cn.wise.sc.cement.business.config;
import cn.wise.sc.cement.business.util.GlobalHolder;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 上下文初始化
* 以及跨域的支持
*/
public class RequestInterceptor extends HandlerInterceptorAdapter {
/**
* 拦截request和response并放到上下文中
*
* @param request 要拦截的request
* @param response 要拦截的response
* @param handler spring 机制传递过来的
* @return 不中断,继续执行,返回为true
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
//request 和response存到 上下文中
GlobalHolder.setHttpResponse(response);
GlobalHolder.setHttpRequest(request);
return super.preHandle(request, response, handler);
}
/**
* 处理完成 从上下文中移除 request 和respseon
*
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
GlobalHolder.remove();
super.afterCompletion(request, response, handler, ex);
}
}
package cn.wise.sc.cement.business.config;
import cn.wise.sc.cement.business.filter.SwaggerInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.MappedInterceptor;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
//api接口包扫描路径
public static final String SWAGGER_SCAN_BASE_PACKAGE = "cn.wise.sc.cement.business.controller";
public static final String VERSION = "1.0.0";
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2).groupName("swagger接口文档")
.apiInfo(new ApiInfoBuilder().title("swagger接口文档")
.contact(new Contact("Wisenergy", "http://www.wisenergy.cn/", "service@wisenergy.cn"))
.description("天津院项目")
.version(VERSION).build())
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
.paths(PathSelectors.any()).build()
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
.enableUrlTemplating(false)
;
}
private ApiKey apiKey() {
return new ApiKey("BearerToken", "Authorization", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/.*"))
.build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(new SecurityReference("BearerToken", authorizationScopes));
}
@Value("${swagger.basic.username}")
private String username;
@Value("${swagger.basic.password}")
private String password;
/* 必须在此处配置拦截器,要不然拦不到swagger的静态资源 */
@Bean
@ConditionalOnProperty(name = "swagger.basic.enable", havingValue = "true")
public MappedInterceptor getMappedInterceptor() {
return new MappedInterceptor(new String[]{"/swagger-ui.html", "/webjars/**"}, new SwaggerInterceptor(username, password));
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.config;
/**
* top地址相关配置
*
* @author openapi@dingtalk
* @date 2020/2/4
*/
public class UrlConstant {
private static final String HOST = "https://oapi.dingtalk.com";
/**
* 钉钉网关 gettoken 地址
*/
public static final String URL_GET_TOKEN = HOST + "/gettoken";
/**
* 获取 jsapi_ticket 地址
*/
public static final String URL_GET_JSTICKET = HOST + "/get_jsapi_ticket";
/**
* 获取用户在企业内 userId 的接口URL
*/
public static final String URL_GET_USER_INFO = HOST + "/user/getuserinfo";
/**
* 获取用户姓名的接口URL
*/
public static final String URL_USER_GET = HOST + "/user/get";
/**
* 获取部门列表接口URL
*/
public static final String URL_DEPARTMENT_LIST = HOST + "/department/list";
/**
* 获取部门用户接口URL
*/
public static final String URL_USER_SIMPLELIST = HOST + "/user/simplelist";
}
package cn.wise.sc.cement.business.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 加载自定义的 拦截器
*/
@Configuration
public class WebInterceptorConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/**");
}
}
package cn.wise.sc.cement.business.config;
import org.apache.catalina.session.StandardSessionFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
@Configuration
public class WebSocketConfig extends ServerEndpointConfig.Configurator {
private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);
/**
* 修改握手信息
*/
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
StandardSessionFacade ssf = (StandardSessionFacade) request.getHttpSession();
if (ssf != null) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
//关键操作
sec.getUserProperties().put("sessionId", httpSession.getId());
log.info("获取到的SessionID:" + httpSession.getId());
}
super.modifyHandshake(sec, request, response);
}
/**
* WebSocket的支持 b
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
//这个对象说一下,貌似只有服务器是tomcat的时候才需要配置,具体我没有研究
return new ServerEndpointExporter();
}
}
package cn.wise.sc.cement.business.config.lock;
import org.redisson.api.RLock;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
public interface DistributedLocker {
RLock lock(String lockKey);
RLock lock(String lockKey, int timeout);
RLock lock(String lockKey, TimeUnit unit, int timeout);
boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime);
void unlock(String lockKey);
void unlock(RLock lock);
<T> T executeLock(String key, Function<String, T> consumer, String t);
<T> void executeLock(String lockKey, Consumer<T> consumer, T t);
}
\ No newline at end of file
package cn.wise.sc.cement.business.config.lock;
import org.redisson.api.RLock;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
public class RedissLockUtil {
private static DistributedLocker redissLock;
public static void setLocker(DistributedLocker locker) {
redissLock = locker;
}
public static RLock lock(String lockKey) {
return redissLock.lock(lockKey);
}
public static <T> T readWriteLock(String lockKey, Function<String, T> function) {
return redissLock.executeLock(lockKey, function, null);
}
public static <T> void playersLock(String lockKey, Consumer<T> consumer, T t) {
redissLock.executeLock(lockKey, consumer, null);
}
public static void unlock(String lockKey) {
redissLock.unlock(lockKey);
}
public static void unlock(RLock lock) {
redissLock.unlock(lock);
}
public static RLock lock(String lockKey, int timeout) {
return redissLock.lock(lockKey, timeout);
}
public static RLock lock(String lockKey, TimeUnit unit, int timeout) {
return redissLock.lock(lockKey, unit, timeout);
}
public static boolean tryLock(String lockKey, int waitTime, int leaseTime) {
return redissLock.tryLock(lockKey, TimeUnit.SECONDS, waitTime, leaseTime);
}
public static boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
return redissLock.tryLock(lockKey, unit, waitTime, leaseTime);
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.config.lock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
@Slf4j
public class RedissonDistributedLocker implements DistributedLocker {
private RedissonClient redissonClient;
@Override
public RLock lock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock();
return lock;
}
@Override
public RLock lock(String lockKey, int leaseTime) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(leaseTime, TimeUnit.SECONDS);
return lock;
}
@Override
public RLock lock(String lockKey, TimeUnit unit, int timeout) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(timeout, unit);
return lock;
}
@Override
public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
RLock lock = redissonClient.getLock(lockKey);
try {
return lock.tryLock(waitTime, leaseTime, unit);
} catch (InterruptedException e) {
return false;
}
}
public static void realeaseLock(RLock fairLock) {
fairLock.unlock();
}
@Override
public void unlock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.unlock();
}
@Override
public void unlock(RLock lock) {
lock.unlock();
}
@Override
public <T> T executeLock(String key, Function<String, T> function, String t) {
RLock lock = redissonClient.getLock(key);
boolean locked = false;
try {
lock.lock();
return (T) function.apply(t);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return null;
}
@Override
public <T> void executeLock(String lockKey, Consumer<T> consumer, T t) {
RLock lock = redissonClient.getLock(lockKey);
boolean locked = false;
try {
while (true) {
locked = lock.tryLock();
if (locked) break;
}
if (locked) {
consumer.accept(t);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (locked) {
lock.unlock();
}
}
}
public void setRedissonClient(RedissonClient redissonClient) {
this.redissonClient = redissonClient;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.controller;
import cn.wise.sc.cement.business.enumation.FileExt;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.dfs.FastDFSUtils;
import cn.wise.sc.cement.business.util.dfs.FileTypeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 附件管理Controller
*
* @author ztw
*/
@Api(tags = "附件管理")
@RestController
@RequestMapping("/enclosure")
public class EntityEnclosureController {
private static final Logger logger = LoggerFactory.getLogger("EntityEnclosureController");
@Resource
protected HttpServletResponse response;
@Autowired
protected HttpServletRequest request;
@Autowired
private ISysUserService userService;
/**
* 判断文件大小
*
* @param len
* 文件长度
* @param size
* 限制大小
* @param unit
* 限制单位(B,K,M,G)
* @return
*/
public static boolean checkFileSize(Long len, int size, String unit) {
// long len = file.length();
double fileSize = 0;
if ("B".equals(unit.toUpperCase())) {
fileSize = (double) len;
} else if ("K".equals(unit.toUpperCase())) {
fileSize = (double) len / 1024;
} else if ("M".equals(unit.toUpperCase())) {
fileSize = (double) len / 1048576;
} else if ("G".equals(unit.toUpperCase())) {
fileSize = (double) len / 1073741824;
}
if (fileSize > size) {
return false;
}
return true;
}
@ApiOperation(value = "单个文件上传")
@PostMapping("/fileUpLoad")
public BaseResponse fileUpLoad(MultipartFile file) {
Map<String, Object> map = new HashMap<>();
String filePath = null;
String fileName = null;
String extName = null;
try {
boolean ref = checkFileSize( file.getSize(),30,"M");
if(!ref){
return BaseResponse.errorMsg("文件不能大于30M");
}
LoginUser loginUser = userService.getLoginUser();
if (loginUser != null) {
filePath = FastDFSUtils.uploadPic(file.getBytes(), file.getOriginalFilename(), file.getSize());
fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
} else {
return BaseResponse.noLogin("登录信息失效");
}
if (extName.contains(FileExt.EXCL.getName()) || extName.contains(FileExt.EXCLX.getName())) {
String pdfPath = FastDFSUtils.conventAndUploadExcel(file.getInputStream(), fileName);
map.put("pdfPath", pdfPath);
} else if (extName.contains(FileExt.DOC.getName()) || extName.contains(FileExt.DOCX.getName())) {
String pdfPath = FastDFSUtils.conventAndUploadWord(file.getInputStream(), fileName);
map.put("pdfPath", pdfPath);
} else {
map.put("pdfPath", filePath);
}
String picUrl = filePath;
map.put("fileUrl", picUrl);
map.put("fileName", fileName);
map.put("extName", extName);
return BaseResponse.okData(map);
} catch (Exception e) {
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
@ApiOperation(value = "单个图片上传")
@PostMapping("/imgUpLoad")
public BaseResponse imgUpLoad(MultipartFile file) {
Map<String, Object> map = new HashMap<>();
String filePath = null;
String fileName = null;
String extName = null;
try {
boolean ref = checkFileSize( file.getSize(),30,"M");
if(!ref){
return BaseResponse.errorMsg("文件不能大于30M");
}
LoginUser loginUser = userService.getLoginUser();
if (loginUser != null) {
if (!FileTypeUtil.isImageByExtension(file.getOriginalFilename())) {
return BaseResponse.errorMsg("请上传有效图片");
}
filePath = FastDFSUtils.uploadPic(file.getBytes(), file.getOriginalFilename(), file.getSize());
fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
} else {
return BaseResponse.noLogin("登录信息失效");
}
String picUrl = filePath;
map.put("fileUrl", picUrl);
map.put("fileName", fileName);
map.put("extName", extName);
map.put("pdfPath", filePath);
return BaseResponse.okData(map);
} catch (Exception e) {
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
@ApiOperation(value = "多个文件上传")
@PostMapping("/filesUpLoad")
public BaseResponse filesUpLoad(HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
List<MultipartFile> files = null;
String filePath = null;
String fileName = null;
String extName = null;
List<Map<String, Object>> filePathList = null;
try {
filePathList = new ArrayList<>();
files = ((MultipartHttpServletRequest) request).getFiles("files");
LoginUser loginUser = userService.getLoginUser();
if (loginUser != null) {
if (files != null && files.size() > 0) {
for (MultipartFile file : files) {
boolean ref = checkFileSize( file.getSize(),30,"M");
if(!ref){
return BaseResponse.errorMsg("文件不能大于30M");
}
Map<String, Object> mapSub = new HashMap<>();
filePath = FastDFSUtils.uploadPic(file.getBytes(), file.getOriginalFilename(), file.getSize());
fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String picUrl = filePath;
mapSub.put("fileUrl", picUrl);
mapSub.put("fileName", fileName);
mapSub.put("extName", extName);
if (extName.contains(FileExt.EXCL.getName()) || extName.contains(FileExt.EXCLX.getName())) {
String pdfPath = FastDFSUtils.conventAndUploadExcel(file.getInputStream(), fileName);
mapSub.put("pdfPath", pdfPath);
} else if (extName.contains(FileExt.DOC.getName()) || extName.contains(FileExt.DOCX.getName())) {
String pdfPath = FastDFSUtils.conventAndUploadWord(file.getInputStream(), fileName);
mapSub.put("pdfPath", pdfPath);
} else {
mapSub.put("pdfPath", filePath);
}
filePathList.add(mapSub);
}
} else {
return BaseResponse.errorMsg("没有文件");
}
} else {
return BaseResponse.noLogin("登录信息失效");
}
return BaseResponse.okData(map);
} catch (Exception e) {
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
@ApiOperation(value = "单个文件下载")
@PostMapping("/fileDownload")
public BaseResponse fileDownload(String fileUrl, String fileName, String extName) {
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + extName);
response.setContentType("application/force-download");
out = response.getOutputStream();
LoginUser loginUser = userService.getLoginUser();
if (loginUser != null) {
fileUrl = fileUrl.substring(fileUrl.indexOf("g"));
byte[] by = FastDFSUtils.fileDownload(fileUrl);
out.write(by);
out.close();
// BASE64Encoder encoder = new BASE64Encoder();
// String data = encoder.encode(by);
// return BaseResponse.okMsg(data);
} else {
return BaseResponse.noLogin("登录信息失效");
}
return BaseResponse.okMsg("成功");
} catch (Exception e) {
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
@ApiOperation(value = "app扫描二维码下载")
@GetMapping("/appDownload")
public BaseResponse appDownload(String fileUrl) {
Map<String, Object> map = new HashMap<>();
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment;filename=app-release.apk");
response.setContentType("application/force-download");
out = response.getOutputStream();
fileUrl = fileUrl.substring(fileUrl.indexOf("g"));
byte[] by = FastDFSUtils.fileDownload(fileUrl);
out.write(by);
out.close();
return BaseResponse.okMsg("成功");
} catch (Exception e) {
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
@ApiOperation(value = "删除相关文件")
@PostMapping("/fileDeleted")
public BaseResponse fileDeleted(String[] filePaths) {
Map<String, Object> map = new HashMap<>();
String filePath = null;
boolean rel = false;
try {
LoginUser loginUser = userService.getLoginUser();
if (loginUser != null) {
for (String url : filePaths) {
/*filePath = url.substring(0,url.indexOf("g"));*/
rel = FastDFSUtils.deletePic(url);
if (!rel) {
return BaseResponse.errorMsg("删除失败");
}
}
} else {
return BaseResponse.noLogin("登录信息失效");
}
return BaseResponse.okMsg("成功");
} catch (Exception e) {
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
}
package cn.wise.sc.cement.business.controller;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.service.ISysLogsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-08-24
*/
@Api(tags = "系统管理-日志管理")
@RestController
@RequestMapping("/business/sys-logs")
public class SysLogsController {
private static final Logger log = LoggerFactory.getLogger("SysLogsController");
@Autowired
private ISysLogsService logsService;
@ApiOperation(value = "日志分页列表")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "startDate", value = "开始日期", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "endDate", value = "结束日期", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "objType", value = "日志类型(0系统日志, 1委托管理)", paramType = "query", dataType = "Integer"),
@ApiImplicitParam(name = "objId", value = "对象表id", paramType = "query", dataType = "Integer")
})
@GetMapping("/getPage")
public BaseResponse getPage(PageQuery pageQuery, String startDate, String endDate, Integer objType, Integer objId) {
try {
return logsService.getPage(pageQuery, startDate, endDate, objType, objId);
} catch (Exception e) {
log.debug("日志分页列表{}", e);
}
return BaseResponse.errorMsg("失败!");
}
}
package cn.wise.sc.cement.business.controller;
import cn.wise.sc.cement.business.entity.SysPermission;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.service.ISysPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-08-20
*/
@Api(tags = "系统管理-权限管理")
@RestController
@RequestMapping("/business/sys-permission")
public class SysPermissionController {
private static final Logger log = LoggerFactory.getLogger("SysPermissionController");
@Autowired
private ISysPermissionService permissionService;
@ApiOperation(value = "当前登录用户拥有的权限")
@GetMapping("/current")
public BaseResponse permissionsCurrent() {
try {
return permissionService.current();
} catch (Exception e) {
log.debug("当前登录用户拥有的权限{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "菜单列表")
@GetMapping("/permissionsList")
public BaseResponse permissionsList() {
try {
return permissionService.permissionsList();
} catch (Exception e) {
log.debug("菜单列表{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "一级菜单")
@GetMapping("/parents")
public BaseResponse parentMenu() {
try {
return permissionService.parents();
} catch (Exception e) {
log.debug("一级菜单{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "菜单树")
@GetMapping("/tree")
public BaseResponse tree() {
try {
return permissionService.tree();
} catch (Exception e) {
log.debug("菜单树{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "根据角色id获取权限")
@GetMapping("/listByRoleId")
public BaseResponse listByRoleId(Integer roleId) {
try {
return permissionService.listByRoleId(roleId);
} catch (Exception e) {
log.debug("根据角色id获取权限{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "保存菜单")
@PostMapping("/create")
public BaseResponse create(@RequestBody SysPermission permission) {
try {
return permissionService.create(permission);
} catch (Exception e) {
log.debug("保存菜单{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "修改菜单")
@PostMapping("/update")
public BaseResponse update(@RequestBody SysPermission permission) {
try {
return permissionService.update(permission);
} catch (Exception e) {
log.debug("修改菜单{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@GetMapping("/{id}")
@ApiOperation(value = "菜单详情")
public BaseResponse get(@PathVariable Integer id) {
try {
SysPermission permission = permissionService.getById(id);
return BaseResponse.okData(permission);
} catch (Exception e) {
log.debug("根据菜单id获取菜单{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@PostMapping("/delete/{id}")
@ApiOperation(value = "删除菜单")
@Transactional
public BaseResponse delete(@PathVariable Integer id) {
try {
permissionService.removeById(id);
return BaseResponse.okMsg("成功");
} catch (Exception e) {
log.debug("删除菜单{}", e);
}
return BaseResponse.errorMsg("失败!");
}
}
package cn.wise.sc.cement.business.controller;
import cn.wise.sc.cement.business.entity.SysPost;
import cn.wise.sc.cement.business.entity.SysUser;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.PostQuery;
import cn.wise.sc.cement.business.service.ISysPostService;
import cn.wise.sc.cement.business.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-08-25
*/
@Api(tags = "系统管理-职务管理")
@RestController
@RequestMapping("/business/sys-post")
public class SysPostController {
private static final Logger log = LoggerFactory.getLogger("SysPostController");
@Autowired
private ISysPostService postService;
@Autowired
private ISysUserService userService;
@ApiOperation(value = "职务分页列表")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "name", value = "职务名称", paramType = "query", dataType = "String")
})
@GetMapping("/getPage")
public BaseResponse getPage(PageQuery pageQuery, String name) {
try {
return postService.getPage(pageQuery, name);
} catch (Exception e) {
log.debug("职务分页列表{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "新增职务")
@PostMapping("/create")
public BaseResponse create(@RequestBody PostQuery query) {
try {
return postService.create(query);
} catch (Exception e) {
log.debug("新增职务{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "修改职务")
@PostMapping("/update")
public BaseResponse update(@RequestBody PostQuery query) {
try {
return postService.update(query);
} catch (Exception e) {
log.debug("修改职务{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "职务详情")
@GetMapping("/{id}")
public BaseResponse getById(@PathVariable Integer id) {
try {
SysPost post = postService.getById(id);
if (post == null) {
return BaseResponse.errorMsg("信息错误!");
}
return BaseResponse.okData(post);
} catch (Exception e) {
log.debug("职务详情{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "职务列表")
@GetMapping("/getList")
public BaseResponse getList() {
try {
List<SysPost> list = postService.list();
return BaseResponse.okData(list);
} catch (Exception e) {
log.debug("职务列表{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "删除职务")
@PostMapping("/delete/{id}")
public BaseResponse delete(@PathVariable Integer id) {
try {
if(id == 1 || id == 2){
return BaseResponse.errorMsg("职务不允许删除!");
}
QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
sysUserQueryWrapper.eq("post_id", id);
Integer conunts = userService.count(sysUserQueryWrapper);
if (conunts != 0 && conunts > 0) {
return BaseResponse.errorMsg(conunts + "个用户正在使用!");
}
postService.removeById(id);
return BaseResponse.okData("删除成功");
} catch (Exception e) {
log.debug("删除职务{}", e);
}
return BaseResponse.errorMsg("失败!");
}
}
package cn.wise.sc.cement.business.controller;
import cn.wise.sc.cement.business.entity.SysRole;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.RoleQuery;
import cn.wise.sc.cement.business.service.ISysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-08-20
*/
@Api(tags = "系统管理-角色管理")
@RestController
@RequestMapping("/business/sys-role")
public class SysRoleController {
private static final Logger log = LoggerFactory.getLogger("SysRoleController");
@Autowired
private ISysRoleService roleService;
@ApiOperation(value = "角色分页列表")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "name", value = "角色名称", paramType = "query", dataType = "String")
})
@GetMapping("/getPage")
public BaseResponse getPage(PageQuery pageQuery, String name) {
try {
return roleService.getPage(pageQuery, name);
} catch (Exception e) {
log.debug("角色分页列表{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "新增角色")
@PostMapping("/create")
public BaseResponse create(@RequestBody RoleQuery query) {
try {
return roleService.create(query);
} catch (Exception e) {
log.debug("新增角色{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "修改角色")
@PostMapping("/update")
public BaseResponse update(@RequestBody RoleQuery query) {
try {
return roleService.update(query);
} catch (Exception e) {
log.debug("修改角色{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "角色详情")
@GetMapping("/{id}")
public BaseResponse getById(@PathVariable Integer id) {
try {
SysRole role = roleService.getById(id);
if (role == null) {
return BaseResponse.errorMsg("信息错误!");
}
return BaseResponse.okData(role);
} catch (Exception e) {
log.debug("角色详情{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "所有角色")
@GetMapping("/getAll")
public BaseResponse getAll() {
try {
List<SysRole> list = roleService.list();
return BaseResponse.okData(list);
} catch (Exception e) {
log.debug("所有角色{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "根据用户id获取拥有的角色")
@GetMapping("/byUserId")
public BaseResponse byUserId(Integer userId) {
try {
return roleService.byUserId(userId);
} catch (Exception e) {
log.debug("根据用户id获取拥有的角色{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "删除角色")
@PostMapping("/delete/{id}")
public BaseResponse delete(@PathVariable Integer id) {
try {
return roleService.delete(id);
} catch (Exception e) {
log.debug("删除角色{}", e);
}
return BaseResponse.errorMsg("失败!");
}
}
package cn.wise.sc.cement.business.controller;
import cn.wise.sc.cement.business.entity.SysUser;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.SysUserEnclosureQuery;
import cn.wise.sc.cement.business.model.query.UserQuery;
import cn.wise.sc.cement.business.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-08-14
*/
@Api(tags = "系统管理-人员管理")
@RestController
@RequestMapping("/tcdri/sys-user")
public class SysUserController {
private static final Logger log = LoggerFactory.getLogger("SysUserController");
@Autowired
private ISysUserService userService;
@ApiOperation(value = "人员分页列表")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "status", value = "状态0:禁用 1:启用", paramType = "query", dataType = "Integer"),
@ApiImplicitParam(name = "groupId", value = "工作组id", paramType = "query", dataType = "Integer"),
@ApiImplicitParam(name = "name", value = "姓名", paramType = "query", dataType = "String")
})
@GetMapping("/getPage")
public BaseResponse getPage(PageQuery pageQuery, Integer status, Integer groupId, String name) {
try {
return userService.getPage(pageQuery, status, groupId, name);
} catch (Exception e) {
log.debug("人员分页列表{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "新增人员")
@PostMapping("/create")
public BaseResponse create(@RequestBody UserQuery query) {
try {
return userService.create(query);
} catch (Exception e) {
log.debug("新增人员{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "更新人员")
@PostMapping("/update")
public BaseResponse update(@RequestBody UserQuery query) {
try {
return userService.update(query);
} catch (Exception e) {
log.debug("更新人员{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "启用禁用")
@PostMapping("/status")
public BaseResponse status(Integer status, Integer id) {
try {
return userService.status(status, id);
} catch (Exception e) {
log.debug("启用禁用{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "人员详情")
@GetMapping("/{id}")
public BaseResponse getById(@PathVariable Integer id) {
try {
return userService.findById(id);
} catch (Exception e) {
log.debug("人员详情{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "人员列表")
@GetMapping("/getList")
public BaseResponse getList() {
try {
LoginUser loginUser = userService.getLoginUser();
QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
if(loginUser != null && loginUser.getGroupId() != null){
queryWrapper.eq("group_id", loginUser.getGroupId());
}
List<SysUser> list = userService.list(queryWrapper);
return BaseResponse.okData(list);
} catch (Exception e) {
log.debug("人员列表{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "上传附件")
@PostMapping("/uploadPeoplePF")
public BaseResponse uploadPeoplePF(@RequestBody SysUserEnclosureQuery query){
try {
return userService.uploadPeoplePF(query);
}catch (Exception e){
log.debug("上传附件{}",e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "附件分页列表")
@GetMapping("/getUserEnclosurePage")
public BaseResponse getUserEnclosurePage(PageQuery pageQuery, Integer userId) {
try {
return userService.getUserEnclosurePage(pageQuery, userId);
} catch (Exception e) {
log.debug("附件分页列表{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "删除人员附件")
@PostMapping("/deleteUserEnclosure")
public BaseResponse deleteUserEnclosure(Integer id) {
try {
return userService.deleteUserEnclosure(id);
} catch (Exception e) {
log.debug("删除人员附件{}", e);
}
return BaseResponse.errorMsg("失败!");
}
// @ApiOperation("人员详情导出列表")
// @PostMapping("/exportList")
// public void exportList(Integer status,String filename,String name, HttpServletResponse response) {
// try {
// userService.exportList(status, filename,name, response);
// } catch (Exception e) {
// log.debug("人员详情导出列表{}", e);
// }
// }
}
package cn.wise.sc.cement.business.controller;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.service.ISysUserMessageService;
import cn.wise.sc.cement.business.wrapper.WrapMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-10-13
*/
@Api(tags = "企业微信移动端-消息管理")
@RestController
@RequestMapping("/business/sys-user-message")
public class SysUserMessageController {
private static final Logger log = LoggerFactory.getLogger("SysUserMessageController");
@Autowired
private ISysUserMessageService userMessageService;
@ApiOperation(value = "消息通知列表")
@GetMapping("/getMessages")
public BaseResponse getMessages() {
try {
return userMessageService.getMessages();
} catch (Exception e) {
log.debug("消息通知列表{}", e);
}
return BaseResponse.errorMsg("失败!");
}
}
package cn.wise.sc.cement.business.controller;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.service.impl.WeiXinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Api(tags = "登录接口")
@RestController
@RequestMapping("/tcdri/weixin")
public class WeiXinController {
//
private static final Logger log = LoggerFactory.getLogger("WeiXinController");
@Autowired
private WeiXinService weiXinService;
@Value("${spring.profiles.active}")
private String active;
@ApiOperation(value = "获取登录token-小程序端")
@GetMapping("/getToken")
public BaseResponse getToken(String code) {
log.debug("============================================");
log.debug("code: {}", code);
log.debug("=============================================");
try {
if(active.equals("dev")){
//测试服务器
return weiXinService.getTestToken(code);
}else{
//正式服务器
// return weiXinService.getToken(code, "APP");
}
} catch (Exception e) {
log.debug("获取登录token{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "获取登录token-管理端")
@GetMapping("/getPCToken")
public BaseResponse getPCToken(String code) {
try {
if(active.equals("dev")){
//测试服务器
return weiXinService.getTestToken(code);
}else{
//正式服务器
// return weiXinService.getToken(code, "PC");
}
} catch (Exception e) {
log.debug("获取登录token{}", e);
}
return BaseResponse.errorMsg("失败!");
}
@ApiOperation(value = "当前登录用户")
@GetMapping("/getLoginUser")
public BaseResponse getLoginUser() {
try {
return weiXinService.getLoginUser();
} catch (Exception e) {
log.debug("当前登录用户{}", e);
}
return BaseResponse.errorMsg("失败!");
}
/**
* 将字节数组转换为十六进制字符串
*
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 将字节转换为十六进制字符串
*
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}
package cn.wise.sc.cement.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-09-02
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class EntityEnclosure implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("实体id")
private Integer entityId;
/**
* 实体类型(0:用户(头像),
* 3设备校核附件,4标样材料)
*/
@ApiModelProperty("实体类型")
private Integer entityType;
@ApiModelProperty("附件地址")
private String enclosureUrl;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("更新时间")
private LocalDateTime updateTime;
@ApiModelProperty("是否删除(0:已经删除,1:未删除)")
private Integer isDeleted;
@ApiModelProperty("文件名")
private String alias;
@ApiModelProperty("扩展名")
private String extName;
@ApiModelProperty("pdf路径")
private String pdfUrl;
public interface EntityType {
int HEAD = 0;
int EQUIPMENT_TEST = 3;
int STANDARD_SAMPLE = 4;
int ENTRUST_REPORT = 5;
}
}
package cn.wise.sc.cement.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-08-24
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysLogs implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("操作用户")
private Integer userId;
@ApiModelProperty("日志类型(1委托详情)")
private Integer objType;
@ApiModelProperty("对象表id(委托表id)")
private Integer objId;
@ApiModelProperty("操作内容")
private String module;
@ApiModelProperty("操作状态1成功,0失败")
private Integer flag;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("备注")
private String remark;
public interface ObjType {
int SYSTEM_LOG = 0;
int ENTRUST_LOG = 1;
}
}
package cn.wise.sc.cement.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import java.util.List;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-08-20
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysPermission implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("上级ID(如果是一级为0)")
private Integer parentId;
@ApiModelProperty("名字")
private String name;
@ApiModelProperty("菜单图标")
private String css;
@ApiModelProperty("链接")
private String href;
@ApiModelProperty("1菜单权限,2按钮权限")
private Integer type;
@ApiModelProperty("接口权限")
private String permission;
@ApiModelProperty("排序")
private Integer sort;
@ApiModelProperty("备注")
private String remark;
@ApiModelProperty("子元素")
@TableField(exist = false)
private List<SysPermission> child;
}
package cn.wise.sc.cement.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-08-25
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysPost implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("职务名称")
private String name;
@ApiModelProperty("审批级别")
private Integer level;
@ApiModelProperty("状态(0禁用,1启用)")
private Integer status;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("备注")
private String remark;
}
package cn.wise.sc.cement.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-08-20
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysRole implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("角色名称")
private String name;
@ApiModelProperty("(0禁用,1启用)")
private Integer status;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("备注")
private String remark;
}
package cn.wise.sc.cement.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-08-14
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysUser implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("用户账号")
private String username;
@ApiModelProperty("真实姓名")
private String name;
@ApiModelProperty("性别0女1男")
private Integer sex;
@ApiModelProperty("部门id")
private Integer groupId;
@ApiModelProperty("职务id")
private Integer postId;
@ApiModelProperty("微信号")
private String wxId;
@ApiModelProperty("职称")
private String qualifications;
@ApiModelProperty("状态(0禁用,1启用")
private Integer status;
@ApiModelProperty("工作年限")
private Double workYear;
@ApiModelProperty("手机号")
private String phone;
@ApiModelProperty("传真")
private String fax;
@ApiModelProperty("专业")
private String major;
@ApiModelProperty("邮箱")
private String email;
@ApiModelProperty("从事本技术领域日期")
private LocalDate technologyDate;
@ApiModelProperty("从事本技术领域年限")
private Double technologyYear;
@ApiModelProperty("文化程度")
private String education;
@ApiModelProperty("(0删除,1正常)")
private Integer isDelete;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("修改时间")
private LocalDateTime updateTime;
@ApiModelProperty("备注")
private String remark;
}
package cn.wise.sc.cement.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName(value = "sys_user_enclosure")
public class SysUserEnclosure implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private static final long serialVersionUID = 42L;
private Integer userId;
@ApiModelProperty("附件地址")
private String enclosureUrl;
@ApiModelProperty("状态(0未上传,1成功,2上传失败)")
private Integer FlStatus;
@ApiModelProperty("文件名")
private String alias;
@ApiModelProperty("扩展名")
private String extName;
@ApiModelProperty("上传时间")
private LocalDateTime uploadTime;
}
package cn.wise.sc.cement.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-10-13
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysUserMessage implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 接收人id
*/
private Integer userId;
/**
* 接收信息
*/
private String message;
/**
* 相关内容(委托表id)
*/
private Integer appId;
/**
* 是否查看(0:否,1:是)
*/
private Integer isCheck;
/**
* 消息类型(1委托管理)
*/
private Integer messageType;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
/**
* 是否处理(0:未处理,1:已处理)
*/
private Integer isDeal;
public interface MessageType {
int ENTRUST = 1; //委托
int EQUIPMENT = 2; //设备检定
}
}
package cn.wise.sc.cement.business.enumation;
import com.alibaba.fastjson.annotation.JSONType;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @description: 文件扩展名
* @author: qh
* @create: 2020-10-16 13:40
**/
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@JSONType(serializeEnumAsJavaBean = true)
@Getter
@AllArgsConstructor
public enum FileExt {
//office后缀名
DOC(".doc"),
DOCX(".docx"),
EXCL(".xls"),
PDF("pdf"),
EXCLX(".xlsx");
@EnumValue
private String name;
}
package cn.wise.sc.cement.business.enumation;
import com.alibaba.fastjson.annotation.JSONType;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author neo.shu
* @since 2020/4/22 17:40
*/
@JSONType(serializeEnumAsJavaBean = true)
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@AllArgsConstructor
@Getter
public enum ProjectRole {
PM("PM", "项目经理", true),
PD("PD", "产品设计", false),
UD("UD", "UI设计", false),
FD("FD", "前端开发", false),
BD("BD", "后端开发", false),
TD("TD", "测试经理", false),
QA("QA", "质量管理", true),
;
@EnumValue
private String dbName;
private String label;
private boolean isManage;
public int getValue() {
return this.ordinal();
}
}
package cn.wise.sc.cement.business.exception;
import cn.hutool.core.util.StrUtil;
import java.util.Collection;
/**
* @description: 断言接口 公共断言方法放这里
* @author: qh
* @create: 2020-05-15 15:32
**/
public interface Assert {
/**
* 创建异常
*
* @param args
* @return
*/
BaseException newException(Object... args);
/**
* 创建异常
*
* @param t
* @param args
* @return
*/
BaseException newException(Throwable t, Object... args);
/**
* 断言对象 obj 非空。如果对象 obj 为空,则抛出异常
*
* @param obj 待判断对象
*/
default void assertNotNull(Object obj) {
if (obj == null) {
throw newException(obj);
}
}
default void assertNotEmpty(String str) {
if (StrUtil.isEmpty(str)) {
throw newException(str);
}
}
/**
* 断言对象obj非空。如果对象为空,则抛出异常
* 异常信息message支持传递参数方式,避免在判断之前进行字符串拼接操作
*
* @param obj 待判断对象
* @param args message占位符对应的参数列表
*/
default void assertNotNull(Object obj, Object... args) {
if (obj == null) {
throw newException(args);
}
}
/**
* 断言是个异常 直接抛出这个异常
*
* @param e
*/
default void assertIsException(Throwable e) {
if (e != null) {
throw newException(e, null);
}
}
/**
* 断言 字符串参数不能为空
*
* @param params 字符串参数
*/
default void assertNotEmpty(String... params) {
for (String str : params) {
if (StrUtil.isEmpty(str)) {
throw newException(params);
}
}
}
/**
* 断言 集合不为空和长度不为0
*
* @param list
*/
default void assertCollectionNotILLEGAL(Collection list) {
if (list == null || list.size() == 0) {
throw newException(list);
}
}
/**
* 断言数值参数 不为0和空
*
* @param obj 待判断的参数
*/
default void assertNotDefaultOrNull(Object obj) {
double tmp;
try {
tmp = (double) obj;
} catch (ClassCastException e) {
throw newException(obj);
}
if ((obj == null) || (tmp == 0D)) {
throw newException(obj);
}
}
}
package cn.wise.sc.cement.business.exception;
/**
* @description: 基础异常
* @author: qh
* @create: 2020-05-15 15:27
**/
public class BaseException extends RuntimeException {
protected static final long serialVersionUID = 1L;
private int code;
private String message;
private Object[] args;
public BaseException(IResponseEnum responseEnum, Object[] args, String message) {
super(responseEnum.getMessage());
this.code = responseEnum.getCode();
this.message = message;
this.args = args;
}
public BaseException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
super(message, cause);
this.code = responseEnum.getCode();
this.message = message;
this.args = args;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package cn.wise.sc.cement.business.exception;
/**
* @description: 业务方面的异常
* @author: qh
* @create: 2020-05-15 15:28
**/
public class BusinessException extends BaseException {
private static final long serialVersionUID = 1L;
public BusinessException(IResponseEnum responseEnum, Object[] args, String message) {
super(responseEnum, args, message);
}
public BusinessException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
super(responseEnum, args, message, cause);
}
}
package cn.wise.sc.cement.business.exception;
import java.text.MessageFormat;
import java.util.Date;
/**
* @description: 业务异常与断言结合的接口 适配器
* @author: qh
* @create: 2020-05-15 15:36
**/
public interface BusinessExceptionAssert extends IResponseEnum, Assert {
@Override
default BaseException newException(Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg);
}
@Override
default BaseException newException(Throwable t, Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg, t);
}
/**
* 断言对象 时间段合法
*
* @param start 开始时间
* @param end 结束时间
*/
default void assertTimeVail(Long start, Long end) {
if (end == null || start == null) {
throw newException(start, end);
}
if (end == 0 && start == 0) {
throw newException(start, end);
}
if (start > end) {
throw newException(start, end);
}
if (start < 0 || end < 0) {
throw newException(start, end);
}
}
/**
* 断言对象 时间段合法
*
* @param startDate 开始时间
* @param endDate 结束时间
*/
default void assertTimeVail(Date startDate, Date endDate) {
Long start = startDate.getTime();
Long end = endDate.getTime();
assertTimeVail(start, end);
}
}
package cn.wise.sc.cement.business.exception;
import lombok.Getter;
/**
* @description: 最终业务异常实现
* @author: qh
* @create: 2020-05-15 15:37
*/
@Getter
public enum BusinessExceptionEnum implements BusinessExceptionAssert {
/**
* Bad licence type
*/
BAD_LICENCE_TYPE(7001, "字段不能为空!"),
/**
* Licence not found
*/
LICENCE_NOT_FOUND(7002, "Licence not found."),
/**
* 成功
*/
SUCCESS(200, "Success."),
BAD_TIME(400, "时间段无效! 开始时间>结束时间&&不能为NUll"),
COLLECTION_NOT_ILLEGAL(400, "参数集合无效!"),
CACHE_NOT_FOUND(7002, "缓存未找到!"),
OPEN_TS_DB_CONNECTION_ERROR(7003, "请求OpenTSDB失败"),
/**
* 业务异常
*/
BUSINESS_ERROR(400, "Business not pass."),
/**
* 用户未登录
*/
NO_LOGIN(401, "Please login.");
BusinessExceptionEnum(int code, String message) {
this.code = code;
this.message = message;
}
/**
* 返回码
*/
private int code;
/**
* 返回消息
*/
private String message;
}
package cn.wise.sc.cement.business.exception;
import org.springframework.http.HttpStatus;
/**
* @author shulidong
* @since 2019/2/19/0019 16:48
**/
public abstract class BusinessOldException extends RuntimeException {
protected HttpStatus statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
private String errorCode;
public HttpStatus getStatusCode() {
return statusCode;
}
public void setStatusCode(HttpStatus statusCode) {
this.statusCode = statusCode;
}
public BusinessOldException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public BusinessOldException(String message, Throwable e) {
super(message, e);
}
public BusinessOldException(String message) {
super(message);
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
package cn.wise.sc.cement.business.exception;
/**
* @description: 代码错误
* @author: qh
* @create: 2020-07-09 16:07
**/
public class CodeException extends BaseException {
private static final long serialVersionUID = 1L;
public CodeException(IResponseEnum responseEnum, Object[] args, String message) {
super(responseEnum, args, message);
}
public CodeException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
super(responseEnum, args, message, cause);
}
}
package cn.wise.sc.cement.business.exception;
import java.text.MessageFormat;
/**
* @description: 代码逻辑错误断言接口
* @author: qh
* @create: 2020-07-09 16:05
**/
public interface CodeExceptionAssert extends Assert, IResponseEnum {
@Override
default BaseException newException(Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg);
}
@Override
default BaseException newException(Throwable t, Object... args) {
String msg = MessageFormat.format(this.getMessage(), args);
return new BusinessException(this, args, msg, t);
}
}
package cn.wise.sc.cement.business.exception;
import lombok.Getter;
/**
* @description: 代码逻辑错误枚举
* @author: qh
* @create: 2020-07-09 16:09
**/
@Getter
public enum CodeExceptionEnum implements CodeExceptionAssert {
OBJECT_NOT_EMPTY(6001, "{0} is NULL!"),
STRING_NOT_EMPTY(6001, "{0} is Empty!");
CodeExceptionEnum(int code, String message) {
this.code = code;
this.message = message;
}
/**
* 返回码
*/
private int code;
/**
* 返回消息
*/
private String message;
}
package cn.wise.sc.cement.business.exception;
/**
* 封装fastdfs的异常,使用运行时异常
*
* @author yuqih
* @author tobato
*/
public abstract class FdfsException extends RuntimeException {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
protected FdfsException(String message) {
super(message);
}
/**
* @param message
* @param cause
*/
protected FdfsException(String message, Throwable cause) {
super(message, cause);
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.exception;
/**
* 从Url解析StorePath文件路径对象错误
*
* @author wuyf
*/
public class FdfsUnsupportStorePathException extends FdfsException {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 8116336411011152869L;
public FdfsUnsupportStorePathException(String message) {
super(message);
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.exception;
/**
* @description: 公共属性接口 提供公共属性
* @author: qh
* @create: 2020-05-15 15:28
**/
public interface IResponseEnum {
int getCode();
String getMessage();
}
package cn.wise.sc.cement.business.exception;
/**
* redis 操作异常
*/
public class RedisHandleException extends RuntimeException {
public RedisHandleException(String msg) {
super(msg);
}
public RedisHandleException(String message, Throwable throwable) {
super(message, throwable);
}
public RedisHandleException(Throwable throwable) {
super(throwable);
}
}
package cn.wise.sc.cement.business.filter;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class SwaggerInterceptor extends HandlerInterceptorAdapter {
private String username;
private String password;
public SwaggerInterceptor(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String authorization = request.getHeader("Authorization");
boolean isAuthSuccess = httpBasicAuth(authorization);
if (!isAuthSuccess) {
response.setCharacterEncoding("utf-8");
response.setStatus(401);
// response.setStatus(401,"Unauthorized");
response.setHeader("WWW-authenticate", "Basic realm=\"Realm\"");
try (PrintWriter writer = response.getWriter()) {
writer.print("Forbidden, unauthorized user");
}
}
return isAuthSuccess;
}
public boolean httpBasicAuth(String authorization) throws IOException {
if (authorization != null && authorization.split(" ").length == 2) {
String userAndPass = new String(new BASE64Decoder().decodeBuffer(authorization.split(" ")[1]));
String username = userAndPass.split(":").length == 2 ? userAndPass.split(":")[0] : null;
String password = userAndPass.split(":").length == 2 ? userAndPass.split(":")[1] : null;
if (this.username.equals(username) && this.password.equals(password)) {
return true;
}
}
return false;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
String uri = request.getRequestURI();
AntPathMatcher pathMatcher = new AntPathMatcher();
if (!pathMatcher.match("/swagger-ui.html", uri) && !pathMatcher.match("/webjars/**", uri)) {
response.setStatus(404);
return;
}
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:/META-INF/resources" + uri);
if (resources != null && resources.length > 0) {
FileCopyUtils.copy(resources[0].getInputStream(), response.getOutputStream());
} else {
response.setStatus(404);
}
}
}
package cn.wise.sc.cement.business.filter;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.wise.sc.cement.business.exception.BusinessException;
import cn.wise.sc.cement.business.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Token过滤器
*
* @author zhutianwei
*/
@Component
public class TokenFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger("TokenFilter");
public static final String TOKEN_KEY = "Authorization";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = getToken(request);
if (StringUtils.isNotBlank(token)) {
Map map = null;
try {
map = JwtUtil.parserToken(token);
//过期时间
Long gqTime = Long.valueOf(map.get("timeStamp").toString()) + 60 * 60 * 1000;
long nowTime = (new Date()).getTime();
if (nowTime > gqTime) {
log.error("token过期");
}
} catch (Exception e) {
e.printStackTrace();
}
}
filterChain.doFilter(request, response);
}
/**
* 根据参数或者header获取token
*
* @param request
* @return
*/
public static String getToken(HttpServletRequest request) {
String token = request.getParameter(TOKEN_KEY);
if (StringUtils.isBlank(token)) {
token = request.getHeader(TOKEN_KEY);
}
return token;
}
}
package cn.wise.sc.cement.business.mapper;
import cn.wise.sc.cement.business.entity.EntityEnclosure;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-09-02
*/
public interface EntityEnclosureMapper extends BaseMapper<EntityEnclosure> {
}
package cn.wise.sc.cement.business.mapper;
import cn.wise.sc.cement.business.entity.SysLogs;
import cn.wise.sc.cement.business.model.vo.LogVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-08-24
*/
public interface SysLogsMapper extends BaseMapper<SysLogs> {
IPage<LogVo> getPage(@Param("page") Page page, @Param("params") Map<String, Object> params);
}
package cn.wise.sc.cement.business.mapper;
import cn.wise.sc.cement.business.entity.SysPermission;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
import java.util.Set;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-08-20
*/
public interface SysPermissionMapper extends BaseMapper<SysPermission> {
@Select("select distinct sp.* from sys_permission sp " +
"inner join sys_role_permission rp on sp.id = rp.permission_id " +
"inner join sys_role_user ru on ru.role_id = rp.role_id " +
"where ru.user_id = #{userId} order by sp.parent_id,sp.sort")
List<SysPermission> listByUserId(Integer userId);
@Select("select p.* from sys_permission p inner join sys_role_permission rp on p.id = rp.permission_id where rp.role_id = #{roleId} order by p.parent_id, p.sort")
List<SysPermission> listByRoleId(Integer roleId);
@Select("select * from sys_permission t where t.id = #{id}")
SysPermission getById(Integer id);
}
package cn.wise.sc.cement.business.mapper;
import cn.wise.sc.cement.business.entity.SysPost;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-08-25
*/
public interface SysPostMapper extends BaseMapper<SysPost> {
}
package cn.wise.sc.cement.business.mapper;
import cn.wise.sc.cement.business.entity.SysRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-08-20
*/
public interface SysRoleMapper extends BaseMapper<SysRole> {
int saveRolePermission(@Param("roleId") Integer roleId, @Param("permissionIds") List<Integer> permissionIds);
@Delete("delete from sys_role_permission where role_id = #{roleId}")
int deleteRolePermission(Integer roleId);
@Select("select * from sys_role r inner join sys_role_user ru on r.id = ru.role_id where ru.user_id = #{userId}")
SysRole byUserId(Integer userId);
@Select("select count(*) from sys_role_user t where t.role_id = #{id}")
Integer getUserByRoleId(@Param("id") Integer id);
}
package cn.wise.sc.cement.business.mapper;
import cn.wise.sc.cement.business.entity.SysUserEnclosure;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wlb
* @since 2020-11-9
*/
public interface SysUserEnclosureMapper extends BaseMapper<SysUserEnclosure> {
IPage<SysUserEnclosure> getPage(@Param("page") Page page, @Param("params") Map<String, Object> params);
}
package cn.wise.sc.cement.business.mapper;
import cn.wise.sc.cement.business.entity.SysUser;
import cn.wise.sc.cement.business.model.vo.UserVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-08-14
*/
public interface SysUserMapper extends BaseMapper<SysUser> {
IPage<UserVo> getPage(@Param("page") Page page, @Param("params") Map<String, Object> params);
UserVo getById(Integer id);
// List<Map<String,Object>> exportList(@Param("params") Map<String,Object> params);
@Delete("delete from sys_role_user where user_id = #{userId}")
int deleteUserRole(Integer userId);
int saveUserRoles(@Param("userId") Integer userId, @Param("roleId") Integer roleId);
}
package cn.wise.sc.cement.business.mapper;
import cn.wise.sc.cement.business.entity.SysUserMessage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-10-13
*/
public interface SysUserMessageMapper extends BaseMapper<SysUserMessage> {
List<SysUserMessage> getNoCheck(@Param(value = "userId") Integer userId,
@Param(value = "appId") Integer appId,
@Param(value = "messageType") Integer messageType);
List<SysUserMessage> getNoDeal(@Param(value = "userId") Integer userId,
@Param(value = "appId") Integer appId,
@Param(value = "messageType") Integer messageType);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wise.sc.cement.business.mapper.EntityEnclosureMapper">
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wise.sc.cement.business.mapper.SysLogsMapper">
<sql id="where">
<where>
<if test="params.startDate != null and params.startDate != ''">
and DATE(t.create_time) &gt;= #{params.startDate}
</if>
<if test="params.endDate != null and params.endDate != ''">
and DATE(t.create_time) &lt;= #{params.endDate}
</if>
<if test="params.objType != null">
and t.obj_type = #{params.objType}
</if>
<if test="params.objId != null">
and t.obj_id = #{params.objId}
</if>
</where>
</sql>
<select id="getPage" resultType="cn.wise.sc.cement.business.model.vo.LogVo">
select t.*,su.name as userName
from sys_logs t
left join sys_user su on su.id = t.user_id
<include refid="where"/>
order by t.create_time desc
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wise.sc.cement.business.mapper.SysPermissionMapper">
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wise.sc.cement.business.mapper.SysPostMapper">
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wise.sc.cement.business.mapper.SysRoleMapper">
<insert id="saveRolePermission">
insert into sys_role_permission(role_id, permission_id) values
<foreach collection="permissionIds" item="permissionId"
separator=",">
(#{roleId}, #{permissionId})
</foreach>
</insert>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wise.sc.cement.business.mapper.SysUserEnclosureMapper">
<select id="getPage" resultType="cn.wise.sc.cement.business.entity.SysUserEnclosure">
select sue.*
from sys_user_enclosure sue
<if test="params.userId != null">
where sue.user_id = #{params.userId}
</if>
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wise.sc.cement.business.mapper.SysUserMapper">
<sql id="where">
<where>
<if test="params.status != null ">
and su.status = #{params.status}
</if>
<if test="params.groupId != null">
and su.group_id = #{params.groupId}
</if>
<if test="params.name != null and params.name != ''">
and su.name like concat('%', #{params.name}, '%')
</if>
</where>
</sql>
<select id="getPage" resultType="cn.wise.sc.cement.business.model.vo.UserVo">
SELECT su.*, sg.name as groupName, sp.name as postName
FROM sys_user su
left join sys_group sg on sg.id = su.group_id
left join sys_post sp on sp.id = su.post_id
<include refid="where"/>
ORDER BY su.create_time DESC
</select>
<select id="getById" resultType="cn.wise.sc.cement.business.model.vo.UserVo">
SELECT su.*, sg.name as groupName, sp.name as postName,
sr.id as roleId, sr.name as roleName
FROM sys_user su
left join sys_group sg on sg.id = su.group_id
left join sys_post sp on sp.id = su.post_id
left join sys_role_user sru on sru.user_id = su.id
left join sys_role sr on sr.id = sru.role_id
where su.id = #{id}
</select>
<insert id="saveUserRoles">
insert into sys_role_user(role_id, user_id) values
(#{roleId}, #{userId})
</insert>
<!-- <select id="exportList" resultType="java.util.HashMap">-->
<!-- SELECT-->
<!-- su.id as 序号,-->
<!-- su.username as 用户账号,-->
<!-- su.name as 真实姓名,-->
<!-- (-->
<!-- CASE su.sex-->
<!-- WHEN 0 THEN '女'-->
<!-- ELSE '男'-->
<!-- END-->
<!-- )as 性别,-->
<!-- su.group_id as 组别id,-->
<!-- su.post_id as 职务id,-->
<!-- su.wx_id as 微信号,-->
<!-- su.qualifications as 职称,-->
<!-- (-->
<!-- CASE su.status-->
<!-- WHEN 0 THEN '禁用'-->
<!-- ELSE '启用'-->
<!-- END-->
<!-- )as 状态,-->
<!-- su.work_year as 工作年限,-->
<!-- su.phone as 手机号,-->
<!-- su.fax as 传真,-->
<!-- su.major as 专业,-->
<!-- su.email as 邮箱,-->
<!-- su.technology_date as 从事本技术领域日期,-->
<!-- su.technology_year as 从事本技术领域年限,-->
<!-- su.education as 文化程度,-->
<!-- su.create_time as 创建时间,-->
<!-- su.update_time as 修改时间,-->
<!-- su.remark as 备注-->
<!-- FROM sys_user su-->
<!-- <include refid="where" />-->
<!-- ORDER BY su.id ASC-->
<!-- </select>-->
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.wise.sc.cement.business.mapper.SysUserMessageMapper">
<!-- 未查看消息 -->
<select id="getNoCheck" resultType="cn.wise.sc.cement.business.entity.SysUserMessage">
select *
FROM sys_user_message rum
where rum.is_check=0
<if test="userId != null and userId !=''">
and rum.user_id = #{userId}
</if>
<if test="appId != null and appId !=''">
and rum.app_id = #{appId}
</if>
<if test="messageType != null and messageType !=''">
and rum.message_type = #{messageType}
</if>
</select>
<!-- 未处理消息记录 -->
<select id="getNoDeal" resultType="cn.wise.sc.cement.business.entity.SysUserMessage">
select *
FROM sys_user_message rum
where rum.is_deal=0
<if test="userId != null and userId !=''">
and rum.user_id = #{userId}
</if>
<if test="appId != null and appId !=''">
and rum.app_id = #{appId}
</if>
<if test="messageType != null and messageType !=''">
and rum.message_type = #{messageType}
</if>
</select>
</mapper>
package cn.wise.sc.cement.business.model;
import cn.wise.sc.cement.business.model.vo.BaseVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 封装公共的接口
*
* @param <T> service对象
* @param <M> 实体对象
* @author 秦虎
*/
@Slf4j
public class BaseController<T extends IService<M>, M extends BaseEntity> {
T iService;
public BaseController(T iService) {
this.iService = iService;
}
@PostMapping("/list")
public BaseResponse<List<M>> list(@RequestBody WrapperQuery wrapperQuery) {
QueryWrapper queryWrapper = PageWrapperQueryMyBatisResolver.getQueryWrapper(wrapperQuery);
try {
List<M> list = iService.list(queryWrapper);
return BaseResponse.okData(list);
} catch (Exception ex) {
log.error("查询操作失败 ===== " + iService.toString() + ".list() ====== 异常: {}", ex.getMessage());
return BaseResponse.errorMsg("查询失败");
}
}
@PostMapping("/page")
public BaseResponse<IPage<M>> page(@RequestBody WrapperQuery pageQuery) {
QueryWrapper queryWrapper = PageWrapperQueryMyBatisResolver.getQueryWrapper(pageQuery);
IPage<M> page = new Page(pageQuery.getPageQuery().getPageNo(), pageQuery.getPageQuery().getPageSize());
try {
page = iService.page(page, queryWrapper);
return BaseResponse.okData(page);
} catch (Exception ex) {
log.error("查询操作失败 ===== " + iService.toString() + ".page() ====== 异常: {}", ex.getMessage());
return BaseResponse.errorMsg("分页查询失败");
}
}
@GetMapping("/{id}")
public BaseResponse<BaseVo> getById(@PathVariable("id") long id) {
try {
M model = iService.getById(id);
return BaseResponse.okData(model.toVo());
} catch (Exception ex) {
log.error("查询操作失败 ===== " + iService.toString() + ".create() ====== 异常: {}", ex.getMessage());
return BaseResponse.errorMsg("获取详情信息失败");
}
}
@PostMapping
public BaseResponse<BaseVo> create(@RequestBody M model) {
try {
iService.save(model);
return BaseResponse.okData(model.toVo());
} catch (Exception ex) {
log.error("查询操作失败 ===== " + iService.toString() + ".create() ====== 异常: {}", ex.getMessage());
return BaseResponse.errorMsg("添加失败");
}
}
@PutMapping
public BaseResponse<Boolean> update(@RequestBody M model) {
try {
boolean update = iService.updateById(model);
return BaseResponse.okData(update);
} catch (Exception ex) {
log.error("查询操作失败 ===== " + iService.toString() + ".create() ====== 异常: {}", ex.getMessage());
return BaseResponse.errorMsg("更新记录失败");
}
}
@DeleteMapping("/{id}")
public BaseResponse<Boolean> delById(@PathVariable("id") long id) {
try {
boolean removeById = iService.removeById(id);
return BaseResponse.okData(removeById);
} catch (Exception ex) {
log.error("查询操作失败 ===== " + iService.toString() + ".create() ====== 异常: {}", ex.getMessage());
return BaseResponse.errorMsg("获取详情信息失败");
}
}
}
package cn.wise.sc.cement.business.model;
import cn.wise.sc.cement.business.model.vo.BaseVo;
/**
* @description:
* @author: qh
* @create: 2020-08-07 15:58
**/
public abstract class BaseEntity {
public BaseVo toVo() {
return new BaseVo();
}
}
package cn.wise.sc.cement.business.model;
import cn.wise.sc.cement.business.exception.BusinessExceptionEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @description: 统一返回参数实体
* @author: qh
* @create: 2020-05-18 10:49
**/
@Data
@AllArgsConstructor
public class BaseResponse<T> {
/**
* 响应状态码
*/
private int code;
/**
* 响应数据
*/
private T data;
/**
* 响应提示信息
*/
private String msg;
BaseResponse() {
}
/**
* 200,带提示信息
*
* @param msg 提示信息
* @param <T> 响应数据
* @return BaseResponse
*/
public static <T> BaseResponse<T> okMsg(String msg) {
BaseResponse<T> baseResponse = new BaseResponse<>();
baseResponse.setMsg(msg);
baseResponse.setCode(BusinessExceptionEnum.SUCCESS.getCode());
baseResponse.setData(null);
return baseResponse;
}
/**
* 200,带默认提示信息
*
* @param <T> 响应数据
* @return BaseResponse
*/
public static <T> BaseResponse<T> okData(T t) {
BaseResponse<T> baseResponse = new BaseResponse<>();
baseResponse.setMsg("操作成功!");
baseResponse.setCode(BusinessExceptionEnum.SUCCESS.getCode());
baseResponse.setData(t);
return baseResponse;
}
/**
* 200,带默认提示信息和响应数据
*
* @param t 响应数据
* @param msg 提示信息
* @param <T> 响应数据类型
* @return BaseResponse
*/
public static <T> BaseResponse<T> okDataMsg(T t, String msg) {
BaseResponse<T> baseResponse = new BaseResponse<>();
baseResponse.setMsg(msg);
baseResponse.setCode(BusinessExceptionEnum.SUCCESS.getCode());
baseResponse.setData(t);
return baseResponse;
}
/**
* 400,带提示信息
*
* @param msg 提示信息
* @param <T> 响应数据类型
* @return BaseResponse
*/
public static <T> BaseResponse<T> errorMsg(String msg) {
BaseResponse<T> baseResponse = new BaseResponse<>();
baseResponse.setMsg(msg);
baseResponse.setCode(BusinessExceptionEnum.BUSINESS_ERROR.getCode());
baseResponse.setData(null);
return baseResponse;
}
/**
* 401,用户未登录
*
* @param msg 提示信息
* @param <T> 响应数据类型
* @return BaseResponse
*/
public static <T> BaseResponse<T> noLogin(String msg) {
BaseResponse<T> baseResponse = new BaseResponse<>();
baseResponse.setMsg(msg);
baseResponse.setCode(BusinessExceptionEnum.NO_LOGIN.getCode());
baseResponse.setData(null);
return baseResponse;
}
}
package cn.wise.sc.cement.business.model;
import java.util.List;
import cn.wise.sc.cement.business.entity.SysPermission;
import cn.wise.sc.cement.business.entity.SysRole;
import cn.wise.sc.cement.business.entity.SysUser;
import lombok.Data;
@Data
public class LoginUser extends SysUser {
private List<SysPermission> permissions;
private String token;
/**
* 登陆时间戳(毫秒)
*/
private Long loginTime;
/**
* 过期时间戳
*/
private Long expireTime;
private String postName;
SysRole roleList;
}
package cn.wise.sc.cement.business.model;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Message implements Serializable {
private static final long serialVersionUID = 8508882582940066562L;
@ApiModelProperty("接收人id")
private String userId;
@ApiModelProperty("接收信息")
private String message;
@ApiModelProperty("消息类型: 1个人报销,2对公收付款")
private Integer messageType;
@ApiModelProperty("相关对象表id(个人报销表或对公收付款表)")
private Integer appId;
@ApiModelProperty("发送时间")
private LocalDateTime createTime;
}
package cn.wise.sc.cement.business.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NonNull;
import java.io.Serializable;
/**
* @description: 分页查询页大小的Query对象
* @author: qinhu
* @create: 2019-11-05 15:40
**/
@Data
@ApiModel
public class PageQuery implements Serializable {
private static final long serialVersionUID = 3979320797076183357L;
@ApiModelProperty(value = "当前所在页码")
@NonNull
private Integer pageNo = 1;
@ApiModelProperty(value = "每页显示数量")
@NonNull
private Integer pageSize = 20;
}
package cn.wise.sc.cement.business.model;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* 分页查询参数
*
* @author zhutianwei
* <p>
* 说明: 页码start 每页返回数量 length 其他筛选字段按照对象传入 sql:limit start*length length
* 时间筛选 beginTime endTime
* 排序 orderBy 例如order by payTime desc
*/
public class PageTableRequest implements Serializable {
private static final long serialVersionUID = 7328071045193618467L;
@ApiModelProperty("当前页数(从1开始)")
private Long current;
@ApiModelProperty("当前每页显示数")
private Long size;
public Long getCurrent() {
return current;
}
public void setCurrent(Long current) {
this.current = current;
}
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
}
package cn.wise.sc.cement.business.model;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
/**
* @description: 分页条件查询 mybatis解析
* @author: qh
* @create: 2020-01-08 22:11
**/
public class PageWrapperQueryMyBatisResolver {
public static WrapperQuery create() {
return new WrapperQuery();
}
/**
* 组装查询条件
*
* @param query
* @return
*/
public static QueryWrapper getQueryWrapper(WrapperQuery query) {
QueryWrapper queryWrapper = Wrappers.query();
//拼装等于条件
if (query.getEq() != null) {
for (String key : query.getEq().keySet()) {
queryWrapper.eq(key, query.getEq().get(key));
}
}
//拼装小于条件
if (query.getLt() != null) {
for (String key : query.getLt().keySet()) {
queryWrapper.lt(key, query.getLt().get(key));
}
}
//拼装小于等于条件
if (query.getLe() != null) {
for (String key : query.getLe().keySet()) {
queryWrapper.le(key, query.getLe().get(key));
}
}
//拼装大于于条件
if (query.getGt() != null) {
for (String key : query.getGt().keySet()) {
queryWrapper.gt(key, query.getGt().get(key));
}
}
//拼装大于等于条件
if (query.getGe() != null) {
for (String key : query.getGe().keySet()) {
queryWrapper.ge(key, query.getGe().get(key));
}
}
//in条件
if (query.getIn() != null) {
for (String key : query.getIn().keySet()) {
queryWrapper.in(key, query.getIn().get(key));
}
}
//拼装like条件
if (query.getLike() != null) {
for (String key : query.getLike().keySet()) {
queryWrapper.like(key, query.getLike().get(key));
}
}
if (query.getOr() != null) {
for (String key : query.getOr().keySet()) {
queryWrapper.or(true).eq(key, query.getLike().get(key));
}
}
if (StrUtil.isNotEmpty(query.getSql())) {
queryWrapper.last(query.getSql());
}
return queryWrapper;
}
}
package cn.wise.sc.cement.business.model;
/**
* @author: Seven.wk
* @description: 数据返回类
* @create: 2018/07/04
*/
public class ResultVO<T> {
private Integer code;
private String message;
private T data;
public ResultVO() {
}
public ResultVO(Integer code, String message) {
this.code = code;
this.message = message;
}
public ResultVO(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
package cn.wise.sc.cement.business.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
/**
* @description: 分页条件查询
* @author: qh
* @create: 2019-12-16 15:26
**/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WrapperQuery {
/**
* 分页
*/
private PageQuery pageQuery;
/**
* 等于
*/
private Map<String, Object> eq;
/**
* 小于
*/
private Map<String, Object> lt;
/**
* 小于等于
*/
private Map<String, Object> le;
/**
* 大于
*/
private Map<String, Object> gt;
/**
* 大于等于
*/
private Map<String, Object> ge;
/**
* like
*/
private Map<String, Object> like;
/**
* 或者
*/
private Map<String, Object> or;
/**
* sql条件
*/
private String sql;
/**
* in条件
*/
private Map<String, List<Long>> in;
}
package cn.wise.sc.cement.business.model.query;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* @description:
* @author: ztw
* @create: 2020-08-07 14:58
**/
@Data
@ApiModel("职务请求")
public class PostQuery {
private Integer id;
@ApiModelProperty("职务名称")
private String name;
@ApiModelProperty("审批级别")
private Integer level;
@ApiModelProperty("备注")
private String remark;
}
package cn.wise.sc.cement.business.model.query;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/**
* @description:
* @author: qh
* @create: 2020-08-07 14:58
**/
@Data
@ApiModel("角色请求")
public class RoleQuery {
private Integer id;
@ApiModelProperty("角色名称")
private String name;
@ApiModelProperty("备注")
private String remark;
@ApiModelProperty("权限id数组")
private List<Integer> permissionIds;
}
package cn.wise.sc.cement.business.model.query;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @description: 人员管理附件
* @author: wlb
* @create: 2020-10-19
**/
@Data
@ApiModel("人员管理附件")
public class SysUserEnclosureQuery {
@ApiModelProperty("用户id")
private Integer userId;
@ApiModelProperty("文件名")
private String alias;
@ApiModelProperty("扩展名")
private String extName;
@ApiModelProperty("路径")
private String enclosureUrl;
}
package cn.wise.sc.cement.business.model.query;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* @description: 用户请求
* @author: qh
* @create: 2020-08-07 14:58
**/
@Data
@ApiModel("用户请求")
public class UserQuery {
private Integer id;
@ApiModelProperty("用户账号")
private String username;
@ApiModelProperty("真实姓名")
private String name;
@ApiModelProperty("性别0女1男")
private Integer sex;
@ApiModelProperty("部门id")
private Integer groupId;
@ApiModelProperty("职务id")
private Integer postId;
@ApiModelProperty("微信号")
private String wxId;
@ApiModelProperty("职称")
private String qualifications;
@ApiModelProperty("工作年限")
private Double workYear;
@ApiModelProperty("手机号")
private String phone;
@ApiModelProperty("传真")
private String fax;
@ApiModelProperty("专业")
private String major;
@ApiModelProperty("邮箱")
private String email;
@ApiModelProperty("从事本技术领域日期")
private LocalDate technologyDate;
@ApiModelProperty("从事本技术领域年限")
private Double technologyYear;
@ApiModelProperty("文化程度")
private String education;
@ApiModelProperty("备注")
private String remark;
@ApiModelProperty("角色id")
private Integer roleId;
}
package cn.wise.sc.cement.business.model.vo;
/**
* @description:
* @author: qh
* @create: 2020-08-07 15:59
**/
public class BaseVo {
}
package cn.wise.sc.cement.business.model.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/**
* @description:
* @author: ztw
* @create: 2020-08-07 14:58
**/
@Data
@ApiModel("日志Vo")
public class LogVo {
private Integer id;
/**
* 操作用户
*/
@ApiModelProperty("操作用户id")
private Integer userId;
@ApiModelProperty("操作用户姓名")
private String userName;
@ApiModelProperty("日志类型(1委托详情)")
private Integer objType;
@ApiModelProperty("对象表id(委托表id)")
private Integer objId;
@ApiModelProperty("操作内容")
private String module;
@ApiModelProperty("操作状态1成功,0失败")
private Integer flag;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("备注")
private String remark;
}
package cn.wise.sc.cement.business.model.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* @description:
* @author: ztw
* @create: 2020-08-07 14:58
**/
@Data
@ApiModel("用户Vo")
public class UserVo {
private Integer id;
@ApiModelProperty("用户账号")
private String username;
@ApiModelProperty("真实姓名")
private String name;
@ApiModelProperty("性别0女1男")
private Integer sex;
@ApiModelProperty("部门id")
private Integer groupId;
@ApiModelProperty("职务id")
private Integer postId;
@ApiModelProperty("微信号")
private String wxId;
@ApiModelProperty("职称")
private String qualifications;
@ApiModelProperty("状态(0禁用,1启用)")
private Integer status;
@ApiModelProperty("工作年限")
private Double workYear;
@ApiModelProperty("手机号")
private String phone;
@ApiModelProperty("传真")
private String fax;
@ApiModelProperty("专业")
private String major;
@ApiModelProperty("邮箱")
private String email;
@ApiModelProperty("从事本技术领域日期")
private LocalDate technologyDate;
@ApiModelProperty("从事本技术领域年限")
private Double technologyYear;
@ApiModelProperty("文化程度")
private String education;
@ApiModelProperty("(0删除,1正常)")
private Integer isDelete;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("修改时间")
private LocalDateTime updateTime;
@ApiModelProperty("备注")
private String remark;
@ApiModelProperty("组名称")
private String groupName;
@ApiModelProperty("职务名称")
private String postName;
@ApiModelProperty("角色id")
private Integer roleId;
@ApiModelProperty("角色名称")
private String roleName;
}
package cn.wise.sc.cement.business.service;
import cn.wise.sc.cement.business.entity.EntityEnclosure;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-09-02
*/
public interface IEntityEnclosureService extends IService<EntityEnclosure> {
}
package cn.wise.sc.cement.business.service;
import cn.wise.sc.cement.business.entity.SysLogs;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.vo.LogVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-08-24
*/
public interface ISysLogsService extends IService<SysLogs> {
BaseResponse<IPage<LogVo>> getPage(PageQuery pageQuery, String startDate, String endDate, Integer objType, Integer objId);
void saveLog(Integer objType, Integer objId, String module, String remark);
}
package cn.wise.sc.cement.business.service;
import cn.wise.sc.cement.business.entity.SysPermission;
import cn.wise.sc.cement.business.model.BaseResponse;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-08-20
*/
public interface ISysPermissionService extends IService<SysPermission> {
BaseResponse<List<SysPermission>> current();
BaseResponse<List<SysPermission>> permissionsList();
BaseResponse<List<SysPermission>> parents();
BaseResponse<JSONArray> tree();
BaseResponse<List<SysPermission>> listByRoleId(Integer roleId);
BaseResponse<SysPermission> create(SysPermission permission);
BaseResponse<SysPermission> update(SysPermission permission);
}
package cn.wise.sc.cement.business.service;
import cn.wise.sc.cement.business.entity.SysPost;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.PostQuery;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-08-25
*/
public interface ISysPostService extends IService<SysPost> {
BaseResponse<IPage<SysPost>> getPage(PageQuery pageQuery, String name);
BaseResponse<SysPost> create(PostQuery query);
BaseResponse<SysPost> update(PostQuery query);
}
package cn.wise.sc.cement.business.service;
import cn.wise.sc.cement.business.entity.SysRole;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.RoleQuery;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-08-20
*/
public interface ISysRoleService extends IService<SysRole> {
BaseResponse<IPage<SysRole>> getPage(PageQuery pageQuery, String name);
BaseResponse<SysRole> create(RoleQuery query);
BaseResponse<SysRole> update(RoleQuery query);
BaseResponse<SysRole> byUserId(Integer userId);
BaseResponse<String> delete(Integer id);
}
package cn.wise.sc.cement.business.service;
import cn.wise.sc.cement.business.entity.SysUserMessage;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.util.WebSocketServer;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-10-13
*/
public interface ISysUserMessageService extends IService<SysUserMessage> {
BaseResponse<String> sendMessage(Integer userId, String message, Integer appId, Integer messageType);
BaseResponse<String> checkMessage(Integer userId, Integer appId, Integer messageType);
BaseResponse<String> dealMessage(Integer userId, Integer appId, Integer messageType);
BaseResponse<List<SysUserMessage>> getMessages();
}
package cn.wise.sc.cement.business.service;
import cn.wise.sc.cement.business.entity.SysUser;
import cn.wise.sc.cement.business.entity.SysUserEnclosure;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.SysUserEnclosureQuery;
import cn.wise.sc.cement.business.model.query.UserQuery;
import cn.wise.sc.cement.business.model.vo.UserVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-08-14
*/
public interface ISysUserService extends IService<SysUser> {
LoginUser getLoginUser();
BaseResponse<IPage<UserVo>> getPage(PageQuery pageQuery, Integer status, Integer groupId, String name);
BaseResponse<SysUser> create(UserQuery query);
BaseResponse<SysUser> update(UserQuery query);
BaseResponse<String> status(Integer status, Integer id);
BaseResponse<UserVo> findById(Integer id);
BaseResponse<String> uploadPeoplePF(SysUserEnclosureQuery query);
BaseResponse<IPage<SysUserEnclosure>> getUserEnclosurePage(PageQuery pageQuery, Integer userId);
BaseResponse<String> deleteUserEnclosure(Integer id);
/**
* 人员详情列表导出
* @param status 状态
* @param filename 文件名
* @param name 姓名
* @param response
*/
// void exportList(Integer status,String filename,String name, HttpServletResponse response);
}
package cn.wise.sc.cement.business.service.impl;
import cn.wise.sc.cement.business.entity.EntityEnclosure;
import cn.wise.sc.cement.business.mapper.EntityEnclosureMapper;
import cn.wise.sc.cement.business.service.IEntityEnclosureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-09-02
*/
@Service
public class EntityEnclosureServiceImpl extends ServiceImpl<EntityEnclosureMapper, EntityEnclosure> implements IEntityEnclosureService {
}
package cn.wise.sc.cement.business.service.impl;
import cn.wise.sc.cement.business.entity.SysLogs;
import cn.wise.sc.cement.business.mapper.SysLogsMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.vo.LogVo;
import cn.wise.sc.cement.business.service.ISysLogsService;
import cn.wise.sc.cement.business.service.ISysUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-08-24
*/
@Service
public class SysLogsServiceImpl extends ServiceImpl<SysLogsMapper, SysLogs> implements ISysLogsService {
@Resource
private SysLogsMapper logsMapper;
@Autowired
private ISysUserService userService;
/**
* 分页列表
*
* @param pageQuery
* @param startDate
* @param endDate
* @param objType
* @param objId
* @return
*/
@Override
public BaseResponse<IPage<LogVo>> getPage(PageQuery pageQuery, String startDate, String endDate, Integer objType, Integer objId) {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
params.put("objType", objType);
params.put("objId", objId);
Page<LogVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
IPage<LogVo> pages = logsMapper.getPage(page, params);
return BaseResponse.okData(pages);
}
/**
* 添加日志
*
* @param objType
* @param objId
* @param module
* @param remark
*/
@Transactional
@Override
public void saveLog(Integer objType, Integer objId, String module, String remark) {
LoginUser loginUser = userService.getLoginUser();
SysLogs sysLogs = new SysLogs();
sysLogs.setUserId(loginUser.getId())
.setObjType(objType)
.setObjId(objId)
.setModule(module)
.setFlag(1)
.setCreateTime(LocalDateTime.now())
.setRemark(remark);
logsMapper.insert(sysLogs);
}
}
package cn.wise.sc.cement.business.service.impl;
import cn.wise.sc.cement.business.entity.SysPermission;
import cn.wise.sc.cement.business.mapper.SysPermissionMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.service.ISysPermissionService;
import cn.wise.sc.cement.business.service.ISysUserService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-08-20
*/
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {
@Resource
private SysPermissionMapper permissionMapper;
@Autowired
private ISysUserService userService;
/**
* 当前登录用户拥有的权限
*
* @return
*/
@Override
public BaseResponse<List<SysPermission>> current() {
LoginUser loginUser = userService.getLoginUser();
List<SysPermission> list = loginUser.getPermissions();
final List<SysPermission> permissions = list.stream().filter(l -> l.getType().equals(1))
.collect(Collectors.toList());
// setChild(permissions);
//
// return permissions.stream().filter(p -> p.getParentId().equals(0L)).collect(Collectors.toList());
// 2018.06.09 支持多级菜单
List<SysPermission> firstLevel = permissions.stream().filter(p -> p.getParentId().equals(0)).collect(Collectors.toList());
firstLevel.parallelStream().forEach(p -> {
setChild(p, permissions);
});
return BaseResponse.okData(firstLevel);
}
private void setChild(SysPermission p, List<SysPermission> permissions) {
List<SysPermission> child = permissions.parallelStream().filter(a -> a.getParentId().equals(p.getId())).collect(Collectors.toList());
p.setChild(child);
if (!CollectionUtils.isEmpty(child)) {
child.parallelStream().forEach(c -> {
//递归设置子元素,多级菜单支持
setChild(c, permissions);
});
}
}
/**
* 菜单列表
*/
@Override
public BaseResponse<List<SysPermission>> permissionsList() {
List<SysPermission> permissionsAll = this.list();
List<SysPermission> list = Lists.newArrayList();
setPermissionsList(0, permissionsAll, list);
return BaseResponse.okData(list);
}
private void setPermissionsList(Integer pId, List<SysPermission> permissionsAll, List<SysPermission> list) {
for (SysPermission per : permissionsAll) {
if (per.getParentId().equals(pId)) {
list.add(per);
if (permissionsAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
setPermissionsList(per.getId(), permissionsAll, list);
}
}
}
}
/**
* 一级菜单
*
* @return
*/
@Override
public BaseResponse<List<SysPermission>> parents() {
QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("type", 1);
queryWrapper.eq("parent_id", 0);
queryWrapper.orderByAsc("parent_id", "sort");
List<SysPermission> list = this.list(queryWrapper);
return BaseResponse.okData(list);
}
/**
* 菜单树
*
* @return
*/
@Override
public BaseResponse<JSONArray> tree() {
List<SysPermission> permissionsAll = this.list();
JSONArray array = new JSONArray();
setPermissionsTree(0, permissionsAll, array);
return BaseResponse.okData(array);
}
private void setPermissionsTree(Integer pId, List<SysPermission> permissionsAll, JSONArray array) {
for (SysPermission per : permissionsAll) {
if (per.getParentId().equals(pId)) {
String string = JSONObject.toJSONString(per);
JSONObject parent = (JSONObject) JSONObject.parse(string);
array.add(parent);
if (permissionsAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
JSONArray child = new JSONArray();
parent.put("child", child);
setPermissionsTree(per.getId(), permissionsAll, child);
}
}
}
}
/**
* 根据角色id获取权限
*
* @param roleId
* @return
*/
@Override
public BaseResponse<List<SysPermission>> listByRoleId(Integer roleId) {
List<SysPermission> list = permissionMapper.listByRoleId(roleId);
return BaseResponse.okData(list);
}
/**
* 新增
*
* @param permission
* @return
*/
@Override
@Transactional
public BaseResponse<SysPermission> create(SysPermission permission) {
if (StringUtils.isEmpty(permission.getName())) {
return BaseResponse.errorMsg("权限名称不可为空");
}
this.save(permission);
return BaseResponse.okData(permission);
}
/**
* 修改
*
* @param permission
* @return
*/
@Override
@Transactional
public BaseResponse<SysPermission> update(SysPermission permission) {
if (StringUtils.isEmpty(permission.getName())) {
return BaseResponse.errorMsg("权限名称不可为空");
}
this.updateById(permission);
return BaseResponse.okData(permission);
}
}
package cn.wise.sc.cement.business.service.impl;
import cn.wise.sc.cement.business.entity.SysPost;
import cn.wise.sc.cement.business.mapper.SysPostMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.PostQuery;
import cn.wise.sc.cement.business.service.ISysPostService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-08-25
*/
@Service
public class SysPostServiceImpl extends ServiceImpl<SysPostMapper, SysPost> implements ISysPostService {
@Resource
private SysPostMapper postMapper;
/**
* 获取分页
*
* @param pageQuery
* @param name
* @return
*/
@Override
public BaseResponse<IPage<SysPost>> getPage(PageQuery pageQuery, String name) {
QueryWrapper<SysPost> qw = new QueryWrapper<>();
if (StringUtils.isNotEmpty(name)) {
qw.like("name", name);
}
qw.orderByDesc("create_time");
IPage<SysPost> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
page = postMapper.selectPage(page, qw);
return BaseResponse.okData(page);
}
/**
* 新增职务
*
* @param query
* @return
*/
@Override
@Transactional
public BaseResponse<SysPost> create(PostQuery query) {
if (StringUtils.isEmpty(query.getName())) {
return BaseResponse.errorMsg("职务名称不能为空!");
}
QueryWrapper<SysPost> qw = new QueryWrapper<>();
qw.eq("name", query.getName());
int count = postMapper.selectCount(qw);
if (count > 0) {
return BaseResponse.errorMsg(query.getName() + "已存在");
}
SysPost post = new SysPost();
BeanUtils.copyProperties(query, post);
post.setStatus(1);
post.setCreateTime(LocalDateTime.now());
postMapper.insert(post);
return BaseResponse.okData(post);
}
/**
* 修改职务
*
* @param query
* @return
*/
@Override
public BaseResponse<SysPost> update(PostQuery query) {
if (StringUtils.isEmpty(query.getName())) {
return BaseResponse.errorMsg("职务名称不能为空!");
}
QueryWrapper<SysPost> qw = new QueryWrapper<>();
qw.eq("name", query.getName());
qw.ne("id", query.getId());
int count = postMapper.selectCount(qw);
if (count > 0) {
return BaseResponse.errorMsg(query.getName() + "已存在");
}
SysPost post = new SysPost();
BeanUtils.copyProperties(query, post);
postMapper.updateById(post);
return BaseResponse.okData(post);
}
}
package cn.wise.sc.cement.business.service.impl;
import cn.wise.sc.cement.business.entity.SysRole;
import cn.wise.sc.cement.business.mapper.SysRoleMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.RoleQuery;
import cn.wise.sc.cement.business.service.ISysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-08-20
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
@Resource
private SysRoleMapper roleMapper;
/**
* 获取分页
*
* @param pageQuery
* @param name
* @return
*/
@Override
public BaseResponse<IPage<SysRole>> getPage(PageQuery pageQuery, String name) {
QueryWrapper<SysRole> qw = new QueryWrapper<>();
if (StringUtils.isNotEmpty(name)) {
qw.like("name", name);
}
qw.orderByDesc("create_time");
IPage<SysRole> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
page = roleMapper.selectPage(page, qw);
return BaseResponse.okData(page);
}
/**
* 新增角色
*
* @param query
* @return
*/
@Override
@Transactional
public BaseResponse<SysRole> create(RoleQuery query) {
if (StringUtils.isEmpty(query.getName())) {
return BaseResponse.errorMsg("角色名称不能为空!");
}
QueryWrapper<SysRole> qw = new QueryWrapper<>();
qw.eq("name", query.getName());
int count = roleMapper.selectCount(qw);
if (count > 0) {
return BaseResponse.errorMsg(query.getName() + "已存在");
}
SysRole role = new SysRole();
BeanUtils.copyProperties(query, role);
List<Integer> permissionIds = query.getPermissionIds();
if(!permissionIds.contains(2)){
permissionIds.add(2);
}
if(!permissionIds.contains(11)){
permissionIds.add(11);
}
role.setStatus(1);
role.setCreateTime(LocalDateTime.now());
roleMapper.insert(role);
if (!CollectionUtils.isEmpty(permissionIds)) {
roleMapper.saveRolePermission(role.getId(), permissionIds);
}
return BaseResponse.okData(role);
}
@Override
@Transactional
public BaseResponse<SysRole> update(RoleQuery query) {
if(query.getId() == 1){
return BaseResponse.errorMsg("系统管理员角色不允许修改!");
}
if (StringUtils.isEmpty(query.getName())) {
return BaseResponse.errorMsg("角色名称不能为空!");
}
QueryWrapper<SysRole> qw = new QueryWrapper<>();
qw.eq("name", query.getName());
qw.ne("id", query.getId());
int count = roleMapper.selectCount(qw);
if (count > 0) {
return BaseResponse.errorMsg(query.getName() + "已存在");
}
SysRole role = new SysRole();
BeanUtils.copyProperties(query, role);
List<Integer> permissionIds = query.getPermissionIds();
if(!permissionIds.contains(2)){
permissionIds.add(2);
}
if(!permissionIds.contains(11)){
permissionIds.add(11);
}
roleMapper.updateById(role);
roleMapper.deleteRolePermission(role.getId());
if (!CollectionUtils.isEmpty(permissionIds)) {
roleMapper.saveRolePermission(role.getId(), permissionIds);
}
return BaseResponse.okData(role);
}
/**
* 根据用户id获取拥有的角色
*
* @param userId
* @return
*/
@Override
public BaseResponse<SysRole> byUserId(Integer userId) {
if (userId == null) {
return BaseResponse.errorMsg("用户id不能为空!");
}
SysRole role = roleMapper.byUserId(userId);
return BaseResponse.okData(role);
}
/**
* 删除角色
*
* @param id
* @return
*/
@Override
@Transactional
public BaseResponse<String> delete(Integer id) {
if(id == 1){
return BaseResponse.errorMsg("系统管理员角色不允许删除!");
}
if(id == 2){
return BaseResponse.errorMsg("角色不允许删除!");
}
SysRole role = roleMapper.selectById(id);
if (role == null) {
return BaseResponse.errorMsg("角色不存在!");
}
Integer conunts = roleMapper.getUserByRoleId(id);
if (conunts != 0 && conunts > 0) {
return BaseResponse.errorMsg(conunts + "个用户正在使用!");
}
roleMapper.deleteById(id);
return BaseResponse.okData("删除成功");
}
}
package cn.wise.sc.cement.business.service.impl;
import cn.wise.sc.cement.business.entity.SysUser;
import cn.wise.sc.cement.business.entity.SysUserMessage;
import cn.wise.sc.cement.business.mapper.SysUserMessageMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.Message;
import cn.wise.sc.cement.business.service.ISysUserMessageService;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.WebSocketServer;
import cn.wise.sc.cement.business.wrapper.WrapMapper;
import cn.wise.sc.cement.business.wrapper.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-10-13
*/
@Service
public class SysUserMessageServiceImpl extends ServiceImpl<SysUserMessageMapper, SysUserMessage> implements ISysUserMessageService {
@Resource
private SysUserMessageMapper userMessageMapper;
@Resource
protected HttpServletResponse response;
@Autowired
protected HttpServletRequest request;
@Autowired
WebSocketServer webSocketServer;
@Autowired
private ISysUserService userService;
/**
* 发送消息
*
* @param userId
* @param message
* @param appId
* @param messageType
* @return
*/
@Override
public BaseResponse<String> sendMessage(Integer userId, String message, Integer appId, Integer messageType) {
int ret = 0;
SysUserMessage userMessage = new SysUserMessage();
userMessage.setUserId(userId);
userMessage.setMessage(message);
userMessage.setAppId(appId);
userMessage.setIsCheck(0);
userMessage.setMessageType(messageType);
userMessage.setCreateTime(LocalDateTime.now());
userMessage.setUpdateTime(userMessage.getCreateTime());
userMessage.setIsDeal(0);
ret = this.userMessageMapper.insert(userMessage);
if (ret == 0) {
return BaseResponse.errorMsg("消息推送失败");
}
String dealer = String.valueOf(userId);
Message m = Message.builder().userId(dealer).message(message).messageType(messageType).appId(appId)
.createTime(userMessage.getCreateTime()).build();
webSocketServer.sendTo(m);
/*SysUser sysUser = userService.getById(userId);
if(sysUser != null && StringUtils.isNotBlank(sysUser.getPhone())){
SMSUtil.sendCode(sysUser.getPhone(), message);
}*/
return BaseResponse.okData("成功");
}
/**
* 查看消息
*
* @param userId
* @param appId
* @param messageType
* @return
*/
@Override
public BaseResponse<String> checkMessage(Integer userId, Integer appId, Integer messageType) {
int ret = 0;
List<SysUserMessage> list = this.userMessageMapper.getNoCheck(userId, appId, messageType);
if (list != null && list.size() > 0) {
for (SysUserMessage um : list) {
um.setIsCheck(1);
ret = this.userMessageMapper.updateById(um);
if (ret == 0) {
return BaseResponse.errorMsg("查看消息记录更新失败");
}
}
}
return BaseResponse.okData("成功");
}
/**
* 处理消息
*
* @param userId
* @param appId
* @param messageType
* @return
*/
@Override
public BaseResponse<String> dealMessage(Integer userId, Integer appId, Integer messageType) {
int ret = 0;
List<SysUserMessage> list = this.userMessageMapper.getNoDeal(userId, appId, messageType);
if (list != null && list.size() > 0) {
for (SysUserMessage um : list) {
um.setIsCheck(1);
um.setIsDeal(1);
ret = this.userMessageMapper.updateById(um);
if (ret == 0) {
return BaseResponse.errorMsg("处理消息记录更新失败");
}
}
}
return BaseResponse.okData("成功");
}
/**
* 消息列表
*
* @return
*/
@Override
public BaseResponse<List<SysUserMessage>> getMessages() {
LoginUser loginUser = userService.getLoginUser();
if (loginUser == null) {
return BaseResponse.noLogin("请登录账号");
}
List<SysUserMessage> list = this.userMessageMapper.getNoDeal(loginUser.getId(), null, null);
return BaseResponse.okData(list);
}
}
package cn.wise.sc.cement.business.service.impl;
import cn.wise.sc.cement.business.entity.*;
import cn.wise.sc.cement.business.exception.BusinessExceptionEnum;
import cn.wise.sc.cement.business.mapper.SysPermissionMapper;
import cn.wise.sc.cement.business.mapper.SysRoleMapper;
import cn.wise.sc.cement.business.mapper.SysUserEnclosureMapper;
import cn.wise.sc.cement.business.mapper.SysUserMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.SysUserEnclosureQuery;
import cn.wise.sc.cement.business.model.query.UserQuery;
import cn.wise.sc.cement.business.model.vo.UserVo;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.JwtUtil;
import cn.wise.sc.cement.business.util.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-08-07
*/
@Service
public class UserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
@Resource
private SysUserMapper userMapper;
@Resource
private HttpServletRequest request;
@Autowired
RedisUtil redisUtil;
@Resource
private SysPermissionMapper permissionMapper;
@Resource
private SysRoleMapper roleMapper;
@Autowired
private UserServiceImpl userService;
@Resource
private SysUserEnclosureMapper sysUserEnclosureMapper;
/**
* 当前登录用户
*
* @return
*/
@Override
public LoginUser getLoginUser() {
try {
String token = request.getHeader("Authorization");
System.out.println("==================当前登录用户的Authorization===================");
System.out.println(token);
Map map = JwtUtil.parserToken(token);
Object obj = redisUtil.getString(map.get("id").toString());
BusinessExceptionEnum.CACHE_NOT_FOUND.assertNotNull(obj);
SysUser sysUser = userMapper.selectById(Integer.valueOf(map.get("id").toString()));
LoginUser loginUser = new LoginUser();
BeanUtils.copyProperties(sysUser, loginUser);
List<SysPermission> permissionList = permissionMapper.listByUserId(loginUser.getId());
SysRole sysRole = roleMapper.byUserId(sysUser.getId());
loginUser.setRoleList(sysRole);
loginUser.setPermissions(permissionList);
return loginUser;
} catch (Exception e) {
return null;
}
}
/**
* 人员分页列表
*
* @param pageQuery
* @param status
* @param groupId
* @param name
* @return
*/
@Override
public BaseResponse<IPage<UserVo>> getPage(PageQuery pageQuery, Integer status, Integer groupId, String name) {
Map<String, Object> params = new HashMap<>();
params.put("status", status);
params.put("groupId", groupId);
params.put("name", name);
Page<UserVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
IPage<UserVo> pages = userMapper.getPage(page, params);
return BaseResponse.okData(pages);
}
/**
* 新增人员
*
* @param query
* @return
*/
@Override
@Transactional
public BaseResponse<SysUser> create(UserQuery query) {
if (StringUtils.isEmpty(query.getPhone())) {
return BaseResponse.errorMsg("手机号码不可为空!");
}
if(query.getRoleId() == null){
return BaseResponse.errorMsg("请选择角色信息!");
}
QueryWrapper<SysUser> qw = new QueryWrapper<>();
qw.eq("phone", query.getPhone());
int count = userMapper.selectCount(qw);
if (count > 0) {
return BaseResponse.errorMsg("手机号已存在!");
}
SysUser user = new SysUser();
BeanUtils.copyProperties(query, user);
user.setStatus(1).setIsDelete(1).setCreateTime(LocalDateTime.now());
userMapper.insert(user);
saveUserRoles(user.getId(), query.getRoleId());
return BaseResponse.okData(user);
}
/**
* 修改人员
*
* @param query
* @return
*/
@Override
@Transactional
public BaseResponse<SysUser> update(UserQuery query) {
if(query.getId() == 1){
return BaseResponse.errorMsg("不允许更改系统管理员信息!");
}
if (StringUtils.isEmpty(query.getPhone())) {
return BaseResponse.errorMsg("手机号码不可为空!");
}
if(query.getRoleId() == null){
return BaseResponse.errorMsg("请选择角色信息!");
}
QueryWrapper<SysUser> qw = new QueryWrapper<>();
qw.eq("phone", query.getPhone());
qw.ne("id", query.getId());
int count = userMapper.selectCount(qw);
if (count > 0) {
return BaseResponse.errorMsg("手机号已存在!");
}
SysUser user = new SysUser();
BeanUtils.copyProperties(query, user);
user.setId(query.getId());
userMapper.updateById(user);
saveUserRoles(user.getId(), query.getRoleId());
return BaseResponse.okData(user);
}
/**
* 保存用户和角色信息
* @param userId
* @param roleId
*/
private void saveUserRoles(Integer userId, Integer roleId) {
if (userId != null) {
userMapper.deleteUserRole(userId);
if (roleId != null) {
userMapper.saveUserRoles(userId, roleId);
}
}
}
/**
* 禁用启用
*
* @param status
* @param id
* @return
*/
@Override
@Transactional
public BaseResponse<String> status(Integer status, Integer id) {
if(id == 1){
return BaseResponse.errorMsg("不允许更改系统管理员状态!");
}
if (status == null || id == null) {
return BaseResponse.errorMsg("参数错误!");
}
SysUser user = userMapper.selectById(id);
if (user == null) {
return BaseResponse.errorMsg("数据错误!");
}
user.setStatus(status);
userMapper.updateById(user);
String result = "";
if (user.getStatus() == 1) {
result = "已启用";
} else {
result = "已禁用";
}
return BaseResponse.okData(result);
}
/**
* 人员详情
*
* @param id
* @return
*/
@Override
public BaseResponse<UserVo> findById(Integer id) {
BusinessExceptionEnum.BAD_LICENCE_TYPE.assertNotNull(id);
UserVo userVo = userMapper.getById(id);
return BaseResponse.okData(userVo);
}
/**
* 上传人员附件
* @param query
* @return
*/
@Override
@Transactional
public BaseResponse<String> uploadPeoplePF(SysUserEnclosureQuery query) {
LoginUser loginUser = userService.getLoginUser();
if (loginUser == null){
return BaseResponse.noLogin("请登录账号");
}
if (query == null || query.getUserId() == null){
return BaseResponse.errorMsg("参数错误");
}
SysUserEnclosure sysUserEnclosure = new SysUserEnclosure();
sysUserEnclosure.setUserId(query.getUserId())
.setEnclosureUrl(query.getEnclosureUrl())
.setExtName(query.getExtName())
.setAlias(query.getAlias())
.setFlStatus(1)
.setUploadTime(LocalDateTime.now());
sysUserEnclosureMapper.insert(sysUserEnclosure);
return BaseResponse.okMsg("成功");
}
/**
* 附件列表
* @param pageQuery
* @param userId
* @return
*/
@Override
public BaseResponse<IPage<SysUserEnclosure>> getUserEnclosurePage(PageQuery pageQuery, Integer userId) {
if(userId == null){
return BaseResponse.errorMsg("请传入用户id");
}
Map<String, Object> params = new HashMap<>();
params.put("userId", userId);
Page<SysUserEnclosure> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
IPage<SysUserEnclosure> pages = sysUserEnclosureMapper.getPage(page, params);
return BaseResponse.okData(pages);
}
/**
* 删除人员附件
* @param id
* @return
*/
@Transactional
@Override
public BaseResponse<String> deleteUserEnclosure(Integer id) {
if(id == null){
return BaseResponse.errorMsg("参数错误");
}
SysUserEnclosure userEnclosure = sysUserEnclosureMapper.selectById(id);
if(userEnclosure == null){
return BaseResponse.errorMsg("人员附件信息错误");
}
sysUserEnclosureMapper.deleteById(id);
return BaseResponse.okData("附件信息删除成功");
}
/**
* 人员详情列表导出
* @param status 状态
* @param name 姓名
* @return
*/
// @Override
// public void exportList(Integer status, String filename, String name, HttpServletResponse response) {
// Map<String, Object> params = new HashMap<>();
// params.put("status", status);
// params.put("name", name);
// List<Map<String, Object>> list= userMapper.exportList(params);
//
// if (!CollectionUtils.isEmpty(list)){
// Map<String,Object> map=list.get(0);
// String[] headers=new String[20];
// headers[0] = "序号";
// headers[1] = "用户账号";
// headers[2] = "真实姓名";
// headers[3] = "性别";
// headers[4] = "组别id";
// headers[5] = "职务id";
// headers[6] = "微信号";
// headers[7] = "职称";
// headers[8] = "状态";
// headers[9] = "工作年限";
// headers[10] = "手机号";
// headers[11] = "传真";
// headers[12] = "专业";
// headers[13] = "邮箱";
// headers[14] = "从事本技术领域日期";
// headers[15] = "从事本技术领域年限";
// headers[16] = "文化程度";
// headers[17] = "创建时间";
// headers[18] = "修改时间";
// headers[19] = "备注";
//
// List<Object[]> datas=new ArrayList<>(list.size());
// for (Map<String,Object>m:list){
// Object[] objects=new Object[headers.length];
// for (int j=0;j<headers.length;j++){
// String obj=m.get(headers[j])==null?"":m.get(headers[j]).toString();
// if (j==0 && obj!=null){
// obj=obj.split("\\.")[0];
// }
// objects[j] = obj;
// }
// datas.add(objects);
// }
// ExcelUtil.excelExport(
// filename==null || filename.trim().length() <= 0 ? "人员详情":filename ,headers, datas ,response);
// }
// }
}
package cn.wise.sc.cement.business.service.impl;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.wise.sc.cement.business.entity.SysUser;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.query.UserQuery;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.JwtUtil;
import cn.wise.sc.cement.business.util.RedisUtil;
import cn.wise.sc.cement.business.util.weixin.Global;
import cn.wise.sc.cement.business.util.weixin.WeiXinUtil;
import cn.wise.sc.cement.business.util.weixin.WeixinInterfaceUtil;
import cn.wise.sc.cement.business.util.weixin.message.send.BaseMessage;
import cn.wise.sc.cement.business.util.weixin.message.send.Text;
import cn.wise.sc.cement.business.util.weixin.message.send.TextMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class WeiXinService {
private static Logger log = LoggerFactory.getLogger(WeiXinService.class);
@Autowired
private ISysUserService userService;
@Autowired
RedisUtil redisUtil;
/**
* 获取登录token 测试服务器部署
*
* @param code
* @return
*/
public BaseResponse<String> getTestToken(String code) {
if (StrUtil.isEmpty(code)) {
return BaseResponse.errorMsg("code为必填项!");
}
System.out.println("==================code===================");
System.out.println(code);
try {
QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
wrapper.eq("phone", code); //暂时用手机号代替code
SysUser sysUser = userService.getOne(wrapper);
if (sysUser == null) {
return BaseResponse.errorMsg("非系统用户不允许登录!");
}
if (sysUser.getStatus() == 0) {
return BaseResponse.errorMsg("用户被禁用!");
}
if (sysUser.getIsDelete() == 0) {
return BaseResponse.errorMsg("用户被删除!");
}
//生成token,存入redis
String token = JwtUtil.createToken(sysUser.getId(), sysUser.getUsername(),
sysUser.getName(), sysUser.getPhone());
System.out.println(token);
redisUtil.setString(sysUser.getId().toString(), token, 3600);
return BaseResponse.okData(token);
} catch (Exception e) {
return BaseResponse.errorMsg(e.getMessage());
}
}
/**
* 当前登录用户
*
* @return
*/
public BaseResponse<LoginUser> getLoginUser() {
LoginUser loginUser = userService.getLoginUser();
return BaseResponse.okData(loginUser);
}
}
package cn.wise.sc.cement.business.util;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.cookie.SM;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 校核计算工具类
*
* @author zhutianwei
*
*/
public class CheckCountUtil {
//倍数
public final static BigDecimal param10 = new BigDecimal(10.00);
public final static BigDecimal param100 = new BigDecimal(100.00);
public final static BigDecimal param1000 = new BigDecimal(1000.00);
public final static BigDecimal param10000 = new BigDecimal(10000.00);
//object 转成 BigDecimal
public static BigDecimal getBigDecimal(Object value ) {
BigDecimal ret = null;
if( value != null && !value.equals("") ) {
if( value instanceof BigDecimal ) {
ret = (BigDecimal) value;
} else if( value instanceof String ) {
ret = new BigDecimal( (String) value );
} else if( value instanceof BigInteger) {
ret = new BigDecimal( (BigInteger) value );
} else if( value instanceof Number ) {
ret = new BigDecimal( ((Number)value).doubleValue() );
} else {
throw new ClassCastException("Not possible to coerce ["+value+"] from class "+value.getClass()+" into a BigDecimal.");
}
}
return ret;
}
/**
* 检测项名称
* @param name
* @return
*/
//加 add 减 subtract 乘 multiply 除 divide
public static String checkCount(String name, Map<String, String> resultMap) {
BigDecimal endResult = null;
if(name.equals("L.O.I")){
if( StringUtils.isNotBlank(resultMap.get("样重m1")) &&
StringUtils.isNotBlank(resultMap.get("空埚重m2"))&&
StringUtils.isNotBlank(resultMap.get("烧后重m3"))){
//样重m1—保留4位⼩数
BigDecimal m1 = getBigDecimal(resultMap.get("样重m1").trim()).setScale(4,BigDecimal.ROUND_HALF_UP);
//空埚重m2—保留4位⼩数
BigDecimal m2 = getBigDecimal(resultMap.get("空埚重m2").trim()).setScale(4,BigDecimal.ROUND_HALF_UP);
//烧后重m3—保留4位⼩数
BigDecimal m3 = getBigDecimal(resultMap.get("烧后重m3").trim()).setScale(4,BigDecimal.ROUND_HALF_UP);
//计算的核心公式结果
BigDecimal countResult = (m1.add(m2).subtract(m3)).divide(m1,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100.multiply(param100));
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.multiply(param100).setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.multiply(param100).subtract(new BigDecimal(0.0000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("SiO<sub>2</sub>")){
if( StringUtils.isNotBlank(resultMap.get("VSiO<sub>2</sub>")) &&
StringUtils.isNotBlank(resultMap.get("TSiO<sub>2</sub>"))&&
StringUtils.isNotBlank(resultMap.get("样重m"))){
//毫升数
BigDecimal VSiO2 = getBigDecimal(resultMap.get("VSiO<sub>2</sub>").trim());
//滴定度
BigDecimal TSiO2 = getBigDecimal(resultMap.get("TSiO<sub>2</sub>").trim());
//样m
BigDecimal m = getBigDecimal(resultMap.get("样重m").trim());
//计算的核心公式结果
BigDecimal countResult = VSiO2.multiply(TSiO2).divide(m,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.0000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("Al<sub>2</sub>O<sub>3</sub>+TiO<sub>2</sub>")){
if( StringUtils.isNotBlank(resultMap.get("TAl<sub>2</sub>O<sub>3</sub>")) &&
StringUtils.isNotBlank(resultMap.get("VAl<sub>2</sub>O<sub>3</sub>"))&&
StringUtils.isNotBlank(resultMap.get("K"))&&
StringUtils.isNotBlank(resultMap.get("VCuSO<sub>4</sub>(I)"))&&
StringUtils.isNotBlank(resultMap.get("样重m"))
){
BigDecimal TAl2O3 = getBigDecimal(resultMap.get("TAl<sub>2</sub>O<sub>3</sub>").trim());
BigDecimal VAl2O3 = getBigDecimal(resultMap.get("VAl<sub>2</sub>O<sub>3</sub>").trim());
BigDecimal K = getBigDecimal(resultMap.get("K").trim());
BigDecimal VCuSO4_I = getBigDecimal(resultMap.get("VCuSO<sub>4</sub>(I)").trim());
BigDecimal m = getBigDecimal(resultMap.get("样重m").trim());
//计算的核心公式结果
BigDecimal countResult = TAl2O3.multiply(VAl2O3.subtract(K.multiply(VCuSO4_I))).divide(m,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.0000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("Al<sub>2</sub>O<sub>3</sub>")){
if( StringUtils.isNotBlank(resultMap.get("TAl<sub>2</sub>O<sub>3</sub>")) &&
StringUtils.isNotBlank(resultMap.get("VAl<sub>2</sub>O<sub>3</sub>"))&&
StringUtils.isNotBlank(resultMap.get("K"))&&
StringUtils.isNotBlank(resultMap.get("VCuSO<sub>4</sub>(I)"))&&
StringUtils.isNotBlank(resultMap.get("样重m"))&&
StringUtils.isNotBlank(resultMap.get("VCuSO<sub>4</sub>(II)"))
){
BigDecimal TAl2O3 = getBigDecimal(resultMap.get("TAl<sub>2</sub>O<sub>3</sub>").trim());
BigDecimal VAl2O3 = getBigDecimal(resultMap.get("VAl<sub>2</sub>O<sub>3</sub>").trim());
BigDecimal K = getBigDecimal(resultMap.get("K").trim());
BigDecimal VCuSO4_I = getBigDecimal(resultMap.get("VCuSO<sub>4</sub>(I)").trim());
BigDecimal m = getBigDecimal(resultMap.get("样重m").trim());
BigDecimal VCuSO4_II = getBigDecimal(resultMap.get("VCuSO<sub>4</sub>(II)").trim());
//计算的核心公式结果
BigDecimal countResult = TAl2O3.multiply(VAl2O3.subtract(K.multiply(VCuSO4_I.add(VCuSO4_II)))).divide(m,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.0000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("Fe<sub>2</sub>O<sub>3</sub>")){
if( StringUtils.isNotBlank(resultMap.get("TFe<sub>2</sub>O<sub>3</sub>")) &&
StringUtils.isNotBlank(resultMap.get("VF<sub>2</sub>O<sub>3</sub>"))&&
StringUtils.isNotBlank(resultMap.get("样重m"))
){
BigDecimal TFe2O3 = getBigDecimal(resultMap.get("TFe<sub>2</sub>O<sub>3</sub>").trim());
BigDecimal VF2O3 = getBigDecimal(resultMap.get("VF<sub>2</sub>O<sub>3</sub>").trim());
BigDecimal m = getBigDecimal(resultMap.get("样重m").trim());
//计算的核心公式结果
BigDecimal countResult = TFe2O3.multiply(VF2O3).divide(m,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.0000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("CaO")){
if( StringUtils.isNotBlank(resultMap.get("TCaO")) &&
StringUtils.isNotBlank(resultMap.get("VCaO"))&&
StringUtils.isNotBlank(resultMap.get("样重m"))
){
BigDecimal TCaO = getBigDecimal(resultMap.get("TCaO").trim());
BigDecimal VCaO = getBigDecimal(resultMap.get("VCaO").trim());
BigDecimal m = getBigDecimal(resultMap.get("样重m").trim());
//计算的核心公式结果
BigDecimal countResult = TCaO.multiply(VCaO).divide(m,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.00000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("MgO")){
if( StringUtils.isNotBlank(resultMap.get("TMgO")) &&
StringUtils.isNotBlank(resultMap.get("VMgO"))&&
StringUtils.isNotBlank(resultMap.get("VCaO"))&&
StringUtils.isNotBlank(resultMap.get("样重m"))
){
BigDecimal TMgO = getBigDecimal(resultMap.get("TMgO").trim());
BigDecimal VMgO = getBigDecimal(resultMap.get("VMgO").trim());
BigDecimal VCaO = getBigDecimal(resultMap.get("VCaO").trim());
BigDecimal m = getBigDecimal(resultMap.get("样重m").trim());
//计算的核心公式结果
BigDecimal countResult = TMgO.multiply(VMgO.subtract(VCaO)).divide(m,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.0000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("TiO<sub>2</sub>")){
if( StringUtils.isNotBlank(resultMap.get("TTiO<sub>2</sub>")) &&
StringUtils.isNotBlank(resultMap.get("VCuSO<sub>4</sub>(II)"))&&
StringUtils.isNotBlank(resultMap.get("K"))&&
StringUtils.isNotBlank(resultMap.get("样重m"))
){
BigDecimal TTiO2 = getBigDecimal(resultMap.get("TTiO<sub>2</sub>").trim());
BigDecimal VCuSO4_II = getBigDecimal(resultMap.get("VCuSO<sub>4</sub>(II)").trim());
BigDecimal K = getBigDecimal(resultMap.get("K").trim());
BigDecimal m = getBigDecimal(resultMap.get("样重m").trim());
//计算的核心公式结果
BigDecimal countResult = TTiO2.multiply(VCuSO4_II).multiply(K).divide(m,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.00000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("重量法SO<sub>3</sub>")){
if( StringUtils.isNotBlank(resultMap.get("烧重m2")) &&
StringUtils.isNotBlank(resultMap.get("埚重m1"))&&
StringUtils.isNotBlank(resultMap.get("空白m3"))&&
StringUtils.isNotBlank(resultMap.get("样重m"))
){
BigDecimal m2 = getBigDecimal(resultMap.get("烧重m2").trim());
BigDecimal m1 = getBigDecimal(resultMap.get("埚重m1").trim());
BigDecimal m3 = getBigDecimal(resultMap.get("空白m3").trim());
BigDecimal m = getBigDecimal(resultMap.get("样重m").trim());
//计算的核心公式结果
BigDecimal countResult = m2.subtract(m1).subtract(m3).divide(m,10,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(0.343));
endResult = countResult.multiply(param100).setScale(2,BigDecimal.ROUND_HALF_EVEN);
}else{
endResult = new BigDecimal(0);
}
}else if(name.equals("K<sub>2</sub>O")){
if( StringUtils.isNotBlank(resultMap.get("CK<sub>2</sub>O")) &&
StringUtils.isNotBlank(resultMap.get("V"))&&
StringUtils.isNotBlank(resultMap.get("AK<sub>2</sub>O"))&&
StringUtils.isNotBlank(resultMap.get("样重R2O"))
){
BigDecimal CK2O = getBigDecimal(resultMap.get("CK<sub>2</sub>O").trim());
BigDecimal V = getBigDecimal(resultMap.get("V").trim());
BigDecimal AK2O = getBigDecimal(resultMap.get("AK<sub>2</sub>O").trim());
BigDecimal mR20 = getBigDecimal(resultMap.get("样重R2O").trim());
//计算的核心公式结果
BigDecimal countResult = CK2O.multiply(V).multiply(AK2O).divide(mR20,10,BigDecimal.ROUND_HALF_UP).divide(param10000,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.00000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("Na<sub>2</sub>O")){
if( StringUtils.isNotBlank(resultMap.get("CNa<sub>2</sub>O")) &&
StringUtils.isNotBlank(resultMap.get("V"))&&
StringUtils.isNotBlank(resultMap.get("ANa<sub>2</sub>O"))&&
StringUtils.isNotBlank(resultMap.get("样重R2O"))
){
BigDecimal CNa2O = getBigDecimal(resultMap.get("CNa<sub>2</sub>O").trim());
BigDecimal V = getBigDecimal(resultMap.get("V").trim());
BigDecimal ANa2O = getBigDecimal(resultMap.get("ANa<sub>2</sub>O").trim());
BigDecimal mR20 = getBigDecimal(resultMap.get("样重R2O").trim());
//计算的核心公式结果
BigDecimal countResult = CNa2O.multiply(V).multiply(ANa2O).divide(mR20,10,BigDecimal.ROUND_HALF_UP).divide(param10000,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.00000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("MnO")){
if( StringUtils.isNotBlank(resultMap.get("CMnO")) &&
StringUtils.isNotBlank(resultMap.get("V"))&&
StringUtils.isNotBlank(resultMap.get("AMnO"))&&
StringUtils.isNotBlank(resultMap.get("样重R2O"))
){
BigDecimal CMnO = getBigDecimal(resultMap.get("CMnO").trim());
BigDecimal V = getBigDecimal(resultMap.get("V").trim());
BigDecimal AMnO = getBigDecimal(resultMap.get("AMnO").trim());
BigDecimal mR20 = getBigDecimal(resultMap.get("样重R2O").trim());
//计算的核心公式结果
BigDecimal countResult = CMnO.multiply(V).multiply(AMnO).divide(mR20,10,BigDecimal.ROUND_HALF_UP).divide(param10000,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.00000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("Cl<sup>-</sup>")){
if( StringUtils.isNotBlank(resultMap.get("T")) &&
StringUtils.isNotBlank(resultMap.get("V2"))&&
StringUtils.isNotBlank(resultMap.get("V1"))&&
StringUtils.isNotBlank(resultMap.get("样重Cl"))
){
BigDecimal T = getBigDecimal(resultMap.get("T").trim());
BigDecimal V2 = getBigDecimal(resultMap.get("V2").trim());
BigDecimal V1 = getBigDecimal(resultMap.get("V1").trim());
BigDecimal mCl = getBigDecimal(resultMap.get("样重Cl").trim());
//计算的核心公式结果
BigDecimal countResult = T.multiply(V2.subtract(V1)).divide(mCl,10,BigDecimal.ROUND_HALF_UP).divide(param10,10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = countResult.multiply(param1000);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = countResult.setScale(3,BigDecimal.ROUND_HALF_UP);
}else{
endResult = countResult.subtract(new BigDecimal(0.00000000001)).setScale(3,BigDecimal.ROUND_HALF_UP);
}
}
}else if(name.equals("Mad1")){
if( StringUtils.isNotBlank(resultMap.get("样重M1")) &&
StringUtils.isNotBlank(resultMap.get("皿重M1"))&&
StringUtils.isNotBlank(resultMap.get("烧重M1"))
){
BigDecimal YZ_M1 = getBigDecimal(resultMap.get("样重M1").trim());
BigDecimal MZ_M1 = getBigDecimal(resultMap.get("皿重M1").trim());
BigDecimal SZ_M1 = getBigDecimal(resultMap.get("烧重M1").trim());
//计算的核心公式结果
BigDecimal countResult = YZ_M1.add(MZ_M1).subtract(SZ_M1).divide(YZ_M1,10,BigDecimal.ROUND_HALF_UP);
endResult = countResult.multiply(param100).setScale(3,BigDecimal.ROUND_HALF_EVEN);
}
}else if(name.equals("Mad2")){
if( StringUtils.isNotBlank(resultMap.get("样重M2")) &&
StringUtils.isNotBlank(resultMap.get("皿重M2"))&&
StringUtils.isNotBlank(resultMap.get("烧重M2"))
){
BigDecimal YZ_M2 = getBigDecimal(resultMap.get("样重M2").trim());
BigDecimal MZ_M2 = getBigDecimal(resultMap.get("皿重M2").trim());
BigDecimal SZ_M2 = getBigDecimal(resultMap.get("烧重M2").trim());
//计算的核心公式结果
BigDecimal countResult = YZ_M2.add(MZ_M2).subtract(SZ_M2).divide(YZ_M2,10,BigDecimal.ROUND_HALF_UP);
endResult = countResult.multiply(param100).setScale(3,BigDecimal.ROUND_HALF_EVEN);
}
}else if(name.equals("Aad1")){
if( StringUtils.isNotBlank(resultMap.get("烧重A1")) &&
StringUtils.isNotBlank(resultMap.get("皿重A1"))&&
StringUtils.isNotBlank(resultMap.get("样重A1"))
){
BigDecimal SZ_A1 = getBigDecimal(resultMap.get("烧重A1").trim());
BigDecimal MZ_A1 = getBigDecimal(resultMap.get("皿重A1").trim());
BigDecimal YZ_A1 = getBigDecimal(resultMap.get("样重A1").trim());
//计算的核心公式结果
BigDecimal countResult = SZ_A1.subtract(MZ_A1).divide(YZ_A1,10,BigDecimal.ROUND_HALF_UP);
endResult = countResult.multiply(param100).setScale(3,BigDecimal.ROUND_HALF_EVEN);
}
}else if(name.equals("Aad2")){
if( StringUtils.isNotBlank(resultMap.get("烧重A2")) &&
StringUtils.isNotBlank(resultMap.get("皿重A2"))&&
StringUtils.isNotBlank(resultMap.get("样重A2"))
){
BigDecimal SZ_A2 = getBigDecimal(resultMap.get("烧重A2").trim());
BigDecimal MZ_A2 = getBigDecimal(resultMap.get("皿重A2").trim());
BigDecimal YZ_A2 = getBigDecimal(resultMap.get("样重A2").trim());
//计算的核心公式结果
BigDecimal countResult = SZ_A2.subtract(MZ_A2).divide(YZ_A2,10,BigDecimal.ROUND_HALF_UP);
endResult = countResult.multiply(param100).setScale(3,BigDecimal.ROUND_HALF_EVEN);
}
}else if(name.equals("焦渣")){
if( StringUtils.isNotBlank(resultMap.get("焦渣特征"))
){
endResult = getBigDecimal(resultMap.get("焦渣特征").trim());
}
}
/*else if(name.equals("St,ad")){
if( StringUtils.isNotBlank(resultMap.get("显示值"))
){
endResult = getBigDecimal(resultMap.get("显示值").trim());
}
}*/
return endResult==null?"":endResult.toString();
}
/**
* 求激光粒度分析
* @param resultMap
* @return
*/
public static String countJGLD(Map<String, String> resultMap) {
String count = "";
String D10="";
String D50="";
String D90="";
if( StringUtils.isNotBlank(resultMap.get("D10"))){
D10 = resultMap.get("D10").trim();
}
if( StringUtils.isNotBlank(resultMap.get("D50"))){
D50 = resultMap.get("D50").trim();
}
if( StringUtils.isNotBlank(resultMap.get("D90"))){
D90 = resultMap.get("D90").trim();
}
count = "D10="+D10+" \n D50="+D50+" \n D90="+D90;
return count;
}
/**
* 求可磨
* @param resultMap
* @return
*/
public static String countKm(Map<String, String> resultMap) {
String count = "";
String HGI="";
String ZYL=""; //制样率
if( StringUtils.isNotBlank(resultMap.get("HGI"))){
HGI = resultMap.get("HGI").trim();
}
if( StringUtils.isNotBlank(resultMap.get("制样率"))){
ZYL = resultMap.get("制样率").trim();
}
count = "HGI="+HGI+" \n 制样率="+ZYL+"%";
return count;
}
/**
* 求辊磨
* @param resultMap
* @return
*/
public static String countGm(Map<String, String> resultMap) {
String count = "";
String TMF="";
String TWF="";
if( StringUtils.isNotBlank(resultMap.get("TMF"))){
TMF = resultMap.get("TMF").trim();
}
if( StringUtils.isNotBlank(resultMap.get("TWF(kg/t)"))){
TWF = resultMap.get("TWF(kg/t)").trim();
}
count = "TMF="+TMF+" \n TWF(kg/t)="+TWF;
return count;
}
/**
* 求塑性指数
* @param resultMap
* @return
*/
public static String countSxzs(Map<String, String> resultMap) {
String count = "";
String YX="";
String SX="";
String SXZS="";
if( StringUtils.isNotBlank(resultMap.get("液限"))){
YX = resultMap.get("液限").trim();
}
if( StringUtils.isNotBlank(resultMap.get("塑限"))){
SX = resultMap.get("塑限").trim();
}
if( StringUtils.isNotBlank(resultMap.get("塑性指数"))){
SXZS = resultMap.get("塑性指数").trim();
}
count = "液限="+YX+" \n 塑限="+SX+" \n 塑性指数="+SXZS;
return count;
}
/**
* 求SO3
* @param resultMap
* @param countMap
* @return
*/
public static String countSO3(Map<String, String> resultMap, Map<String, String> countMap) {
BigDecimal count = null;
if( StringUtils.isNotBlank(countMap.get("重量法SO<sub>3</sub>")) &&
StringUtils.isNotBlank(resultMap.get("显示值"))&&
StringUtils.isNotBlank(resultMap.get("样重SO<sub>3</sub>"))
){
BigDecimal weightSO3 = getBigDecimal(countMap.get("重量法SO<sub>3</sub>"));
BigDecimal displaySO3= getBigDecimal(resultMap.get("显示值").trim());
BigDecimal mSO3= getBigDecimal(resultMap.get("样重SO<sub>3</sub>").trim());
BigDecimal elseResult = displaySO3.multiply(new BigDecimal(2.5));
BigDecimal countResult = weightSO3.compareTo(new BigDecimal(0))==1?
weightSO3:elseResult;
BigDecimal result1 = countResult.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
BigDecimal jsResult = weightSO3.compareTo(new BigDecimal(0))==1?
weightSO3:elseResult.multiply(mSO3).divide(mSO3,10,BigDecimal.ROUND_HALF_UP);
count = jsResult.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
BigDecimal osResult = weightSO3.compareTo(new BigDecimal(0))==1?
weightSO3:elseResult.multiply(mSO3).divide(mSO3,10,BigDecimal.ROUND_HALF_UP);
count = osResult.subtract(new BigDecimal(0.00000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}else if(StringUtils.isNotBlank(resultMap.get("显示值"))){
BigDecimal displaySO3= getBigDecimal(resultMap.get("显示值").trim());
count = displaySO3.multiply(new BigDecimal(2.5)).setScale(2, BigDecimal.ROUND_HALF_EVEN);
}
//如果有值按照“四舍六入五留双”修约规则保留至小数后两位
return count==null?"":count.toString();
}
/**
* 求合量 L.O.I+SiO2+(Al2O3+TiO2)+Al2O3+Fe2O3+CaO+MgO+TiO2+K2O+Na2O+MnO+SO3
* @param countMap
* @return
*/
public static String countHL(Map<String, String> countMap) {
BigDecimal count = new BigDecimal(0);
List<String> list = new ArrayList<>();
list.add(StringUtils.isEmpty(countMap.get("L.O.I"))?"0":countMap.get("L.O.I"));
list.add(StringUtils.isEmpty(countMap.get("SiO<sub>2</sub>"))?"0":countMap.get("SiO<sub>2</sub>"));
// list.add(countMap.get("Al2O3+TiO2"));
list.add(StringUtils.isEmpty(countMap.get("Al<sub>2</sub>O<sub>3</sub>"))?"0":countMap.get("Al<sub>2</sub>O<sub>3</sub>"));
list.add(StringUtils.isEmpty(countMap.get("Fe<sub>2</sub>O<sub>3</sub>"))?"0":countMap.get("Fe<sub>2</sub>O<sub>3</sub>"));
list.add(StringUtils.isEmpty(countMap.get("CaO"))?"0":countMap.get("CaO"));
list.add(StringUtils.isEmpty(countMap.get("MgO"))?"0":countMap.get("MgO"));
list.add(StringUtils.isEmpty(countMap.get("TiO<sub>2</sub>"))?"0":countMap.get("TiO<sub>2</sub>"));
list.add(StringUtils.isEmpty(countMap.get("K<sub>2</sub>O"))?"0":countMap.get("K<sub>2</sub>O"));
list.add(StringUtils.isEmpty(countMap.get("Na<sub>2</sub>O"))?"0":countMap.get("Na<sub>2</sub>O"));
list.add(StringUtils.isEmpty(countMap.get("MnO"))?"0":countMap.get("MnO"));
list.add(StringUtils.isEmpty(countMap.get("SO<sub>3</sub>"))?"0":countMap.get("SO<sub>3</sub>"));
for(String s:list) {
count = count.add(new BigDecimal(s));
}
return count.setScale(2,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求KH (CaO - 1.65*{Al2O3+TiO2} * Fe2O3) / 2.8 / SiO2
* @param countMap
* @return
*/
public static String countKH(Map<String, String> countMap) {
BigDecimal KH = null;
if( StringUtils.isNotBlank(countMap.get("Ca0")) &&
StringUtils.isNotBlank(countMap.get("Al<sub>2</sub>O<sub>3</sub>+TiO<sub>2</sub>"))&&
StringUtils.isNotBlank(countMap.get("Fe<sub>2</sub>O<sub>3</sub>"))&&
StringUtils.isNotBlank(countMap.get("SiO<sub>2</sub>"))
){
BigDecimal CaO = getBigDecimal(countMap.get("CaO"));
BigDecimal Al2O3_TiO2= getBigDecimal(countMap.get("Al<sub>2</sub>O<sub>3</sub>+TiO<sub>2</sub>"));
BigDecimal Fe2O3 = getBigDecimal(countMap.get("Fe<sub>2</sub>O<sub>3</sub>"));
BigDecimal SiO2 = getBigDecimal(countMap.get("SiO<sub>2</sub>"));
KH =CaO.subtract(new BigDecimal(1.65).multiply(Al2O3_TiO2)).subtract(new BigDecimal(0.35).multiply(Fe2O3)).divide(new BigDecimal(2.8),10,BigDecimal.ROUND_HALF_UP).divide(SiO2,10,BigDecimal.ROUND_HALF_UP);
}
return KH==null?"":KH.setScale(3,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求SM SiO2/ ({Al2O3+TiO2} + Fe2O3)
* @param countMap
* @return
*/
public static String countSM(Map<String, String> countMap) {
BigDecimal SM = null;
if( StringUtils.isNotBlank(countMap.get("SiO<sub>2</sub>")) &&
StringUtils.isNotBlank(countMap.get("Al<sub>2</sub>O<sub>3</sub>+TiO<sub>2</sub>"))&&
StringUtils.isNotBlank(countMap.get("Fe<sub>2</sub>O<sub>3</sub>"))
){
BigDecimal SiO2 = getBigDecimal(countMap.get("SiO<sub>2</sub>"));
BigDecimal Al2O3_TiO2= getBigDecimal(countMap.get("Al<sub>2</sub>O<sub>3</sub>+TiO<sub>2</sub>"));
BigDecimal Fe2O3 = getBigDecimal(countMap.get("Fe<sub>2</sub>O<sub>3</sub>"));
SM = SiO2.divide(Al2O3_TiO2.add(Fe2O3),10,BigDecimal.ROUND_HALF_UP);
}
return SM==null?"":SM.setScale(2,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求AM 「Al2O3+TiO2」/ Fe2O3
* @param countMap
* @return
*/
public static String countAM(Map<String, String> countMap) {
BigDecimal AM = null;
if( StringUtils.isNotBlank(countMap.get("Al<sub>2</sub>O<sub>3</sub>+TiO<sub>2</sub>"))&&
StringUtils.isNotBlank(countMap.get("Fe<sub>2</sub>O<sub>3</sub>"))
){
BigDecimal Al2O3_TiO2= getBigDecimal(countMap.get("Al<sub>2</sub>O<sub>3</sub>+TiO<sub>2</sub>"));
BigDecimal Fe2O3 = getBigDecimal(countMap.get("Fe<sub>2</sub>O<sub>3</sub>"));
AM = Al2O3_TiO2.divide(Fe2O3,10,BigDecimal.ROUND_HALF_UP);
}
return AM==null?"":AM.setScale(2,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求易烧性等级
* @param resultMap 输入集合
* @param countMap 输出集合
* @return
*/
public static String countBurnupLevel(Map<String, String> resultMap, Map<String, String> countMap) {
String endResult = "";
if( StringUtils.isNotBlank(resultMap.get("fCaO_1450"))&&
StringUtils.isNotBlank(countMap.get("KH"))
){
BigDecimal fCaO_1450 = getBigDecimal(resultMap.get("fCaO_1450").trim());
BigDecimal KH= getBigDecimal(countMap.get("KH").trim());
BigDecimal E = new BigDecimal(45).multiply(KH).subtract(new BigDecimal(37.4));
BigDecimal D = new BigDecimal(35).multiply(KH).subtract(new BigDecimal(29.3));
BigDecimal C = new BigDecimal(26.25).multiply(KH).subtract(new BigDecimal(22.15));
BigDecimal B = new BigDecimal(18.75).multiply(KH).subtract(new BigDecimal(16));
if(fCaO_1450.compareTo(E) == 1){
endResult = "E";
}else if (fCaO_1450.compareTo(D) == 1){
endResult = "D";
}else if (fCaO_1450.compareTo(C) == 1){
endResult = "C";
}else if (fCaO_1450.compareTo(B) == 1){
endResult = "B";
}else{
endResult = "A";
}
}
return endResult;
}
/**
* 求报出_Mad (Mad1 + Mad2 )/ 2
* @param countMap
* @return
*/
public static String countBCMad(Map<String, String> countMap) {
BigDecimal BC_Mad = null;
if( StringUtils.isNotBlank(countMap.get("Mad1"))&&
StringUtils.isNotBlank(countMap.get("Mad2"))
){
BigDecimal Mad1= getBigDecimal(countMap.get("Mad1"));
BigDecimal Mad2= getBigDecimal(countMap.get("Mad2"));
//计算Mad1 和 Mad2 的平均值
BC_Mad = Mad1.add(Mad2).divide(new BigDecimal(2),10,BigDecimal.ROUND_HALF_UP);
}
return BC_Mad==null?"":BC_Mad.toString();
}
/**
* 求Mad 报出_Mad *100 判断奇偶数判断后的结果
* @param countMap
* @return
*/
public static String countMad(Map<String, String> countMap) {
BigDecimal Mad = null;
if( StringUtils.isNotBlank(countMap.get("报出_Mad"))
){
BigDecimal BC_Mad= getBigDecimal(countMap.get("报出_Mad"));
//判断奇偶数的最终值
BigDecimal result1 = BC_Mad.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
Mad = BC_Mad.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
Mad = BC_Mad.subtract(new BigDecimal(0.00000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
return Mad==null?"":Mad.setScale(2,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求报出_Aad (Aad1 + Aad2)/2
* @param countMap
* @return
*/
public static String countBCAad(Map<String, String> countMap) {
BigDecimal BC_Aad = null;
if( StringUtils.isNotBlank(countMap.get("Aad1")) &&
StringUtils.isNotBlank(countMap.get("Aad2"))
){
BigDecimal Aad1= getBigDecimal(countMap.get("Aad1"));
BigDecimal Aad2= getBigDecimal(countMap.get("Aad2"));
//计算Mad1 和 Mad2 的平均值
BC_Aad = Aad1.add(Aad2).divide(new BigDecimal(2),10,BigDecimal.ROUND_HALF_UP);
}
return BC_Aad==null?"":BC_Aad.toString();
}
/**
* 求Aad 报出_Aad *100 判断奇偶数判断后的结果
* @param countMap
* @return
*/
public static String countAad(Map<String, String> countMap) {
BigDecimal Aad = null;
if( StringUtils.isNotBlank(countMap.get("报出_Aad"))
){
BigDecimal BC_Aad= getBigDecimal(countMap.get("报出_Aad"));
//判断奇偶数的最终值
BigDecimal result1 = BC_Aad.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
Aad = BC_Aad.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
Aad = BC_Aad.subtract(new BigDecimal(0.00000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
return Aad==null?"":Aad.setScale(2,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求Vad1
* @param resultMap
* @param countMap
* @return
*/
public static String countVad1(Map<String, String> resultMap, Map<String, String> countMap) {
BigDecimal count = null;
if( StringUtils.isNotBlank(resultMap.get("样重V1")) &&
StringUtils.isNotBlank(resultMap.get("皿重V1")) &&
StringUtils.isNotBlank(resultMap.get("烧重V1")) &&
StringUtils.isNotBlank(countMap.get("报出_Mad"))
){
BigDecimal YZ_V1 = getBigDecimal(resultMap.get("样重V1").trim());
BigDecimal MZ_V1 = getBigDecimal(resultMap.get("皿重V1").trim());
BigDecimal SZ_V1 = getBigDecimal(resultMap.get("烧重V1").trim());
BigDecimal BC_Mad = getBigDecimal(countMap.get("报出_Mad"));
//计算的核心公式结果
BigDecimal countResult = YZ_V1.add(MZ_V1).subtract(SZ_V1).divide(YZ_V1,10,BigDecimal.ROUND_HALF_UP);
count = countResult.multiply(param100).subtract(BC_Mad);
}
return count==null?"":count.setScale(3,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求Vad2
* @param resultMap
* @param countMap
* @return
*/
public static String countVad2(Map<String, String> resultMap, Map<String, String> countMap) {
BigDecimal count = null;
if( StringUtils.isNotBlank(resultMap.get("样重V2")) &&
StringUtils.isNotBlank(resultMap.get("皿重V2")) &&
StringUtils.isNotBlank(resultMap.get("烧重V2")) &&
StringUtils.isNotBlank(countMap.get("报出_Mad"))
){
BigDecimal YZ_V2 = getBigDecimal(resultMap.get("样重V2"));
BigDecimal MZ_V2 = getBigDecimal(resultMap.get("皿重V2"));
BigDecimal SZ_V2 = getBigDecimal(resultMap.get("烧重V2"));
BigDecimal BC_Mad = getBigDecimal(countMap.get("报出_Mad"));
//计算的核心公式结果
BigDecimal countResult = YZ_V2.add(MZ_V2).subtract(SZ_V2).divide(YZ_V2,10,BigDecimal.ROUND_HALF_UP);
count = countResult.multiply(param100).subtract(BC_Mad);
}
return count==null?"":count.setScale(3,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求报出_Vad (Vad1+ Vad2)/2
* @param countMap
* @return
*/
public static String countBCVad(Map<String, String> countMap) {
BigDecimal BC_Vad = null;
if( StringUtils.isNotBlank(countMap.get("Vad1")) &&
StringUtils.isNotBlank(countMap.get("Vad2"))
){
BigDecimal Vad1= getBigDecimal(countMap.get("Vad1"));
BigDecimal Vad2= getBigDecimal(countMap.get("Vad2"));
//计算Vad1 和 Vad2 的平均值
BC_Vad = Vad1.add(Vad2).divide(new BigDecimal(2),10,BigDecimal.ROUND_HALF_UP);
}
return BC_Vad==null?"":BC_Vad.toString();
}
/**
* 求Vad 报出_Vad *100 判断奇偶数判断后的结果
* @param countMap
* @return
*/
public static String countVad(Map<String, String> countMap) {
BigDecimal Vad = null;
if( StringUtils.isNotBlank(countMap.get("报出_Vad"))
){
BigDecimal BC_Vad= getBigDecimal(countMap.get("报出_Vad"));
//判断奇偶数的最终值
BigDecimal result1 = BC_Vad.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
Vad = BC_Vad.setScale(2,BigDecimal.ROUND_HALF_UP);
}else{
Vad = BC_Vad.subtract(new BigDecimal(0.00000000001)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
return Vad==null?"":Vad.setScale(2,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求Vdaf Vad *100/(100-Mad-Aad)
* @param countMap
* @return
*/
public static String countVdaf(Map<String, String> countMap) {
BigDecimal Vdaf = null;
if( StringUtils.isNotBlank(countMap.get("Vad")) &&
StringUtils.isNotBlank(countMap.get("Mad")) &&
StringUtils.isNotBlank(countMap.get("Aad"))
){
BigDecimal Vad= getBigDecimal(countMap.get("Vad"));
BigDecimal Mad= getBigDecimal(countMap.get("Mad"));
BigDecimal Aad= getBigDecimal(countMap.get("Aad"));
Vdaf = Vad.multiply(param100).multiply(param100.subtract(Mad).subtract(Aad));
}
return Vdaf==null?"":Vdaf.toString();
}
/**
* 求K1,
* @param countMap
* @return
*/
public static String countK1_(Map<String, String> countMap) {
BigDecimal K1_= null;
if( StringUtils.isNotBlank(countMap.get("Vdaf"))
){
BigDecimal Vdaf= getBigDecimal(countMap.get("Vdaf"));
K1_=
Vdaf.compareTo(new BigDecimal(62))==1?new BigDecimal(61.5):(
Vdaf.compareTo(new BigDecimal(56))==1?new BigDecimal(63):(
Vdaf.compareTo(new BigDecimal(49))==1?new BigDecimal(65):(
Vdaf.compareTo(new BigDecimal(45))==1?new BigDecimal(67):(
Vdaf.compareTo(new BigDecimal(37))==1?new BigDecimal(68.5):
new BigDecimal(0)
))));
}
return K1_==null?"":K1_.setScale(1,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求K if 焦渣特征=1 JZB1 if 焦渣特征=1.5 JZB1_5 f 焦渣特征=2 JZB2
* @param resultMap
* @param countMap
* @return
*/
public static String countK(Map<String, String> resultMap, Map<String, String> countMap) {
String count = "";
if( StringUtils.isNotBlank(resultMap.get("焦渣特征")) &&
StringUtils.isNotBlank(countMap.get("Vdaf"))
){
String JZTZ= resultMap.get("焦渣特征").trim();
BigDecimal Vdaf= getBigDecimal(countMap.get("Vdaf"));
//获取焦渣特征序号对应的值
Map<String, String> map = JZTZCountUtil.getJZTZ(Vdaf);
if(JZTZ.equals("1")){
count = map.get(JZTZ);
}else if(JZTZ.equals("1.5")){
count = map.get(JZTZ);
}else if(JZTZ.equals("2")){
count = map.get(JZTZ);
}else if(JZTZ.equals("2.5")){
count = map.get(JZTZ);
}else if(JZTZ.equals("3")){
count = map.get(JZTZ);
}else if(JZTZ.equals("3.5")){
count = map.get(JZTZ);
}else if(JZTZ.equals("4")){
count = map.get(JZTZ);
}else if(JZTZ.equals("4.5")){
count = map.get(JZTZ);
}else if(JZTZ.equals("5")){
count = map.get(JZTZ);
}else if(JZTZ.equals("5.5")){
count = map.get(JZTZ);
}else if(JZTZ.equals("6")){
count = map.get(JZTZ);
}else if(JZTZ.equals("6.5")){
count = map.get(JZTZ);
}else if(JZTZ.equals("7")){
count = map.get(JZTZ);
}else if(JZTZ.equals("7.5")){
count = map.get(JZTZ);
}else if(JZTZ.equals("8")){
count = map.get(JZTZ);
}else{
count = "false";
}
}
return count;
}
/**
* 求Vdaf判断 Vdaf<35?1:0
* @param countMap
* @return
*/
public static String countVdafPD(Map<String, String> countMap) {
Integer VdafPD = null;
if( StringUtils.isNotBlank(countMap.get("Vdaf"))
){
BigDecimal Vdaf= getBigDecimal(countMap.get("Vdaf"));
VdafPD = Vdaf.compareTo(new BigDecimal(35))==-1?1:0;
}
return VdafPD==null?"":VdafPD.toString();
}
/**
* 求Mad判断 Mad>3?1:0
* @param countMap
* @return
*/
public static String countMadPD(Map<String, String> countMap) {
Integer MadPD = null;
if( StringUtils.isNotBlank(countMap.get("报出_Mad"))
){
BigDecimal BC_Mad= getBigDecimal(countMap.get("报出_Mad"));
MadPD = BC_Mad.compareTo(new BigDecimal(3))==1?1:0;
}
return MadPD==null?"":MadPD.toString();
}
/**
* 求40Mad 0或1 Vdaf判断* Mad判断
* @param countMap
* @return
*/
public static String count40Mad0Or1(Map<String, String> countMap) {
BigDecimal count = null;
if( StringUtils.isNotBlank(countMap.get("Vdaf判断")) &&
StringUtils.isNotBlank(countMap.get("Mad判断"))
){
BigDecimal VdafPD= getBigDecimal(countMap.get("Vdaf判断"));
BigDecimal MadPD= getBigDecimal(countMap.get("Mad判断"));
count = VdafPD.multiply(MadPD);
}
return count==null?"":count.toString();
}
/**
* 求Ad
* @param countMap
* @return
*/
public static String countAd(Map<String, String> countMap) {
BigDecimal count = null;
if( StringUtils.isNotBlank(countMap.get("报出_Aad")) &&
StringUtils.isNotBlank(countMap.get("报出_Mad"))
){
BigDecimal BC_Aad= getBigDecimal(countMap.get("报出_Aad"));
BigDecimal BC_Mad= getBigDecimal(countMap.get("报出_Mad"));
if(BC_Mad.compareTo(param100)!=0){
count = BC_Aad.multiply(param100).divide(param100.subtract(BC_Mad),10,BigDecimal.ROUND_HALF_UP);
}
}
return count==null?"":count.toString();
}
/**
* 求Ad系数0.1或0 if Ad>20 0.1 else 0
* @param countMap
* @return
*/
public static String countAdXS(Map<String, String> countMap) {
BigDecimal count = null;
if( StringUtils.isNotBlank(countMap.get("Ad"))
){
BigDecimal Ad= getBigDecimal(countMap.get("Ad"));
count =
Ad.compareTo(new BigDecimal(20))==1?new BigDecimal(0.1):new BigDecimal(0);
}
return count==null?"":count.toString();
}
public static String countVdafXS(Map<String, String> countMap) {
Double count = null;
if( StringUtils.isNotBlank(countMap.get("Ad"))
){
BigDecimal Ad= getBigDecimal(countMap.get("Ad"));
count =
Ad.compareTo(new BigDecimal(30))==1?0.8:(
Ad.compareTo(new BigDecimal(25))==1?0.85:(
Ad.compareTo(new BigDecimal(20))==1?0.95:(
Ad.compareTo(new BigDecimal(15))==1?0.8:(
Ad.compareTo(new BigDecimal(10))==1?0.9:
0.95
))));
}
return count==null?"":count.toString();
}
/**
* 求V,daf [Vdaf系数0.8~0.95]* Vdaf- [Ad系数0.1或0]*Ad
* @param countMap
* @return
*/
public static String countV_daf(Map<String, String> countMap) {
BigDecimal count = null;
if( StringUtils.isNotBlank(countMap.get("Vdaf系数0.8~0.95")) &&
StringUtils.isNotBlank(countMap.get("Vdaf")) &&
StringUtils.isNotBlank(countMap.get("Ad系数0.1或0")) &&
StringUtils.isNotBlank(countMap.get("Ad"))
){
BigDecimal VdafXS= getBigDecimal(countMap.get("Vdaf系数0.8~0.95"));
BigDecimal Vdaf= getBigDecimal(countMap.get("Vdaf"));
BigDecimal AdXS= getBigDecimal(countMap.get("Ad系数0.1或0"));
BigDecimal Ad= getBigDecimal(countMap.get("Ad"));
count = VdafXS.multiply(Vdaf).subtract(AdXS.multiply(Ad));
}
return count==null?"":count.toString();
}
/**
* 求K0, if V,daf >8 8500 if V,daf >5.5 8400 if V,daf >3 8300 else 8200
* @param countMap
* @return
*/
public static String countK0_(Map<String, String> countMap) {
BigDecimal count = null;
if( StringUtils.isNotBlank(countMap.get("V,daf"))
){
BigDecimal V_daf= getBigDecimal(countMap.get("V,daf"));
count =
V_daf.compareTo(new BigDecimal(8))==1?new BigDecimal(8500):(
V_daf.compareTo(new BigDecimal(5.5))==1?new BigDecimal(8400):(
V_daf.compareTo(new BigDecimal(3))==1?new BigDecimal(8300):
new BigDecimal(8200)
));
}
return count==null?"":count.toString();
}
/**
* 求Qnet,ad MJ/kg
* @param countMap
* @return
*/
public static String countQnet_adMJ_kg(Map<String, String> resultMap, Map<String, String> countMap) {
BigDecimal count = null;
if( StringUtils.isNotBlank(resultMap.get("烟无褐123")) &&
StringUtils.isNotBlank(countMap.get("K1,")) &&
StringUtils.isNotBlank(countMap.get("报出_Mad")) &&
StringUtils.isNotBlank(countMap.get("报出_Aad")) &&
StringUtils.isNotBlank(countMap.get("报出_Vad")) &&
StringUtils.isNotBlank(countMap.get("K")) &&
StringUtils.isNotBlank(countMap.get("40Mad 0或1")) &&
StringUtils.isNotBlank(countMap.get("K0,"))
){
BigDecimal YWH_123= getBigDecimal(resultMap.get("烟无褐123").trim());
BigDecimal K1_= getBigDecimal(countMap.get("K1,"));
BigDecimal BC_Mad= getBigDecimal(countMap.get("报出_Mad"));
BigDecimal BC_Aad= getBigDecimal(countMap.get("报出_Aad"));
BigDecimal BC_Vad= getBigDecimal(countMap.get("报出_Vad"));
BigDecimal K= getBigDecimal(countMap.get("K"));
BigDecimal _40Mad_0_1= getBigDecimal(countMap.get("40Mad 0或1"));
BigDecimal K0_= getBigDecimal(countMap.get("K0,"));
BigDecimal value = null;
if(YWH_123.compareTo(new BigDecimal(3))==0){
value =param100.multiply(K1_).subtract(K1_.add(new BigDecimal(6)).multiply(BC_Mad.add(BC_Aad)))
.subtract(BC_Vad);
} else if(YWH_123.compareTo(new BigDecimal(1))==0){
value =param100.multiply(K).subtract(K.add(new BigDecimal(6)).multiply(BC_Mad.add(BC_Aad)))
.subtract(new BigDecimal(3).multiply(BC_Vad))
.subtract(new BigDecimal(40).multiply(BC_Mad).multiply(_40Mad_0_1));
}else if(YWH_123.compareTo(new BigDecimal(2))==0){
value =K0_.subtract(new BigDecimal(86).multiply(BC_Mad))
.subtract(new BigDecimal(92).multiply(BC_Aad))
.subtract(new BigDecimal(24).multiply(BC_Vad));
}
count = value.multiply(new BigDecimal(4.1816)).divide(param1000,10,BigDecimal.ROUND_HALF_UP);
}
return count==null?"":count.setScale(2,BigDecimal.ROUND_HALF_EVEN).toString();
}
/**
* 求工业分析
* @param countMap
* @return
*/
public static String countGYFX(Map<String, String> countMap) {
String count = "";
String Mad= "";
String Aad= "";
String Vad= "";
String Qnet_ad_MJ_kg= "";
String JZ= "";
if( StringUtils.isNotBlank(countMap.get("Mad"))){
Mad= getBigDecimal(countMap.get("Mad")).toString();
}
if( StringUtils.isNotBlank(countMap.get("Aad"))){
Aad= getBigDecimal(countMap.get("Aad")).toString();
}
if( StringUtils.isNotBlank(countMap.get("Vad"))){
Vad= getBigDecimal(countMap.get("Vad")).toString();
}
if( StringUtils.isNotBlank(countMap.get("Qnet,ad MJ/kg"))){
Qnet_ad_MJ_kg= getBigDecimal(countMap.get("Qnet,ad MJ/kg")).toString();
}
if( StringUtils.isNotBlank(countMap.get("焦渣"))){
JZ= getBigDecimal(countMap.get("焦渣")).toString();
}
count = "Mad="+Mad+" \n Aad="+Aad+" \n Vad="+Vad+" \n Qnet,ad MJ/kg="+Qnet_ad_MJ_kg+" \n 焦渣="+JZ;
return count;
}
/**
* 求易磨性等级
* @param resultMap
* @return
*/
public static String countYMXGrade(Map<String, String> resultMap) {
String count = "";
if( StringUtils.isNotBlank(resultMap.get("易磨性(kWh/t)"))
){
BigDecimal YMX_kWh_t = getBigDecimal(resultMap.get("易磨性(kWh/t)"));
if(YMX_kWh_t.compareTo(new BigDecimal(18))==1){
count = "E";
}else if(YMX_kWh_t.compareTo(new BigDecimal(13))==1){
count = "D";
}else if(YMX_kWh_t.compareTo(new BigDecimal(10))==1){
count = "C";
}else if(YMX_kWh_t.compareTo(new BigDecimal(8))==1){
count = "B";
}else{
count = "A";
}
String YMX_kWh_t_str = "";
if(YMX_kWh_t != null){
YMX_kWh_t_str = YMX_kWh_t.toString();
}
count = "易磨性值="+YMX_kWh_t_str+" \n 易磨性等级="+count;
}
return count;
}
/**
* 求易磨性校验码
* @param resultMap
* @return
*/
public static String countYMXCode(Map<String, String> resultMap) {
String count = "";
if( StringUtils.isNotBlank(resultMap.get("G")) &&
StringUtils.isNotBlank(resultMap.get("P80")) &&
StringUtils.isNotBlank(resultMap.get("F80")) &&
StringUtils.isNotBlank(resultMap.get("易磨性(kWh/t)")) &&
StringUtils.isNotBlank(resultMap.get("易磨性(MJ/t)"))
){
Double G = Double.valueOf(resultMap.get("G").trim());
Double P80 = Double.valueOf(resultMap.get("P80").trim());
Double F80 = Double.valueOf(resultMap.get("F80").trim());
BigDecimal YMX_kWh_t = getBigDecimal(resultMap.get("易磨性(kWh/t)").trim());
BigDecimal YMX_MJ_t = getBigDecimal(resultMap.get("易磨性(MJ/t)").trim());
Double countResult =
Math.pow(80,0.23)*Math.pow(G,0.82)*(10/(Math.pow(P80,0.5)- 10/Math.pow(F80,0.5)));
BigDecimal result1 = new BigDecimal(countResult);
BigDecimal value1 =
new BigDecimal(176.2).divide(result1,10,BigDecimal.ROUND_HALF_UP).subtract(new BigDecimal(3.6).multiply(new BigDecimal(P80))).abs();
BigDecimal value2 = YMX_MJ_t.divide(YMX_kWh_t,10,BigDecimal.ROUND_HALF_UP);
if(value1.compareTo(new BigDecimal(0.5) ) == -1 &&
value2.compareTo(new BigDecimal(3.5)) == 1 &&
value2.compareTo(new BigDecimal(3.7)) == -1){
count = "OK";
}else{
count = "出错了";
}
}
return count;
}
/**
* 计算平行数
* @param mainResult 主样数据
* @param secondaryResult 次样数据
* @return
*/
public static String countParallel(String mainResult, String secondaryResult) {
BigDecimal main = getBigDecimal(mainResult);
BigDecimal secondary = getBigDecimal(secondaryResult);
BigDecimal aveCount = main.add(secondary).divide(new BigDecimal(2),10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = aveCount.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
BigDecimal endResult = null;
if((resultInt1&1) == 1){ //如果结果为奇数
endResult = aveCount.setScale(2,BigDecimal.ROUND_HALF_EVEN);
}else{
endResult = aveCount.subtract(new BigDecimal(0.0000000001)).setScale(2,BigDecimal.ROUND_HALF_EVEN);
}
return endResult.toString();
}
/**
* 计算平行样的平均值 最大误差值
* @return
*/
public static Map<String,Map<String,String>> countParallelAvgError(Map<String,String> groupMap) {
Map<String,Map<String,String>> map = new HashMap<>();
Map<String,String> countResults = new HashMap<>();
Map<String,String> countError = new HashMap<>();
for(Map.Entry<String,String> entry : groupMap.entrySet()){
String[] values = entry.getValue().split(",");
BigDecimal resultSum = null; //求总和
BigDecimal maxNum = null; //求最大值
BigDecimal minNum = null; //求最小值
for(String val : values){
BigDecimal valBD = getBigDecimal(val);
resultSum = resultSum == null?valBD:resultSum.add(valBD);
maxNum = maxNum ==null?valBD:(valBD.compareTo(maxNum) == 1?valBD:maxNum);
minNum = minNum==null?valBD:(valBD.compareTo(minNum) == -1?valBD:minNum);
}
//平均值
BigDecimal ResultsValue = null;
if(resultSum != null){
BigDecimal aveCount = resultSum.divide(new BigDecimal(values.length),10,BigDecimal.ROUND_HALF_UP);
BigDecimal result1 = aveCount.multiply(param100);
int resultInt1 = result1.setScale( 0, BigDecimal.ROUND_DOWN ).intValue();
if((resultInt1&1) == 1){ //如果结果为奇数
ResultsValue = aveCount.setScale(2,BigDecimal.ROUND_HALF_EVEN);
}else{
ResultsValue = aveCount.subtract(new BigDecimal(0.0000000001)).setScale(2,BigDecimal.ROUND_HALF_EVEN);
}
}
//最大误差值
BigDecimal errorValue = null;
if(maxNum != null && minNum != null){
errorValue = maxNum.subtract(minNum).setScale(2,BigDecimal.ROUND_HALF_EVEN);
}
countResults.put(entry.getKey(),ResultsValue == null?"":ResultsValue.toString());
countError.put(entry.getKey(),errorValue==null?"":errorValue.toString());
}
map.put("countResults",countResults);
map.put("countError",countError);
return map;
}
}
package cn.wise.sc.cement.business.util;
import java.time.LocalDateTime;
import java.time.temporal.WeekFields;
import java.util.Date;
/**
* @author neo.shu
* @since 2020/4/5 22:26
*/
public class DateUtil {
/**
* 获取自然周数
*
* @param localDateTime
* @return
*/
public static int getWeek(LocalDateTime localDateTime) {
WeekFields weekFields = WeekFields.ISO;
return localDateTime.get(weekFields.weekOfWeekBasedYear());
}
/**
* 获取开始时间
*
* @param type 类型 1:本周 2:本月 3:本年
* @return 开始时间
*/
public static Date getStartTime(Integer type) {
Date rts = null;
if (type == 1) {
rts = cn.hutool.core.date.DateUtil.beginOfWeek(cn.hutool.core.date.DateUtil.date());
} else if (type == 2) {
rts = cn.hutool.core.date.DateUtil.beginOfMonth(cn.hutool.core.date.DateUtil.date());
} else {
rts = cn.hutool.core.date.DateUtil.beginOfYear(cn.hutool.core.date.DateUtil.date());
}
return rts;
}
}
package cn.wise.sc.cement.business.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.FontFormatting;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
/**
* excel工具类
*
* @author zhutianwei
*/
public class ExcelUtil {
/**
* 导出excel
*
* @param fileName
* @param headers
* @param datas
* @param response
*/
public static void excelExport(String fileName, String[] headers, List<Object[]> datas,
HttpServletResponse response) {
Workbook workbook = getWorkbook(headers, datas);
if (workbook != null) {
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
String suffix = ".xlsx";
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((fileName + suffix).getBytes(), "iso-8859-1"));
OutputStream outputStream = response.getOutputStream();
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void excelExportNew(String fileName, String[] headers, List<Object[]> datas,
HttpServletResponse response) {
Workbook workbook = getWorkbookNew(headers, datas);
if (workbook != null) {
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
String suffix = ".xlsx";
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((fileName + suffix).getBytes(), "iso-8859-1"));
OutputStream outputStream = response.getOutputStream();
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void excelExportNew(String fileName, Workbook workbook,
HttpServletResponse response) {
if (workbook != null) {
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
String suffix = ".xlsx";
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((fileName + suffix).getBytes(), "iso-8859-1"));
OutputStream outputStream = response.getOutputStream();
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param headers 列头
* @param datas 数据
* @return
*/
public static Workbook getWorkbook(String[] headers, List<Object[]> datas) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
Row row = null;
Cell cell = null;
XSSFFont font = workbook.createFont();
int line = 0, maxColumn = 0;
if (headers != null && headers.length > 0) { // 设置列头
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
row = sheet.createRow(line++);
row.setHeightInPoints(23);
font.setBold(true);
font.setFontHeightInPoints((short) 13);
style.setFont(font);
style.setWrapText(true);
maxColumn = headers.length;
for (int i = 0; i < maxColumn; i++) {
cell = row.createCell(i);
XSSFFont xxsfFont = workbook.createFont();
//表头处理上下标
if (headers[i] != null) {
//处理下标
if (headers[i].contains("<sup>") || headers[i].contains("</sup>")) {
headers[i] = headers[i].replaceAll("<sup>-</sup>", "⁻");
}
if (headers[i].contains("<sub>") || headers[i].contains("</sub>")) {
xxsfFont.setTypeOffset(FontFormatting.SS_SUB);
cell.setCellStyle(style);
XSSFRichTextString richString = new XSSFRichTextString( headers[i].replaceAll("</sub>", "<sub>").replaceAll("<sub>", ""));
//提取下标位置
applyRichStringFontsub( headers[i], richString, xxsfFont);
cell.setCellValue(richString);
// value = cell.getStringCellValue();
}else{
cell.setCellStyle(style);
cell.setCellValue( headers[i]);
}
}
// cell.setCellValue(headers[i]);
// cell.setCellStyle(style);
}
}
if (datas != null && datas.size() > 0) {// 渲染数据
CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
XSSFFont xxsfFont = workbook.createFont();
for (int index = 0, size = datas.size(); index < size; index++) {
Object[] data = datas.get(index);
if (data != null && data.length > 0) {
row = sheet.createRow(line++);
row.setHeightInPoints(20);
int length = data.length;
if (length > maxColumn) {
maxColumn = length;
}
for (int i = 0; i < length; i++) {
String value = data[i] == null ? null : data[i].toString();
cell = row.createCell(i);
if (value != null) {
//处理下标
if (value.contains("<sup>") || value.contains("</sup>")) {
value = value.replaceAll("<sup>-</sup>", "⁻");
}
if (value.contains("<sub>") || value.contains("</sub>")) {
xxsfFont.setTypeOffset(FontFormatting.SS_SUB);
cell.setCellStyle(style);
XSSFRichTextString richString = new XSSFRichTextString(value.replaceAll("</sub>", "<sub>").replaceAll("<sub>", ""));
//提取下标位置
applyRichStringFontsub(value, richString, xxsfFont);
cell.setCellValue(richString);
// value = cell.getStringCellValue();
} else {
cell.setCellValue(value);
cell.setCellStyle(style);
}
/*if (value.contains("<sup>") || value.contains("</sup>")) {
xxsfFont.setTypeOffset(FontFormatting.SS_SUPER);
cell.setCellStyle(style);
XSSFRichTextString richString = new XSSFRichTextString(value.replaceAll("</sup>", "<sup>").replaceAll("<sup>", ""));
//提取下标位置
applyRichStringFontsup(value, richString, xxsfFont);
cell.setCellValue(richString);
value = cell.getStringCellValue();
}*/
}
}
}
}
}
for (int i = 0; i < maxColumn; i++) {
sheet.autoSizeColumn(i);
//单元格自适应宽度
sheet.setColumnWidth(i, Math.max(15 * 256, Math.min(255 * 256, sheet.getColumnWidth(i) * 12 / 10)));
}
return workbook;
}
private static void applyRichStringFontsub(String sub, XSSFRichTextString richString, XSSFFont xxsfFont) {
String[] split = sub.replaceAll("</sub>", "<sub>").split("<sub>");
String it_str = "";
for (int i = 1; i < split.length + 1; i++) {
if (i % 2 != 0) {
it_str = it_str + split[i - 1];
} else {
richString.applyFont(it_str.length(), (it_str + split[i - 1]).length(), xxsfFont);
it_str = it_str + split[i - 1];
}
}
}
public static XSSFRichTextString applyFontsub(String sub, XSSFFont xxsfFont) {
XSSFRichTextString richString = new XSSFRichTextString();
if (sub.contains("<sup>") || sub.contains("</sup>")) {
sub = sub.replaceAll("<sup>-</sup>", "⁻");
}
if (sub.contains("<sub>") || sub.contains("</sub>")) {
xxsfFont.setTypeOffset(FontFormatting.SS_SUB);
richString.setString(sub.replaceAll("</sub>", "<sub>").replaceAll("<sub>", ""));
//提取下标位置
applyRichStringFontsub(sub, richString, xxsfFont);
} else {
richString.setString(sub);
}
return richString;
}
private static void applyRichStringFontsup(String sup, XSSFRichTextString richString, XSSFFont xxsfFont) {
String[] split = sup.replaceAll("</sup>", "<sup>").split("<sup>");
String it_str = "";
for (int i = 1; i < split.length + 1; i++) {
if (i % 2 != 0) {
it_str = it_str + split[i - 1];
} else {
richString.applyFont(it_str.length(), (it_str + split[i - 1]).length(), xxsfFont);
it_str = it_str + split[i - 1];
}
}
}
public static Workbook getWorkbookNew(String[] headers, List<Object[]> datas) {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet();
workbook.setSheetName(0, "样品处置记录");
Row row = null;
Cell cell = null;
Font font = workbook.createFont();
int line = 0, maxColumn = 0;
if (headers != null && headers.length > 0) { // 设置列头
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
style.setVerticalAlignment(VerticalAlignment.CENTER);
row = sheet.createRow(line++);
row.setHeightInPoints(23);
font.setFontHeightInPoints((short) 12);
font.setFontName("宋体");
style.setFont(font);
maxColumn = headers.length;
for (int i = 0; i < maxColumn; i++) {
cell = row.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(style);
}
}
if (datas != null && datas.size() > 0) {// 渲染数据
CellStyle style = workbook.createCellStyle();
for (int index = 0, size = datas.size(); index < size; index++) {
Object[] data = datas.get(index);
if (data != null && data.length > 0) {
row = sheet.createRow(line++);
row.setHeightInPoints(20);
int length = data.length;
if (length > maxColumn) {
maxColumn = length;
}
for (int i = 0; i < length; i++) {
style.setWrapText(true); //关键
style.setFont(font);
cell = row.createCell(i);
cell.setCellValue(data[i] == null ? null : data[i].toString());
cell.setCellStyle(style);
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
}
}
}
}
for (int i = 0; i < maxColumn; i++) {
sheet.autoSizeColumn(i);
//单元格自适应宽度
sheet.setColumnWidth(i, Math.max(15 * 256, Math.min(255 * 256, sheet.getColumnWidth(i) * 12 / 10)));
}
return workbook;
}
/**
* @param infoHeader 委托人信息表头
* @param teamsHeader 检测项表头
* @return
*/
private static XSSFWorkbook generatoronsignationWorkbook(List<String> infoHeader, List<String> teamsHeader) {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("sheet1");
XSSFCellStyle style = wb.createCellStyle();
//水平居中
style.setAlignment(HorizontalAlignment.CENTER);
//垂直居中
style.setVerticalAlignment(VerticalAlignment.CENTER);
int rownum = 0;
//创建第一行
XSSFRow row0 = sheet.createRow(rownum++);
//处理委托人信息表头
for (int i = 0; i < infoHeader.size(); i++) {
XSSFCell tempCell = row0.createCell(i);
tempCell.setCellValue(infoHeader.get(i));
tempCell.setCellStyle(style);
}
//处理检测项总产值表头
for (int i = infoHeader.size(); i < teamsHeader.size() + infoHeader.size(); i++) {
XSSFCell tempCell = row0.createCell(i);
tempCell.setCellValue(teamsHeader.get(i - infoHeader.size()));
tempCell.setCellStyle(style);
}
//增加1空列
{
XSSFCell tempCell = row0.createCell(teamsHeader.size() + infoHeader.size());
tempCell.setCellValue("");
tempCell.setCellStyle(style);
}
//处理检测项信息表头
for (int i = teamsHeader.size() + infoHeader.size() + 1; i < infoHeader.size() + 1 + teamsHeader.size() * 3; i++) {
String header = teamsHeader.get((i - teamsHeader.size() - infoHeader.size() - 1) / 2);
XSSFCell tempCell1 = row0.createCell(i);
tempCell1.setCellStyle(style);
tempCell1.setCellValue(header);
XSSFCell tempCell2 = row0.createCell(++i);
tempCell2.setCellValue(header);
tempCell2.setCellStyle(style);
//合并表头
sheet.addMergedRegion(new CellRangeAddress(0, 0, i - 1, i));
}
//创建第二行
XSSFRow row1 = sheet.createRow(rownum++);
//处理委托人信息表头
for (int i = 0; i < infoHeader.size(); i++) {
XSSFCell tempCell = row1.createCell(i);
tempCell.setCellValue("");
tempCell.setCellStyle(style);
//合并表头
sheet.addMergedRegion(new CellRangeAddress(0, 1, i, i));
}
//处理检测项总产值表头
for (int i = infoHeader.size(); i < teamsHeader.size() + infoHeader.size(); i++) {
XSSFCell tempCell = row1.createCell(i);
tempCell.setCellValue("计算产值");
tempCell.setCellStyle(style);
}
//增加1空列
{
XSSFCell tempCell = row0.createCell(teamsHeader.size() + infoHeader.size());
tempCell.setCellValue("");
tempCell.setCellStyle(style);
}
//处理检测项信息表头
for (int i = teamsHeader.size() + 1 + infoHeader.size(); i < infoHeader.size() + 1 + teamsHeader.size() * 3; i++) {
XSSFCell tempCell1 = row1.createCell(i);
tempCell1.setCellValue("单价");
tempCell1.setCellStyle(style);
XSSFCell tempCell2 = row1.createCell(++i);
tempCell2.setCellValue("数量");
tempCell2.setCellStyle(style);
}
return wb;
}
/**
* 读取文件
* @param fis
* @return
* @throws Exception
*/
@SuppressWarnings("resource")
public static List<Map<Integer, String>> readData(FileInputStream fis) throws Exception {
XSSFWorkbook hwb = new XSSFWorkbook(fis);
List<Map<Integer, String>> usermap = new ArrayList<>();
// 获取第一个sheet页
XSSFSheet sheetAt = hwb.getSheetAt(0);
if (sheetAt == null) {
return usermap;
}
// 遍历行里面的单元格内容.
for (int i = 1; i <= sheetAt.getLastRowNum(); i++) {
// User user = new User();
Map<Integer, String> map = new HashMap<Integer, String>();
// 得到每一行
XSSFRow row = sheetAt.getRow(i);
// 如果为空就跳出
if (row == null) {
continue;
}
// 遍历列
for (int j = 0; j < row.getLastCellNum(); j++) {
// 遍历列里面的内容
XSSFCell cell = row.getCell(j);
if (cell == null) {
map.put(j, null);
}
try {
map.put(j, cell.getStringCellValue());
} catch (Exception e) {
map.put(j, new DecimalFormat("#0").format(cell.getNumericCellValue()).toString());
}
}
usermap.add(map);
}
return usermap;
}
public static void main(String[] args) throws IOException {
//指定数据存放的位置
OutputStream outputStream = new FileOutputStream("D:\\test.xlsx");
String[] in_fo = {
"委托单号",
"委托单位",
"项目编号",
"项目名称",
"委托人",
"样品数量",
"发样日期",
"是否加急",
"实际产值",
};
List info = Arrays.asList(in_fo);
String a = "荧光检测 L.O.I SiO2 Al2O3+TiO2 Al2O3 TiO2 Fe2O3 CaO MgO K2O Na2O 有效钾 有效钠 重量法SO3 SO3 挥发性硫 硫酸盐硫 Cl⁻ fCaO 1350 fCaO 1400 fCaO 1450 fCaO 附着水 结晶水 工业分析 St,ad 水分 密度 比表面积 45μm细度 80μm细度 200μm细度 激光粒度分析 颗粒形貌分析 塑性指数 白度 粒度筛析 易磨性 T3000 T5000 磨蚀性 可磨 辊磨 易烧性 其他-工艺性能 MnO TiO2 五氧化二磷 铜(Cu) 铅(Pb) 锰(Mn) 镍(Ni) 锌(Zn) 钴(Co) 总铬(Cr) 镉(Cd) 汞(Hg) 砷(As) 锑(Sb) 水溶性铬(VI) 水泥强度检测1天 水泥强度检测2天 水泥强度检测3天 水泥强度检测7天 水泥强度检测28天 标准稠度用水量 流动度 凝结时间 安定性 岩相 衍射 弹筒发热量 热分析 金属铁 水化热 燃烧特性 不溶物 氟离子 游离硅 f-SiO2 f-SiO2+45 f-SiO2+80 其他 煤中硫";
String[] te_rm = a.split("\t");
List term = Arrays.asList(te_rm);
XSSFWorkbook workbook = generatoronsignationWorkbook(info, term);
workbook.write(outputStream);
outputStream.close();
}
}
package cn.wise.sc.cement.business.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.util.TextUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 使用磁盘文件模拟accessToken和jsTicket的数据持久化
* 正式项目请是写入到Mysql等持久化存储
*
* @author openapi@dingtalk
* @date 2020/2/4
*/
public class FileUtil {
private static final String FILEPATH = "Permanent_Data";
/**
* 将json写入文件
*
* @param json 需要写入的json对象
* @param fileName 文件名称
*/
public synchronized static void write2File(Object json, String fileName) {
BufferedWriter writer = null;
File filePath = new File(FILEPATH);
JSONObject eJson = null;
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdirs();
}
File file = new File(FILEPATH + File.separator + fileName + ".xml");
System.out.println("path:" + file.getPath() + " abs path:" + file.getAbsolutePath());
if (!file.exists()) {
try {
file.createNewFile();
} catch (Exception e) {
System.out.println("createNewFile,出现异常:");
e.printStackTrace();
}
} else {
eJson = read2JSON(fileName);
}
try {
writer = new BufferedWriter(new FileWriter(file));
if (eJson == null) {
writer.write(json.toString());
} else {
Object[] array = ((JSONObject) json).keySet().toArray();
for (Object o : array) {
eJson.put(o.toString(), ((JSONObject) json).get(o.toString()));
}
writer.write(eJson.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 读文件到json
*
* @param fileName 文件名称
* @return 文件内容Json对象
*/
public static JSONObject read2JSON(String fileName) {
File file = new File(FILEPATH + File.separator + fileName + ".xml");
if (!file.exists()) {
return null;
}
BufferedReader reader = null;
String laststr = "";
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
laststr += tempString;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return (JSONObject) JSON.parse(laststr);
}
/**
* 通过key值获取文件中的value
*
* @param fileName 文件名称
* @param key key值
* @return key对应的value
*/
public static Object getValue(String fileName, String key) {
JSONObject eJSON = null;
eJSON = read2JSON(fileName);
if (null != eJSON && eJSON.containsKey(key)) {
@SuppressWarnings("unchecked")
Map<String, Object> values = JSON.parseObject(eJSON.toString(), Map.class);
return values.get(key);
} else {
return null;
}
}
public static HashMap<Long, Long> toHashMap(JSONObject js) {
if (js == null) {
return null;
}
HashMap<Long, Long> data = new HashMap<Long, Long>();
// 将json字符串转换成jsonObject
Set<String> set = js.keySet();
// 遍历jsonObject数据,添加到Map对象
for (String s : set) {
String key = String.valueOf(s);
Long keyLong = Long.valueOf(key);
String value = js.getString(key);
Long valueLong;
if (TextUtils.isEmpty(value)) {
valueLong = js.getLong(key);
} else {
valueLong = Long.valueOf(value);
}
data.put(keyLong, valueLong);
}
return data;
}
}
package cn.wise.sc.cement.business.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 用ThreadLocal来存储resquest
*/
public class GlobalHolder {
private static ThreadLocal<HttpServletRequest> requestThreadLocalHolder = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> responseThreadLocalHolder = new ThreadLocal<HttpServletResponse>();
public static void setHttpRequest(HttpServletRequest request) {
requestThreadLocalHolder.set(request);
}
public static void setHttpResponse(HttpServletResponse response) {
responseThreadLocalHolder.set(response);
}
public static void remove() {
requestThreadLocalHolder.remove();
responseThreadLocalHolder.remove();
}
public static HttpServletResponse getHttpResponse() {
return responseThreadLocalHolder.get();
}
public static HttpServletRequest getHttpRequest() {
return requestThreadLocalHolder.get();
}
public static String corpId() {
HttpServletRequest request = requestThreadLocalHolder.get();
//前台传递值
return request.getHeader("corpId");
}
}
package cn.wise.sc.cement.business.util;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 焦渣特征序号值计算工具类
*
* @author zhutianwei
*/
public class JZTZCountUtil {
public static final BigDecimal NO42 = new BigDecimal(42);
public static final BigDecimal NO38 = new BigDecimal(42);
public static final BigDecimal NO35 = new BigDecimal(42);
public static final BigDecimal NO32 = new BigDecimal(42);
public static final BigDecimal NO29 = new BigDecimal(42);
public static final BigDecimal NO23 = new BigDecimal(42);
public static final BigDecimal NO20 = new BigDecimal(42);
public static final BigDecimal NO17 = new BigDecimal(42);
public static final BigDecimal NO13_5 = new BigDecimal(42);
public static final BigDecimal NO10 = new BigDecimal(42);
/**
* 根据Vdaf获取焦渣特征编号对应值
*
* @param Vdaf
* @return
*/
public static Map<String, String> getJZTZ(BigDecimal Vdaf) {
Map<String, String> map = new HashMap<>();
String JZTZ1 =
Vdaf.compareTo(NO42) == 1 ? "72.5" : (
Vdaf.compareTo(NO38) == 1 ? "73" : (
Vdaf.compareTo(NO35) == 1 ? "73" : (
Vdaf.compareTo(NO32) == 1 ? "73" : (
Vdaf.compareTo(NO29) == 1 ? "76.5" : (
Vdaf.compareTo(NO23) == 1 ? "76.5" : (
Vdaf.compareTo(NO20) == 1 ? "78.5" : (
Vdaf.compareTo(NO17) == 1 ? "80" : (
Vdaf.compareTo(NO13_5) == 1 ? "80.5" : (
Vdaf.compareTo(NO10) == 1 ? "84" : "false")))))))));
String JZTZ1_5 =
Vdaf.compareTo(NO42) == 1 ? "73.5" : (
Vdaf.compareTo(NO38) == 1 ? "74.25" : (
Vdaf.compareTo(NO35) == 1 ? "74.75" : (
Vdaf.compareTo(NO32) == 1 ? "75.25" : (
Vdaf.compareTo(NO29) == 1 ? "77.25" : (
Vdaf.compareTo(NO23) == 1 ? "77.5" : (
Vdaf.compareTo(NO20) == 1 ? "79.75" : (
Vdaf.compareTo(NO17) == 1 ? "81" : (
Vdaf.compareTo(NO13_5) == 1 ? "82" : (
Vdaf.compareTo(NO10) == 1 ? "84" : "false")))))))));
String JZTZ2 =
Vdaf.compareTo(NO42) == 1 ? "74.5" : (
Vdaf.compareTo(NO38) == 1 ? "75.5" : (
Vdaf.compareTo(NO35) == 1 ? "76.5" : (
Vdaf.compareTo(NO32) == 1 ? "77.5" : (
Vdaf.compareTo(NO29) == 1 ? "78" : (
Vdaf.compareTo(NO23) == 1 ? "78.5" : (
Vdaf.compareTo(NO20) == 1 ? "81" : (
Vdaf.compareTo(NO17) == 1 ? "82.75" : (
Vdaf.compareTo(NO13_5) == 1 ? "83.5" : (
Vdaf.compareTo(NO10) == 1 ? "84" : "false")))))))));
String JZTZ2_5 =
Vdaf.compareTo(NO42) == 1 ? "75.5" : (
Vdaf.compareTo(NO38) == 1 ? "76.75" : (
Vdaf.compareTo(NO35) == 1 ? "77.5" : (
Vdaf.compareTo(NO32) == 1 ? "78.25" : (
Vdaf.compareTo(NO29) == 1 ? "79" : (
Vdaf.compareTo(NO23) == 1 ? "79.75" : (
Vdaf.compareTo(NO20) == 1 ? "81.75" : (
Vdaf.compareTo(NO17) == 1 ? "82.75" : (
Vdaf.compareTo(NO13_5) == 1 ? "84" : (
Vdaf.compareTo(NO10) == 1 ? "84.25" : "false")))))))));
String JZTZ3 =
Vdaf.compareTo(NO42) == 1 ? "76.5" : (
Vdaf.compareTo(NO38) == 1 ? "78" : (
Vdaf.compareTo(NO35) == 1 ? "78.5" : (
Vdaf.compareTo(NO32) == 1 ? "79" : (
Vdaf.compareTo(NO29) == 1 ? "80" : (
Vdaf.compareTo(NO23) == 1 ? "81" : (
Vdaf.compareTo(NO20) == 1 ? "82.5" : (
Vdaf.compareTo(NO17) == 1 ? "83.5" : (
Vdaf.compareTo(NO13_5) == 1 ? "84.5" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ3_5 =
Vdaf.compareTo(NO42) == 1 ? "77" : (
Vdaf.compareTo(NO38) == 1 ? "78.5" : (
Vdaf.compareTo(NO35) == 1 ? "79" : (
Vdaf.compareTo(NO32) == 1 ? "79.5" : (
Vdaf.compareTo(NO29) == 1 ? "80.5" : (
Vdaf.compareTo(NO23) == 1 ? "81.5" : (
Vdaf.compareTo(NO20) == 1 ? "82.75" : (
Vdaf.compareTo(NO17) == 1 ? "83.75" : (
Vdaf.compareTo(NO13_5) == 1 ? "84.75" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ4 =
Vdaf.compareTo(NO42) == 1 ? "77.5" : (
Vdaf.compareTo(NO38) == 1 ? "79" : (
Vdaf.compareTo(NO35) == 1 ? "79.5" : (
Vdaf.compareTo(NO32) == 1 ? "80" : (
Vdaf.compareTo(NO29) == 1 ? "81" : (
Vdaf.compareTo(NO23) == 1 ? "82" : (
Vdaf.compareTo(NO20) == 1 ? "83" : (
Vdaf.compareTo(NO17) == 1 ? "84" : (
Vdaf.compareTo(NO13_5) == 1 ? "85" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ4_5 =
Vdaf.compareTo(NO42) == 1 ? "78.5" : (
Vdaf.compareTo(NO38) == 1 ? "79.5" : (
Vdaf.compareTo(NO35) == 1 ? "80.25" : (
Vdaf.compareTo(NO32) == 1 ? "80.75" : (
Vdaf.compareTo(NO29) == 1 ? "81.75" : (
Vdaf.compareTo(NO23) == 1 ? "82.75" : (
Vdaf.compareTo(NO20) == 1 ? "83.5" : (
Vdaf.compareTo(NO17) == 1 ? "84.5" : (
Vdaf.compareTo(NO13_5) == 1 ? "85" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ5 =
Vdaf.compareTo(NO42) == 1 ? "79.5" : (
Vdaf.compareTo(NO38) == 1 ? "80" : (
Vdaf.compareTo(NO35) == 1 ? "81" : (
Vdaf.compareTo(NO32) == 1 ? "81.5" : (
Vdaf.compareTo(NO29) == 1 ? "82.5" : (
Vdaf.compareTo(NO23) == 1 ? "83.5" : (
Vdaf.compareTo(NO20) == 1 ? "84" : (
Vdaf.compareTo(NO17) == 1 ? "85" : (
Vdaf.compareTo(NO13_5) == 1 ? "85" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ5_5 =
Vdaf.compareTo(NO42) == 1 ? "79.5" : (
Vdaf.compareTo(NO38) == 1 ? "80" : (
Vdaf.compareTo(NO35) == 1 ? "81" : (
Vdaf.compareTo(NO32) == 1 ? "81.5" : (
Vdaf.compareTo(NO29) == 1 ? "82.5" : (
Vdaf.compareTo(NO23) == 1 ? "83.5" : (
Vdaf.compareTo(NO20) == 1 ? "84" : (
Vdaf.compareTo(NO17) == 1 ? "85" : (
Vdaf.compareTo(NO13_5) == 1 ? "85" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ6 =
Vdaf.compareTo(NO42) == 1 ? "79.5" : (
Vdaf.compareTo(NO38) == 1 ? "80" : (
Vdaf.compareTo(NO35) == 1 ? "81" : (
Vdaf.compareTo(NO32) == 1 ? "81.5" : (
Vdaf.compareTo(NO29) == 1 ? "82.5" : (
Vdaf.compareTo(NO23) == 1 ? "83.5" : (
Vdaf.compareTo(NO20) == 1 ? "84" : (
Vdaf.compareTo(NO17) == 1 ? "85" : (
Vdaf.compareTo(NO13_5) == 1 ? "85" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ6_5 =
Vdaf.compareTo(NO42) == 1 ? "80.25" : (
Vdaf.compareTo(NO38) == 1 ? "81" : (
Vdaf.compareTo(NO35) == 1 ? "81.75" : (
Vdaf.compareTo(NO32) == 1 ? "82.25" : (
Vdaf.compareTo(NO29) == 1 ? "83.25" : (
Vdaf.compareTo(NO23) == 1 ? "84" : (
Vdaf.compareTo(NO20) == 1 ? "84.5" : (
Vdaf.compareTo(NO17) == 1 ? "85" : (
Vdaf.compareTo(NO13_5) == 1 ? "85" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ7 =
Vdaf.compareTo(NO42) == 1 ? "81" : (
Vdaf.compareTo(NO38) == 1 ? "82" : (
Vdaf.compareTo(NO35) == 1 ? "82.5" : (
Vdaf.compareTo(NO32) == 1 ? "83" : (
Vdaf.compareTo(NO29) == 1 ? "84" : (
Vdaf.compareTo(NO23) == 1 ? "84.5" : (
Vdaf.compareTo(NO20) == 1 ? "85" : (
Vdaf.compareTo(NO17) == 1 ? "85" : (
Vdaf.compareTo(NO13_5) == 1 ? "85" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ7_5 =
Vdaf.compareTo(NO42) == 1 ? "81.5" : (
Vdaf.compareTo(NO38) == 1 ? "82.25" : (
Vdaf.compareTo(NO35) == 1 ? "82.75" : (
Vdaf.compareTo(NO32) == 1 ? "83" : (
Vdaf.compareTo(NO29) == 1 ? "84.25" : (
Vdaf.compareTo(NO23) == 1 ? "84.75" : (
Vdaf.compareTo(NO20) == 1 ? "85.25" : (
Vdaf.compareTo(NO17) == 1 ? "85" : (
Vdaf.compareTo(NO13_5) == 1 ? "85" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
String JZTZ8 =
Vdaf.compareTo(NO42) == 1 ? "82" : (
Vdaf.compareTo(NO38) == 1 ? "82.5" : (
Vdaf.compareTo(NO35) == 1 ? "83" : (
Vdaf.compareTo(NO32) == 1 ? "83.5" : (
Vdaf.compareTo(NO29) == 1 ? "84.5" : (
Vdaf.compareTo(NO23) == 1 ? "85" : (
Vdaf.compareTo(NO20) == 1 ? "85.5" : (
Vdaf.compareTo(NO17) == 1 ? "85" : (
Vdaf.compareTo(NO13_5) == 1 ? "85" : (
Vdaf.compareTo(NO10) == 1 ? "84.5" : "false")))))))));
map.put("1", JZTZ1);
map.put("1.5", JZTZ1_5);
map.put("2", JZTZ2);
map.put("2.5", JZTZ2_5);
map.put("3", JZTZ3);
map.put("3.5", JZTZ3_5);
map.put("4", JZTZ4);
map.put("4.5", JZTZ4_5);
map.put("5", JZTZ5);
map.put("5.5", JZTZ5_5);
map.put("6", JZTZ6);
map.put("6.5", JZTZ6_5);
map.put("7", JZTZ7);
map.put("7.5", JZTZ7_5);
map.put("8", JZTZ8);
return map;
}
}
package cn.wise.sc.cement.business.util;
import java.security.Key;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;
/**
* 通过 jwt 生成token 及 验证
*
* @author ztw
*/
public class JwtUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(JwtUtil.class);
private static final String SECRET_KEY = "_MeD5CiNov0_TecH";
/**
* 签名算法
*/
private static final SignatureAlgorithm DEFAULTSIGN = SignatureAlgorithm.HS256;
/**
* 根据用户信息生成 token
*
* @return
*/
public static String createToken(Integer id, String username, String name, String
phone) {
Claims claim = new DefaultClaims();
// 设置 签发人
long timeStamp = (new Date()).getTime();
claim.setIssuer("cement");
claim.put("id", id);
claim.put("username", username);
claim.put("name", name);
claim.put("phone", phone);
claim.put("timeStamp", timeStamp);
Key signingKey = getKey(SECRET_KEY, DEFAULTSIGN.getJcaName());
JwtBuilder builder = Jwts.builder().setClaims(claim).signWith(DEFAULTSIGN, signingKey);
return builder.compact();
}
/**
* 根据 params 生成 token
*
* @return
*/
public static String createToken(JSONObject params) {
Claims claim = new DefaultClaims();
// 设置 签发人
long timeStamp = (new Date()).getTime();
claim.setIssuer("cement");
Set<String> keys = params.keySet();
for (String key : keys) {
claim.put(key, params.getString(key));
}
claim.put("timeStamp", timeStamp);
Key signingKey = getKey(SECRET_KEY, DEFAULTSIGN.getJcaName());
JwtBuilder builder = Jwts.builder().setClaims(claim).signWith(DEFAULTSIGN, signingKey);
return builder.compact();
}
/**
* 根据 userId 生成 token
*
* @param userId
* @return
*/
public static String createToken(String userId) {
Claims claim = new DefaultClaims();
// claim.setAudience("www.bizconf.cn");// 设置接收方
// 设置 签发人
long timeStamp = (new Date()).getTime();
claim.setIssuer("goldwind");
claim.put("userId", userId);
claim.put("timeStamp", timeStamp);
Key signingKey = getKey(SECRET_KEY, DEFAULTSIGN.getJcaName());
JwtBuilder builder = Jwts.builder().setClaims(claim).signWith(DEFAULTSIGN, signingKey);
return builder.compact();
}
/**
* 该方法使用 HS256 算法和 Secret: 生成signKey
*
* @param key
* @param jcaName
* @return
*/
private static Key getKey(String key, String jcaName) {
byte[] keyb = null;
if ("".equals(key) || key == null) {
keyb = DatatypeConverter.parseBase64Binary(SECRET_KEY);
} else {
keyb = DatatypeConverter.parseBase64Binary(key);
}
String jcaName1 = null;
if ("".equals(jcaName) || jcaName == null) {
jcaName1 = DEFAULTSIGN.getJcaName();
} else {
jcaName1 = jcaName;
}
Key signKey = new SecretKeySpec(keyb, jcaName1);
return signKey;
}
/**
* 解析 token
*
* @param token
* @return
*/
public static Map parserToken(String token) throws Exception {
Claims claims = null;
claims = Jwts.parser().setSigningKey(getKey(SECRET_KEY, DEFAULTSIGN.getJcaName())).parseClaimsJws(token)
.getBody();
//userid = (String) claims.get("userId");
return claims;
}
/**
* 获得userId 如果解析错误返回 -1
*
* @param token
* @return
*/
public static String getUserIdByToken(String token) {
Claims claims = null;
String userid = "-1";
try {
claims = Jwts.parser().setSigningKey(getKey(SECRET_KEY, DEFAULTSIGN.getJcaName())).parseClaimsJws(token)
.getBody();
userid = claims.get("id").toString();
} catch (Exception e) {
LOGGER.info("解密userId失败:" + token);
return userid;
}
return userid;
}
/**
* 获得username 如果解析错误返回 -1
*
* @param token
* @return
*/
public static String getUserNameByToken(String token) {
Claims claims = null;
String username = "-1";
try {
claims = Jwts.parser().setSigningKey(getKey(SECRET_KEY, DEFAULTSIGN.getJcaName())).parseClaimsJws(token)
.getBody();
username = (String) claims.get("username");
} catch (Exception e) {
LOGGER.info("解密userId失败:" + token);
return username;
}
return username;
}
/**
* 获得userId 如果解析错误返回 -1
*
* @param token
* @return
*/
public static String getValueByToken(String token, String value) {
Claims claims = null;
try {
claims = Jwts.parser().setSigningKey(getKey(SECRET_KEY, DEFAULTSIGN.getJcaName())).parseClaimsJws(token)
.getBody();
value = String.valueOf(claims.get(value));
if (value == null || "".equals(value)) {
value = "-1";
return value;
}
} catch (Exception e) {
e.printStackTrace();
value = "-1";
return value;
}
return value;
}
public static void main(String[] args) throws Exception {
String token = createToken(1, "34466", "荀玉龙", "17601636518");
System.out.println(token);
System.out.println(parserToken(token));
System.out.println(getValueByToken(token, "enterpriseId"));
System.out.println(getUserIdByToken(token));
long timeStamp = (long) parserToken(token).get("timeStamp");
long ts = System.currentTimeMillis();
if (ts - timeStamp > 1000 * 120) {
System.out.println("token超时");
} else {
System.out.println("token有效");
}
//System.out.println(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
}
}
package cn.wise.sc.cement.business.util;
import cn.hutool.core.collection.CollectionUtil;
import cn.wise.sc.cement.business.model.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
/**
* @description:
* @author: qh
* @create: 2020-09-27 18:19
**/
public class PageUtil {
public static <T> Page<T> listConvertToPage(List<T> list, PageQuery pageQuery) {
if (CollectionUtil.isEmpty(list)){
return new Page<>();
}
int start = pageQuery.getPageNo() > 0 ? pageQuery.getPageNo() : 1;
int pageSize = pageQuery.getPageSize() > 0 ? pageQuery.getPageSize() : 10;
int end = Math.min((start * pageSize), list.size());
long pageStart = (start - 1) * pageSize;
Page<T> page = new Page<>(start, pageSize, list.size());
if (pageStart >= list.size()) {
return page;
}
page.setRecords(list.subList((int) (pageStart), end));
return page;
}
}
package cn.wise.sc.cement.business.util;
import cn.wise.sc.cement.business.exception.RedisHandleException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @description:用途: redis 缓存集合
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
//---------------------- common --------------------------
/**
* 指定缓存失效时间
*
* @param key key值
* @param time 缓存时间
*/
public void expire(String key, long time) {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
} else {
throw new RedisHandleException("设置的时间不能为0或者小于0!!");
}
}
/**
* 判断key是否存在
*
* @param key 传入ke值
* @return true 存在 false 不存在
*/
public Boolean existsKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 判断key存储的值类型
*
* @param key key值
* @return DataType[string、list、set、zset、hash]
*/
public DataType typeKey(String key) {
return redisTemplate.type(key);
}
/**
* 删除指定的一个数据
*
* @param key key值
* @return true 删除成功,否则返回异常信息
*/
public Boolean deleteKey(String key) {
try {
return redisTemplate.delete(key);
} catch (Exception ex) {
throw new RedisHandleException("删除失败!", ex);
}
}
/**
* 删除多个数据
*
* @param keys key的集合
* @return true删除成功,false删除失败
*/
public Boolean deleteKey(Collection<String> keys) {
return redisTemplate.delete(keys) != 0;
}
//-------------------- String ----------------------------
/**
* 普通缓存放入
*
* @param key 键值
* @param value 值
* @return true成功 要么异常
*/
public Boolean setString(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception ex) {
throw new RedisHandleException("插入缓存失败!", ex);
}
}
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object getString(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 设置缓存存在时间
*
* @param key key值
* @param value value值
* @param time 时间 秒为单位
* @return 成功返回true,失败返回异常信息
*/
public boolean setString(String key, Object value, long time) {
try {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
return true;
} catch (Exception ex) {
throw new RedisHandleException("插入缓存失败!", ex);
}
}
//----------------------------- list ------------------------------
/**
* 将list放入缓存
*
* @param key key的值
* @param value 放入缓存的数据
* @return true 代表成功,否则返回异常信息
*/
public Boolean setList(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception ex) {
throw new RedisHandleException("插入List缓存失败!", ex);
}
}
/**
* 将Object数据放入List缓存,并设置时间
*
* @param key key值
* @param value 数据的值
* @param time 缓存的时间
* @return true插入成功,否则返回异常信息
*/
public Boolean setList(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForList().rightPush(key, value);
expire(key, time);
return true;
}
return false;
} catch (Exception ex) {
throw new RedisHandleException("插入List缓存失败!", ex);
}
}
/**
* 将list集合放入List缓存,并设置时间
*
* @param key key值
* @param listStr 数据的值
* @param time 缓存的时间
* @return true插入成功,否则返回异常信息
*/
public Boolean setListAll(String key, String listStr, long time) {
try {
if (time > 0) {
setString(key,listStr,time);
return true;
}
return false;
} catch (Exception ex) {
throw new RedisHandleException("插入List缓存失败!", ex);
}
}
/**
* 根据索引获取缓存List中的内容
*
* @param key key的值
* @param start 索引开始
* @param end 索引结束 0 到 -1代表所有值
* @return 返回数据
*/
public List<Object> getList(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception ex) {
throw new RedisHandleException("获取缓存List中的内容失败了!", ex);
}
}
/**
* 删除List缓存中多个list数据
*
* @param key key值
* @param count 移除多少个
* @param value 可以传null 或者传入存入的Value的值
* @return 返回删除了多少个
*/
public long deleteListIndex(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception ex) {
throw new RedisHandleException("删除List中的内容失败了!", ex);
}
}
/**
* 获取List缓存的数据
*
* @param key key值
* @return 返回长度
*/
public long getListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception ex) {
throw new RedisHandleException("获取List长度失败", ex);
}
}
}
package cn.wise.sc.cement.business.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 序列化对象工具类,用于保存和读取redis数据使用
* Function:
* Date: 2018年9月12日10:18:56
*/
public class SerializeUtil {
private static Logger log = LoggerFactory.getLogger(SerializeUtil.class);
/**
* 序列化对象
*
* @param object
* @return
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
byte[] bytes = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
}
if (baos != null) {
baos.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return bytes;
}
/**
* 反序列化对象
*
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
Object obj = null;
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
obj = ois.readObject();
ois.close();
bais.close();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 关闭的数据源或目标。调用 close()方法可释放对象保存的资源(如打开文件)
* 关闭此流并释放与此流关联的所有系统资源。如果已经关闭该流,则调用此方法无效。
*
* @param closeable
*/
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
log.info("Unable to close %s", closeable, e);
}
}
}
/**
* 列表序列化(用于Redis整存整取)
*
* @param value
* @return
*/
public static <T> byte[] serialize(List<T> value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] rv = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
for (T obj : value) {
os.writeObject(obj);
}
os.writeObject(null);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
}
return rv;
}
/**
* 反序列化列表(用于Redis整存整取)
*
* @param in
* @return
*/
public static <T> List<T> unserializeForList(byte[] in) {
List<T> list = new ArrayList<T>();
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
while (true) {
T obj = (T) is.readObject();
if (obj == null) {
break;
} else {
list.add(obj);
}
}
is.close();
bis.close();
}
} catch (IOException e) {
log.warn("Caught IOException decoding %d bytes of data",
in == null ? 0 : in.length, e);
} catch (ClassNotFoundException e) {
log.warn("Caught CNFE decoding %d bytes of data",
in == null ? 0 : in.length, e);
} finally {
close(is);
close(bis);
}
return list;
}
}
package cn.wise.sc.cement.business.util;
import cn.wise.sc.cement.business.model.Message;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/test-websocket/{sid}")
@Component
@Slf4j
public class WebSocketServer {
/**
* 用于存放所有在线客户端
*/
private static Map<String, Session> clients = new ConcurrentHashMap<>();
// private static Map<String, List<Message>> messages = new ConcurrentHashMap<>();
/*@Value("${websocket.socketKey}")
private String SOCKET_KEY;
@Value("${websocket.host}")
private String host;
@Value("${websocket.port}")
private int port;
@Value("${websocket.timeout}")
private int timeout;
@Value("${websocket.clientDB}")
private long clientDB;
@Value("${websocket.selectDB}")
private int selectDB;
@Value("${websocket.password}")
private String password;*/
private static final String SOCKET_KEY = "socketkey";
private static final String host = "localhost";
private static final int port = 6379;
private static final int timeout = 100000;
private static final long clientDB = 2;
private static final int selectDB = 2;
private static final String password = "Wise_@123456";
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
log.info("有新的客户端上线: {}", session.getId());
clients.put(sid, session);
Jedis jedis = new Jedis(host, port, timeout);
// jedis.auth(password);
jedis.select(selectDB);
// jedis.getClient().setDb(clientDB);
List<Message> messageList = SerializeUtil.unserializeForList(jedis.get((SOCKET_KEY + sid).getBytes()));
if (session != null) {
for (int i = 0; i < messageList.size(); i++) {
Message message = messageList.get(i);
try {
JSONObject json = (JSONObject) JSONObject.toJSON(message);
String msg = json.toJSONString();
session.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
jedis.del((SOCKET_KEY + sid).getBytes());
}
}
@OnClose
public void onClose(Session session, @PathParam("sid") String sid) {
String sessionId = session.getId();
log.info("有客户端离线: {}", sessionId);
clients.remove(sid);
}
@OnError
public void onError(Session session, Throwable throwable, @PathParam("sid") String sid) {
throwable.printStackTrace();
if (clients.get(sid) != null) {
clients.remove(sid);
}
}
@OnMessage
public void onMessage(String message) {
log.info("收到客户端发来的消息: {}", message);
this.sendTo(JSON.parseObject(message, Message.class));
}
/**
* 发送消息
*
* @param message 消息对象
*/
public void sendTo(Message message) {
if (clients.get(message.getUserId()) == null) {
Jedis jedis = new Jedis(host, port, timeout);
// jedis.auth(password);
jedis.select(selectDB);
// jedis.getClient().setDb(clientDB);
List<Message> messageList = SerializeUtil.unserializeForList(jedis.get((SOCKET_KEY + message.getUserId()).getBytes()));
messageList.add(message);
jedis.set((SOCKET_KEY + message.getUserId()).getBytes(), SerializeUtil.serialize(messageList));
} else {
Session s = clients.get(message.getUserId());
if (s != null) {
try {
JSONObject json = (JSONObject) JSONObject.toJSON(message);
String msg = json.toJSONString();
s.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package cn.wise.sc.cement.business.util;
import cn.hutool.core.io.file.FileReader;
import cn.wise.sc.cement.business.util.dfs.FastDFSUtils;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author neo.shu
* @since 2020/9/10 20:38
*/
public class Word2PdfUtil {
public static void main(String[] args) {
try {
long time = System.currentTimeMillis();
File file = new File("D:\\JavaProject\\tianjin-cement\\cement-business\\src\\main\\resources\\检测报告模板(最新).xls");
Workbook document = new Workbook(new FileInputStream(file));
//pdf路径
File outputFile = new File("temp-" + System.currentTimeMillis() + ".pdf");
//操作文档保存
document.save(outputFile.getAbsolutePath(), SaveFormat.PDF);
FileReader fileReader = new FileReader(outputFile.getAbsolutePath());
String filePath = FastDFSUtils.uploadPic(fileReader.readBytes(), outputFile.getName(), file.length());
long time1 = System.currentTimeMillis();
System.out.println((time1 - time) / 1000);
System.out.println(filePath);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package cn.wise.sc.cement.business.util;
import cn.wise.sc.cement.business.enumation.FileExt;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
/**
* @description:
* @author: qh
* @create: 2020-10-10 15:22
**/
@Slf4j
public class WordUtil {
/**
* 模板路径
*/
private static final String FTL_FP = "/templates/";
private static Configuration configuration;
static {
configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
configuration.setDefaultEncoding("utf-8");
}
/**
* 根据模板导出office文件
*
* @param templeName 导出的文件名
* @param templateFileName 模板名字
* @param beanParams 替换模板中的参数 <${模板占位符},对应值>
* @param response 响应体
*/
public static void writeWordReport(
String templeName,
String templateFileName,
Map<String, Object> beanParams,
HttpServletResponse response,
FileExt fileExt) {
Writer out = null;
File file = null;
try {
configuration.setClassForTemplateLoading(WordUtil.class, FTL_FP);
Template template = configuration.getTemplate(templateFileName, "UTF-8");
if (template ==null){
System.out.println("==========================\n 报错-================\n");
}
String filePath;
filePath = "";
file = new File(filePath + templeName);
//输出文件
FileOutputStream fos = new FileOutputStream(file);
out = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
//变量替换
template.process(beanParams, out);
FileInputStream in = new FileInputStream(file);
/*HSSFWorkbook xssfWorkbook = new HSSFWorkbook(in);
ByteArrayOutputStream os = new ByteArrayOutputStream();
xssfWorkbook.write(os);
byte[] bytes = os.toByteArray();*/
byte[] buffer = new byte[in.available()];
int i = in.read(buffer);
if (i == -1) {
return;
}
in.close();
response.reset();
ServletOutputStream outputStream = response.getOutputStream();
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
response.setContentType("application/octet-stream");
templeName = new String((templeName).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setHeader("Content-Disposition", "attachment;filename=" + templeName + fileExt.getName());
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
boolean delete = file.delete();
if (!delete) {
log.debug(file.getName() + "文件删除失败!");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 根据模板导出office文件 带上下标的
*
* @param templeName 导出的文件名
* @param templateFileName 模板名字
* @param beanParams 替换模板中的参数 <${模板占位符},对应值>
* @param response 响应体
*/
public static void writeWordReportSXB(
String templeName,
String templateFileName,
Map<String, Object> beanParams,
HttpServletResponse response,
FileExt fileExt) {
Writer out = null;
File file = null;
try {
configuration.setClassForTemplateLoading(WordUtil.class, FTL_FP);
Template template = configuration.getTemplate(templateFileName, "UTF-8");
if (template ==null){
System.out.println("==========================\n 报错-================\n");
}
String filePath;
filePath = "";
file = new File(filePath + templeName);
//输出文件
FileOutputStream fos = new FileOutputStream(file);
out = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
template.process(beanParams, out);
FileInputStream in = new FileInputStream(file);
/*HSSFWorkbook xssfWorkbook = new HSSFWorkbook(in);
ByteArrayOutputStream os = new ByteArrayOutputStream();
xssfWorkbook.write(os);
byte[] bytes = os.toByteArray();*/
byte[] buffer = new byte[in.available()];
int i = in.read(buffer);
if (i == -1) {
return;
}
in.close();
response.reset();
ServletOutputStream outputStream = response.getOutputStream();
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
response.setContentType("application/octet-stream");
templeName = new String((templeName).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setHeader("Content-Disposition", "attachment;filename=" + templeName + fileExt.getName());
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
boolean delete = file.delete();
if (!delete) {
log.debug(file.getName() + "文件删除失败!");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package cn.wise.sc.cement.business.util.dfs;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import com.aspose.cells.License;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 上传图片到FastDFS
*/
public class FastDFSUtils {
static {
try {
// ClientGlobal.initByProperties(FastDFSUtils.class.getClassLoader().getResource("fastdfs-client.properties").getPath());
ClientGlobal.initByProperties("fastdfs-client.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}
public static String[] uploadPic(String path, String fileName, long size) {
String[] fileIds = null;
try {
// ClientGloble 读配置文件
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String extName = FilenameUtils.getExtension(fileName);
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", extName);
meta_list[2] = new NameValuePair("fileSize", String.valueOf(size));
// http://172.16.15.244:8081/group1/M00/00/00/rBAP9FfFG62AZsuBAADeW7MfEHA287.png
// group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
fileIds = storageClient.upload_file(path, extName, meta_list);
} catch (Exception e) {
e.printStackTrace();
}
return fileIds;
}
public static String[] uploadPic(InputStream inStream, String fileName, long size) {
String[] fileIds = null;
try {
// ClientGloble 读配置文件
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String extName = FilenameUtils.getExtension(fileName);
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", extName);
meta_list[2] = new NameValuePair("fileSize", String.valueOf(size));
// http://172.16.15.244:8081/group1/M00/00/00/rBAP9FfFG62AZsuBAADeW7MfEHA287.png
// group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
fileIds = storageClient.upload_file(null, size, new UploadFileSender(inStream), extName, meta_list);
} catch (Exception e) {
e.printStackTrace();
}
return fileIds;
}
public static byte[] fileDownload(String fileUrl) {
byte[] by = null;
TrackerClient trackerClient = null;
TrackerServer trackerServer = null;
StorageClient1 storageClient1 = null;
StorageServer storageServer = null;
try {
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageClient1 = new StorageClient1(trackerServer, storageServer);
// 根据文件标识下载文件
by = storageClient1.download_file1(fileUrl);
// 将数据写入输出流
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
return by;
}
public static String uploadPic(byte[] pic, String fileName, long size) {
String[] fileIds = null;
try {
// ClientGloble 读配置文件
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String extName = FilenameUtils.getExtension(fileName);
// 设置图片meta信息
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", extName);
meta_list[2] = new NameValuePair("fileSize", String.valueOf(size));
// 上传且返回path
fileIds = storageClient.upload_file(pic, extName, meta_list);
return fileIds[0] + "/" + fileIds[1];
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean deletePic(String fileUrl) {
try {
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
StorePath storePath = StorePath.praseFromUrl(fileUrl);
int i = storageClient.delete_file(storePath.getGroup(), storePath.getPath());
System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
return i == 0;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static String deletePic(String[] fileIds) {
try {
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
int i = storageClient.delete_file(fileIds[0], fileIds[1]);
System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
} catch (Exception e) {
e.printStackTrace();
}
return fileIds[1];
}
private static class UploadFileSender implements UploadCallback {
private InputStream inStream;
public UploadFileSender(InputStream inStream) {
this.inStream = inStream;
}
@Override
public int send(OutputStream out) throws IOException {
int readBytes;
while ((readBytes = inStream.read()) > 0) {
out.write(readBytes);
}
return 0;
}
}
public static String conventAndUploadWord(InputStream inputStream, String filename) {
File outputFile = new File(filename + ".pdf");
String filePath = "";
try {
Document document = new Document(inputStream);
document.save(outputFile.getAbsolutePath(), com.aspose.words.SaveFormat.PDF);
FileReader fileReader = new FileReader(outputFile.getAbsolutePath());
filePath = uploadPic(fileReader.readBytes(), outputFile.getName(), outputFile.length());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
//删除创建的输出文件
FileUtil.del(outputFile);
return filePath;
}
}
public static String conventAndUploadExcel(InputStream inputStream, String filename) {
// 验证License
getLicense();
File outputFile = new File(filename + ".pdf");
String filePath = "";
try {
Workbook document = new Workbook(inputStream);
//pdf路径
//操作文档保存
document.save(outputFile.getAbsolutePath(), SaveFormat.PDF);
FileReader fileReader = new FileReader(outputFile.getAbsolutePath());
filePath = uploadPic(fileReader.readBytes(), outputFile.getName(), outputFile.length());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
//删除创建的输出文件
FileUtil.del(outputFile);
return filePath;
}
}
public static void getLicense() {
try {
InputStream is = FastDFSUtils.class.getClassLoader().getResourceAsStream("\\license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
} catch (Exception e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.dfs;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class FileTypeUtil {
private final static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();
private final static List<String> imageAllowFiles = Arrays
.asList(new String[]{"png", "jpg", "jpeg", "gif", "bmp"});/* 允许上传的图片格式 */
static {
getAllFileType(); // 初始化文件类型信息
}
/**
* <p>
* Discription:[getAllFileType,常见文件头信息] 注:TXT文件没有文件头
* </p>
*/
private static void getAllFileType() {
FILE_TYPE_MAP.put("jpg", "FFD8FF"); // JPEG (jpg)
FILE_TYPE_MAP.put("png", "89504E47"); // PNG (png)
FILE_TYPE_MAP.put("gif", "47494638"); // GIF (gif)
FILE_TYPE_MAP.put("tif", "49492A00"); // TIFF (tif)
FILE_TYPE_MAP.put("bmp", "424D"); // Windows Bitmap (bmp)
FILE_TYPE_MAP.put("dwg", "41433130"); // CAD (dwg)
FILE_TYPE_MAP.put("html", "68746D6C3E"); // HTML (html)
FILE_TYPE_MAP.put("rtf", "7B5C727466"); // Rich Text Format (rtf)
FILE_TYPE_MAP.put("xml", "3C3F786D6C");
FILE_TYPE_MAP.put("zip", "504B0304");
FILE_TYPE_MAP.put("rar", "52617221");
FILE_TYPE_MAP.put("psd", "38425053"); // Photoshop (psd)
FILE_TYPE_MAP.put("eml", "44656C69766572792D646174653A"); // Email
// [thorough
// only]
// (eml)
FILE_TYPE_MAP.put("dbx", "CFAD12FEC5FD746F"); // Outlook Express (dbx)
FILE_TYPE_MAP.put("pst", "2142444E"); // Outlook (pst)
FILE_TYPE_MAP.put("xls", "D0CF11E0"); // MS Word
FILE_TYPE_MAP.put("doc", "D0CF11E0"); // MS Excel 注意:word 和 excel的文件头一样
FILE_TYPE_MAP.put("mdb", "5374616E64617264204A"); // MS Access (mdb)
FILE_TYPE_MAP.put("wpd", "FF575043"); // WordPerfect (wpd)
FILE_TYPE_MAP.put("eps", "252150532D41646F6265");
FILE_TYPE_MAP.put("ps", "252150532D41646F6265");
FILE_TYPE_MAP.put("pdf", "255044462D312E"); // Adobe Acrobat (pdf)
FILE_TYPE_MAP.put("qdf", "AC9EBD8F"); // Quicken (qdf)
FILE_TYPE_MAP.put("pwl", "E3828596"); // Windows Password (pwl)
FILE_TYPE_MAP.put("wav", "57415645"); // Wave (wav)
FILE_TYPE_MAP.put("avi", "41564920");
FILE_TYPE_MAP.put("ram", "2E7261FD"); // Real Audio (ram)
FILE_TYPE_MAP.put("rm", "2E524D46"); // Real Media (rm)
FILE_TYPE_MAP.put("mpg", "000001BA"); //
FILE_TYPE_MAP.put("mov", "6D6F6F76"); // Quicktime (mov)
FILE_TYPE_MAP.put("asf", "3026B2758E66CF11"); // Windows Media (asf)
FILE_TYPE_MAP.put("mid", "4D546864"); // MIDI (mid)
}
/**
* <p>
* Discription:[getFileTypeByStream]
* </p>
*/
public final static String getFileTypeByStream(byte[] b) {
String filetypeHex = String.valueOf(getFileHexString(b));
Iterator<Entry<String, String>> entryiterator = FILE_TYPE_MAP.entrySet().iterator();
while (entryiterator.hasNext()) {
Entry<String, String> entry = entryiterator.next();
String fileTypeHexValue = entry.getValue();
if (filetypeHex.toUpperCase().startsWith(fileTypeHexValue)) {
return entry.getKey();
}
}
return null;
}
/**
* <p>
* Discription:[getFileByFile,获取文件类型,包括图片,若格式不是已配置的,则返回null]
* </p>
*/
public final static String getFileTypeByFile(File file) {
String fileType = null;
byte[] b = new byte[50];
try {
InputStream is = new FileInputStream(file);
is.read(b);
fileType = getFileTypeByStream(b);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileType;
}
/**
* <p>
* Discription:[getFileHexString]
* </p>
*/
public final static String getFileHexString(byte[] b) {
StringBuilder stringBuilder = new StringBuilder();
if (b == null || b.length <= 0) {
return null;
}
for (int i = 0; i < b.length; i++) {
int v = b[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* <p>
* Discription:[getImageFileType,获取图片文件实际类型,若不是图片则返回null]
* </p>
*/
public final static String getImageFileType(File f) {
if (isImage(f)) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(f);
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = iter.next();
iis.close();
return reader.getFormatName();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return null;
}
/**
* 只根据后缀名判断是否为图片
*
* @param file
* @return
*/
public static final boolean isImage(File file) {
return isImage(file, true);
}
/**
* <p>
* Discription:[isImage,判断文件是否为图片]
* </p>
*
* @param file 源文件
* @param onlyByExtension 是否值验证后缀名
* @return true 是 | false 否
*/
public static final boolean isImage(File file, boolean onlyByExtension) {
boolean flag = false;
try {
boolean allowFile = isImageByExtension(file.getName());
if (onlyByExtension) {
flag = allowFile;
} else {
if (allowFile) {
BufferedImage bufreader = ImageIO.read(file);
int width = bufreader.getWidth();
int height = bufreader.getHeight();
if (width == 0 || height == 0) {
flag = false;
} else {
flag = true;
}
}
}
} catch (IOException e) {
flag = false;
e.printStackTrace();
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
return flag;
}
/**
* 只通过后缀名判断是否为图片
*
* @param fileName
* @return
*/
public static final boolean isImageByExtension(String fileName) {
boolean flag = false;
String fileExtName = FilenameUtils.getExtension(fileName);
if (StringUtils.isNotBlank(fileExtName)) {
flag = imageAllowFiles.contains(fileExtName.toLowerCase());
}
return flag;
}
}
package cn.wise.sc.cement.business.util.dfs;
import cn.wise.sc.cement.business.exception.FdfsUnsupportStorePathException;
import org.apache.commons.lang3.Validate;
/**
* 存储文件的路径信息
*
* @author yuqih
*/
public class StorePath {
private String group;
private String path;
/**
* 解析路径
*/
private static final String SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR = "/";
/**
* group
*/
private static final String SPLIT_GROUP_NAME = "group";
/**
* 存储文件路径
*/
public StorePath() {
}
/**
* 存储文件路径
*
* @param group
* @param path
*/
public StorePath(String group, String path) {
super();
this.group = group;
this.path = path;
}
/**
* @return the group
*/
public String getGroup() {
return group;
}
/**
* @param group the group to set
*/
public void setGroup(String group) {
this.group = group;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* 获取文件全路径
*
* @return
*/
public String getFullPath() {
return this.group.concat(SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR).concat(this.path);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "StorePath [group=" + group + ", path=" + path + "]";
}
/**
* 从Url当中解析存储路径对象
*
* @param filePath 有效的路径样式为(group/path) 或者 (http://ip/group/path),路径地址必须包含group
* @return
*/
public static StorePath praseFromUrl(String filePath) {
Validate.notNull(filePath, "解析文件路径不能为空");
// 获取group起始位置
int groupStartPos = getGroupStartPos(filePath);
String groupAndPath = filePath.substring(groupStartPos);
int pos = groupAndPath.indexOf(SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR);
if ((pos <= 0) || (pos == groupAndPath.length() - 1)) {
throw new FdfsUnsupportStorePathException("解析文件路径错误,有效的路径样式为(group/path) 而当前解析路径为".concat(filePath));
}
String group = groupAndPath.substring(0, pos);
String path = groupAndPath.substring(pos + 1);
return new StorePath(group, path);
}
/**
* 获得group起始位置
*
* @param filePath
*/
private static int getGroupStartPos(String filePath) {
int pos = filePath.indexOf(SPLIT_GROUP_NAME);
if ((pos == -1)) {
throw new FdfsUnsupportStorePathException("解析文件路径错误,被解析路径url没有group,当前解析路径为".concat(filePath));
}
return pos;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin;
/**
* @desc : 微信通用接口凭证
*
* @author: shirayner
* @date : 2017-8-20 下午9:35:11
*/
public class AccessToken {
// 获取到的凭证
private String token;
// 凭证有效时间,单位:秒
private int expiresIn;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin;
import org.springframework.beans.factory.annotation.Value;
/**
* 功能说明:企业微信全局接口地址
* 修改说明:
* @author zhenglibing
* @date 2018年1月8日 下午2:27:43
* @version 0.1
*/
public interface Global {
//企业ID
public final static String corpId = "ww348f91b2573c1867";
//企业应用的id,整型。可在应用的设置页面查看
public final static int agentId = 1000002;
public final static int agentIdPC = 1000003;
//应用的凭证密钥
public final static String agentSecret = "gFa_7XvXtCaoeAYERzjRwwz_OTJkJfgBb8weOKjmI3o";
public final static String agentSecretPC = "itCLYcwl9ggA9VfZam_iz96Ikp9StDFfVr4Adb0yY7A";
//编译后的回调地址
public final static String backUrl = "https%3a%2f%2fccdcmtl.sinoma-tianjin.com%2flab-system";
//实验室管理系统链接
public final static String systemUrl =
"<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+corpId+"&redirect_uri="+backUrl+"%2f&response_type=code&scope=snsapi_base&state=#wechat_redirect\">物化检测流程" + "</a>,";
public final static String systemUrlTmp =
"<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww348f91b2573c1867&redirect_uri=https%3a%2f%2fccdcmtl.sinoma-tianjin.com%2flab-system%2f&response_type=code&scope=snsapi_base&state=#wechat_redirect\">物化检测流程" + "</a>,";
/**
* 微信公众平台,获取AccessToken的接口地址,Https请求方式:GET
* 接口地址示例:https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=id&corpsecret=secrect
*/
public static final String ACCESSTOKENURL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
/**
* 微信公众平台,获取访问用户身份的接口地址,Https请求方式:GET
* 接口地址示例:https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE
*/
public static final String USERINFOURL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
/**
* 微信公众平台,获取访问用户信息的接口地址,Https请求方式:GET
* 接口地址示例:https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID
*/
public static final String USERURL = "https://qyapi.weixin.qq.com/cgi-bin/user/get";
public static final String ticket = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket";
/**
* 微信公众平台,发送应用消息的接口地址,Https请求方式:GET
* 接口地址示例:https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN
*/
public static final String SENDMESSAGE = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
public static final String userTicket = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get";
}
package cn.wise.sc.cement.business.util.weixin;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* 证书信任管理器(用于https请求)
*
* @author liufeng
* @date 2013-08-08
*/
public class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class WeiXinUtil {
private static Logger log = LoggerFactory.getLogger(WeiXinUtil.class);
//微信的请求url
//获取access_token的接口地址(GET) 限200(次/天)
public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpsecret}";
//获取jsapi_ticket的接口地址(GET) 限200(次/天)
public final static String jsapi_ticket_url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=ACCESSTOKEN";
@Value("${weixin.corpId}")
private String corpId;
@Value("${weixin.agentId}")
private int agentId;
@Value("${weixin.agentSecret}")
private String agentSecret;
/**
* 1.发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
// jsonObject = JSONObject.fromObject(buffer.toString());
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:{}", e);
}
return jsonObject;
}
/**
* 2.发送https请求之获取临时素材
* @param requestUrl
* @param savePath 文件的保存路径,此时还缺一个扩展名
* @return
* @throws Exception
*/
public static File getFile(String requestUrl,String savePath) throws Exception {
//String path=System.getProperty("user.dir")+"/img//1.png";
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
//获取文件扩展名
String ext=getExt(httpUrlConn.getContentType());
savePath=savePath+ext;
System.out.println("savePath"+savePath);
//下载文件到f文件
File file = new File(savePath);
// 获取微信返回的输入流
InputStream in = httpUrlConn.getInputStream();
//输出流,将微信返回的输入流内容写到文件中
FileOutputStream out = new FileOutputStream(file);
int length=100*1024;
byte[] byteBuffer = new byte[length]; //存储文件内容
int byteread =0;
int bytesum=0;
while (( byteread=in.read(byteBuffer)) != -1) {
bytesum += byteread; //字节数 文件大小
out.write(byteBuffer,0,byteread);
}
System.out.println("bytesum: "+bytesum);
in.close();
// 释放资源
out.close();
in = null;
out=null;
httpUrlConn.disconnect();
return file;
}
/**
* @desc :2.微信上传素材的请求方法
*
* @param requestUrl 微信上传临时素材的接口url
* @param file 要上传的文件
* @return String 上传成功后,微信服务器返回的消息
*/
public static String httpRequest(String requestUrl, File file) {
StringBuffer buffer = new StringBuffer();
try{
//1.建立连接
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); //打开链接
//1.1输入输出设置
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
httpUrlConn.setUseCaches(false); // post方式不能使用缓存
//1.2设置请求头信息
httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
//1.3设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
httpUrlConn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ BOUNDARY);
// 请求正文信息
// 第一部分:
//2.将文件头输出到微信服务器
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
+ "\";filename=\""+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
// 将表头写入输出流中:输出表头
outputStream.write(head);
//3.将文件正文部分输出到微信服务器
// 把文件以流文件的方式 写入到微信服务器中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
outputStream.write(bufferOut, 0, bytes);
}
in.close();
//4.将结尾部分输出到微信服务器
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
outputStream.write(foot);
outputStream.flush();
outputStream.close();
//5.将微信服务器返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
return buffer.toString();
}
/**
* 2.发起http请求获取返回结果
*
* @param requestUrl 请求地址
* @return
*/
public static String httpRequest(String requestUrl) {
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(false);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
//InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
} catch (Exception e) {
}
return buffer.toString();
}
/**
* 3.获取access_token
*
* @param appid 凭证
* @param appsecret 密钥
* @return
*/
public static AccessToken getAccessToken(String appid, String appsecret) {
AccessToken accessToken = null;
String requestUrl = access_token_url.replace("{corpId}", appid).replace("{corpsecret}", appsecret);
JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
// 如果请求成功
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
} catch (JSONException e) {
accessToken = null;
// 获取token失败
log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
}
}
return accessToken;
}
/**
* 4. 获取JsapiTicket
* @param accessToken
* @return
*/
public static String getJsapiTicket(String accessToken){
String requestUrl = jsapi_ticket_url.replace("ACCESSTOKEN", accessToken);
JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
String jsapi_ticket="";
// 如果请求成功
if (null != jsonObject) {
try {
jsapi_ticket=jsonObject.getString("ticket");
} catch (JSONException e) {
// 获取token失败
log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
}
}
return jsapi_ticket;
}
/**
* 3.获取企业微信的JSSDK配置信息
* @param request
* @return
*/
public static Map<String, Object> getWxConfig(HttpServletRequest request) {
Map<String, Object> ret = new HashMap<String, Object>();
//1.准备好参与签名的字段
String nonceStr = UUID.randomUUID().toString(); // 必填,生成签名的随机串
//System.out.println("nonceStr:"+nonceStr);
String accessToken=WeiXinUtil.getAccessToken(Global.corpId, Global.agentSecret).getToken();
String jsapi_ticket =getJsapiTicket(accessToken);// 必填,生成签名的H5应用调用企业微信JS接口的临时票据
//System.out.println("jsapi_ticket:"+jsapi_ticket);
String timestamp = Long.toString(System.currentTimeMillis() / 1000); // 必填,生成签名的时间戳
//System.out.println("timestamp:"+timestamp);
String url=request.getRequestURL().toString();
//System.out.println("url:"+url);
//2.字典序 ,注意这里参数名必须全部小写,且必须有序
String sign = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr+ "&timestamp=" + timestamp + "&url=" + url;
//3.sha1签名
String signature = "";
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(sign.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
//System.out.println("signature:"+signature);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ret.put("appId", Global.corpId);
ret.put("timestamp", timestamp);
ret.put("nonceStr", nonceStr);
ret.put("signature", signature);
return ret;
}
/**
* 方法名:byteToHex</br>
* 详述:字符串加密辅助方法 </br>
* 开发人员:souvc </br>
* 创建时间:2016-1-5 </br>
* @param hash
* @return 说明返回值含义
* @throws
*
*/
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
private static String getExt(String contentType){
if("image/jpeg".equals(contentType)){
return ".jpg";
}else if("image/png".equals(contentType)){
return ".png";
}else if("image/gif".equals(contentType)){
return ".gif";
}
return null;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.util.*;
/**
* 对外开放接口 工具类
*/
public class WeixinInterfaceUtil {
public static void main(String[] args){
String param = "corpid=%s&corpsecret=%s";
param = String.format(param, "ww348f91b2573c1867", "gFa_7XvXtCaoeAYERzjRwwz_OTJkJfgBb8weOKjmI3o");
try {
JSONObject jsonObject = WeixinInterfaceUtil.doGet(Global.ACCESSTOKENURL, param);
String accessToken = jsonObject.getString("access_token");
System.out.println("accessToken" + accessToken);
} catch (Exception e) {
e.printStackTrace();
}
}
public static JSONObject doGet(String url, String param) {
String path= url+"?"+ param;
RestTemplate restTemplate = new RestTemplate();
JSONObject resultMap = restTemplate.getForObject(path,JSONObject.class);
return resultMap;
}
}
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 文章
* @author shirayner
*
*/
public class Article {
//是 标题,不超过128个字节,超过会自动截断
private String title;
//否 描述,不超过512个字节,超过会自动截断
private String description;
//是 点击后跳转的链接。
private String url;
//否 图文消息的图片链接,支持JPG、PNG格式,较好的效果为大图640320,小图8080。
private String picurl;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPicurl() {
return picurl;
}
public void setPicurl(String picurl) {
this.picurl = picurl;
}
}
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 消息基类(企业号 -> 普通用户)
* @author shirayner
*
*/
public class BaseMessage {
// 否 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向该企业应用的全部成员发送
private String touser;
// 否 部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
private String toparty;
// 否 标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
private String totag;
// 是 消息类型
private String msgtype;
// 是 企业应用的id,整型。可在应用的设置页面查看
private int agentid;
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getToparty() {
return toparty;
}
public void setToparty(String toparty) {
this.toparty = toparty;
}
public String getTotag() {
return totag;
}
public void setTotag(String totag) {
this.totag = totag;
}
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public int getAgentid() {
return agentid;
}
public void setAgentid(int agentid) {
this.agentid = agentid;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 文件消息
* @author shirayner
*
*/
public class FileMessage extends BaseMessage {
//文件
private Media file ;
//否 表示是否是保密消息,0表示否,1表示是,默认0
private int safe;
public Media getFile() {
return file;
}
public void setFile(Media file) {
this.file = file;
}
public int getSafe() {
return safe;
}
public void setSafe(int safe) {
this.safe = safe;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 图片消息
* @author shirayner
*
*/
public class ImgMessage extends BaseMessage {
//图片
private Media image ;
//否 表示是否是保密消息,0表示否,1表示是,默认0
private int safe;
public Media getImage() {
return image;
}
public void setImage(Media image) {
this.image = image;
}
public int getSafe() {
return safe;
}
public void setSafe(int safe) {
this.safe = safe;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 图片、语音、文件
* @author shirayner
*
*/
public class Media {
//是 图片/语音/文件 媒体文件id,可以调用上传临时素材接口获取
private String media_id;
public String getMedia_id() {
return media_id;
}
public void setMedia_id(String media_id) {
this.media_id = media_id;
}
}
package cn.wise.sc.cement.business.util.weixin.message.send;
import java.util.List;
/**
* 图文
* @author shirayner
*
*/
public class News {
//文章列表
private List<Article> articles;
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
}
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 图文消息
* @author shirayner
*
*/
public class NewsMessage extends BaseMessage {
//图文
private News news;
public News getNews() {
return news;
}
public void setNews(News news) {
this.news = news;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 文本
* @author shirayner
*
*/
public class Text {
//是 消息内容,最长不超过2048个字节
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 文本消息
* @author shirayner
*
*/
public class TextMessage extends BaseMessage {
//文本
private Text text;
//否 表示是否是保密消息,0表示否,1表示是,默认0
private int safe;
public Text getText() {
return text;
}
public void setText(Text text) {
this.text = text;
}
public int getSafe() {
return safe;
}
public void setSafe(int safe) {
this.safe = safe;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 文本卡片
* @author shirayner
*
*/
public class Textcard {
//是 标题,不超过128个字节,超过会自动截断
private String title;
//是 描述,不超过512个字节,超过会自动截断
private String description;
//是 点击后跳转的链接。
private String url;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 文本卡片消息
* @author shirayner
*
*/
public class TextcardMessage extends BaseMessage {
//文本
private Textcard textcard;
//btntxt 否 按钮文字。 默认为“详情”, 不超过4个文字,超过自动截断。
public Textcard getTextcard() {
return textcard;
}
public void setTextcard(Textcard textcard) {
this.textcard = textcard;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 视频
* @author shirayner
*
*/
public class Video {
//是 视频媒体文件id,可以调用上传临时素材接口获取
private String media_id;
//否 视频消息的标题,不超过128个字节,超过会自动截断
private String title;
//否 视频消息的描述,不超过512个字节,超过会自动截断
private String description;
public String getMedia_id() {
return media_id;
}
public void setMedia_id(String media_id) {
this.media_id = media_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 视频消息
* @author shirayner
*
*/
public class VideoMessage extends BaseMessage {
//视频
private Video video ;
//否 表示是否是保密消息,0表示否,1表示是,默认0
private int safe;
public Video getVideo() {
return video;
}
public void setVideo(Video video) {
this.video = video;
}
public int getSafe() {
return safe;
}
public void setSafe(int safe) {
this.safe = safe;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.util.weixin.message.send;
/**
* 语音消息
* @author shirayner
*
*/
public class VoiceMessage extends BaseMessage {
//语音
private Media voice ;
//否 表示是否是保密消息,0表示否,1表示是,默认0
private int safe;
public Media getVoice() {
return voice;
}
public void setVoice(Media voice) {
this.voice = voice;
}
public int getSafe() {
return safe;
}
public void setSafe(int safe) {
this.safe = safe;
}
}
\ No newline at end of file
package cn.wise.sc.cement.business.wrapper;
import cn.wise.sc.cement.business.wrapper.page.PageUtil;
/**
* The class Page wrap mapper.
*
* @author paascloud.net@gmail.com
*/
public class PageWrapMapper {
/**
* Instantiates a new page wrap mapper.
*/
private PageWrapMapper() {
}
private static <E> PageWrapper<E> wrap(int code, String message, E o, PageUtil pageUtil) {
return new PageWrapper<E>(code, message, o, pageUtil);
}
/**
* Wrap data with default code=200.
*
* @param <E> the type parameter
* @param o the o
* @param pageUtil the page util
* @return the page wrapper
*/
public static <E> PageWrapper<E> wrap(E o, PageUtil pageUtil) {
return wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, o, pageUtil);
}
/**
* Wrap.
*
* @param <E> the type parameter
* @param code the code
* @param message the message
* @return the page wrapper
*/
public static <E> PageWrapper<E> wrap(int code, String message) {
return wrap(code, message, null, null);
}
/**
* Wrap.
*
* @param <E> the type parameter
* @param code the code
* @return the page wrapper
*/
public static <E> PageWrapper<E> wrap(int code) {
return wrap(code, null, null, null);
}
/**
* Wrap.
*
* @param <E> the type parameter
* @param e the e
* @return the page wrapper
*/
public static <E> PageWrapper<E> wrap(Exception e) {
return new PageWrapper<E>(Wrapper.ERROR_CODE, e.getMessage(), null, null);
}
/**
* Un wrapper.
*
* @param <E> the type parameter
* @param wrapper the wrapper
* @return the e
*/
public static <E> E unWrap(PageWrapper<E> wrapper) {
return wrapper.getData();
}
/**
* Wrap ERROR. code=100
*
* @param <E> the type parameter
* @return the page wrapper
*/
public static <E> PageWrapper<E> illegalArgument() {
return wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, Wrapper.ILLEGAL_ARGUMENT_MESSAGE, null, null);
}
/**
* Wrap ERROR. code=500
*
* @param <E> the type parameter
* @return the page wrapper
*/
public static <E> PageWrapper<E> error() {
return wrap(Wrapper.ERROR_CODE, Wrapper.ERROR_MESSAGE, null, null);
}
/**
* Wrap SUCCESS. code=200
*
* @param <E> the type parameter
* @return the page wrapper
*/
public static <E> PageWrapper<E> ok() {
return new PageWrapper<E>();
}
}
package cn.wise.sc.cement.business.wrapper;
import cn.wise.sc.cement.business.wrapper.page.PageUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* The class Page wrapper.
*
* @param <T> the type parameter @author paascloud.net@gmail.com
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class PageWrapper<T> extends Wrapper<T> {
private static final long serialVersionUID = 666985064788933395L;
private PageUtil pageUtil;
/**
* Instantiates a new Page wrapper.
*/
PageWrapper() {
super();
}
/**
* Instantiates a new Page wrapper.
*
* @param code the code
* @param message the message
*/
public PageWrapper(int code, String message) {
super(code, message);
}
/**
* Instantiates a new pageWrapper default code=200
*
* @param result the result
* @param pageUtil the page util
*/
public PageWrapper(T result, PageUtil pageUtil) {
super();
this.setData(result);
this.setPageUtil(pageUtil);
}
/**
* Instantiates a new Page wrapper.
*
* @param code the code
* @param message the message
* @param result the result
* @param pageUtil the page util
*/
PageWrapper(int code, String message, T result, PageUtil pageUtil) {
super(code, message, result);
this.pageUtil = pageUtil;
}
/**
* Sets the 分页数据 , 返回自身的引用.
*
* @param pageUtil the page util
* @return the page wrapper
*/
public PageWrapper<T> pageUtil(PageUtil pageUtil) {
this.setPageUtil(pageUtil);
return this;
}
/**
* Sets the 结果数据 , 返回自身的引用.
*
* @param result the result
* @return the page wrapper
*/
@Override
public PageWrapper<T> data(T result) {
super.setData(result);
return this;
}
}
package cn.wise.sc.cement.business.wrapper;
import org.apache.commons.lang3.StringUtils;
/**
* The class Wrap mapper.
*/
public class WrapMapper {
/**
* Instantiates a new wrap mapper.
*/
private WrapMapper() {
}
/**
* Wrap.
*
* @param <E> the element type
* @param code the code
* @param message the message
* @param o the o
* @return the wrapper
*/
public static <E> Wrapper<E> wrap(int code, String message, E o) {
return new Wrapper<>(code, message, o);
}
/**
* Wrap.
*
* @param <E> the element type
* @param code the code
* @param message the message
* @return the wrapper
*/
public static <E> Wrapper<E> wrap(int code, String message) {
return wrap(code, message, null);
}
/**
* Wrap.
*
* @param <E> the element type
* @param code the code
* @return the wrapper
*/
public static <E> Wrapper<E> wrap(int code) {
return wrap(code, null);
}
/**
* Wrap.
*
* @param <E> the element type
* @param e the e
* @return the wrapper
*/
public static <E> Wrapper<E> wrap(Exception e) {
return new Wrapper<>(Wrapper.ERROR_CODE, e.getMessage());
}
/**
* Un wrapper.
*
* @param <E> the element type
* @param wrapper the wrapper
* @return the e
*/
public static <E> E unWrap(Wrapper<E> wrapper) {
return wrapper.getData();
}
/**
* Wrap ERROR. code=100
*
* @param <E> the element type
* @return the wrapper
*/
public static <E> Wrapper<E> illegalArgument() {
return wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, Wrapper.ILLEGAL_ARGUMENT_MESSAGE);
}
/**
* Wrap ERROR. code=500
*
* @param <E> the element type
* @return the wrapper
*/
public static <E> Wrapper<E> error() {
return wrap(Wrapper.ERROR_CODE, Wrapper.ERROR_MESSAGE);
}
/**
* Error wrapper.
*
* @param <E> the type parameter
* @param message the message
* @return the wrapper
*/
public static <E> Wrapper<E> error(String message) {
return wrap(Wrapper.ERROR_CODE, StringUtils.isBlank(message) ? Wrapper.ERROR_MESSAGE : message);
}
/**
* Wrap SUCCESS. code=200
*
* @param <E> the element type
* @return the wrapper
*/
public static <E> Wrapper<E> ok() {
return new Wrapper<>();
}
/**
* Ok wrapper.
*
* @param <E> the type parameter
* @param o the o
* @return the wrapper
*/
public static <E> Wrapper<E> ok(E o) {
return new Wrapper<>(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, o);
}
}
package cn.wise.sc.cement.business.wrapper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import java.io.Serializable;
/**
* The class Wrapper.
*/
@Data
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Wrapper<T> implements Serializable {
/**
* 序列化标识
*/
/**
* 成功码.
*/
public static final int SUCCESS_CODE = 200;
/**
* 成功信息.
*/
public static final String SUCCESS_MESSAGE = "操作成功";
/**
* 错误码.
*/
public static final int ERROR_CODE = 500;
/**
* 错误信息.
*/
public static final String ERROR_MESSAGE = "内部异常";
/**
* 错误码:参数非法
*/
public static final int ILLEGAL_ARGUMENT_CODE_ = 100;
/**
* 错误信息:参数非法
*/
public static final String ILLEGAL_ARGUMENT_MESSAGE = "参数非法";
private static final long serialVersionUID = 3271183695751869867L;
/**
* 编号.
*/
private int code;
/**
* 信息.
*/
private String message;
/**
* 结果数据
*/
private T data;
/**
* Instantiates a new wrapper. default code=200
*/
Wrapper() {
this(SUCCESS_CODE, SUCCESS_MESSAGE);
}
/**
* Instantiates a new wrapper.
*
* @param code the code
* @param message the message
*/
Wrapper(int code, String message) {
this(code, message, null);
}
/**
* Instantiates a new wrapper.
*
* @param code the code
* @param message the message
* @param result the result
*/
Wrapper(int code, String message, T result) {
super();
this.code(code).message(message).data(result);
}
/**
* Sets the 编号 , 返回自身的引用.
*
* @param code the new 编号
* @return the wrapper
*/
private Wrapper<T> code(int code) {
this.setCode(code);
return this;
}
/**
* Sets the 信息 , 返回自身的引用.
*
* @param message the new 信息
* @return the wrapper
*/
private Wrapper<T> message(String message) {
this.setMessage(message);
return this;
}
/**
* Sets the 结果数据 , 返回自身的引用.
*
* @param data the new 结果数据
* @return the wrapper
*/
public Wrapper<T> data(T data) {
this.setData(data);
return this;
}
/**
* 判断是否成功: 依据 Wrapper.SUCCESS_CODE == this.code
*
* @return code =200,true;否则 false.
*/
@JsonIgnore
public boolean success() {
return Wrapper.SUCCESS_CODE == this.code;
}
/**
* 判断是否成功: 依据 Wrapper.SUCCESS_CODE != this.code
*
* @return code !=200,true;否则 false.
*/
@JsonIgnore
public boolean error() {
return !success();
}
}
package cn.wise.sc.cement.business.wrapper.page;
import lombok.Data;
/**
* 分页请求包装类
*/
@Data
public class PageUtil {
/**
* The cur page.当前页
*/
private int currentPage = 1;
/**
* The next page.下一页
*/
private int nextPage;
/**
* The pre page. 上一页
*/
private int prePage;
/**
* The total row. 总条数
*/
private int totalRow;
/**
* The page size.每页条数
*/
private int pageSize = 10;
/**
* The total page.总页数
*/
private int totalPage;
/**
* The start. 开始条数
*/
private int start;
/**
* The buttons.
*/
private int[] buttons;
/**
* 当前页条数
*/
private int curPageSize;
/**
* Instantiates a new page util.
*/
public PageUtil() {
}
/**
* Instantiates a new page util.
*
* @param currentPage the current page
*/
public PageUtil(int currentPage) {
this.currentPage = currentPage;
}
/**
* Instantiates a new page util.
*
* @param currentPage the current page
* @param pageSize the page size
*/
public PageUtil(int currentPage, int pageSize) {
this.currentPage = currentPage;
this.pageSize = pageSize;
}
}
package cn.wise.sc.cement.business.wrapper.page;
import lombok.Data;
import java.io.Serializable;
/**
*
*/
@Data
public class Query implements Serializable {
private static final long serialVersionUID = 8933019121780323520L;
/**
* 当前页
*/
private int pageNum = 1;
/**
* 每页的数量
*/
private int pageSize = 20;
}
server:
port: 7008
#-Dspring.config.location=D:\idea_workspases\tianjin-cement\cement-business\src\main\resources\application.yml
spring:
application: tianjin-cement
profiles:
active: dev
datasource:
# 192.168.110.85 data-acquisition
url: jdbc:mysql://192.168.110.85:3306/data-acquisition?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: admin!@#123
driverClassName: com.mysql.cj.jdbc.Driver
hikari:
minimum-idle: 3
maximum-pool-size: 10
max-lifetime: 30000 #不能小于30秒,否则默认回到1800秒
connection-test-query: SELECT 1
redis:
port: 6379
host: 192.168.110.85
# password: Wise_@123456
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
# 设置swagger用户名密码
swagger:
basic:
enable: false
username: admin
password: admin
mybatis-plus:
# 启动时是否检查MyBatis XML文件是否存在
check-config-location: true
type-aliases-package: cn.wise.sc.cement.business.entity.**
mapper-locations: classpath:/cn/wise/sc/cement/business/mapper/xml/*Mapper.xml
#-Dspring.config.location=D:\idea_workspases\tianjin-cement\cement-business\src\main\resources\application.yml
server:
port: 7008
spring:
application: tianjin-cement
profiles:
active: prod
datasource:
# 192.168.110.85 data-acquisition
url: jdbc:mysql://192.168.110.85:3306/data-acquisition?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: admin!@#123
driverClassName: com.mysql.cj.jdbc.Driver
hikari:
minimum-idle: 3
maximum-pool-size: 10
max-lifetime: 30000 #不能小于30秒,否则默认回到1800秒
connection-test-query: SELECT 1
redis:
port: 6379
host: localhost
# password: Wise_@123456
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
# 设置swagger用户名密码
swagger:
basic:
enable: false
username: admin
password: admin
mybatis-plus:
# 启动时是否检查MyBatis XML文件是否存在
check-config-location: true
type-aliases-package: cn.wise.sc.cement.business.entity.**
mapper-locations: classpath:/cn/wise/sc/cement/business/mapper/xml/*Mapper.xml
server:
port: 7012
spring:
application: bangye
profiles:
active: show
datasource:
# 192.168.110.85 data-acquisition
url: jdbc:mysql://192.168.110.85:3306/data-acquisition?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: admin!@#123
driverClassName: com.mysql.cj.jdbc.Driver
hikari:
minimum-idle: 3
maximum-pool-size: 10
max-lifetime: 30000 #不能小于30秒,否则默认回到1800秒
connection-test-query: SELECT 1
redis:
port: 6379
host: localhost
database: 1
# password: Wise_@123456
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
# 设置swagger用户名密码
swagger:
basic:
enable: false
username: admin
password: admin
mybatis-plus:
# 启动时是否检查MyBatis XML文件是否存在
check-config-location: true
type-aliases-package: cn.wise.sc.cement.business.entity.**
mapper-locations: classpath:/cn/wise/sc/cement/business/mapper/xml/*Mapper.xml
fastdfs.connect_timeout=2000
fastdfs.network_timeout=1501
fastdfs.charset=UTF-8
fastdfs.http.tracker_http_port=8888
fastdfs.http.anti_steal_token=no
fastdfs.http.secret_key=FastDFS1234567890
fastdfs.tracker_servers=localhost:22122
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文档如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文档是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。
当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="10 seconds">
<contextName>logback-spring</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义后,可以使“${}”来使用变量。 -->
<!-- <property name="logging.path" value="./../wise-came/logs"/>-->
<!--0. 日志格式和颜色渲染 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN"
value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!--1. 输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--2. 输出到文档-->
<!-- 2.1 level为 DEBUG 日志,时间滚动输出 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.path}/debug.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${logging.path}/debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 2.2 level为 INFO 日志,时间滚动输出 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.path}/info.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${logging.path}/info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 2.3 level为 WARN 日志,时间滚动输出 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.path}/warn.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logging.path}/warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 2.4 level为 ERROR 日志,时间滚动输出 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.path}/error.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logging.path}/error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
以及指定<appender>。<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
如果未设置此属性,那么当前logger将会继承上级的级别。
addtivity:是否向上级logger传递打印信息。默认是true。
<logger name="org.springframework.web" level="info"/>
<logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>
-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
【logging.level.org.mybatis=debug logging.level.dao=debug】
-->
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
不能设置为INHERITED或者同义词NULL。默认是DEBUG
可以包含零个或多个元素,标识这个appender将会添加到这个logger。
-->
<!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
<logger name="org.springframework" level="WARN"></logger>
<logger name="org.springframework.web.servlet.mvc.method.annotation" level="WARN"></logger>
<logger name="org.mybatis" level="WARN"></logger>
<logger name="com.zaxxer.hikari" level="ERROR"></logger>
<logger name="com.baomidou" level="WARN"></logger>
<logger name="io.netty" level="WARN"></logger>
<!--<logger name="org.apache.zookeeper" level="INFO"></logger>-->
<!-- 4. 最终的策略 -->
<!-- 4.1 开发环境:打印控制台-->
<springProfile name="dev">
<logger name="cn.wise.sc.cement.business.controller" level="debug"/><!-- 修改此处扫描包名 -->
<root level="debug">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="DEBUG_FILE"/>
<appender-ref ref="INFO_FILE"/>
<appender-ref ref="WARN_FILE"/>
<appender-ref ref="ERROR_FILE"/>
</root>
</springProfile>
<!--4.2 生产环境:输出到文档-->
<springProfile name="prod">
<logger name="cn.wise.sc.cement.business.controller" level="debug"/><!-- 修改此处扫描包名 -->
<root level="debug">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="DEBUG_FILE"/>
<appender-ref ref="INFO_FILE"/>
<appender-ref ref="ERROR_FILE"/>
<appender-ref ref="WARN_FILE"/>
</root>
</springProfile>
<!--4.3 演示环境:输出到文档-->
<springProfile name="show">
<logger name="cn.wise.sc.cement.business.controller" level="debug"/><!-- 修改此处扫描包名 -->
<root level="debug">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="DEBUG_FILE"/>
<appender-ref ref="INFO_FILE"/>
<appender-ref ref="ERROR_FILE"/>
<appender-ref ref="WARN_FILE"/>
</root>
</springProfile>
</configuration>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.wise.sc.acquisition</groupId>
<artifactId>acquisition-common</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>common-swagger</artifactId>
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.8.1</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package cn.wise.sc.cement.common.swagger;
/**
* @Auther: yangjing
* @Date: 2020/3/29 12:17
* @ClassName: PACKAGE_NAME
* @Description: TODO
*/
public class PackageInfo {
}
package cn.wise.sc.cement.common.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Auther: yangjing
* @Date: 2020/3/29 12:17
* @ClassName: PACKAGE_NAME
* @Description: TODO
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
@Bean
public Docket createRestApi() {// 创建API基本信息
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.wise.sc.consume"))// 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())//egex("/api/.*") 拦截的接口路径
.build();
}
private ApiInfo apiInfo() {// 创建API的基本信息,这些信息会在Swagger UI中进行显示
return new ApiInfoBuilder()
.title("swagger-api")// API 标题
.description("系统接口测试对接api")// API描述
.contact("杨**")// 联系人
// .license("Apache License Version 2.0")// 开源协议
.version("1.0")// 版本号
.build();
}
/**
* 重定向静态资源的路径,千万不要注释 不然 你们在访问api的时候会404的
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
// //下面是图片的虚拟路径配置
// registry.addResourceHandler(fileVirtualPath+"**").
// addResourceLocations("file:"+fileRealPath);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.wise.sc.acquisition</groupId>
<artifactId>data-acquisition</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>acquisition-common</artifactId>
<packaging>pom</packaging>
<modules>
<module>common-swagger</module>
</modules>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.wise.sc.acquisition</groupId>
<artifactId>data-acquisition</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis-generator</artifactId>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package cn.wise.sc.cement.mg;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.Scanner;
/**
* @author neo.shu
* @since 2020/3/28 15:31
* 使用方式:
* 1.配置数据源 line50-54
* 2.配置文件路径 line60
* 3.运行main方法
* 4.根据控制台打印的填写模块名和要生成的table名
*/
public class GeneratorApplication {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://192.168.110.85:3306/sinoma_tcdri?useUnicode=true&useSSL=false&characterEncoding=utf8");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("admin!@#123");
mpg.setDataSource(dsc);
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "\\cement-business\\src\\main\\java");
gc.setAuthor("ztw");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("cn.wise.sc.cement");
mpg.setPackageInfo(pc);
// 自定义配置
//InjectionConfig cfg = new InjectionConfig() {
// @Override
// public void initMap() {
// to do nothing
// }
// };
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
//List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
//focList.add(new FileOutConfig(templatePath) {
// @Override
// public String outputFile(TableInfo tableInfo) {
// // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
// return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
// + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
// }
//});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
//cfg.setFileOutConfigList(focList);
//mpg.setCfg(cfg);
// 配置模板
//TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
//templateConfig.setXml(null);
//mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
//mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.wise.sc.acquisition</groupId>
<artifactId>data-acquisition</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>acquisition-common</module>
<module>acquisition-business</module>
<module>mybatis-generator</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.artofsolving/jodconverter -->
<!-- <dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.2</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.8</version>
</dependency>
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1</version>
</dependency>
<!--日志-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.10.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment