This commit is contained in:
songjinsheng 2022-06-22 08:38:11 +08:00
commit c9abb90c97
232 changed files with 21660 additions and 0 deletions

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

240
pom.xml Normal file
View File

@ -0,0 +1,240 @@
<?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>com.xkrs.microservice</groupId>
<artifactId>shandong_hydrology_new</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>shandong_hydrology_new</name>
<description>山东省水文局项目_新</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.8</version>
<relativePath/>
</parent>
<properties>
<yauaa.version>6.6</yauaa.version>
<jjwt.version>0.11.2</jjwt.version>
<log4j-web.version>2.17.1</log4j-web.version>
<httpmime.version>4.5.13</httpmime.version>
<hibernate-validator.version>7.0.2.Final</hibernate-validator.version>
<hibernate-spatial.version>5.6.3.Final</hibernate-spatial.version>
<disruptor.version>3.4.4</disruptor.version>
<jsoup.version>1.14.3</jsoup.version>
<dysmsapi20170525.version>2.0.8</dysmsapi20170525.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>${log4j-web.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--排除logback依赖-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
<!--排除内置的tomcat-->
<!--<exclusions>-->
<!--<exclusion>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
<!--</exclusion>-->
<!--</exclusions>-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!--排除logback依赖-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<!--排除logback依赖-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<!--排除logback依赖-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<!--排除logback依赖-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<!--排除logback依赖-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<!--排除logback依赖-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId> mysql</groupId>
<artifactId> mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>nl.basjes.parse.useragent</groupId>
<artifactId>yauaa</artifactId>
<version>${yauaa.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpmime.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>${hibernate-spatial.version}</version>
</dependency>
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${disruptor.version}</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>${dysmsapi20170525.version}</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.txt</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
</project>

8
readme.md Normal file
View File

@ -0,0 +1,8 @@
# 简介
山东省水文局项目后端
## 提交说明
🐞 bug修复
⚡ 安全问题
🌟 功能增强
🎈 性能优化

View File

@ -0,0 +1,17 @@
package com.xkrs.microservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 微服务入口
* @author tajochen
*/
@SpringBootApplication(exclude = {org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class})
public class MicroserviceApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceApplication.class, args);
}
}

View File

@ -0,0 +1,36 @@
package com.xkrs.microservice.common.account;
/**
* 账户实体
* @author tajochen
*/
public class AccountCredentials {
private String userName;
private String password;
private boolean remember;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isRemember() {
return remember;
}
public void setRemember(boolean remember) {
this.remember = remember;
}
}

View File

@ -0,0 +1,109 @@
package com.xkrs.microservice.common.account;
import com.xkrs.microservice.model.entity.SysAuthorityEntity;
import com.xkrs.microservice.model.entity.SysUserEntity;
import com.xkrs.microservice.service.SysAuthorityService;
import com.xkrs.microservice.service.SysRoleService;
import com.xkrs.microservice.service.SysUserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import static com.xkrs.microservice.util.EncryptDecryptUtil.encrypt256;
/**
* 自定义认证Provider
* @author tajochen
*/
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Resource
private SysUserService sysUserService;
@Resource
private SysRoleService sysRoleService;
@Resource
private SysAuthorityService sysAuthorityService;
/**
* 初使化时将已静态化的Service实例化
*/
protected static CustomAuthenticationProvider customAuthenticationProvider;
/**
* 通过@PostConstruct实现初始化bean之前进行的操作
*/
@PostConstruct
public void init() {
customAuthenticationProvider = this;
customAuthenticationProvider.sysUserService = this.sysUserService;
customAuthenticationProvider.sysRoleService = this.sysRoleService;
customAuthenticationProvider.sysAuthorityService = this.sysAuthorityService;
}
/**
* 用户认证授权
* @param authentication 认证类
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// 获取认证的用户名 & 密码
String userName = authentication.getName();
String password = authentication.getCredentials().toString();
SysUserEntity userEntity = customAuthenticationProvider.sysUserService.getSysUserByUserName(userName);
// 检查用户是否存在
if(userEntity == null){
throw new BadCredentialsException("user don't exist");
}
// 检查用户是否激活
if(userEntity.getActiveFlag() != 0){
throw new DisabledException("user not activated");
}
//检查用户状态是否正常
if(userEntity.getStatusCode() != 0){
throw new DisabledException("user state exception");
}
// 认证逻辑
String encryptPassword = encrypt256(password + userEntity.getSalt());
if (encryptPassword.equals(userEntity.getPassword())) {
// 设置权限列表
ArrayList<GrantedAuthority> permissions = new ArrayList<>();
List<SysAuthorityEntity> permissionList = customAuthenticationProvider.sysAuthorityService.
getSysAuthorityListByUserName(userName);
for(SysAuthorityEntity sysAuthorityEntity : permissionList) {
permissions.add(new GrantedAuthorityImpl(sysAuthorityEntity.getAuthorityName()));
}
// 生成令牌
return new UsernamePasswordAuthenticationToken(userName, encryptPassword, permissions);
}
else {
throw new BadCredentialsException("user password error");
}
}
/**
* 是否可以提供输入类型的认证服务
* @param authentication 认证类
*/
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}

View File

@ -0,0 +1,25 @@
package com.xkrs.microservice.common.account;
import org.springframework.security.core.GrantedAuthority;
/**
* 权限认证服务
* @author tajochen
*/
public class GrantedAuthorityImpl implements GrantedAuthority {
private String authority;
public GrantedAuthorityImpl(String authority) {
this.authority = authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
@Override
public String getAuthority() {
return this.authority;
}
}

View File

@ -0,0 +1,28 @@
package com.xkrs.microservice.common.account;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 拦截所有需要JWT的请求然后调用TokenAuthenticationService类的静态方法去做JWT验证
* @author tajochen
*/
public class JwtAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest)request);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request,response);
}
}

View File

@ -0,0 +1,135 @@
package com.xkrs.microservice.common.account;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.service.SysUserService;
import com.xkrs.microservice.util.IpUtil;
import com.xkrs.microservice.common.encapsulation.OutputEncapsulation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Locale;
/**
* jwt登录过滤器
* @author tajochen
*/
public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger logger = LoggerFactory.getLogger(JwtLoginFilter.class);
@Resource
private SysUserService sysUserService;
public JwtLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
/**
* 登录时验证
* @param req 请求
* @param res 响应
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) {
try {
req.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
logger.error(String.valueOf(e));
}
res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader("Access-Control-Allow-Credentials", "false");
AccountCredentials cred = new AccountCredentials();
//获取表单数据
String userName = req.getParameter("userName");
String password = req.getParameter("password");
String rememberMe = req.getParameter("remember");
//如果用户名密码为空
if(userName == null||password == null|| userName.trim().isEmpty()||password.trim().isEmpty()){
throw new BadCredentialsException("user or password is null");
}
if(rememberMe == null||rememberMe.isEmpty()){
rememberMe = "false";
}
cred.setUserName(userName.trim());
cred.setPassword(password.trim());
cred.setRemember(Boolean.parseBoolean(rememberMe));
// 返回一个验证令牌
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
cred.getUserName(),
cred.getPassword()
)
);
}
/**
* 验证成功后调用
* @param req 请求
* @param response 响应
* @param chain 过滤器声明
* @param auth 认证
*/
@Override
protected void successfulAuthentication(
HttpServletRequest req, HttpServletResponse response, FilterChain chain, Authentication auth) {
if(sysUserService==null){
ServletContext servletContext = req.getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
assert webApplicationContext != null;
sysUserService = webApplicationContext.getBean(SysUserService.class);
}
//更新用户登录信息
sysUserService.updateSysUserLogin(auth.getName(), IpUtil.getIpAddr(req));
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "false");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
TokenAuthenticationService.addAuthentication(response, auth.getName(),auth.getAuthorities());
}
/**
* 验证失败后调用
* @param request 请求
* @param response 响应
* @param failed 失败
*/
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException failed) {
Locale locale = LocaleContextHolder.getLocale();
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "false");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// JWT 写入 body
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
logger.warn(String.valueOf(e));
}
assert out != null;
out.append(OutputEncapsulation.outputEncapsulationObject(PromptMessageEnum.DATA_WRONG, failed.getLocalizedMessage(), locale));
response.setStatus(HttpServletResponse.SC_OK);
}
}

View File

@ -0,0 +1,123 @@
package com.xkrs.microservice.common.account;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.common.encapsulation.OutputEncapsulation;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
/**
* token认证服务
* @author tajochen
*/
public class TokenAuthenticationService {
private static final Logger logger = LoggerFactory.getLogger(TokenAuthenticationService.class);
/**
* 过期时间6小时
*/
static public final long EXPIRATIONTIME = 21_600_000;
/**
* 加密密钥
*/
static public final String SECRET_KEY = "0Y9H364Q9Y908262F25LMXGIKIN5N858XM3674GWL2DD8X1DS4W6I722IRY8PS4XPNB6U303" +
"45HBVCUL94STG8C3Z53T7A09JJ100I56YE9894CI11PX9J71HIZ8L5Y2O504C4E2K8276425UA8734833F45K36878FXAG799QV9LXU" +
"JOI3XA2046UPG8TB2OT84R5T6ZB127N9ZPJ7AJMC41JVHB2WK2B6H8NL45LZNAZ666KHZH3QUT65UX6F8";
/**
* Token前缀
*/
static public final String TOKEN_PREFIX = "Bearer";
/**
* 存放Token的Header Key
*/
static final String HEADER_STRING = "Authorization";
static SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
/**
* JWT生成方法
* @param response 响应
* @param userName 用户名
* @param authorities 认证
*/
static void addAuthentication(HttpServletResponse response, String userName,
Collection<? extends GrantedAuthority > authorities) {
Locale locale = new Locale("zh", "CN");
StringBuffer auths = new StringBuffer();
String authsList = "";
for(GrantedAuthority r : authorities) {
auths.append(",").append(r.getAuthority());
}
authsList = auths.toString();
if(authsList.length()>1){
authsList=authsList.substring(1,authsList.length());
}else{
logger.warn(userName +" has no permission!");
}
// 生成JWT
String jwt = Jwts.builder()
.setSubject(userName)
.setIssuer("https://www.microservice.com")
.setAudience(userName)
// 保存权限
.claim("auths", authsList)
// 有效期设置
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
// 签名设置
.signWith(key)
.compact();
// JWT 写入 body
PrintWriter out = null;
response.setStatus(HttpServletResponse.SC_OK);
try {
out = response.getWriter();
out.append(OutputEncapsulation.outputEncapsulationObject(PromptMessageEnum.SUCCESS, jwt, locale));
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* JWT验证方法
* @param request 请求体
*/
static Authentication getAuthentication(HttpServletRequest request) {
// 从Header中拿到token
String token = request.getHeader(HEADER_STRING);
if (token != null) {
try {
// 解析 Token
Claims claims = Jwts.parserBuilder()
.setSigningKey(key).build()
// 去掉 Bearer
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody();
// 获取用户名
String userName = claims.getSubject();
// 获取权限
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("auths"));
return new UsernamePasswordAuthenticationToken(userName, null, authorities);
} catch(Exception e) {
// the sub field was missing or did not have a value
return null;
}
} else {
return null;
}
}
}

View File

@ -0,0 +1,36 @@
package com.xkrs.microservice.common.config;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
* spring 静态工具类里读取配置文件
* @author tajochen
*/
@Component
public class ConfigConstant {
@Resource
private Environment env;
@PostConstruct
public void readConfig() throws Exception {
String prefix = "my.";
Field[] fields = ConfigConstant.class.getFields();
for(Field field : fields ){
field.set(null, getProperty(prefix + field.getName()));
}
}
private String getProperty(String key) {
return new String(Objects.requireNonNull(env.getProperty(key)).getBytes(StandardCharsets.ISO_8859_1),
StandardCharsets.UTF_8);
}
}

View File

@ -0,0 +1,32 @@
package com.xkrs.microservice.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 跨域配置
* @author tajochen
*/
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许任何域名
corsConfiguration.addAllowedOrigin("*");
// 允许任何头
corsConfiguration.addAllowedHeader("*");
// 允许任何方法
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 注册
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}

View File

@ -0,0 +1,37 @@
package com.xkrs.microservice.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebMVC配置
* @author Tajochen
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/**
* 放行跨域请求
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*");
}
/**
* 定时任务线程池更改防止多个任务并行
*/
@Bean
public TaskScheduler taskScheduler() {
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5);
return scheduler;
}
}

View File

@ -0,0 +1,30 @@
package com.xkrs.microservice.common.config;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
* Redis 缓存自动配置
* @author tajochen
*/
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {
@Bean
public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}

View File

@ -0,0 +1,188 @@
package com.xkrs.microservice.common.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonGenerator;
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.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
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.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.Duration;
/**
* redis配置
* @author tajochen
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
@Resource
private LettuceConnectionFactory lettuceConnectionFactory;
private static final Duration TIME_TO_LIVE = Duration.ofSeconds(3600*6);
@Bean
@Override
public KeyGenerator keyGenerator() {
// 设置自动key的生成规则配置spring boot的注解进行方法级别的缓存
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(":");
sb.append(method.getName());
for (Object obj : params) {
sb.append(":").append(obj);
}
// logger.info("自动生成Redis Key -> [{}]", rsToUse);
return String.valueOf(sb);
};
}
@Bean
@Override
public CacheManager cacheManager() {
// 关键点spring cache的注解使用的序列化都从这来没有这个配置的话使用的jdk自己的序列化
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
//key序列化方式
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
//value序列化方式
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
.disableCachingNullValues()
.entryTtl(TIME_TO_LIVE);
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(lettuceConnectionFactory)
.cacheDefaults(config)
.transactionAware();
return builder.build();
}
/**
* RedisTemplate配置 在单独使用redisTemplate的时候 重新定义序列化方式
*/
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
// 设置序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 配置null值序列化成空字符串
om.getSerializerProvider().setNullValueSerializer(new JsonSerializer<>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
});
// 解决jackson无法反序列化LocalDateTime的问题,引入jsr310标准
JavaTimeModule javaTimeModule = new JavaTimeModule();
om.registerModule(javaTimeModule);
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 其他设置
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,
ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
RedisSerializer<?> stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
}
private RedisSerializer<Object> valueSerializer() {
// 设置序列化
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
Object.class);
ObjectMapper om = new ObjectMapper();
// 解决jackson无法反序列化LocalDateTime的问题,引入jsr310标准
JavaTimeModule javaTimeModule = new JavaTimeModule();
om.registerModule(javaTimeModule);
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 其他设置
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,
ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
return jackson2JsonRedisSerializer;
}
@Override
public CacheResolver cacheResolver() {
return null;
}
/**
* 设置数据存入 redis 的序列化方式,并开启事务
*
* @param redisTemplate
* @param factory
*/
private void initRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
//如果不配置Serializer那么存储的时候缺省使用String如果用User类型存储那么会提示错误User can't cast to String
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// 开启事务
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setConnectionFactory(factory);
}
/**
* 注入封装RedisTemplate 给RedisUtil提供操作类
* @param redisTemplate
* @return RedisUtil
*/
@Bean(name = "redisUtil")
public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
RedisUtil redisUtil = new RedisUtil();
redisUtil.setRedisTemplate(redisTemplate);
return redisUtil;
}
@Override
@Bean
public CacheErrorHandler errorHandler() {
// 异常处理当Redis发生异常时打印日志但是程序正常走
logger.info("初始化 -> [{}]", "Redis CacheErrorHandler");
return null;
}
}

View File

@ -0,0 +1,533 @@
package com.xkrs.microservice.common.config;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* redis工具类
* @author tajochen
*/
public class RedisUtil {
private RedisTemplate<String, Object> redisTemplate;
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 指定缓存失效时间
* @param key
* @param time 时间()
* @return
*/
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 不能为null
* @return 时间() 返回0 代表为永久有效
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key
* @return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String ... key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(String.valueOf(CollectionUtils.arrayToList(key)));
}
}
}
//============================String=============================
/**
* 普通缓存获取
* @param key
* @return
*/
public Object get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key
* @param value
* @return true成功 false失败
*/
public boolean set(String key,Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key
* @param value
* @param time 时间() time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key,Object value,long time){
try {
if(time>0){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
* @param key 不能为null
* @param item 不能为null
* @return
*/
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key
* @return 对应的多个键值
*/
public Map<Object,Object> hmget(String key){
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String,Object> map){
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
* @param key
* @param map 对应多个键值
* @param time 时间()
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String,Object> map, long time){
try {
redisTemplate.opsForHash().putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key
* @param item
* @param value
* @return true 成功 false失败
*/
public boolean hset(String key,String item,Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key
* @param item
* @param value
* @param time 时间() 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key,String item,Object value,long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
* @param key 不能为null
* @param item 可以使多个 不能为null
*/
public void hdel(String key, Object... item){
redisTemplate.opsForHash().delete(key,item);
}
/**
* 判断hash表中是否有该项的值
* @param key 不能为null
* @param item 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item){
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key
* @param item
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
* @param key
* @param item
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item,-by);
}
//============================set=============================
/**
* 根据key获取Set中的所有值
* @param key
* @return
*/
public Set<Object> sGet(String key){
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
* @param key
* @param value
* @return true 存在 false不存在
*/
public boolean sHasKey(String key,Object value){
try {
return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, value));
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
* @param key
* @param values 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object...values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
* @param key
* @param time 时间()
* @param values 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key,long time,Object...values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if(time>0)
{expire(key, time);}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
* @param key
* @return
*/
public long sGetSetSize(String key){
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
* @param key
* @param values 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object ...values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//===============================list=================================
/**
* 获取list缓存的内容
* @param key
* @param start 开始
* @param end 结束 0 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end){
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
* @param key
* @return
*/
public long lGetListSize(String key){
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
* @param key
* @param index 索引 index>=0时 0 表头1 第二个元素依次类推index<0时-1表尾-2倒数第二个元素依次类推
* @return
*/
public Object lGetIndex(String key,long index){
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @param time 时间()
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
{expire(key, time);}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @param time 时间()
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
* @param key
* @param index 索引
* @param value
* @return
*/
public boolean lUpdateIndex(String key, long index,Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
* @param key
* @param count 移除多少个
* @param value
* @return 移除的个数
*/
public long lRemove(String key,long count,Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}

View File

@ -0,0 +1,66 @@
package com.xkrs.microservice.common.config;
import com.xkrs.microservice.common.account.CustomAuthenticationProvider;
import com.xkrs.microservice.common.account.JwtAuthenticationFilter;
import com.xkrs.microservice.common.account.JwtLoginFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 设置 HTTP 验证规则
* @param http http隐私认证
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 关闭csrf验证
http.csrf().disable()
// 对请求进行认证
.authorizeRequests()
// 所有 / 的所有请求 都放行
.antMatchers("/").permitAll()
// 所有OPTIONS请求都放行
.antMatchers(HttpMethod.OPTIONS).permitAll()
// 所有 /user/add 用户注册 的POST请求 都放行
.antMatchers(HttpMethod.POST, "/api/user/add").permitAll()
// 所有 /user/check/duplicate 检查用户名是否重复 的POST请求 都放行
.antMatchers(HttpMethod.GET, "/api/user/check/duplicate").permitAll()
// 所有 /login 用户登录 的POST请求 都放行
.antMatchers(HttpMethod.POST, "/api/login").permitAll()
// 所有 app 农户用户注册 的POST请求 都放行
.antMatchers(HttpMethod.POST, "/api/typical-farmer/add").permitAll()
// 所有 水文站点数据 相关操作 都放行
.antMatchers(HttpMethod.GET, "/api/hydrological-station/get/all").permitAll()
.antMatchers(HttpMethod.GET, "/api/hydrological-station/get/time").permitAll()
.antMatchers(HttpMethod.POST, "/api/hydrological-station/add").permitAll()
// 所有 app 检查版本更新 的GET请求 都放行
.antMatchers(HttpMethod.GET, "/api/app-file/get/new-version").permitAll()
// 所有其它请求需要身份认证
.anyRequest().authenticated()
.and()
// 添加一个过滤器 所有访问 /login 的请求交给 JWTLoginFilter 来处理 这个类处理所有的JWT相关内容
.addFilterBefore(new JwtLoginFilter("/api/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
// 添加一个过滤器验证其他请求的Token是否合法
.addFilterBefore(new JwtAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
// 使用自定义身份验证组件
auth.authenticationProvider(new CustomAuthenticationProvider());
}
}

View File

@ -0,0 +1,59 @@
package com.xkrs.microservice.common.encapsulation;
import java.io.Serializable;
/**
* 输出信息对象
* @author tajochen
* @param <T>
*/
public class EncapsulationObject<T> implements Serializable {
/**
* 状态码
*/
int status;
/**
* 提示信息
*/
String msg;
/**
* 数据
*/
T data;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "EncapsulationObejct{" +
"status=" + status +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}

View File

@ -0,0 +1,94 @@
package com.xkrs.microservice.common.encapsulation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* 输出信息封装
* @author tajochen
*/
@Component
public class OutputEncapsulation {
private static final Logger logger = LoggerFactory.getLogger(OutputEncapsulation.class);
/**
* 读取多国语言文件
*/
public static MessageSource messageSource() {
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
// 使用properties对象加载输入流
try {
Properties properties = new Properties();
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
/**
* 封装输出数据
* @param promptMessageEnum 封装枚举
* @param obj 对象
* @param locale 本地语言
*/
public static String outputEncapsulationObject(PromptMessageEnum promptMessageEnum, Object obj, Locale locale) {
EncapsulationObject<Object> encapsulationObject = new EncapsulationObject<>();
encapsulationObject.setStatus(promptMessageEnum.getCode());
encapsulationObject.setMsg(messageSource().getMessage(promptMessageEnum.getText(),null,locale));
encapsulationObject.setData(obj);
ObjectMapper objectMapper = new ObjectMapper();
// 忽略无法转换的对象
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
// 忽略json字符串中不识别的属性
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 解决jackson无法反序列化LocalDateTime的问题,引入jsr310标准
JavaTimeModule javaTimeModule = new JavaTimeModule();
objectMapper.registerModule(javaTimeModule);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String strByEo = "";
try {
strByEo = objectMapper.writeValueAsString(encapsulationObject);
} catch (JsonProcessingException e) {
e.printStackTrace();
logger.warn(e.toString());
}
return strByEo;
}
/**
* 输出请求值检验错误信息
* @param fieldErrors 错误列表
* @param locale 本地语言
*/
public static String outputEncapsulationErrorList(List<FieldError> fieldErrors, Locale locale){
List<String> errorMsg = new ArrayList<>();
for (FieldError fieldError : fieldErrors) {
String errMessage = Objects.requireNonNull(fieldError.getDefaultMessage()).
subSequence(1,fieldError.getDefaultMessage().length()-1).toString();
errorMsg.add(messageSource().getMessage(errMessage,null,locale));
}
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,errorMsg,locale);
}
}

View File

@ -0,0 +1,64 @@
package com.xkrs.microservice.common.encapsulation;
/**
* 提示信息枚举
* @author tajochen
*/
public enum PromptMessageEnum{
// 执行成功
SUCCESS(0, "sys.message.success"),
// 用户权限错误或非法操作 1001-1999
USER_NOT_LOGGED(1001, "sys.message.user.not_logged_in"),
USER_LOGIN_ERROR(1002, "sys.message.user.login_error"),
USER_ACCOUNT_FORBIDDEN(1003, "sys.message.user.account_forbidden"),
USER_ACCOUNT_NOT_ACTIVATED(1004, "sys.message.user.account_not_activated"),
USER_HAS_OVERTIME(1005, "sys.message.user.overtime"),
USER_NO_PERMISSION(1006,"sys.message.user.no_permission"),
USER_ALREADY_LOGGED(1007, "sys.message.user.already_logged"),
USER_ALREADY_EXIST(1008, "sys.message.user.already_exist"),
// 请求参数错误或非法2001-2999
PARAM_NULL(2001, "sys.message.param.null"),
PARAM_ILLEGAL(2002, "sys.message.param.illegal"),
// 数据返回错误3001-3999
DATA_NONE(3001, "sys.message.data.none"),
DATA_WRONG(3002, "sys.message.data.wrong"),
DATA_REPEAT(3003, "sys.message.data.repeat"),
// 操作失败4001-4999
PROCESS_FAIL(4001,"sys.message.process.fail"),
PROCESS_OVERTIME(4002,"sys.message.process.overtime"),
FILE_EXISTS(4003,"sys.message.file.exists"),
FILE_WRITE_ERROR(4004,"sys.message.file.write.error"),
FILE_READ_ERROR(4005,"sys.message.file.read.error"),
// 系统内部错误或异常5001-5999
SYSTEM_INNER_ERROR(5001,"sys.message.system.inner_error"),
SYSTEM_ABNORMAL(5002,"sys.message.system.abnormal"),
SYSTEM_BUSY(5003,"sys.message.system.busy"),
SYSTEM_MAINTAIN(5004,"sys.message.system.maintain"),
// 数据库错误6001-6999
DATABASE_ERROR(6001,"sys.message.database.error");
private int code;
private String text;
PromptMessageEnum(int code,String text) {
this.code = code;
this.text = text;
}
public String getText() {
return this.text;
}
public int getCode() {
return this.code;
}
}

View File

@ -0,0 +1,59 @@
package com.xkrs.microservice.common.schedule;
import com.xkrs.microservice.common.tool.JackSonTool;
import com.xkrs.microservice.common.tool.WeatherGet;
import com.xkrs.microservice.model.vo.MonitoringStationReturnVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import javax.annotation.Resource;
import java.time.*;
import java.util.*;
import static com.xkrs.microservice.util.RequestUtil.getStandard;
/**
* 定时任务
* @author tajochen
*/
@Configuration
@EnableScheduling
public class SaticScheduleTask {
Logger logger = LoggerFactory.getLogger(SaticScheduleTask.class);
@Resource
private WeatherGet weatherGet;
// /**
// * 定时获取数据每天9:31 触发
// */
// @Scheduled(cron = "00 31 9 ? * *")
// private void dailyReportFireLastTasks() {
// LocalDate pdfStartDate = LocalDate.of(2021, 5, 20);
// String url = "http://47.105.215.208:8005/intfa/queryData/16079680";
// Map<String,String> postParam = new HashMap<>(8);
//
// }
/**
* 定时获取气象站数据 5 分钟触发
*/
@Scheduled(cron = "0 0/5 * * * ?")
private void configureTasks() {
logger.info("执行静态定时任务时间: " + LocalDateTime.now());
weatherGet.findWeather();
}
public static void main(String[] args) {
String url = "http://47.105.215.208:8005/intfa/queryData/16079680";
Map<String,String> postParam = new HashMap<>(8);
String res = getStandard(url, postParam);
MonitoringStationReturnVo de = JackSonTool.decode(res, MonitoringStationReturnVo.class);
System.out.println(res);
}
}

View File

@ -0,0 +1,246 @@
package com.xkrs.microservice.common.tool;
import com.xkrs.microservice.model.vo.ForecastWeather7DayVo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import static com.xkrs.microservice.util.DateTimeUtil.dateToStringNoLine;
/**
* 爬取静态页面 新版中国天气网7天
* @author wd
*/
public class CrawlingWeather7Day {
private static final Logger log = LoggerFactory.getLogger(CrawlingWeather7Day.class);
/**
* 获取7天的天气预报和昨天的历史数据
* {d0:昨天 d7:第七天}
* @param cityCode 城市编码
* @param stationId 气象站点id
*/
public static ForecastWeather7DayVo getReptileWeather7Day(String cityCode, String stationId) {
// 城市
String city = null;
// 天气
String[] weather = new String[8];
// 风向
String[] wd = new String[8];
// 风力
String[] ws = new String[8];
// 最高温数组
String[] tempMax = new String[8];
// 最低温数组
String[] tempMin = new String[8];
// 天气数组
Map<String, String> weatherMap = new HashMap<>(8);
// 昨天天气
Map<String, String> weatherYesterMap = new HashMap<>(8);
// 7天预报和昨天数据
Map<String, Map<String, String>> weatherMap7Day = new HashMap<>(8);
// 爬取成功标志
boolean isSuccess = false;
// 重复次数
int retryTimes = 5;
// 时间
LocalDate localDate = LocalDate.now();
// 降水数据
Map<String, String> rainForecast =getRainForecast(stationId);
String url = "http://www.weather.com.cn/weathern/" + cityCode + ".shtml";
while (!isSuccess && retryTimes > 0) {
try {
// 获得连接
Document doc = Jsoup.connect(url).timeout(10000).get();
// 获得地址
Elements localEle = doc.getElementsByClass("webox");
StringBuffer sb = new StringBuffer();
for (Element e : localEle) {
sb.append(e.getElementsByTag("a").text().substring(0, 2));
sb.append(">");
}
String citySb = sb.toString();
if (citySb.trim().isEmpty()) {
log.info("city 为空");
} else {
city = citySb.substring(0, citySb.length() - 1);
weatherYesterMap.put("city", city);
}
Elements conEle = doc.getElementsByClass("blueFor-container");
for (Element e : conEle) {
// 获得气温数组
Document eDoc = Jsoup.parse(e.toString());
// script有两个一个是7天15天的气温一个是小时预报
Elements scripts = eDoc.getElementsByTag("script");
//拿到气温数据
Elements eq = scripts.eq(0);
for (Element ele :
eq) {
String[] datas = ele.data().split("var");
for (String data :
datas) {
// 数据不为空包含"="
if (data.contains("=")) {
String[] datass = data.split("=");
if ("eventDay".equals(datass[0].trim())) {
String dataSquare = data.split("=")[1];
tempMax = getTemp(dataSquare);
}
if ("eventNight".equals(datass[0].trim())) {
String dataSquare = data.split("=")[1];
tempMin = getTemp(dataSquare);
}
}
}
weatherYesterMap.put("tempMax", tempMax[0]);
weatherYesterMap.put("tempMin", tempMin[0]);
// 昨天天气
Elements yestEle = eDoc.select("li[class^=blue-item yesterday]");
// 获得天气
weather[0] = yestEle.select("p[class^=weather-info info-style]").text();
weatherYesterMap.put("weather", weather[0]);
// 获得风气
Elements winds = yestEle.select("i[class^=wind-icon]");
StringBuffer sbb = new StringBuffer();
for (Element wind :
winds) {
sbb.append(wind.getElementsByTag("i").attr("title"));
sbb.append(">");
}
String sbbs = sbb.toString();
wd[0] = sbbs.substring(0, sbbs.length() - 1);
weatherYesterMap.put("wd", wd[0]);
// 风力
ws[0] = yestEle.select("p[class^=wind-info info-style]").text();
weatherYesterMap.put("ws", ws[0]);
weatherYesterMap.put("rain", null);
weatherMap7Day.put("d0", weatherYesterMap);
// 7天天气预报
Elements forecasts = eDoc.select("li[class^=blue-item lv]");
int i = 1;
for (Element e1 :
forecasts) {
// 时间
LocalDate date = localDate.plusDays(i - 1);
// 天气数组
weatherMap = new HashMap<>(7);
String day = "d" + i;
// 天气
weather[i] = e1.select("p[class^=weather-info]").get(0).text();
weatherMap.put("weather", weather[i]);
// 获得风气
Elements winds7Day = e1.select("i[class^=wind-icon]");
sbb.setLength(0);
sbb.delete(0, sbb.length());
for (Element wind :
winds7Day) {
sbb.append(wind.getElementsByTag("i").attr("title"));
sbb.append(">");
}
sbbs = sbb.toString();
wd[i] = sbbs.substring(0, sbbs.length() - 1);
weatherMap.put("wd", wd[i]);
// 风力
ws[i] = e1.select("p[class^=wind-info]").text();
weatherMap.put("ws", ws[i]);
weatherMap.put("tempMax", tempMax[i]);
weatherMap.put("tempMin", tempMin[i]);
weatherMap.put("city",city);
// 三天内的数据又降水预报站点数据
if (i < 4){
weatherMap.put("rain",rainForecast.get(dateToStringNoLine(date)));
}else{
weatherMap.put("rain","null");
}
weatherMap7Day.put(day, weatherMap);
i++;
}
}
}
isSuccess = true;
} catch (IOException e) {
log.info("连接超时");
retryTimes--;
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
log.info("天气查询完毕");
ForecastWeather7DayVo forecastWeather7DayVo = new ForecastWeather7DayVo();
forecastWeather7DayVo.setCity(city);
forecastWeather7DayVo.setTempMax(tempMax);
forecastWeather7DayVo.setTempMin(tempMin);
forecastWeather7DayVo.setWd(wd);
forecastWeather7DayVo.setWs(ws);
forecastWeather7DayVo.setWeather(weather);
forecastWeather7DayVo.setWeatherMap7Day(weatherMap7Day);
return forecastWeather7DayVo;
}
/**
* 气温数据存储
* @param data 气温字符串
*/
private static String[] getTemp(String data) {
String[] temps = data.substring(1, data.length() - 3).split(",");
String[] temp = new String[8];
for (int i = 0; i < temps.length; i++) {
temp[i] = temps[i].substring(1, temps[i].length() - 1);
}
return temp;
}
/**
* 获取降水量预报
* @param cityStationId 城市站点id
*/
public static Map<String, String> getRainForecast(String cityStationId) {
Map<String,String> map = new HashMap<>(3);
map.put("staId",cityStationId);
map.put("funitemmenuid","1150101020");
map.put("typeCode","NWST");
map.put("url", Precipitation.FORECAST_PERCIPITION_URL);
return Precipitation.forecastDataHandler(map);
}
public static void main(String[] args) {
ForecastWeather7DayVo res = getReptileWeather7Day("101121304","54861");
System.out.println(res);
}
}

View File

@ -0,0 +1,259 @@
package com.xkrs.microservice.common.tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xkrs.microservice.model.vo.RealTimeWeatherVo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import static com.xkrs.microservice.util.DateTimeUtil.dateTimeToString;
/**
* 得到实时数据
* @author wd
*/
public class CrawlingWeatherNew {
private static final Logger log = LoggerFactory.getLogger(CrawlingWeatherNew.class);
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36";
private static final String COOKIE = "f_city=%E9%83%91%E5%B7%9E%7C101180101%7C; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1546482322; Hm_lpvt_080dabacb001a";
public static final String REFERER = "http://www.weather.com.cn/";
public static RealTimeWeatherVo handlerWeatherData(String cityCode){
RealTimeWeatherVo realTimeWeather = new RealTimeWeatherVo();
// 时间
LocalDateTime localDateTime = LocalDateTime.now();
// 拿到数据
String data = getRealTimeWeather(cityCode);
// 建立treeJson
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(data);
// 根据路径获取数据
String cityName = jsonNode.path("cityname").asText();
String weather = jsonNode.path("weather").asText();
String temp = jsonNode.path("temp").asText();
String tempf = jsonNode.path("tempf").asText();
String wd = jsonNode.path("WD").asText();
String ws = jsonNode.path("WS").asText();
String sd = jsonNode.path("SD").asText();
String wse = jsonNode.path("wse").asText();
String qy = jsonNode.path("qy").asText();
String njd = jsonNode.path("njd").asText();
String rain = jsonNode.path("rain").asText();
String rain24 = jsonNode.path("rain24h").asText();
String aqi = jsonNode.path("aqi").asText();
String aqiPm25 = jsonNode.path("aqi_pm25").asText();
realTimeWeather.setWeather(weather);
realTimeWeather.setTemp(temp);
realTimeWeather.setTempf(tempf);
realTimeWeather.setWd(wd);
realTimeWeather.setWs(ws);
realTimeWeather.setSd(sd);
realTimeWeather.setWse(wse);
realTimeWeather.setQy(qy);
realTimeWeather.setNjd(njd);
realTimeWeather.setRain(rain);
realTimeWeather.setRain24(rain24);
realTimeWeather.setAqi(aqi);
realTimeWeather.setAqiPm25(aqiPm25);
realTimeWeather.setRealTime(dateTimeToString(localDateTime));
return realTimeWeather;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取实时天气
* @param cityCode 城市代码
* @return
*{"nameen":"qingdao","cityname":"青岛","city":"101120201","temp":"18","tempf":"64","WD":"东南风 ","wde":"SE","WS":"4级","wse":"16-24km/h",
* "SD":"98%","time":"09:15","weather":"","weathere":"rain","weathercode":"d301","qy":"999","njd":"3.6km","sd":"98%","rain":"0","rain24h":"0",
* "aqi":"16","limitnumber":"","aqi_pm25":"16","date":"11月18日(星期三)"}
*/
public static String getRealTimeWeather(String cityCode){
// 读取成功标志
boolean isSuccess = false;
// 重复次数
int count = 10;
// 创建http对象
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(60000)
.build();
CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig).build();
// 创建并设置URI
URIBuilder uri = null;
// 创建Get请求
HttpGet get = null;
String url = "";
try {
url = "http://d1.weather.com.cn/sk_2d/" + cityCode + ".html?_=" + System.currentTimeMillis();
uri = new URIBuilder(url);
get = new HttpGet(uri.build());
// 设置请求头
get.setHeader("Accept"
, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
get.setHeader("Accept-Encoding"
, "gzip, deflate");
get.setHeader("Accept-Language"
, "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6");
get.setHeader("Connection"
, "keep-alive");
get.setHeader("Cache-Control"
, "no-cache");
get.setHeader("Host"
, "d1.weather.com.cn");
get.setHeader("Upgrade-Insecure-Requests"
, "1");
get.setHeader("Cookie", COOKIE);
get.setHeader("User-Agent", USER_AGENT);
get.setHeader("Referer", REFERER);
} catch (Exception e) {
log.info("错误{}", (Object) e.getStackTrace());
}
//发送请求
HttpEntity entity = null;
InputStream is = null;
BufferedReader br = null;
// 创建响应对象
CloseableHttpResponse response = null;
String line = null;
String sLine = null;
String json = null;
while (!isSuccess && count > 0){
try {
response = client.execute(get);
// 获取请求结果
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
log.info("实时天气数据未请求成功");
count --;
continue;
}
entity = response.getEntity();
is = entity.getContent();
br = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8)
);
StringBuffer sb = new StringBuffer();
while((line = br.readLine()) != null){
sb.append(line);
sb.append("/n");
}
sLine = sb.toString();
sLine = sLine.substring(sLine.indexOf("{"));
sLine = sLine.substring(0,sLine.length()-2);
ObjectMapper objectMapper = new ObjectMapper();
//使用ObjectMapper对象对 User对象进行转换
try {
json = objectMapper.writeValueAsString(sLine);
} catch (JsonProcessingException e) {
log.info("json字符串转化异常{}", (Object) e.getStackTrace());
}
isSuccess = true;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
log.info("请求超时等问题:{}", (Object) e.getStackTrace());
}catch (IOException e) {
log.info("I/O问题:{}", (Object) e.getStackTrace());
}finally {
close(is,br,response,client);
}
}
return sLine;
}
// /**
// * 获得7天天气 老版中国天气网
// * @param cityCode 城市代码
// */
// public static void getWeather7d(String cityCode){
//
// String url = "http://www.weather.com.cn/weather/" + cityCode + ".shtml";
// try {
// Document doc = Jsoup.connect(url).get();
// Elements content = doc.getElementsByClass("con");
// for (Element e : content) {
// Document conDoc = Jsoup.parse(e.toString());
// Elements cru = conDoc.getElementsByClass("crumbs");
// Elements sky = content.select("li[class^=sky skyid lv]");
// Elements data = content.select("li[class^=date-item]");
// // 地点
// System.out.println(cru.text());
// // weather
// for (Element sk : sky) {
// System.out.println("时间" + sk.text());
// }
// }
// } catch (Exception e) {
// log.info("未知错误{}", (Object) e.getStackTrace());
// }
// log.info("天气查询完毕!!");
// }
/**
* 关闭流
* @param is InputStream
* @param br BufferedReader
* @param response CloseableHttpResponse
* @param client CloseableHttpClient
*/
private static void close(InputStream is, BufferedReader br, CloseableHttpResponse response, CloseableHttpClient client){
try {
if (null != is){
is.close();
}
if (null != br){
br.close();
}
if (null != response){
response.close();
}
if (null != client){
client.close();
}
} catch (IOException e) {
log.info("IO错误{}", (Object) e.getStackTrace());
}
}
public static void main(String[] args) {
RealTimeWeatherVo realTimeWeatherVo = handlerWeatherData("101120201");
System.out.println(realTimeWeatherVo);
}
}

View File

@ -0,0 +1,91 @@
package com.xkrs.microservice.common.tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xkrs.microservice.model.vo.FileServerResultVo;
import com.xkrs.microservice.util.RequestUtil;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 文件服务器工具
* @author tajochen
*/
public class FileServerTool {
private static final String UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0";
/**
* 发送管理命令到文件服务器
* @param url 文件服务器路径
* @param map 命令参数集
* @return
*/
public static FileServerResultVo postFileManage(String url, Map<String,String> map){
Logger log = LoggerFactory.getLogger(RequestUtil.class);
String body = "";
// 创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
// 创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
// 装填参数
List<NameValuePair> nvps = new ArrayList<>();
if(map!=null){
for (Map.Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try {
// 设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
// 设置header报文头信息
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", UA);
httpPost.setHeader("Accept", "application");
httpPost.setHeader("Accept-Encoding", "gzip, deflate");
// 执行请求操作并拿到结果同步阻塞
CloseableHttpResponse response = client.execute(httpPost);
// 获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
// 释放链接
response.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
FileServerResultVo fileServerResultVo = new FileServerResultVo();
ObjectMapper mapper = new ObjectMapper();
try {
fileServerResultVo = mapper.readValue(body, FileServerResultVo.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
log.warn(e.toString());
}
return fileServerResultVo;
}
}

View File

@ -0,0 +1,174 @@
package com.xkrs.microservice.common.tool;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* 序列化工具
* @author tajochen
*/
public class JackSonTool {
private static final Logger logger = LoggerFactory.getLogger(JackSonTool.class);
private JackSonTool() {
}
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
OBJECT_MAPPER.getSerializerProvider().setNullValueSerializer(new JsonSerializer<>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
});
// 解决jackson无法反序列化LocalDateTime的问题,引入jsr310标准
JavaTimeModule javaTimeModule = new JavaTimeModule();
OBJECT_MAPPER.registerModule(javaTimeModule);
OBJECT_MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
/**
* 序列化
* @param obj
* @param <T>
* @return
*/
public static <T> String encode(T obj) {
if (Objects.isNull(obj)) {
return null;
}
try {
return OBJECT_MAPPER.writeValueAsString(obj);
} catch (Exception e) {
logger.error("json encode error, obj={}", obj, e);
return null;
}
}
/**
* 反序列化
* @param json
* @param valueType
* @param <T>
* @return
*/
public static <T> T decode(String json, Class<T> valueType) {
if (!json.isEmpty() && !Objects.isNull(valueType)) {
try {
return OBJECT_MAPPER.readValue(json, valueType);
} catch (Exception e) {
logger.error("json decode fail,jsonString={}, type={}", json, valueType.getName(), e);
}
}
return null;
}
/**
* 反序列化成list
* @param <T>
* @param json
* @param clazz
* @return
*/
public static <T> List decode2List(String json, Class<T> clazz) {
if (!json.isEmpty() && !Objects.isNull(clazz)) {
try {
return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
} catch (Exception var3) {
logger.error("json decode2list fail,json={},classType={}", json, clazz.getName(), var3);
}
}
return null;
}
/**
* 字符串转换为 Map<String, Object>
*
* @param jsonString
* @return
* @throws Exception
*/
public static <T> Map json2map(String jsonString) {
try {
return OBJECT_MAPPER.readValue(jsonString, Map.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
/**
* 字符串转换为 Map<String, T>
*/
public static <T> Map<String, T> json2map(String jsonString, Class<T> clazz) {
Map<String, T> map = null;
try {
map = OBJECT_MAPPER.readValue(jsonString, new TypeReference<Map<String, T>>() {
});
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
Map<String, T> result = new HashMap<String, T>(128);
for (Map.Entry<String, T> entry : map.entrySet()) {
result.put(entry.getKey(), OBJECT_MAPPER.convertValue(entry.getValue(), clazz));
}
return result;
}
/**
* 将一个JSON字符串转换为T对象
* @param json
* @param typeReference
* @return
*/
public static <T> T toObject(String json, TypeReference<T> typeReference) {
try {
return OBJECT_MAPPER.readValue(json, typeReference);
} catch (Exception e) {
throw new RuntimeException("failed to convert string to object", e);
}
}
/**
* map转clazz对象
* @param map
* @param clazz
* @param <T>
* @return
*/
public static <T> T mapToObject(Map map, Class<T> clazz) {
String json = null;
try {
json = OBJECT_MAPPER.writeValueAsString(map);
return OBJECT_MAPPER.readValue(json, clazz);
} catch (Exception e) {
logger.error("json map2object fail,map={},ClassName={}", json, clazz.getName());
return null;
}
}
}

View File

@ -0,0 +1,84 @@
package com.xkrs.microservice.common.tool;
import java.io.Serializable;
import java.util.List;
/**
* @author XinYi Song
* 分页的封装
*/
@SuppressWarnings({"ALL", "AlibabaAvoidCommentBehindStatement"})
public class PageBean<T> implements Serializable {
//要封装的list泛型集合
private List<T> list;
//当前页码
private int currentPage;
//每页展示的条数
private int pageSize;
//数据总数
private long totalCount;
//总页数
private int totalPage;
public PageBean() {
}
public PageBean(List<T> list, int currentPage, int pageSize, long totalCount) {
this.list = list;
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalCount = totalCount;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotalCount() {
return totalCount;
}
public void setTotalCount(long totalCount) {
this.totalCount = totalCount;
}
//设置总页数
public int getTotalPage() {
return (int) Math.ceil(totalCount * 1.0 / pageSize);
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
@Override
public String toString() {
return "PageBean{" +
"list=" + list +
", currentPage=" + currentPage +
", pageSize=" + pageSize +
", totalCount=" + totalCount +
", totalPage=" + totalPage +
'}';
}
}

View File

@ -0,0 +1,418 @@
package com.xkrs.microservice.common.tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import static com.xkrs.microservice.util.DateTimeUtil.dateToStringNoLine;
/**
* 降水量
* @author wd
*/
public class Precipitation {
private static final Logger log = LoggerFactory.getLogger(Precipitation.class);
/**
* 历史降雨量
*/
public static final String HISTORICAL_PRECIPITION_URL = "http://data.cma.cn/dataGis/multiSource/getLiveDataInfo3";
/**
* 预报天气
*/
public static final String FORECAST_PERCIPITION_URL = "http://data.cma.cn/dataGis/exhibitionData/getStationInfo";
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36";
private static final String COOKIE = "JSESSIONID=E0AF489776F9463892478C226957FB86; " +
"pgv_pvi=4137831424; " +
"userLoginKey=63730d21fa3139b077bae8a7801cf04e; " +
"trueName=snnbnoone; " +
"userName=54e05d733671bd38af26fc06640f3ba4; " +
"PHPSESSID=eqs8ocriikbhmq28lt2lvdoft0; " +
"pgv_si=s349517824; " +
"Hm_lvt_d9508cf73ee2d3c3a3f628fe26bd31ab=1604459365,1604483274,1604547634,1605764770; " +
"_pk_testcookie.6.dd70=1; " +
"login_id_chat=0; floatDc=1; " +
"Hm_lpvt_d9508cf73ee2d3c3a3f628fe26bd31ab=1606110326; " +
"_pk_ref.6.dd70=%5B%22%22%2C%22%22%2C1606110326%2C%22https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3Dvc5Gc6810ZDAhZd1006vGN0aBUYxE0Hmp1CrfAJLz2G%26wd%3D%26eqid%3Debf41e300000ebb0000000025fa3742d%22%5D; " +
"_pk_ses.6.dd70=1; _pk_ref.1.dd70=%5B%22%22%2C%22%22%2C1606110326%2C%22https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3Dvc5Gc6810ZDAhZd1006vGN0aBUYxE0Hmp1CrfAJLz2G%26wd%3D%26eqid%3Debf41e300000ebb0000000025fa3742d%22%5D; " +
"_pk_id.1.dd70=e952ffa8190db13b.1603759181.13.1606110326.1606042123.; " +
"_pk_ses.1.dd70=*; " +
"login_name_chat=0; " +
"_pk_ses.2.dd70=*; " +
"_pk_id.6.dd70=156cb08aa1aab3cc.1603759181.15.1606110674.1606110326.; " +
"_pk_id.2.dd70=3620e1ea6324ce18.1604461280.4.1606110674.1605837309.";
public static final String REFERER = "http://data.cma.cn/dataGis/static/gridgis/";
/**
* 处理历史降水数据
* @param params 参数列表
* time:时间戳 20201127093100
* needLSB:1
* lat:经度 站点
* lon:纬度 站点
* dataTypeCMPA_PRE
* urlHISTORICAL_PRECIPITION_URL
*/
public static String historyDataHandler(Map<String,String> params){
// 数据
String data = getWeatherData(params);
// 建立treeJson
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(data);
// 根据路径获取数据
JsonNode dsNdoe = jsonNode.path("data");
// 获取数据
if (dsNdoe == null){
log.info("无数据");
return null;
}
for (int i = 0; i < dsNdoe.size(); i++) {
JsonNode node = dsNdoe.get(i);
if ("PRE_10MIN_24HOUR".equals(node.path("fastEle").asText())){
return node.path("value").asText();
}
}
} catch (JsonProcessingException e) {
log.info("转化Json失败{}", (Object) e.getStackTrace());
}
return null;
}
/**
* 处理预报降水
* @param params 参数列表
* staId站点ID
* funitemmenuid1150101020
* typeCodeNWST
* urlFORECAST_PERCIPITION_URL
*/
public static Map<String,String> forecastDataHandler(Map<String,String> params){
Map<String,String> map = new HashMap<>(3);
// 获取日期
LocalDate localDate = LocalDate.now();
// 数据
String data = getWeatherData(params);
if (data.trim().isEmpty()){
log.info("无数据");
return null;
}
// 建立treeJson
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(data);
// 根据路径获取数据
JsonNode dsNdoe = jsonNode.path("list").get(0);
final int rainDay = 3;
// 获取数据
for (int j = 0; j < rainDay; j++) {
String time = dateToStringNoLine(localDate.plusDays(j));
String time1 = dateToStringNoLine(localDate.plusDays(j + 1));
float rain = 0;
if (dsNdoe == null){
log.info("dsNode没有数据");
return null;
}
for (int i = 0; i < dsNdoe.size(); i++) {
JsonNode node = dsNdoe.get(i);
if (node.get(0).asText().trim().isEmpty() || node.get(0).asText().length() != 0){
if (node.get(0).asText().contains(time) || node.get(0).asText().contains(time1 + "000000")){
rain += Float.parseFloat(node.get(1).asText());
}
}
}
String rains = String.valueOf(rain);
map.put(time,rains);
}
return map;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取数据
* @param params 数据列表
*/
private static String getWeatherData(Map<String,String> params){
int connTimes = 5;
boolean isSuccess = false;
String urlWithParam = urlWithParam(params);
StringBuffer data = new StringBuffer();
while(!isSuccess && connTimes > 0){
try {
URL url = new URL(urlWithParam);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line = br.readLine()) != null){
data.append(line);
}
String datas = data.toString();
is.close();
isr.close();
br.close();
if (datas.contains("503 Service Temporarily Unavailable")){
log.info("数据错误");
connTimes --;
try {
Thread.sleep(20000);
} catch (InterruptedException ex) {
log.info("睡眠错误{}", (Object) ex.getStackTrace());
}
}
isSuccess = true;
} catch (IOException e) {
log.info("降水连接超时");
connTimes --;
try {
Thread.sleep(20000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
return data.toString();
}
/**
* 路径加上参数
* @param params 参数列表
*/
private static String urlWithParam(Map<String,String> params){
final String url = "url";
// 拼接字符串
StringBuffer urlAddParam = new StringBuffer();
urlAddParam.append(params.get("url"));
urlAddParam.append("?");
params.forEach((k,v) ->{
if (!url.equals(k)){
urlAddParam.append(k);
urlAddParam.append("=");
urlAddParam.append(v);
urlAddParam.append("&");
}
});
String urlWithParam = urlAddParam.toString();
final String endWith = "&";
if (urlWithParam.endsWith(endWith)){
urlWithParam = urlWithParam.substring(0,urlWithParam.length()-1);
}
log.info(urlWithParam);
return urlWithParam;
}
/**
* 获取降水预报
* @param params 参数列表
* staId站点ID
* funitemmenuid1150101020
* typeCodeNWST
* urlFORECAST_PERCIPITION_URL
*/
public static String getRealTimeRain(Map<String,String> params){
// 成功标志
boolean isSuccess = false;
// 尝试次数
int connTimes = 10;
// 创建响应对象
CloseableHttpResponse response = null;
String line = null;
String sLine = null;
String json = null;
while(!isSuccess && connTimes > 0){
// 创建http对象
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(60000)
.build();
CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig).build();
// 创建并设置URI
URIBuilder uri = null;
// 创建Get请求
HttpGet get = null;
String url = "";
try {
url = urlWithParam(params);
uri = new URIBuilder(url);
get = new HttpGet(uri.build());
// 设置请求头
get.setHeader("Accept"
, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
get.setHeader("Accept-Encoding"
, "gzip, deflate");
get.setHeader("Accept-Language"
, "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6");
get.setHeader("Connection"
, "keep-alive");
get.setHeader("Cache-Control"
, "no-cache");
get.setHeader("Host"
, "data.cma.cn");
get.setHeader("Upgrade-Insecure-Requests"
, "1");
get.setHeader("Cookie", COOKIE);
get.setHeader("User-Agent", USER_AGENT);
get.setHeader("Referer", REFERER);
} catch (Exception e) {
log.info("{}", (Object) e.getStackTrace());
}
//发送请求
HttpEntity entity = null;
InputStream is = null;
BufferedReader br = null;
try {
response = client.execute(get);
// 获取请求结果
entity = response.getEntity();
is = entity.getContent();
br = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8)
);
StringBuffer sb = new StringBuffer();
while((line = br.readLine()) != null){
sb.append(line);
sb.append("/n");
}
sLine = sb.toString();
if (sLine.contains("503 Service Temporarily Unavailable")){
log.info("数据出错");
connTimes --;
closeConn(is,br,response,client);
Thread.sleep(30000);
continue;
}
sLine = sLine.substring(sLine.indexOf("{"));
sLine = sLine.substring(0,sLine.length()-2);
if (sLine.contains("503 Service Temporarily Unavailable")){
return null;
}
ObjectMapper objectMapper = new ObjectMapper();
//使用ObjectMapper对象对 User对象进行转换
try {
json = objectMapper.writeValueAsString(sLine);
} catch (JsonProcessingException e) {
log.info("json字符串转化异常{}", (Object) e.getStackTrace());
}
// ObjectMapper objectMapper = new ObjectMapper();
isSuccess = true;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
log.info("请求超时等问题{}", (Object) e.getStackTrace());
}catch (IOException e) {
log.info("I/O问题{}", (Object) e.getStackTrace());
} catch (InterruptedException e) {
log.info("中断异常{}", (Object) e.getStackTrace());
} finally {
closeConn(is,br,response,client);
}
}
return json;
}
/**
* 关闭连接
* @param is InputStream
* @param br BufferedReader
* @param response CloseableHttpResponse
* @param client CloseableHttpClient
*/
private static void closeConn(InputStream is, BufferedReader br, CloseableHttpResponse response, CloseableHttpClient client ){
try {
if (null != is){
is.close();
}
if (null != br){
br.close();
}
if (null != response){
response.close();
}
if (null != client){
client.close();
}
} catch (IOException e) {
log.info("IO异常{}", (Object) e.getStackTrace());
}
}
public static void main(String[] args) {
// 历史降水
Map<String,String> hisParams = new HashMap<>(6);
// 当前时间戳
hisParams.put("time","20201127100400");
// 站点经纬度
hisParams.put("lat","36.9700");
hisParams.put("lon","120.7300");
hisParams.put("needLSB","1");
hisParams.put("dataType","CMPA_PRE");
hisParams.put("url",HISTORICAL_PRECIPITION_URL);
historyDataHandler(hisParams);
// 预报降水
Map<String,String> foreParams = new HashMap<>(4);
// 站点id
foreParams.put("stationId","");
foreParams.put("funitemmenuid","1150101020");
foreParams.put("typeCode","NWST");
foreParams.put("url",FORECAST_PERCIPITION_URL);
forecastDataHandler(foreParams);
}
}

View File

@ -0,0 +1,52 @@
package com.xkrs.microservice.common.tool;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import javax.crypto.SecretKey;
import java.util.List;
/**
* token工具
* @author tajochen
*/
public class TokenUtil {
/**
* Token前缀
*/
private static final String TOKEN_PREFIX = "Bearer";
private static final String SECRETKEY = "0Y9H364Q9Y908262F25LMXGIKIN5N858XM3674GWL2DD8X1DS4W6I722IRY8PS4XPNB6U30" +
"345HBVCUL94STG8C3Z53T7A09JJ100I56YE9894CI11PX9J71HIZ8L5Y2O504C4E2K8276425UA8734833F45K36878FXAG799QV9L" +
"XUJOI3XA2046UPG8TB2OT84R5T6ZB127N9ZPJ7AJMC41JVHB2WK2B6H8NL45LZNAZ666KHZH3QUT65UX6F8";
static SecretKey key = Keys.hmacShaKeyFor(SECRETKEY.getBytes());
public static String getTokenUserName(String token) {
String userName = "";
if (token != null) {
try {
// 解析 Token
Claims claims = Jwts.parserBuilder()
.setSigningKey(key).build()
// 去掉 Bearer
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody();
// 获取用户名
userName = claims.getSubject();
// 获取权限
List<GrantedAuthority> authorities = AuthorityUtils.
commaSeparatedStringToAuthorityList((String) claims.get("auths"));
} catch(Exception e) {
// the sub field was missing or did not have a 'jsmith' value
return null;
}
} else {
return null;
}
return userName;
}
}

View File

@ -0,0 +1,97 @@
package com.xkrs.microservice.common.tool;
import com.xkrs.microservice.dao.WeatherDao;
import com.xkrs.microservice.model.entity.WeatherEntity;
import com.xkrs.microservice.util.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author XinYi Song
*/
@Component
public class WeatherGet {
public static Logger log = LoggerFactory.getLogger(WeatherGet.class);
@Resource
private WeatherDao weatherDao;
@CacheEvict(value = "WeatherServiceCache",allEntries = true)
public void findWeather(){
// 请求登录接口拿到token
String login = "http://47.105.215.208:8005/login";
String json1 = "{\n" +
" \"username\":\"5281652\",\n" +
" \"password\":\"123456\"\n" +
"}";
String s = RequestUtil.doPostJson(login, json1);
Map map1 = JackSonTool.json2map(s);
String token = (String) map1.get("token");
String getData = "http://47.105.215.208:8005/intfa/queryData/16079680";
Map map = new HashMap(3);
String s1 = RequestUtil.doGet(getData, map, token);
Map map2 = JackSonTool.json2map(s1);
List<Map> data1 = (List<Map>) map2.get("entity");
if(data1 == null || data1.size() == 0){
log.info("----+" + "结束当前方法");
return;
}else {
log.info("-----------开始数据入库");
WeatherEntity weatherEntity = new WeatherEntity();
weatherEntity.setAddTime(data1.get(0).get("datetime").toString());
// 风速
weatherEntity.setWindSpeed(data1.get(0).get("eValue").toString());
// 雨量累计
weatherEntity.setRainfall(data1.get(1).get("eValue").toString());
// 大气温度
weatherEntity.setAtmosphericTemperature(data1.get(2).get("eValue").toString());
// 大气湿度
weatherEntity.setAtmosphericHumidity(data1.get(3).get("eValue").toString());
// 数字气压
weatherEntity.setDigitalAirPressure(data1.get(4).get("eValue").toString());
// 太阳总辐射
weatherEntity.setTotalSolarRadiation(data1.get(5).get("eValue").toString());
// 风向
weatherEntity.setWindDirection(data1.get(6).get("eValue").toString());
// 辐射累计
weatherEntity.setRadiationAccumulation(data1.get(7).get("eValue").toString());
// 土温1
weatherEntity.setSoilTemperatureOne(data1.get(8).get("eValue").toString());
// 土湿1
weatherEntity.setSoilWetOne(data1.get(9).get("eValue").toString());
// 土温2
weatherEntity.setSoilTemperatureTwo(data1.get(10).get("eValue").toString());
// 土湿2
weatherEntity.setSoilWetTwo(data1.get(11).get("eValue").toString());
// 土温3
weatherEntity.setSoilTemperatureThree(data1.get(12).get("eValue").toString());
// 土湿3
weatherEntity.setSoilWetThree(data1.get(13).get("eValue").toString());
// 土温4
weatherEntity.setSoilTemperatureFour(data1.get(14).get("eValue").toString());
// 土湿4
weatherEntity.setSoilWetFour(data1.get(15).get("eValue").toString());
// ph值
weatherEntity.setPhValue(data1.get(16).get("eValue").toString());
// 日照时数
weatherEntity.setSunshineHours(data1.get(17).get("eValue").toString());
// 二氧化碳
weatherEntity.setCarbonDioxide(data1.get(18).get("eValue").toString());
// 盐分
weatherEntity.setSalt(data1.get(19).get("eValue").toString());
weatherDao.save(weatherEntity);
}
}
}

View File

@ -0,0 +1,101 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.FileAppEntity;
import com.xkrs.microservice.model.qo.AppFileQo;
import com.xkrs.microservice.model.validation.AppFileQoInsert;
import com.xkrs.microservice.model.vo.FileServerResultVo;
import com.xkrs.microservice.service.AppManageService;
import com.xkrs.microservice.service.FileServerService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Pattern;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
/**
* App 管理服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/app-file")
public class AppManageController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private AppManageService appManageService;
@Resource
private FileServerService fileServerService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
public String getAllAppFiles() {
Iterable<FileAppEntity> list = appManageService.getAllFile();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/new-version",method = RequestMethod.GET)
@CrossOrigin
public String appFileGetNew(@RequestParam("versionNumber") String versionNumber){
String pattern = "^([1-9]\\d|[1-9])(.([1-9]\\d|\\d)){2}$";
boolean isMatch = Pattern.matches(pattern, versionNumber);
if(!isMatch){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"版本号错误",locale);
}
Iterable<FileAppEntity> list = appManageService.checkLastVersionNumber(versionNumber);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String appFileAdd(@Validated({AppFileQoInsert.class}) @RequestBody AppFileQo appFileQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 检查版本号是否存在
Iterable<FileAppEntity> appFileEntityIterable = appManageService.getByVersionNumber(appFileQo.getVersionNumber());
for (FileAppEntity o : appFileEntityIterable) {
if(o!=null){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"重复的版本号",locale);
}
}
// 获取当前用户名
String userName = getTokenUserName(token);
appManageService.add(appFileQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String appFileDelete(@RequestParam("id") Integer id) {
Optional <FileAppEntity> sf = appManageService.getById(id);
if(sf.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.DATA_WRONG,"指定id文件不存在",locale);
}
try {
FileServerResultVo fileServerResultVo = fileServerService.deleteFile(sf.get().getMd5(),"");
appManageService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,fileServerResultVo,locale);
} catch (Exception e) {
e.printStackTrace();
return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL,"文件服务器出错",locale);
}
}
}

View File

@ -0,0 +1,38 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.service.CacheService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Locale;
/**
* 缓存测试服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/cache")
public class CacheController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private CacheService cacheService;
@GetMapping("/get/test-name")
public String findByNickName(@RequestParam(value="testName", required=false) String testName)
{
return cacheService.findByTestName(testName);
}
@GetMapping("/set/test-name")
public String setNickName(@RequestParam(value="testName", required=false) String testName)
{
return cacheService.setTestName(testName);
}
}

View File

@ -0,0 +1,109 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.CropClassifyRecordEntity;
import com.xkrs.microservice.model.qo.CropClassifyRecordQo;
import com.xkrs.microservice.model.validation.CropClassifyRecordQoInsert;
import com.xkrs.microservice.service.CropClassifyRecordService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
import static com.xkrs.microservice.util.DateTimeUtil.timeMillisToDate;
/**
* 作物种植记录数据服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/crop-classify-record")
public class CropClassifyRecordController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private CropClassifyRecordService cropClassifyRecordService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
@CrossOrigin
public String getCropClassifyAllRecord() {
Iterable<CropClassifyRecordEntity> list = cropClassifyRecordService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode",method = RequestMethod.GET)
@CrossOrigin
public String getCropClassifyByAdmCode(@RequestParam("admCode") Integer admCode) {
Iterable<CropClassifyRecordEntity> list = cropClassifyRecordService.getByAdmCode(admCode);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/towncode/date",method = RequestMethod.GET)
@CrossOrigin
public String getCropClassifyByTownCode(@RequestParam("townCode") String townCode,
@RequestParam("startDateTs") Long startDateTs,
@RequestParam("endDateTs") Long endDateTs) {
if(startDateTs > endDateTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDate sTime = timeMillisToDate(startDateTs);
LocalDate eTime = timeMillisToDate(endDateTs);
Iterable<CropClassifyRecordEntity> list = cropClassifyRecordService.getByTownCodeAndDate(townCode,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode/date",method = RequestMethod.GET)
@CrossOrigin
public String getCropClassifyByAdmCodeAndDate(@RequestParam("admCode") Integer admCode,
@RequestParam("startDateTs") Long startDateTs,
@RequestParam("endDateTs") Long endDateTs) {
if(startDateTs > endDateTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDate sTime = timeMillisToDate(startDateTs);
LocalDate eTime = timeMillisToDate(endDateTs);
Iterable<CropClassifyRecordEntity> list = cropClassifyRecordService.getByAdmCodeAndDateTime(admCode,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String cropClassifyAdd(@Validated({CropClassifyRecordQoInsert.class}) @RequestBody CropClassifyRecordQo cropClassifyRecordQo,
BindingResult bindingResult, @RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
cropClassifyRecordService.add(cropClassifyRecordQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String cropClassifyDelete(@RequestParam("id") Integer id) {
Optional<CropClassifyRecordEntity> cropClassifyRecordEntity = cropClassifyRecordService.getById(id);
if(cropClassifyRecordEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
cropClassifyRecordService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,61 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.*;
import com.xkrs.microservice.service.DicBusinessService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Locale;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
/**
* 系统用户Controller
* @author tajocehn
*/
@RestController
@RequestMapping(value = "/api/data")
public class DicBusinessServiceController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private DicBusinessService dicBusinessService;
@RequestMapping(value="/get/soil-classify/all", method = RequestMethod.GET)
public String getAllSoilClassify(){
Iterable<DicSoilClassifyEntity> res = dicBusinessService.getAllSoilClassify();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
@RequestMapping(value="/get/crop-classify/all", method = RequestMethod.GET)
public String getAllCropClassify(){
Iterable<DicCropClassifyEntity> res = dicBusinessService.getAllCropClassify();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
@RequestMapping(value="/get/drought-classify/all", method = RequestMethod.GET)
public String getAllDroughtClassify(){
Iterable<DicDroughtClassifyEntity> res = dicBusinessService.getAllDroughtClassify();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
@RequestMapping(value="/get/land-classify/all", method = RequestMethod.GET)
public String getAllLandClassify(){
Iterable<DicLandClassifyEntity> res = dicBusinessService.getAllLandClassify();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
@RequestMapping(value="/get/product/all", method = RequestMethod.GET)
public String getAllProduct(){
Iterable<DicProductEntity> res = dicBusinessService.getAllProduct();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
}

View File

@ -0,0 +1,108 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.FarmingInfoEntity;
import com.xkrs.microservice.model.qo.FarmingInfoQo;
import com.xkrs.microservice.model.validation.FarmingInfoQoInsert;
import com.xkrs.microservice.service.FarmingInfoService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
/**
* 农情信息表管理
* @author tajochen
*/
@RestController
@RequestMapping("/api/farming-info")
public class FarmingInfoController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private FarmingInfoService farmingInfoService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
@CrossOrigin
public String getAllRecord() {
Iterable<FarmingInfoEntity> list = farmingInfoService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/dkbh",method = RequestMethod.GET)
@CrossOrigin
public String getByDkbh(@RequestParam("dkbh") String dkbh) {
Iterable<FarmingInfoEntity> list = farmingInfoService.getByDkbh(dkbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/qxbh",method = RequestMethod.GET)
@CrossOrigin
public String getByQxbh(@RequestParam("qxbh") Integer qxbh) {
Iterable<FarmingInfoEntity> list = farmingInfoService.getByQxbh(qxbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/zwdm",method = RequestMethod.GET)
@CrossOrigin
public String getByQxbhAndZwdm(@RequestParam("qxbh") Integer qxbh,@RequestParam("zwdm") Integer zwdm) {
Iterable<FarmingInfoEntity> list = farmingInfoService.getByZwdmAndQxbh(zwdm,qxbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/new",method = RequestMethod.GET)
@CrossOrigin
public String getNewByQxbh(@RequestParam("qxbh") Integer qxbh) {
Iterable<FarmingInfoEntity> list = farmingInfoService.getNewByQxbh(qxbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/user-name",method = RequestMethod.GET)
@CrossOrigin
public String getByUserName(@RequestParam("userName") String userName) {
Iterable<FarmingInfoEntity> list = farmingInfoService.getByUserName(userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor','auth_farm_user')")
@CrossOrigin
public String dataAdd(@Validated({FarmingInfoQoInsert.class}) @RequestBody FarmingInfoQo farmingInfoQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
farmingInfoService.add(farmingInfoQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String dataDelete(@RequestParam("id") Integer id) {
Optional<FarmingInfoEntity> typicalPlotEntity = farmingInfoService.getById(id);
if(typicalPlotEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
farmingInfoService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,82 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.FileDocumentEntity;
import com.xkrs.microservice.model.qo.FileDocumentQo;
import com.xkrs.microservice.model.validation.FileDocumentQoInsert;
import com.xkrs.microservice.model.vo.FileServerResultVo;
import com.xkrs.microservice.service.FileDocumentService;
import com.xkrs.microservice.service.FileServerService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
import static com.xkrs.microservice.util.NumberUtil.isStrNumeric;
/**
* 文档管理服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/document")
public class FileDocumentController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private FileDocumentService fileDocumentService;
@Resource
private FileServerService fileServerService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
public String getAllFiles() {
Iterable<FileDocumentEntity> list = fileDocumentService.getAllFile();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String fileUpload(@Validated({FileDocumentQoInsert.class}) @RequestBody FileDocumentQo fileDocumentQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
fileDocumentService.add(fileDocumentQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String fileDelete(@RequestParam("id") Integer id) {
Optional <FileDocumentEntity> sf = fileDocumentService.getById(id);
if(sf.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.DATA_WRONG,"指定id文件不存在",locale);
}
try {
FileServerResultVo fileServerResultVo = fileServerService.deleteFile(sf.get().getMd5(),"");
fileDocumentService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,fileServerResultVo,locale);
} catch (Exception e) {
e.printStackTrace();
return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL,"文件服务器出错",locale);
}
}
}

View File

@ -0,0 +1,119 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.model.vo.FileServerResultVo;
import com.xkrs.microservice.service.FileServerService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Locale;
/**
* 文件服务器管理服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/file")
public class FileServerController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private FileServerService fileServerService;
/**
* 文件统计
* @return
*/
@RequestMapping(value="/stat",method = RequestMethod.GET)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public FileServerResultVo getFileStat() {
return fileServerService.getFileStat();
}
/**
* 文件删除
* @param md5 信息摘要
* @param path 路径
* @return
*/
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','role_administor')")
@CrossOrigin
public FileServerResultVo deleteFile(@RequestParam(value = "md5",required = false) String md5,
@RequestParam(value = "path",required = false) String path) {
FileServerResultVo fileServerResultVo = new FileServerResultVo();
boolean existed = (md5==null||md5.isEmpty())&&(path==null||path.isEmpty());
if(existed){
fileServerResultVo.setStatus("fail");
fileServerResultVo.setData("");
fileServerResultVo.setMessage("参数为空");
return fileServerResultVo;
}
return fileServerService.deleteFile(md5,path);
}
/**
* 获取文件信息
* @param md5 信息摘要
* @param path 路径
* @return
*/
@RequestMapping(value="/get/info",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','role_administor')")
@CrossOrigin
public FileServerResultVo getFileInfo(@RequestParam(value = "md5",required = false) String md5,
@RequestParam(value = "path",required = false) String path) {
boolean existed = (md5==null||md5.isEmpty())&&(path==null||path.isEmpty());
if(existed){
FileServerResultVo<String> fileServerResultVo = new FileServerResultVo<>();
fileServerResultVo.setStatus("fail");
fileServerResultVo.setData("");
fileServerResultVo.setMessage("参数为空");
return fileServerResultVo;
}
return fileServerService.getFileInfo(md5,path);
}
/**
* 获取文件列表
* @param dir 文件夹
* @return
*/
@RequestMapping(value="/get/list",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','role_administor')")
@CrossOrigin
public FileServerResultVo getFileList(@RequestParam(value = "dir") String dir) {
return fileServerService.getFileList(dir);
}
/**
* 修复统计信息
* @param date 要修复的日期格式如20190725
* @return
*/
@RequestMapping(value="/get/repair-stat",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','role_administor')")
@CrossOrigin
public FileServerResultVo getFileRepairStat(@RequestParam(value = "date") String date) {
return fileServerService.getFileRepairStat(date);
}
/**
* 同步失败修复
* @param force 是否强行修复(0|1)
* @return
*/
@RequestMapping(value="/get/repair",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','role_administor')")
@CrossOrigin
public FileServerResultVo getFileRepair(@RequestParam(value = "force") String force) {
return fileServerService.getFileRepair(force);
}
}

View File

@ -0,0 +1,34 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import java.util.Locale;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
/**
* HelloController
* @author tajochen
*/
@RestController
public class HelloController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
/**
* 返回类型为Mono<String>
* @return
*/
@GetMapping("/hello")
public Mono<String> hello() {
// 使用Mono.just生成响应式数据
return Mono.just(outputEncapsulationObject(PromptMessageEnum.SUCCESS,"Welcome to reactive world ~",locale));
}
}

View File

@ -0,0 +1,74 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.HydrologicalStationEntity;
import com.xkrs.microservice.model.qo.HydrologicalStationQo;
import com.xkrs.microservice.model.validation.HydrologicalStationQoInsert;
import com.xkrs.microservice.service.HydrologicalStationService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Locale;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.util.DateTimeUtil.timeMillisToTime;
/**
* 水文站点数据服务管理
* @author tajochen
*/
@RestController
@RequestMapping("/api/hydrological-station")
public class HydrologicalStationController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private HydrologicalStationService hydrologicalStationService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
public String getAllFiles() {
Iterable<HydrologicalStationEntity> list = hydrologicalStationService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/time",method = RequestMethod.GET)
public String getByTime(@RequestParam("sTimeTs") Long sTimeTs,@RequestParam("eTimeTs") Long eTimeTs) {
LocalDateTime sTime = timeMillisToTime(sTimeTs);
LocalDateTime eTime = timeMillisToTime(eTimeTs);
Iterable<HydrologicalStationEntity> list = hydrologicalStationService.getByTime(sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@CrossOrigin
public String addRecord(@Validated({HydrologicalStationQoInsert.class}) @RequestBody HydrologicalStationQo hydrologicalStationQo,
BindingResult bindingResult) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
hydrologicalStationService.add(hydrologicalStationQo);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String deleteRecord(@RequestParam("id") Integer id) {
int res = hydrologicalStationService.delete(id);
if(res!=0){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"id 不存在",locale);
}
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,87 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.IndependentCheckEntity;
import com.xkrs.microservice.model.qo.IndependentCheckQo;
import com.xkrs.microservice.model.validation.IndependentCheckQoInsert;
import com.xkrs.microservice.service.IndependentCheckService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
/**
* 自主核查表管理
* @author tajochen
*/
@RestController
@RequestMapping("/api/independent-check")
public class IndependentCheckController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private IndependentCheckService independentCheckService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
@CrossOrigin
public String getAllRecord() {
Iterable<IndependentCheckEntity> list = independentCheckService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/qxdm",method = RequestMethod.GET)
@CrossOrigin
public String getByCountyCode(@RequestParam("qxdm") Integer qxdm) {
Iterable<IndependentCheckEntity> list = independentCheckService.getByCountyCode(qxdm);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/user-name",method = RequestMethod.GET)
@CrossOrigin
public String getByUserName(@RequestParam("userName") String userName) {
Iterable<IndependentCheckEntity> list = independentCheckService.getByUserName(userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String dataAdd(@Validated({IndependentCheckQoInsert.class}) @RequestBody IndependentCheckQo independentCheckQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
independentCheckService.add(independentCheckQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String dataDelete(@RequestParam("id") Integer id) {
Optional<IndependentCheckEntity> independentCheckEntity = independentCheckService.getById(id);
if(independentCheckEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
independentCheckService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,117 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.IrrigationCheckEntity;
import com.xkrs.microservice.model.qo.IrrigationCheckQo;
import com.xkrs.microservice.model.validation.IrrigationCheckQoInsert;
import com.xkrs.microservice.service.IrrigationCheckService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
import static com.xkrs.microservice.util.DateTimeUtil.timeMillisToDate;
import static com.xkrs.microservice.util.DateTimeUtil.timeMillisToTime;
/**
* 灌溉核查表管理
* @author tajochen
*/
@RestController
@RequestMapping("/api/irrigation-check")
public class IrrigationCheckController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private IrrigationCheckService irrigationCheckService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
@CrossOrigin
public String getAllRecord() {
Iterable<IrrigationCheckEntity> list = irrigationCheckService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/ggbh",method = RequestMethod.GET)
@CrossOrigin
public String getByGgbh(@RequestParam("ggbh") String ggbh) {
Optional<IrrigationCheckEntity> list = irrigationCheckService.getByGgbh(ggbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/qxbh",method = RequestMethod.GET)
@CrossOrigin
public String getQxbh(@RequestParam("qxbh") Integer qxbh) {
Iterable<IrrigationCheckEntity> list = irrigationCheckService.getByQxbh(qxbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/dkbh",method = RequestMethod.GET)
@CrossOrigin
public String getByDkbh(@RequestParam("dkbh") String dkbh) {
Iterable<IrrigationCheckEntity> list = irrigationCheckService.getByDkbh(dkbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/time",method = RequestMethod.GET)
@CrossOrigin
public String getByQxbhAndCreateTimeBetween(@RequestParam("qxdm") Integer qxdm,@RequestParam("sTimeTs") Long sTimeTs,@RequestParam("eTimeTs") Long eTimeTs) {
if(sTimeTs > eTimeTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDateTime sTime = timeMillisToTime(sTimeTs);
LocalDateTime eTime = timeMillisToTime(eTimeTs);
Iterable<IrrigationCheckEntity> list = irrigationCheckService.getByQxbhAndCreateTimeBetween(qxdm,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/user-name",method = RequestMethod.GET)
@CrossOrigin
public String getByUserName(@RequestParam("userName") String userName) {
Iterable<IrrigationCheckEntity> list = irrigationCheckService.getByUserName(userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String dataAdd(@Validated({IrrigationCheckQoInsert.class}) @RequestBody IrrigationCheckQo irrigationCheckQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
irrigationCheckService.add(irrigationCheckQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String dataDelete(@RequestParam("id") Integer id) {
Optional<IrrigationCheckEntity> typicalPlotIrrigationEntity = irrigationCheckService.getById(id);
if(typicalPlotIrrigationEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
irrigationCheckService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,109 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.IrrigationRecordEntity;
import com.xkrs.microservice.model.qo.IrrigationRecordQo;
import com.xkrs.microservice.model.validation.IrrigationRecordQoInsert;
import com.xkrs.microservice.service.IrrigationRecordService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
import static com.xkrs.microservice.util.DateTimeUtil.timeMillisToDate;
/**
* 灌溉记录数据服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/irrigation-record")
public class IrrigationRecordController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private IrrigationRecordService irrigationRecordService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
@CrossOrigin
public String getIrrigationAllRecord() {
Iterable<IrrigationRecordEntity> list = irrigationRecordService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode",method = RequestMethod.GET)
@CrossOrigin
public String getIrrigationByAdmCode(@RequestParam("admCode") Integer admCode) {
Iterable<IrrigationRecordEntity> list = irrigationRecordService.getByAdmCode(admCode);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/towncode/date",method = RequestMethod.GET)
@CrossOrigin
public String getIrrigationByTownCode(@RequestParam("townCode") String townCode,
@RequestParam("startDateTs") Long startDateTs,
@RequestParam("endDateTs") Long endDateTs) {
if(startDateTs > endDateTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDate sTime = timeMillisToDate(startDateTs);
LocalDate eTime = timeMillisToDate(endDateTs);
Iterable<IrrigationRecordEntity> list = irrigationRecordService.getByTownCodeAndDate(townCode,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode/date",method = RequestMethod.GET)
@CrossOrigin
public String getIrrigationByAdmCodeAndDate(@RequestParam("admCode") Integer admCode,
@RequestParam("startDateTs") Long startDateTs,
@RequestParam("endDateTs") Long endDateTs) {
if(startDateTs > endDateTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDate sTime = timeMillisToDate(startDateTs);
LocalDate eTime = timeMillisToDate(endDateTs);
Iterable<IrrigationRecordEntity> list = irrigationRecordService.getByAdmCodeAndDateTime(admCode,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String irrigationAdd(@Validated({IrrigationRecordQoInsert.class}) @RequestBody IrrigationRecordQo irrigationRecordQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
irrigationRecordService.add(irrigationRecordQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String irrigationDelete(@RequestParam("id") Integer id) {
Optional<IrrigationRecordEntity> irrigationRecordEntity = irrigationRecordService.getById(id);
if(irrigationRecordEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
irrigationRecordService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,123 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.IrrigationSarRecordEntity;
import com.xkrs.microservice.model.qo.IrrigationSarRecordQo;
import com.xkrs.microservice.model.validation.IrrigationSarRecordQoInsert;
import com.xkrs.microservice.service.IrrigationSarRecordService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
import static com.xkrs.microservice.util.DateTimeUtil.timeMillisToDate;
/**
* 灌溉Sar记录数据服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/irrigation-sar-record")
public class IrrigationSarRecordController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private IrrigationSarRecordService irrigationSarRecordService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
@CrossOrigin
public String getIrrigationAllRecord() {
Iterable<IrrigationSarRecordEntity> list = irrigationSarRecordService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode",method = RequestMethod.GET)
@CrossOrigin
public String getIrrigationByAdmCode(@RequestParam("admCode") Integer admCode) {
Iterable<IrrigationSarRecordEntity> list = irrigationSarRecordService.getByAdmCode(admCode);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/towncode/date",method = RequestMethod.GET)
@CrossOrigin
public String getIrrigationByTownCode(@RequestParam("townCode") String townCode,
@RequestParam("startDateTs") Long startDateTs,
@RequestParam("endDateTs") Long endDateTs) {
if(startDateTs > endDateTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDate sTime = timeMillisToDate(startDateTs);
LocalDate eTime = timeMillisToDate(endDateTs);
Iterable<IrrigationSarRecordEntity> list = irrigationSarRecordService.getByTownCodeAndDate(townCode,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/condition",method = RequestMethod.GET)
@CrossOrigin
public String getCondition(@RequestParam("townCode") String townCode,
@RequestParam("startDateTs") Long startDateTs,
@RequestParam("endDateTs") Long endDateTs) {
if(startDateTs > endDateTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDate sTime = timeMillisToDate(startDateTs);
LocalDate eTime = timeMillisToDate(endDateTs);
Iterable<IrrigationSarRecordEntity> list = irrigationSarRecordService.geAllByCondition(townCode,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode/date",method = RequestMethod.GET)
@CrossOrigin
public String getIrrigationByAdmCodeAndDate(@RequestParam("admCode") Integer admCode,
@RequestParam("startDateTs") Long startDateTs,
@RequestParam("endDateTs") Long endDateTs) {
if(startDateTs > endDateTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDate sTime = timeMillisToDate(startDateTs);
LocalDate eTime = timeMillisToDate(endDateTs);
Iterable<IrrigationSarRecordEntity> list = irrigationSarRecordService.getByAdmCodeAndDateTime(admCode,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String irrigationAdd(@Validated({IrrigationSarRecordQoInsert.class}) @RequestBody IrrigationSarRecordQo irrigationSarRecordQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
irrigationSarRecordService.add(irrigationSarRecordQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String irrigationDelete(@RequestParam("id") Integer id) {
Optional<IrrigationSarRecordEntity> irrigationRecordEntity = irrigationSarRecordService.getById(id);
if(irrigationRecordEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
irrigationSarRecordService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,93 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.vo.ShpCityVo;
import com.xkrs.microservice.model.vo.ShpCountyVo;
import com.xkrs.microservice.service.AdministrativeDivisionService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Locale;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.util.NumberUtil.isStrAdmCode;
/**
* 行政区划服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/adm")
public class ShpAdmController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private AdministrativeDivisionService administrativeDivisionService;
@RequestMapping(value="/city/get/all",method = RequestMethod.GET)
public String getAllCity() {
Iterable<ShpCityVo> list = administrativeDivisionService.getAllCity();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/city/get/province-code",method = RequestMethod.GET)
public String getAllCityByProvinceCode(@RequestParam(value="provinceCode") String provinceCode) {
if(!isStrAdmCode(provinceCode)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
Iterable<ShpCityVo> list = administrativeDivisionService.getAllCityByProvinceCode(Integer.valueOf(provinceCode));
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/city/get/city-code",method = RequestMethod.GET)
public String getAllCityCityCode(@RequestParam(value="cityCode") String cityCode) {
if(!isStrAdmCode(cityCode)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
ShpCityVo res = administrativeDivisionService.getCityByCityCode(Integer.valueOf(cityCode));
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
@RequestMapping(value="/county/get/all",method = RequestMethod.GET)
public String getAllCounty() {
Iterable<ShpCountyVo> list = administrativeDivisionService.getAllCounty();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/county/get/province-code",method = RequestMethod.GET)
public String getAllCountyByProvinceCode(@RequestParam(value="provinceCode") String provinceCode) {
if(!isStrAdmCode(provinceCode)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
Iterable<ShpCountyVo> list = administrativeDivisionService.getAllCountyByProvinceCode(
Integer.valueOf(provinceCode));
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/county/get/city-code",method = RequestMethod.GET)
public String getAllCountyByCityCode(@RequestParam(value="cityCode") String cityCode) {
if(!isStrAdmCode(cityCode)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
Iterable<ShpCountyVo> list = administrativeDivisionService.getAllCountyByCityCode(Integer.valueOf(cityCode));
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/county/get/county-code",method = RequestMethod.GET)
public String getAllCountyByCountyCode(@RequestParam(value="countyCode") String countyCode) {
if(!isStrAdmCode(countyCode)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
ShpCountyVo res = administrativeDivisionService.getCountyByCountyCode(Integer.valueOf(countyCode));
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
}

View File

@ -0,0 +1,56 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Locale;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
/**
* 系统管理测试服务
* @author tajochen
*/
@RestController
@RequestMapping(value = "/api")
public class SysManageController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@RequestMapping(value="/hello/role",method = RequestMethod.GET)
@PreAuthorize("hasAnyRole('role_administor','role_system_manager')")
public String hello() {
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"hello vip",locale);
}
@RequestMapping(value="/hello/auth",method = RequestMethod.GET)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user')")
public String world() {
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"world",locale);
}
@RequestMapping(value="/greeting",method = RequestMethod.GET)
public String greeting(@RequestParam(required=false, defaultValue="World") String name,
@RequestHeader(value="User-Agent") String userAgent) {
System.out.println("==== in greeting ====");
System.out.println(userAgent);
UserAgentAnalyzer uaa = UserAgentAnalyzer
.newBuilder()
.hideMatcherLoadStats()
.withCache(10000)
.build();
UserAgent agent = uaa.parse(userAgent);
for (String fieldName: agent.getAvailableFieldNamesSorted()) {
System.out.println(fieldName + " = " + agent.getValue(fieldName));
}
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,name,locale);
}
}

View File

@ -0,0 +1,195 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.SysRoleEntity;
import com.xkrs.microservice.model.qo.SysUserQo;
import com.xkrs.microservice.model.validation.SysUserQoInsert;
import com.xkrs.microservice.model.vo.SysUserVo;
import com.xkrs.microservice.service.SysRoleService;
import com.xkrs.microservice.service.SysUserService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Locale;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
import static com.xkrs.microservice.util.NumberUtil.isStrNumeric;
/**
* 系统用户Controller
* @author tajocehn
*/
@RestController
@RequestMapping(value = "/api/user")
public class SysUserController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private SysUserService sysUserService;
@Resource
private SysRoleService sysRoleService;
/**
* 登录用户Token验证
* @return
*/
@RequestMapping(value = "/logged/check",method = RequestMethod.POST)
public String loginUserTokenCheck(){
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value = "/check/duplicate", method = RequestMethod.GET)
public String checkDuplicate(@RequestParam(value="userName", required=false) String userName){
// 验证用户名是否重复
if(!sysUserService.checkUserName(userName)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"OK",locale);
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@Validated({SysUserQoInsert.class}) @RequestBody SysUserQo userQo,
BindingResult bindingResult){
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 验证用户名是否重复
if(!sysUserService.checkUserName(userQo.getUserName())){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
// 添加新用户
sysUserService.addUser(userQo);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"OK",locale);
}
@RequestMapping(value="/get/all", method = RequestMethod.GET)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
public String getAllSysUser(){
Iterable<SysUserVo> sysUserDtoList = sysUserService.getAllSysUser();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,sysUserDtoList,locale);
}
/**
* 软删除指定id的普通用户
* @param id
* @return
*/
@RequestMapping(value = "/general/delete", method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user')")
public String deleteCustomUser(@RequestParam(value="userId", required=false) int id){
// 验证数据合法性
int res = sysUserService.softDeleteGeneralUser(id);
if(res==1){
return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL,"",locale);
} else {
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}
// @RequestMapping(value = "/update", method = RequestMethod.POST)
// @PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
// public String updateUser(@Validated({SysUserQoUpdate.class}) @RequestBody SysUserQo userQo,
// BindingResult bindingResult){
// // 验证数据合法性
// if(bindingResult.hasErrors()){
// return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
// }
// // 修改用户
// sysUserService.updateSysUser(userQo);
// return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"OK",locale);
// }
@RequestMapping(value = "/update/portrait", method = RequestMethod.POST)
public String updateUserPortrait(@RequestParam(value="portraitId") String portraitId,
@RequestHeader(value="Authorization") String token){
if(!isStrNumeric(portraitId)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
// 头像是否正确
int res = sysUserService.updateSysUserPortrait(userName, Integer.valueOf(portraitId));
if(res==1){
return outputEncapsulationObject(PromptMessageEnum.DATA_WRONG,"",locale);
}
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"OK",locale);
}
@RequestMapping(value = "/update/password", method = RequestMethod.POST)
public String updateUserPassword(@RequestParam(value="oldPassword") String oldPassword,
@RequestParam(value="newPassword") String newPassword,
@RequestHeader(value="Authorization") String token){
// 获取当前用户名
String userName = getTokenUserName(token);
int res = sysUserService.updateSysUserPassword(userName,oldPassword,newPassword);
final int r1 = 1;
final int r2 = 2;
final int r3 = 3;
if(res==r1){
return outputEncapsulationObject(PromptMessageEnum.DATA_WRONG,"未知错误",locale);
} else if(res==r2){
return outputEncapsulationObject(PromptMessageEnum.DATA_WRONG,"旧密码错误",locale);
} else if(res==r3){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"新密码不符合规则",locale);
}
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"OK",locale);
}
@RequestMapping(value = "/get/info", method = RequestMethod.GET)
public String getUserInfo(@RequestHeader(value="Authorization") String token){
// 获取当前用户名
String userName = getTokenUserName(token);
SysUserVo sysUserVo = sysUserService.getSysUserVoByUserName(userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,sysUserVo,locale);
}
@RequestMapping(value="/set/forbidden",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
public String setUserForbidden(@RequestParam(value="userName", required=true) String userName) {
String generalRole = "role_general_user";
String farmerRole = "role_farm_user";
if(sysUserService.checkUserName(userName)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"userName 错误",locale);
}
List<SysRoleEntity> list1 = sysRoleService.getSysRoleListByUserName(userName);
SysRoleEntity sysRoleEntity = list1.get(0);
if(generalRole.equals(sysRoleEntity.getRoleName()) || farmerRole.equals(sysRoleEntity.getRoleName())){
sysUserService.disableSysUser(userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
return outputEncapsulationObject(PromptMessageEnum.USER_NO_PERMISSION,"",locale);
}
@RequestMapping(value="/set/enable",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
public String setUserEnable(@RequestParam(value="userName", required=true) String userName) {
String generalRole = "role_general_user";
String farmerRole = "role_farm_user";
if(sysUserService.checkUserName(userName)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"userName 错误",locale);
}
List<SysRoleEntity> list1 = sysRoleService.getSysRoleListByUserName(userName);
SysRoleEntity sysRoleEntity = list1.get(0);
if(generalRole.equals(sysRoleEntity.getRoleName()) || farmerRole.equals(sysRoleEntity.getRoleName())){
sysUserService.enableSysUser(userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
return outputEncapsulationObject(PromptMessageEnum.USER_NO_PERMISSION,"",locale);
}
}

View File

@ -0,0 +1,110 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.TifProductEntity;
import com.xkrs.microservice.model.qo.TifProductQo;
import com.xkrs.microservice.model.validation.TifProductQoInsert;
import com.xkrs.microservice.service.TifProductService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
import static com.xkrs.microservice.util.DateTimeUtil.timeMillisToDate;
/**
* 栅格产品管理服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/tif-product")
public class TifProductController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private TifProductService tifProductService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
public String getAllFiles() {
Iterable<TifProductEntity> list = tifProductService.getAllFile();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/product-code",method = RequestMethod.GET)
public String getByProductCode(@RequestParam("productCode") String productCode) {
TifProductEntity res = tifProductService.getByProductCode(productCode);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
@RequestMapping(value="/get/product-type",method = RequestMethod.GET)
public String getByProductType(@RequestParam("productType") String productType) {
Iterable<TifProductEntity> list = tifProductService.getByProductType(productType);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode/product-type",method = RequestMethod.GET)
public String getByAdmCodeAndProductType(@RequestParam("admCode") Integer admCode,
@RequestParam("productType") String productType) {
Iterable<TifProductEntity> list = tifProductService.getByAdmCodeAndProductType(admCode,productType);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode/product-type/date",method = RequestMethod.GET)
public String getByAdmCodeAndProductTypeAndDate(@RequestParam("admCode") Integer admCode,
@RequestParam("productType") String productType,
@RequestParam("startDateTs") Long startDateTs,
@RequestParam("endDateTs") Long endDateTs) {
if(startDateTs > endDateTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDate sTime = timeMillisToDate(startDateTs);
LocalDate eTime = timeMillisToDate(endDateTs);
Iterable<TifProductEntity> list = tifProductService.getByAdmCodeAndProductTypeAndDate(admCode,productType,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String fileAdd(@Validated({TifProductQoInsert.class}) @RequestBody TifProductQo tifProductQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 验证数据是否存在
if(tifProductService.getByProductCode(tifProductQo.getProductCode())!=null){
return outputEncapsulationObject(PromptMessageEnum.DATA_REPEAT,"数据已存在",locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
tifProductService.add(tifProductQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String fileDelete(@RequestParam("id") Integer id) {
Optional<TifProductEntity> tifProductEntity = tifProductService.getById(id);
if(tifProductEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
tifProductService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,128 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.TypicalFarmerEntity;
import com.xkrs.microservice.model.qo.TypicalFarmerQo;
import com.xkrs.microservice.model.validation.TypicalFarmerQoInsert;
import com.xkrs.microservice.model.validation.TypicalFarmerQoUpdate;
import com.xkrs.microservice.service.SysUserService;
import com.xkrs.microservice.service.TypicalFarmerService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
/**
* 典型区农户表管理
* @author tajochen
*/
@RestController
@RequestMapping("/api/typical-farmer")
public class TypicalFarmerController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private TypicalFarmerService typicalFarmerService;
@Resource
private SysUserService sysUserService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
@CrossOrigin
public String getAllRecord() {
Iterable<TypicalFarmerEntity> list = typicalFarmerService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/xzdm",method = RequestMethod.GET)
@CrossOrigin
public String getByTownCode(@RequestParam("xzdm") String xzdm) {
Iterable<TypicalFarmerEntity> list = typicalFarmerService.getByTownCode(xzdm);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/qxdm",method = RequestMethod.GET)
@CrossOrigin
public String getByCountyCode(@RequestParam("qxdm") Integer qxdm) {
Iterable<TypicalFarmerEntity> list = typicalFarmerService.getByCountyCode(qxdm);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/lxr",method = RequestMethod.GET)
@CrossOrigin
public String getByLxr(@RequestParam("lxr") String lxr) {
Iterable<TypicalFarmerEntity> list = typicalFarmerService.getByLxr(lxr);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/user-name",method = RequestMethod.GET)
@CrossOrigin
public String getByUserName(@RequestParam("userName") String userName) {
Optional<TypicalFarmerEntity> obj = typicalFarmerService.getByTel(userName);
if(obj.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
} else {
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,obj.get(),locale);
}
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@CrossOrigin
public String dataAdd(@Validated({TypicalFarmerQoInsert.class}) @RequestBody TypicalFarmerQo typicalFarmerQo,
BindingResult bindingResult) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 验证用户名是否重复
if(!sysUserService.checkUserName(typicalFarmerQo.getTel())){
return outputEncapsulationObject(PromptMessageEnum.USER_ALREADY_EXIST,"用户名已存在!",locale);
}
// 添加新用户
typicalFarmerService.add(typicalFarmerQo,typicalFarmerQo.getTel());
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/update",method = RequestMethod.POST)
@CrossOrigin
public String dataUpdate(@Validated({TypicalFarmerQoUpdate.class}) @RequestBody TypicalFarmerQo typicalFarmerQo,
BindingResult bindingResult) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 验证用户名是否存在
if(sysUserService.checkUserName(typicalFarmerQo.getTel())){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"用户名不存在!",locale);
}
// 添加新用户
typicalFarmerService.update(typicalFarmerQo);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String dataDelete(@RequestParam("id") Integer id) {
Optional<TypicalFarmerEntity> typicalPlotEntity = typicalFarmerService.getById(id);
if(typicalPlotEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
typicalFarmerService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,139 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.TypicalPlotEntity;
import com.xkrs.microservice.model.qo.TypicalPlotQo;
import com.xkrs.microservice.model.validation.TypicalPlotQoInsert;
import com.xkrs.microservice.model.validation.TypicalPlotQoUpdate;
import com.xkrs.microservice.service.TypicalPlotService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
/**
* 典型区地块管理
* @author tajochen
*/
@RestController
@RequestMapping("/api/typical-plot")
public class TypicalPlotController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private TypicalPlotService typicalPlotService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
@CrossOrigin
public String getAllRecord() {
Iterable<TypicalPlotEntity> list = typicalPlotService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/qxdm",method = RequestMethod.GET)
@CrossOrigin
public String getByCountyCode(@RequestParam("qxdm") Integer qxdm) {
Iterable<TypicalPlotEntity> list = typicalPlotService.getByCountyCode(qxdm);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/xzdm",method = RequestMethod.GET)
@CrossOrigin
public String getByTownCode(@RequestParam("xzdm") String xzdm) {
Iterable<TypicalPlotEntity> list = typicalPlotService.getByTownCode(xzdm);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/dkbh",method = RequestMethod.GET)
@CrossOrigin
public String getByDkbh(@RequestParam("dkbh") String dkbh) {
Optional<TypicalPlotEntity> res = typicalPlotService.getByDkbh(dkbh);
if(res.isPresent()){
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res.get(),locale);
}
return outputEncapsulationObject(PromptMessageEnum.DATA_WRONG,"dkbh 不存在",locale);
}
@RequestMapping(value="/get/lxr",method = RequestMethod.GET)
@CrossOrigin
public String getByLxr(@RequestParam("lxr") String lxr) {
Iterable<TypicalPlotEntity> list = typicalPlotService.getByLxr(lxr);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/tel",method = RequestMethod.GET)
@CrossOrigin
public String getByTel(@RequestParam("tel") String tel) {
Iterable<TypicalPlotEntity> list = typicalPlotService.getByTel(tel);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/user-name",method = RequestMethod.GET)
@CrossOrigin
public String getByUserName(@RequestParam("userName") String userName) {
Iterable<TypicalPlotEntity> list = typicalPlotService.getByTel(userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/update",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String dataUpdate(@Validated({TypicalPlotQoUpdate.class}) @RequestBody TypicalPlotQo typicalPlotQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
typicalPlotService.update(typicalPlotQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor','auth_farm_user')")
@CrossOrigin
public String dataAdd(@Validated({TypicalPlotQoInsert.class}) @RequestBody TypicalPlotQo typicalPlotQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 监测地块编号是否存在
Optional<TypicalPlotEntity> typicalPlotEntity = typicalPlotService.getByDkbh(typicalPlotQo.getDkbh());
if(typicalPlotEntity.isPresent()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"地块编号已存在",locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
typicalPlotService.add(typicalPlotQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor','auth_farm_user')")
@CrossOrigin
public String dataDelete(@RequestParam("id") Integer id) {
Optional<TypicalPlotEntity> typicalPlotEntity = typicalPlotService.getById(id);
if(typicalPlotEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
typicalPlotService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,131 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.TypicalPlotIrrigationEntity;
import com.xkrs.microservice.model.qo.TypicalPlotIrrigationQo;
import com.xkrs.microservice.model.validation.TypicalPlotIrrigationQoInsert;
import com.xkrs.microservice.service.TypicalPlotIrrigationService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
import static com.xkrs.microservice.util.DateTimeUtil.timeMillisToTime;
/**
* 灌溉信息表管理
* @author tajochen
*/
@RestController
@RequestMapping("/api/typical-plot-irrigation")
public class TypicalPlotIrrigationController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private TypicalPlotIrrigationService typicalPlotIrrigationService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
@CrossOrigin
public String getAllRecord() {
Iterable<TypicalPlotIrrigationEntity> list = typicalPlotIrrigationService.getAllRecord();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/ggbh",method = RequestMethod.GET)
@CrossOrigin
public String getByGgbh(@RequestParam("ggbh") String ggbh) {
Optional<TypicalPlotIrrigationEntity> list = typicalPlotIrrigationService.getByGgbh(ggbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/qxbh",method = RequestMethod.GET)
@CrossOrigin
public String getByQxbh(@RequestParam("qxbh") Integer qxbh) {
Iterable<TypicalPlotIrrigationEntity> list = typicalPlotIrrigationService.getByQxbh(qxbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/dkbh",method = RequestMethod.GET)
@CrossOrigin
public String getByDkbh(@RequestParam("dkbh") String dkbh) {
Iterable<TypicalPlotIrrigationEntity> list = typicalPlotIrrigationService.getByDkbh(dkbh);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/user-name",method = RequestMethod.GET)
@CrossOrigin
public String getByUserName(@RequestParam("userName") String userName) {
Iterable<TypicalPlotIrrigationEntity> list = typicalPlotIrrigationService.getByUserName(userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/condition",method = RequestMethod.GET)
@CrossOrigin
public String getByCondition(@RequestParam("xzbh") String xzbh,
@RequestParam("cropCode") Integer cropCode,
@RequestParam("sTimeTs") Long sTime,
@RequestParam("eTimeTs") Long eTime) {
List<TypicalPlotIrrigationEntity> list = typicalPlotIrrigationService.getAllByCondition(xzbh,cropCode,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/time",method = RequestMethod.GET)
@CrossOrigin
public String getByQxbhAndCreateTimeBetween(@RequestParam("qxdm") Integer qxdm,@RequestParam("sTimeTs") Long sTimeTs,@RequestParam("eTimeTs") Long eTimeTs) {
if(sTimeTs > eTimeTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDateTime sTime = timeMillisToTime(sTimeTs);
LocalDateTime eTime = timeMillisToTime(eTimeTs);
Iterable<TypicalPlotIrrigationEntity> list = typicalPlotIrrigationService.findAllByQxbhAndStrtimeBetween(qxdm,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor','auth_farm_user')")
@CrossOrigin
public String dataAdd(@Validated({TypicalPlotIrrigationQoInsert.class}) @RequestBody TypicalPlotIrrigationQo typicalPlotIrrigationQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 验证灌溉编号是否存在
Optional<TypicalPlotIrrigationEntity> typicalPlotIrrigationEntity = typicalPlotIrrigationService.getByGgbh(typicalPlotIrrigationQo.getGgbh());
if(typicalPlotIrrigationEntity.isPresent()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"灌溉编号重复!",locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
typicalPlotIrrigationService.add(typicalPlotIrrigationQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String dataDelete(@RequestParam("id") Integer id) {
Optional<TypicalPlotIrrigationEntity> typicalPlotIrrigationEntity = typicalPlotIrrigationService.getById(id);
if(typicalPlotIrrigationEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
typicalPlotIrrigationService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,111 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.entity.WcsRecordEntity;
import com.xkrs.microservice.model.qo.WcsRecordQo;
import com.xkrs.microservice.model.validation.WcsRecordQoInsert;
import com.xkrs.microservice.service.WcsRecordService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Locale;
import java.util.Optional;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.common.tool.TokenUtil.getTokenUserName;
import static com.xkrs.microservice.util.DateTimeUtil.timeMillisToDate;
/**
* 栅格服务管理
* @author tajochen
*/
@RestController
@RequestMapping("/api/wcs-record")
public class WcsRecordController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private WcsRecordService wcsRecordService;
@RequestMapping(value="/get/all",method = RequestMethod.GET)
public String getAllFiles() {
Iterable<WcsRecordEntity> list = wcsRecordService.getAllService();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/service-code",method = RequestMethod.GET)
public String getByProductCode(@RequestParam("serviceCode") String serviceCode) {
WcsRecordEntity res = wcsRecordService.getByServiceCode(serviceCode);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
@RequestMapping(value="/get/product-type",method = RequestMethod.GET)
public String getByProductType(@RequestParam("productType") String productType) {
Iterable<WcsRecordEntity> list = wcsRecordService.getByProductType(productType);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode/product-type",method = RequestMethod.GET)
public String getByAdmCodeAndProductTypeAndDate(@RequestParam("admCode") Integer admCode,
@RequestParam("productType") String productType) {
Iterable<WcsRecordEntity> list = wcsRecordService.getByAdmCodeAndProductType(admCode,productType);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/get/admcode/product-type/date",method = RequestMethod.GET)
public String getByAdmCodeAndProductTypeAndDate(@RequestParam("admCode") Integer admCode,
@RequestParam("productType") String productType,
@RequestParam("startDateTs") Long startDateTs,
@RequestParam("endDateTs") Long endDateTs) {
if(startDateTs > endDateTs){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
LocalDate sTime = timeMillisToDate(startDateTs);
LocalDate eTime = timeMillisToDate(endDateTs);
Iterable<WcsRecordEntity> list = wcsRecordService.getByAdmCodeAndProductTypeAndDate(admCode,productType,sTime,eTime);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,list,locale);
}
@RequestMapping(value="/add",method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user','auth_administor')")
@CrossOrigin
public String fileAdd(@Validated({WcsRecordQoInsert.class}) @RequestBody WcsRecordQo wcsRecordQo,
BindingResult bindingResult,@RequestHeader(value="Authorization") String token) {
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 验证数据是否存在
if(wcsRecordService.getByServiceCode(wcsRecordQo.getServiceCode())!=null){
return outputEncapsulationObject(PromptMessageEnum.DATA_REPEAT,"数据已存在",locale);
}
// 获取当前用户名
String userName = getTokenUserName(token);
wcsRecordService.add(wcsRecordQo,userName);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value="/delete",method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
@CrossOrigin
public String fileDelete(@RequestParam("id") Integer id) {
Optional<WcsRecordEntity> wcsRecordEntity = wcsRecordService.getById(id);
if(wcsRecordEntity.isEmpty()){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"参数错误",locale);
}
wcsRecordService.delete(id);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}

View File

@ -0,0 +1,92 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.common.tool.PageBean;
import com.xkrs.microservice.common.tool.WeatherGet;
import com.xkrs.microservice.dao.WeatherDao;
import com.xkrs.microservice.model.entity.WeatherEntity;
import com.xkrs.microservice.service.WeatherService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
/**
* @author XinYiSong
*/
@RestController
@RequestMapping("/api/weather-station")
public class WeatherController {
@Resource
private WeatherGet weatherGet;
@Resource
private WeatherService weatherService;
@Resource
private WeatherDao weatherDao;
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
/**
* 测试
* @return
*/
@PostMapping("/insertWeather")
public void insertWeather(){
weatherGet.findWeather();
}
/**
* 查询相关的天气和气候
* @param map
* @return
*/
@PostMapping("/queryWeather")
public String queryWeather(@RequestBody Map map){
Integer pageNo = (Integer) map.get("pageNo");
String addTimeStart = (String) map.get("addTimeStart");
String addTimeEnd = (String) map.get("addTimeEnd");
PageBean pageBean = weatherService.queryWeather(pageNo, addTimeStart, addTimeEnd);
if(pageBean.getList() == null || pageBean.getList().size() == 0){
return outputEncapsulationObject(PromptMessageEnum.DATA_NONE,"暂时没有相关数据",locale);
}
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,pageBean,locale);
}
/**
* 查询气候最新的一条信息
* @return
*/
@GetMapping("/selectNewest")
public String selectNewest(){
WeatherEntity weatherEntity = weatherDao.selectNewest();
if(weatherEntity == null){
return outputEncapsulationObject(PromptMessageEnum.DATA_NONE,"暂时没有相关数据",locale);
}
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,weatherEntity,locale);
}
/**
* 根据时间查询气象信息
* 修改
* @param map
* @return
*/
@PostMapping("/selectWeather")
public String selectWeather(@RequestBody Map map){
String addTimeStart = (String) map.get("addTimeStart");
String addTimeEnd = (String) map.get("addTimeEnd");
List<WeatherEntity> weatherEntities = weatherService.selectWeather(addTimeStart, addTimeEnd);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,weatherEntities,locale);
}
}

View File

@ -0,0 +1,53 @@
package com.xkrs.microservice.controller;
import com.xkrs.microservice.common.encapsulation.PromptMessageEnum;
import com.xkrs.microservice.model.vo.ForecastWeather7DayVo;
import com.xkrs.microservice.model.vo.RealTimeWeatherVo;
import com.xkrs.microservice.service.MeteorologicalService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Locale;
import static com.xkrs.microservice.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.microservice.util.NumberUtil.isStrAdmCode;
/**
* 行政区划气象站点服务
* @author tajochen
*/
@RestController
@RequestMapping("/api/weather")
public class WeatherStationController {
/**
* 获取区域信息
*/
Locale locale = LocaleContextHolder.getLocale();
@Resource
private MeteorologicalService meteorologicalService;
@RequestMapping(value="/get/now",method = RequestMethod.GET)
public String getWeatherNowByAdmCode(@RequestParam(value="admCode") String admCode) {
if(!isStrAdmCode(admCode)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
RealTimeWeatherVo res = meteorologicalService.getWeatherNowByAdmCode(Integer.valueOf(admCode));
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
@RequestMapping(value="/get/forecast",method = RequestMethod.GET)
public String getWeatherForecastByAdmCode(@RequestParam(value="admCode") String admCode) {
if(!isStrAdmCode(admCode)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
ForecastWeather7DayVo res = meteorologicalService.getWeatherForecastByAdmCode(Integer.valueOf(admCode));
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,res,locale);
}
}

View File

@ -0,0 +1,19 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.FileAppEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* AppFileDao
* @author tajochen
*/
public interface AppFileDao extends JpaRepository<FileAppEntity,Integer> {
/**
* 获取指定版本号的记录
* @param versionNumber 版本号
* @return
*/
Iterable<FileAppEntity> findByVersionNumber(String versionNumber);
}

View File

@ -0,0 +1,49 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.CropClassifyRecordEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDate;
/**
* CropClassifyRecordDao
* @author tajochen
*/
public interface CropClassifyRecordDao extends JpaRepository<CropClassifyRecordEntity,Integer> {
/**
* 获取指定行政区划代码
* @param countyCode 行政区划代码
* @return
*/
Iterable<CropClassifyRecordEntity> findByCountyCode(Integer countyCode);
/**
* 获取指定街道代码
* @param townCode 街道代码
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
Iterable<CropClassifyRecordEntity> findByTownCodeAndCropDateBetween(String townCode,LocalDate startDate,LocalDate endDate);
/**
* 获取指定街道代码
* @param townCode 街道代码
* @param cropCode 作物代码
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
Iterable<CropClassifyRecordEntity> findByTownCodeAndCropCodeAndCropDateBetween(String townCode,Integer cropCode ,LocalDate startDate,LocalDate endDate);
/**
* 获取指定行政区划代码和指定日期段
* @param countyCode 行政区划代码
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
Iterable<CropClassifyRecordEntity> findByCountyCodeAndCropDateBetween(Integer countyCode,LocalDate startDate,LocalDate endDate);
}

View File

@ -0,0 +1,12 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.DicCropClassifyEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* DicLandClassifyDao
* @author tajochen
*/
public interface DicCropClassifyDao extends JpaRepository<DicCropClassifyEntity,Integer> {
}

View File

@ -0,0 +1,12 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.DicDroughtClassifyEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* DicLandClassifyDao
* @author tajochen
*/
public interface DicDroughtClassifyDao extends JpaRepository<DicDroughtClassifyEntity,Integer> {
}

View File

@ -0,0 +1,12 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.DicLandClassifyEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* DicLandClassifyDao
* @author tajochen
*/
public interface DicLandClassifyDao extends JpaRepository<DicLandClassifyEntity,Integer> {
}

View File

@ -0,0 +1,12 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.DicProductEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* DicProductDao
* @author tajochen
*/
public interface DicProductDao extends JpaRepository<DicProductEntity,Integer> {
}

View File

@ -0,0 +1,12 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.DicSoilClassifyEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* DicSoilClassifyDao
* @author tajochen
*/
public interface DicSoilClassifyDao extends JpaRepository<DicSoilClassifyEntity,Integer> {
}

View File

@ -0,0 +1,51 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.FarmingInfoEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
/**
* FarmingInfoDao
* @author tajochen
*/
public interface FarmingInfoDao extends JpaRepository<FarmingInfoEntity,Integer> {
/**
* 查找农情信息根据地块编号
* @param dkbh 地块编号
* @return
*/
Iterable<FarmingInfoEntity> findAllByDkbh(String dkbh);
/**
* 查找农情信息根据作物代码区县编号
* @param zwbh 作物编号
* @param qxbh 区县编号
* @return
*/
Iterable<FarmingInfoEntity> findAllByZwdmAndQxbh(Integer zwbh,Integer qxbh);
/**
* 查找农情信息根据区县编号
* @param qxbh 区县编号
* @return
*/
Iterable<FarmingInfoEntity> findAllByQxbh(Integer qxbh);
/**
* 查找最新农情信息根据区县编号
* @param qxbh 区县编号
* @return
*/
@Query(value = "SELECT * FROM farming_info A WHERE A.create_time = ( SELECT MAX ( B.create_time ) " +
"FROM farming_info B WHERE A.dkbh = B.dkbh ) AND A.qxbh = :qxbh", nativeQuery = true)
Iterable<FarmingInfoEntity> findNewAllByQxbh(Integer qxbh);
/**
* 查找农情信息根据姓名
* @param userName 联系人姓名
* @return
*/
Iterable<FarmingInfoEntity> findAllByAddUserName(String userName);
}

View File

@ -0,0 +1,12 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.FileDocumentEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* FileDocumentDao
* @author tajochen
*/
public interface FileDocumentDao extends JpaRepository<FileDocumentEntity,Integer> {
}

View File

@ -0,0 +1,31 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.HydrologicalStationEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDateTime;
/**
* HydrologicalStationDao
* @author tajochen
*/
public interface HydrologicalStationDao extends JpaRepository<HydrologicalStationEntity,Integer> {
/**
* 根据时间段查询水文站点数据
* @param sTime 开始时间
* @param eTime 结束时间
* @return
*/
Iterable<HydrologicalStationEntity> findByRecordTimeBetween(LocalDateTime sTime,LocalDateTime eTime);
/**
* 根据时间段查询水文站点数据
* @param name 站点名称
* @param sTime 开始时间
* @param eTime 结束时间
* @return
*/
Iterable<HydrologicalStationEntity> findByNameAndRecordTimeBetween(String name, LocalDateTime sTime,LocalDateTime eTime);
}

View File

@ -0,0 +1,26 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.IndependentCheckEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* IndependentCheckDao
* @author tajochen
*/
public interface IndependentCheckDao extends JpaRepository<IndependentCheckEntity,Integer> {
/**
* 查找自主核查结果根据区县代码
* @param qxdm 区县代码
* @return
*/
Iterable<IndependentCheckEntity> findByQxdm(Integer qxdm);
/**
* 查找自主核查结果根据用户名
* @param userName 用户名
* @return
*/
Iterable<IndependentCheckEntity> findAllByAddUserName(String userName);
}

View File

@ -0,0 +1,52 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.IrrigationCheckEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDateTime;
import java.util.Optional;
/**
* IrrigationCheckDao
* @author tajochen
*/
public interface IrrigationCheckDao extends JpaRepository<IrrigationCheckEntity,Integer> {
/**
* 查找灌溉核查结果根据灌溉编号
* @param ggbh 灌溉编号
* @return
*/
Optional<IrrigationCheckEntity> findByGgbh(String ggbh);
/**
* 查找灌溉核查结果根据区县编号
* @param qxbh 区县编号
* @return
*/
Iterable<IrrigationCheckEntity> findAllByQxbh(Integer qxbh);
/**
* 查找灌溉核查结果根据地块编号
* @param dkbh 地块编号
* @return
*/
Iterable<IrrigationCheckEntity> findAllByDkbh(String dkbh);
/**
* 查找灌溉核查结果根据区县编号和时间
* @param qxbh 区县编号
* @param sTime 开始时间
* @param eTime 结束时间
* @return
*/
Iterable<IrrigationCheckEntity> findAllByQxbhAndCreateTimeBetween(Integer qxbh,LocalDateTime sTime,LocalDateTime eTime);
/**
* 查找灌溉核查结果用户名
* @param userName 用户名
* @return
*/
Iterable<IrrigationCheckEntity> findByAddUserName(String userName);
}

View File

@ -0,0 +1,39 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.IrrigationRecordEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDate;
/**
* IrrigationRecordDao
* @author tajochen
*/
public interface IrrigationRecordDao extends JpaRepository<IrrigationRecordEntity,Integer> {
/**
* 获取指定行政区划代码
* @param countyCode 区县代码
* @return
*/
Iterable<IrrigationRecordEntity> findByCountyCode(Integer countyCode);
/**
* 获取指定街道代码
* @param townCode 街道代码
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
Iterable<IrrigationRecordEntity> findByTownCodeAndIrrigationDateBetween(String townCode,LocalDate startDate,LocalDate endDate);
/**
* 获取指定行政区划代码和指定日期段
* @param countyCode 行政区划代码
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
Iterable<IrrigationRecordEntity> findByCountyCodeAndIrrigationDateBetween(Integer countyCode,LocalDate startDate,LocalDate endDate);
}

View File

@ -0,0 +1,52 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.IrrigationSarRecordEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalDate;
/**
* IrrigationSarRecordDao
* @author tajochen
*/
public interface IrrigationSarRecordDao extends JpaRepository<IrrigationSarRecordEntity,Integer> {
/**
* 获取指定行政区划代码
* @param countyCode 区县代码
* @return
*/
Iterable<IrrigationSarRecordEntity> findByCountyCode(Integer countyCode);
/**
* 获取指定街道代码
* @param townCode 街道代码
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
Iterable<IrrigationSarRecordEntity> findByTownCodeAndIrrigationDateBetween(String townCode,LocalDate startDate,LocalDate endDate);
/**
* 获取指定数据动态多条件
* @param townCode 街道代码
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
@Query(value = "SELECT * FROM irrigation_sar_record WHERE CASE WHEN ( :townCode ) <> '' " +
"THEN town_code = :townCode ELSE 1 = 1 END " +
"AND irrigation_date <= :endDate AND irrigation_date >= :startDate ; ", nativeQuery = true)
Iterable<IrrigationSarRecordEntity> getAllByCondition(String townCode,LocalDate startDate,LocalDate endDate);
/**
* 获取指定行政区划代码和指定日期段
* @param countyCode 行政区划代码
* @param startDate 开始日期
* @param endDate 结束日期
* @return
*/
Iterable<IrrigationSarRecordEntity> findByCountyCodeAndIrrigationDateBetween(Integer countyCode,LocalDate startDate,LocalDate endDate);
}

View File

@ -0,0 +1,19 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.MeteorologicalStationEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* RelAdmWeatherStationDao
* @author tajochen
*/
public interface MeteorologicalStationDao extends JpaRepository<MeteorologicalStationEntity,Integer> {
/**
* 获取天气城市站点信息
* @param code
* @return
*/
MeteorologicalStationEntity findByCode(Integer code);
}

View File

@ -0,0 +1,46 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.ShpCityEntity;
import com.xkrs.microservice.model.vo.ShpCityVo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* ShpCityDao 表实体类
* @author tajochen
*/
public interface ShpCityDao extends JpaRepository<ShpCityEntity,Integer> {
/**
* 查找所有地级市
* @return
*/
@Query(value = "select new com.xkrs.microservice.model.vo.ShpCityVo (city.id,city.code,city.name,city.proCode," +
"city.proName,city.shapeArea,city.center) " +
"from ShpCityEntity city ")
List<ShpCityVo> selectAllCity();
/**
* 查找所有地级市根据省级代码
* @param proCode 省级代码
* @return
*/
@Query(value = "select new com.xkrs.microservice.model.vo.ShpCityVo (city.id,city.code,city.name,city.proCode," +
"city.proName,city.shapeArea,city.center) " +
"from ShpCityEntity city where city.proCode = :proCode")
List<ShpCityVo> selectAllCityByProvinceCode(@Param("proCode") Integer proCode);
/**
* 查找指定地级市根据地级市代码
* @param code 地级市代码
* @return
*/
@Query(value = "select new com.xkrs.microservice.model.vo.ShpCityVo (city.id,city.code,city.name,city.proCode," +
"city.proName,city.shapeArea,city.center) " +
"from ShpCityEntity city where city.code = :code")
ShpCityVo selectCityByCityCode(@Param("code") Integer code);
}

View File

@ -0,0 +1,59 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.ShpCountyEntity;
import com.xkrs.microservice.model.vo.ShpCountyVo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* ShpCountyDao 表实体类
* @author tajochen
*/
public interface ShpCountyDao extends JpaRepository<ShpCountyEntity,Integer> {
/**
* 查找所有区县
* @return
*/
@Query(value = "select new com.xkrs.microservice.model.vo.ShpCountyVo (county.id,county.code,county.name," +
"county.cityCode,county.cityName,county.proCode,county.proName,county.shapeArea,county.center," +
"county.memo) " +
"from ShpCountyEntity county")
List<ShpCountyVo> selectAllCounty();
/**
* 查找所有区县根据省级代码
* @param proCode 省级代码
* @return
*/
@Query(value = "select new com.xkrs.microservice.model.vo.ShpCountyVo (county.id,county.code,county.name," +
"county.cityCode,county.cityName,county.proCode,county.proName,county.shapeArea,county.center," +
"county.memo) " +
"from ShpCountyEntity county where county.proCode= :proCode")
List<ShpCountyVo> selectAllCountyByProvinceCode(@Param("proCode") Integer proCode);
/**
* 查找所有区县根据市级代码
* @param cityCode 地级市代码
* @return
*/
@Query(value = "select new com.xkrs.microservice.model.vo.ShpCountyVo (county.id,county.code,county.name," +
"county.cityCode,county.cityName,county.proCode,county.proName,county.shapeArea,county.center," +
"county.memo) " +
"from ShpCountyEntity county where county.cityCode= :cityCode")
List<ShpCountyVo> selectAllCountyByCityCode(@Param("cityCode") Integer cityCode);
/**
* 查找指定区县根据区县代码
* @param code 区县代码
* @return
*/
@Query(value = "select new com.xkrs.microservice.model.vo.ShpCountyVo (county.id,county.code,county.name," +
"county.cityCode,county.cityName,county.proCode,county.proName,county.shapeArea,county.center," +
"county.memo) " +
"from ShpCountyEntity county where county.code= :code")
ShpCountyVo selectCountyByCountyCode(@Param("code") Integer code);
}

View File

@ -0,0 +1,26 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.SysAuthorityEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* SysAuthorityDao
* @author tajochen
*/
public interface SysAuthorityDao extends JpaRepository<SysAuthorityEntity,Integer> {
/**
* 查询权限实体列表根据用户名 Object[]
* @param userName 用户名
* @return 用户实体
*/
@Query(value = "SELECT a.id, a.authority_name, a.authority_name_zh, a.authority_desc " +
"FROM sys_authority a,rel_role_authority ra,sys_role r " +
"WHERE r.id = ra.role_id AND ra.authority_id = a.id AND r.id " +
"IN (SELECT r.id FROM sys_user u,sys_role r,rel_user_role ur " +
" WHERE u.user_name = :userName AND u.id = ur.user_id AND ur.role_id = r.id)", nativeQuery = true)
List<SysAuthorityEntity> selectByUserName(@Param("userName") String userName);
}

View File

@ -0,0 +1,61 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.SysRoleEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* SysRoleDao
* @author tajochen
*/
public interface SysRoleDao extends JpaRepository<SysRoleEntity,Integer> {
/**
* 查询用户角色列表根据用户id
* @param id 编号
* @return
*/
@Query(value = "SELECT sys_role.id,sys_role.role_name,sys_role.role_name_zh,sys_role.role_desc " +
"FROM sys_role,rel_user_role " +
"WHERE sys_role.id = rel_user_role.role_id " +
"AND rel_user_role.user_id = :id ", nativeQuery = true)
List<SysRoleEntity> selectByUserId(@Param("id") Integer id);
/**
* 查询用户角色列表根据用户名
* @param userName 用户名
* @return
*/
@Query(value = "SELECT sys_role.id,sys_role.role_name,sys_role.role_name_zh,sys_role.role_desc " +
"FROM sys_role,rel_user_role,sys_user "+
"WHERE sys_role.ID = rel_user_role.role_id " +
"AND rel_user_role.user_id = sys_user.id " +
"AND rel_user_role.user_id = sys_user.id " +
"AND sys_user.user_name = :userName ", nativeQuery = true)
List<SysRoleEntity> selectByUserName(@Param("userName") String userName);
// /**
// * 根据用户名修改用户角色
// */
// @Modifying
// @Query(value = "UPDATE sys_user SET last_entry_time = now(), last_entry_ip = :ipAddress " +
// "WHERE user_name = :userName ;", nativeQuery = true)
// int updateUserRoleByUserName(@Param("userName") String userName);
/**
* 添加用户角色根据用户名和角色名
* @param userName 用户名
* @param roleName 角色名
* @return
*/
@Modifying
@Query(value = "INSERT INTO rel_user_role (id,role_id, user_id) " +
"SELECT nextval('rel_user_role_seq'),sys_role.ID,sys_user.ID FROM sys_role,sys_user " +
"WHERE sys_role.role_name = :roleName AND sys_user.user_name = :userName ", nativeQuery = true)
int insertRelUserRole(@Param("userName") String userName,@Param("roleName") String roleName);
}

View File

@ -0,0 +1,105 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.SysUserEntity;
import com.xkrs.microservice.model.vo.SysUserVo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* SysUserDao
* @author tajochen
*/
public interface SysUserDao extends JpaRepository<SysUserEntity,Integer> {
/**
* 获取指定userName
* @param userName 用户名
* @return
*/
SysUserEntity findByUserName(String userName);
/**
* 获取指定用户Vo未删除已激活
* @param userName 用户名
* @return
*/
@Query(value = "select new com.xkrs.microservice.model.vo.SysUserVo (u.id, u.userName, u.nickName,u.realName, u.userCode, " +
"u.sex, u.telephone, u.email, u.admCode, u.address,u.birthday,u.signature,r.roleNameZh, u.portraitId," +
"u.statusCode,u.addTime,u.lastEntryTime,u.lastEntryIp,u.memo) from SysUserEntity u ,SysRoleEntity r," +
"RelUserRoleEntity u_r " +
"WHERE u.deleteFlag = 0 AND u.activeFlag = 0 AND r.id = u_r.roleId AND u.id = u_r.userId " +
"AND u.userName = :userName")
SysUserVo selectSysUserByUserName(@Param("userName") String userName);
/**
* 检查系统用户名是否存在
* @param userName 用户名
* @return
*/
@Query(value = "SELECT COUNT(*) FROM sys_user WHERE user_name = :userName", nativeQuery = true)
int checkUserName(@Param("userName") String userName);
/**
* 查找用户实体根据用户名
* @param userName 用户名
* @return
*/
@Query(value = "SELECT * FROM sys_user WHERE user_name = :userName", nativeQuery = true)
SysUserEntity selectByUserName(@Param("userName") String userName);
/**
* 更新用户登录信息
* @param userName 用户名
* @param ipAddress ip地址
* @return
*/
@Modifying
@Query(value = "UPDATE sys_user SET last_entry_time = now(), last_entry_ip = :ipAddress " +
"WHERE user_name = :userName ;", nativeQuery = true)
int updateSysUserLogin(@Param("userName") String userName,@Param("ipAddress") String ipAddress);
/**
* 软删除系统用户根据用户名
* @param userName 用户名
* @return
*/
@Modifying
@Query(value = "UPDATE sys_user SET delete_flag = 1 " +
"WHERE user_name = :userName ;", nativeQuery = true)
int softDeleteSysUserByUserName(@Param("userName") String userName);
/**
* 软删除系统用户根据id
* @param id 编号
* @return
*/
@Modifying
@Query(value = "UPDATE sys_user SET delete_flag = 1 " +
"WHERE id = :id ;", nativeQuery = true)
int softDeleteGeneralUserById(@Param("id") Integer id);
/**
* 获取所有系统用户Vo未删除已激活
* @return
*/
@Query(value = "select new com.xkrs.microservice.model.vo.SysUserVo (u.id, u.userName, u.nickName,u.realName, u.userCode, " +
"u.sex, u.telephone, u.email, u.admCode, u.address,u.birthday,u.signature,r.roleNameZh, u.portraitId," +
"u.statusCode,u.addTime,u.lastEntryTime,u.lastEntryIp,u.memo) from SysUserEntity u ,SysRoleEntity r," +
"RelUserRoleEntity u_r " +
"WHERE u.deleteFlag = 0 AND u.activeFlag = 0 AND r.id = u_r.roleId AND u.id = u_r.userId")
List<SysUserVo> selectAllSysUser();
/**
* 删除系统用户危险操作
* @param userName 用户名
* @return
*/
@Modifying
@Query(value = "DELETE FROM sys_user WHERE user_name = :userName ;", nativeQuery = true)
int deleteSysUser(@Param("userName") String userName);
}

View File

@ -0,0 +1,71 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.TifProductEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDate;
/**
* TifProductDao
* @author tajochen
*/
public interface TifProductDao extends JpaRepository<TifProductEntity,Integer> {
/**
* 根据产品代码查找
* @param productCode 产品代码
* @return
*/
TifProductEntity findByProductCode(String productCode);
/**
* 根据产品类型查找
* @param productType 产品类型
* @return
*/
Iterable<TifProductEntity> findByProductType(String productType);
/**
* 根据产品类型和产品日期查找
* @param productType 产品类型
* @param sDate 开始时间
* @param eDate 结束时间
* @return
*/
Iterable<TifProductEntity> findByProductTypeAndProductDateBetween(String productType, LocalDate sDate,LocalDate eDate);
/**
* 根据行政区划代码查找
* @param admCode 行政区划代码
* @return
*/
Iterable<TifProductEntity> findByAdmCode(Integer admCode);
/**
* 根据行政区划代码和产品日期查找
* @param admCode 行政区划代码
* @param sDate 开始时间
* @param eDate 结束时间
* @return
*/
Iterable<TifProductEntity> findByAdmCodeAndProductDateBetween(Integer admCode, LocalDate sDate,LocalDate eDate);
/**
* 根据产品类型和行政区划代码和产品类型
* @param productType 产品类型
* @param admCode 行政区划代码
* @return
*/
Iterable<TifProductEntity> findByProductTypeAndAdmCode(String productType,Integer admCode);
/**
* 根据产品类型和行政区划代码和产品类型和产品日期查找
* @param productType 产品类型
* @param admCode 行政区划代码
* @param sDate 开始时间
* @param eDate 结束时间
* @return
*/
Iterable<TifProductEntity> findByProductTypeAndAdmCodeAndProductDateBetween(String productType,Integer admCode, LocalDate sDate,LocalDate eDate);
}

View File

@ -0,0 +1,42 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.TypicalFarmerEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
/**
* TypicalFarmerDao
* @author tajochen
*/
public interface TypicalFarmerDao extends JpaRepository<TypicalFarmerEntity,Integer> {
/**
* 查找农户根据姓名
* @param lxr 联系人姓名
* @return
*/
Iterable<TypicalFarmerEntity> findAllByLxr(String lxr);
/**
* 查找农户根据手机号帐号
* @param tel 手机号
* @return
*/
Optional<TypicalFarmerEntity> findByTel(String tel);
/**
* 查找农户根据乡镇代码
* @param xzdm 乡镇代码
* @return
*/
Iterable<TypicalFarmerEntity> findAllByXzdm(String xzdm);
/**
* 查找农户根据区县代码
* @param qxdm 区县代码
* @return
*/
Iterable<TypicalFarmerEntity> findAllByQxdm(Integer qxdm);
}

View File

@ -0,0 +1,49 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.TypicalPlotEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
/**
* TypicalPlotDao
* @author tajochen
*/
public interface TypicalPlotDao extends JpaRepository<TypicalPlotEntity,Integer> {
/**
* 查找典型地块根据地块编号
* @param dkbh
* @return
*/
Optional<TypicalPlotEntity> findAllByDkbh(String dkbh);
/**
* 查找典型地块根据姓名
* @param lxr 联系人姓名
* @return
*/
Iterable<TypicalPlotEntity> findAllByLxr(String lxr);
/**
* 查找典型地块根据手机号帐号
* @param tel 手机号
* @return
*/
Iterable<TypicalPlotEntity> findAllByTel(String tel);
/**
* 查找典型地块根据区县代码
* @param qxdm 区县代码
* @return
*/
Iterable<TypicalPlotEntity> findAllByQxdm(Integer qxdm);
/**
* 查找典型地块根据乡镇代码
* @param xzdm 乡镇代码
* @return
*/
Iterable<TypicalPlotEntity> findAllByXzdm(String xzdm);
}

View File

@ -0,0 +1,69 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.TypicalPlotIrrigationEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
/**
* TypicalPlotIrrigationDao
* @author tajochen
*/
public interface TypicalPlotIrrigationDao extends JpaRepository<TypicalPlotIrrigationEntity,Integer> {
/**
* 查找灌溉记录列表根据地块编号
* @param dkbh 地块编号
* @return
*/
Iterable<TypicalPlotIrrigationEntity> findAllByDkbh(String dkbh);
/**
* 查找灌溉记录列表根据区县代码
* @param countyCode 区县代码
* @return
*/
Iterable<TypicalPlotIrrigationEntity> findAllByQxbh(Integer countyCode);
/**
* 查找灌溉记录根据灌溉编号
* @param qxbh 区县代码
* @param sTime 开始时间
* @param eTime 结束时间
* @return
*/
Iterable<TypicalPlotIrrigationEntity> findAllByQxbhAndEndtimeBetween(Integer qxbh,LocalDateTime sTime,LocalDateTime eTime);
/**
* 查找灌溉记录根据灌溉编号
* @param ggbh 灌溉编号
* @return
*/
Optional<TypicalPlotIrrigationEntity> findByGgbh(String ggbh);
/**
* 查找灌溉记录根据添加用户名
* @param addUserName 添加用户名
* @return
*/
Iterable<TypicalPlotIrrigationEntity> findAllByAddUserName(String addUserName);
/**
* 查找灌溉记录根据区县代码
* @param xzbh 乡镇编号
* @param cropCode 作物代码
* @param startTime 开始时间
* @param endTime 结束时间
* @return
*/
@Query(value = "SELECT * FROM typical_plot_irrigation WHERE CASE WHEN ( :xzbh ) <> '' " +
"THEN xzbh = :xzbh ELSE 1 = 1 END " +
"AND strtime <= :endTime AND endtime >= :startTime " +
"AND CASE WHEN ( :cropCode ) <> 0 " +
"THEN crop_code = :cropCode ELSE 1 = 1 END;", nativeQuery = true)
List<TypicalPlotIrrigationEntity> getAllByCondition(String xzbh, Integer cropCode, LocalDateTime startTime, LocalDateTime endTime);
}

View File

@ -0,0 +1,64 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.WcsRecordEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDate;
/**
* WcsRecordDao
* @author tajochen
*/
public interface WcsRecordDao extends JpaRepository<WcsRecordEntity,Integer> {
/**
* 根据服务代码查找
* @param serviceCode 服务代码
* @return
*/
WcsRecordEntity findByServiceCode(String serviceCode);
/**
* 根据产品类型查找
* @param productType 产品类型
* @return
*/
Iterable<WcsRecordEntity> findByProductType(String productType);
/**
* 根据产品类型和产品日期查找
* @param productType 产品类型
* @param sDate 开始时间
* @param eDate 结束时间
* @return
*/
Iterable<WcsRecordEntity> findByProductTypeAndProductDateBetween(String productType, LocalDate sDate, LocalDate eDate);
/**
* 根据行政区划代码和产品日期查找
* @param admCode 行政区划代码
* @param sDate 开始时间
* @param eDate 结束时间
* @return
*/
Iterable<WcsRecordEntity> findByAdmCodeAndProductDateBetween(Integer admCode, LocalDate sDate, LocalDate eDate);
/**
* 根据产品类型和行政区划代码和产品类型
* @param productType 产品类型
* @param admCode 行政区划代码
* @return
*/
Iterable<WcsRecordEntity> findByProductTypeAndAdmCode(String productType,Integer admCode);
/**
* 根据产品类型和行政区划代码和产品类型和产品日期查找
* @param productType 产品类型
* @param admCode 行政区划代码
* @param sDate 开始时间
* @param eDate 结束时间
* @return
*/
Iterable<WcsRecordEntity> findByProductTypeAndAdmCodeAndProductDateBetween(String productType,Integer admCode, LocalDate sDate,LocalDate eDate);
}

View File

@ -0,0 +1,21 @@
package com.xkrs.microservice.dao;
import com.xkrs.microservice.model.entity.WeatherEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Component;
/**
* @author XinYi Song
*/
@Component
public interface WeatherDao extends JpaRepository<WeatherEntity,Long>, JpaSpecificationExecutor<WeatherEntity> {
/**
* 查询最新的一条记录
* @return
*/
@Query(value = "SELECT * from weather ORDER BY add_time desc limit 1",nativeQuery = true)
WeatherEntity selectNewest();
}

View File

@ -0,0 +1,169 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* CropClassifyRecordEntity 表实体类
* @author tajochen
*/
@Entity
@Table(name="crop_classify_record")
public class CropClassifyRecordEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "crop_classify_record_gen")
@SequenceGenerator(name = "crop_classify_record_seq_gen", sequenceName = "crop_classify_record_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false)
private Integer countyCode;
@Column( length = 32, nullable = false, columnDefinition = "varchar(32)")
private String countyName;
@Column( length = 16, nullable = false, columnDefinition = "varchar(16)")
private String townCode;
@Column( length = 32, nullable = false, columnDefinition = "varchar(32)")
private String townName;
@Column( nullable = false)
private Integer cropCode;
private LocalDate cropDate;
private Long area;
@Column( length = 128, columnDefinition = "varchar(128)")
private String dataSource;
@Column( length = 128, columnDefinition = "varchar(128)")
private String memo;
@Column( length = 32,nullable = false, columnDefinition = "varchar(32)")
private String addUserName;
private LocalDateTime addTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCountyCode() {
return countyCode;
}
public void setCountyCode(Integer countyCode) {
this.countyCode = countyCode;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public String getTownCode() {
return townCode;
}
public void setTownCode(String townCode) {
this.townCode = townCode;
}
public String getTownName() {
return townName;
}
public void setTownName(String townName) {
this.townName = townName;
}
public Integer getCropCode() {
return cropCode;
}
public void setCropCode(Integer cropCode) {
this.cropCode = cropCode;
}
public LocalDate getCropDate() {
return cropDate;
}
public void setCropDate(LocalDate cropDate) {
this.cropDate = cropDate;
}
public Long getArea() {
return area;
}
public void setArea(Long area) {
this.area = area;
}
public String getDataSource() {
return dataSource;
}
public void setDataSource(String dataSource) {
this.dataSource = dataSource;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getAddUserName() {
return addUserName;
}
public void setAddUserName(String addUserName) {
this.addUserName = addUserName;
}
public LocalDateTime getAddTime() {
return addTime;
}
public void setAddTime(LocalDateTime addTime) {
this.addTime = addTime;
}
@Override
public String toString() {
return "CropClassifyRecordEntity{" +
"id=" + id +
", countyCode=" + countyCode +
", countyName='" + countyName + '\'' +
", townCode='" + townCode + '\'' +
", townName='" + townName + '\'' +
", cropCode=" + cropCode +
", cropDate=" + cropDate +
", area=" + area +
", dataSource='" + dataSource + '\'' +
", memo='" + memo + '\'' +
", addUserName='" + addUserName + '\'' +
", addTime=" + addTime +
'}';
}
}

View File

@ -0,0 +1,73 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
/**
* DicLandClassify 表实体类
* @author tajochen
*/
@Entity
@Table(name="dic_crop_classify")
public class DicCropClassifyEntity {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dic_crop_classify_seq_gen")
@SequenceGenerator(name = "dic_crop_classify_seq_gen", sequenceName = "dic_crop_classify_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false, columnDefinition = "int4")
private Integer code;
@Column(length = 128, columnDefinition = "varchar(128)")
private String name;
@Column(length = 128, columnDefinition = "varchar(128)")
private String memo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
@Override
public String toString() {
return "DicCropClassifyEntity{" +
"id=" + id +
", code=" + code +
", name='" + name + '\'' +
", memo='" + memo + '\'' +
'}';
}
}

View File

@ -0,0 +1,73 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
/**
* DicLandClassify 表实体类
* @author tajochen
*/
@Entity
@Table(name="dic_drought_classify")
public class DicDroughtClassifyEntity {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dic_drought_classify_seq_gen")
@SequenceGenerator(name = "dic_drought_classify_seq_gen", sequenceName = "dic_drought_classify_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false, columnDefinition = "int4")
private Integer code;
@Column(length = 128, columnDefinition = "varchar(128)")
private String name;
@Column(length = 128, columnDefinition = "varchar(128)")
private String memo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
@Override
public String toString() {
return "DicDroughtClassifyEntity{" +
"id=" + id +
", code=" + code +
", name='" + name + '\'' +
", memo='" + memo + '\'' +
'}';
}
}

View File

@ -0,0 +1,73 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
/**
* DicLandClassify 表实体类
* @author tajochen
*/
@Entity
@Table(name="dic_land_classify")
public class DicLandClassifyEntity {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dic_land_classify_seq_gen")
@SequenceGenerator(name = "dic_land_classify_seq_gen", sequenceName = "dic_land_classify_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false, columnDefinition = "int4")
private Integer code;
@Column(length = 128, columnDefinition = "varchar(128)")
private String name;
@Column(length = 128, columnDefinition = "varchar(128)")
private String memo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
@Override
public String toString() {
return "DicLandClassifyEntity{" +
"id=" + id +
", code=" + code +
", name='" + name + '\'' +
", memo='" + memo + '\'' +
'}';
}
}

View File

@ -0,0 +1,97 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
/**
* DicLandClassify 表实体类
* @author tajochen
*/
@Entity
@Table(name="dic_product")
public class DicProductEntity {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dic_product_seq_gen")
@SequenceGenerator(name = "dic_product_seq_gen", sequenceName = "dic_product_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false,length = 64,unique = true, columnDefinition = "varchar(64)")
private String productType;
@Column(length = 64, columnDefinition = "varchar(64)")
private String productTypeCn;
@Column(length = 64, columnDefinition = "varchar(64)")
private String productOrigin;
@Column(length = 64, columnDefinition = "varchar(64)")
private String productCycle;
@Column(length = 128, columnDefinition = "varchar(128)")
private String memo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProductTypeCn() {
return productTypeCn;
}
public void setProductTypeCn(String productTypeCn) {
this.productTypeCn = productTypeCn;
}
public String getProductOrigin() {
return productOrigin;
}
public void setProductOrigin(String productOrigin) {
this.productOrigin = productOrigin;
}
public String getProductCycle() {
return productCycle;
}
public void setProductCycle(String productCycle) {
this.productCycle = productCycle;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
@Override
public String toString() {
return "DicProductEntity{" +
"id=" + id +
", productType='" + productType + '\'' +
", productTypeCn='" + productTypeCn + '\'' +
", productOrigin='" + productOrigin + '\'' +
", productCycle='" + productCycle + '\'' +
", memo='" + memo + '\'' +
'}';
}
}

View File

@ -0,0 +1,97 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
/**
* DicSoilClassify 表实体类
* @author tajochen
*/
@Entity
@Table(name="dic_soil_classify")
public class DicSoilClassifyEntity {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dic_soil_classify_seq_gen")
@SequenceGenerator(name = "dic_soil_classify_seq_gen", sequenceName = "dic_soil_classify_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false, columnDefinition = "int4")
private Integer code;
@Column(length = 64, nullable = false, columnDefinition = "varchar(64)")
private String value;
@Column(length = 64, columnDefinition = "varchar(64)")
private String symbol;
@Column(length = 255, columnDefinition = "varchar(255)")
private String engExplanation;
@Column(length = 255, columnDefinition = "varchar(255)")
private String chExplanation;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getEngExplanation() {
return engExplanation;
}
public void setEngExplanation(String engExplanation) {
this.engExplanation = engExplanation;
}
public String getChExplanation() {
return chExplanation;
}
public void setChExplanation(String chExplanation) {
this.chExplanation = chExplanation;
}
@Override
public String toString() {
return "DicSoilClassify{" +
"id=" + id +
", code=" + code +
", value='" + value + '\'' +
", symbol='" + symbol + '\'' +
", engExplanation='" + engExplanation + '\'' +
", chExplanation='" + chExplanation + '\'' +
'}';
}
}

View File

@ -0,0 +1,145 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* FarmingInfoEntity 表实体类
* @author tajochen
*/
@Entity
@Table(name="farming_info")
public class FarmingInfoEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "farming_info_gen")
@SequenceGenerator(name = "farming_info_seq_gen", sequenceName = "farming_info_seq",allocationSize = 1)
private Integer id;
@Column( length = 32, columnDefinition = "varchar(32)", nullable = false)
private String dkbh;
@Column( length = 64, columnDefinition = "varchar(64)")
private String zwmc;
private Integer zwdm;
@Column( nullable = false)
private Integer qxbh;
@Column( length = 512, columnDefinition = "varchar(512)",nullable = false)
private String nqzp;
@Column( length = 64, columnDefinition = "varchar(64)", nullable = false)
private String nqzt;
@Column( length = 64, columnDefinition = "varchar(64)")
private String remark;
@Column( length = 32, columnDefinition = "varchar(32)")
private String addUserName;
private LocalDateTime createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDkbh() {
return dkbh;
}
public void setDkbh(String dkbh) {
this.dkbh = dkbh;
}
public String getZwmc() {
return zwmc;
}
public void setZwmc(String zwmc) {
this.zwmc = zwmc;
}
public Integer getZwdm() {
return zwdm;
}
public void setZwdm(Integer zwdm) {
this.zwdm = zwdm;
}
public Integer getQxbh() {
return qxbh;
}
public void setQxbh(Integer qxbh) {
this.qxbh = qxbh;
}
public String getNqzp() {
return nqzp;
}
public void setNqzp(String nqzp) {
this.nqzp = nqzp;
}
public String getNqzt() {
return nqzt;
}
public void setNqzt(String nqzt) {
this.nqzt = nqzt;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getAddUserName() {
return addUserName;
}
public void setAddUserName(String addUserName) {
this.addUserName = addUserName;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "FarmingInfoEntity{" +
"id=" + id +
", dkbh='" + dkbh + '\'' +
", zwmc='" + zwmc + '\'' +
", zwdm=" + zwdm +
", qxbh=" + qxbh +
", nqzp='" + nqzp + '\'' +
", nqzt='" + nqzt + '\'' +
", remark='" + remark + '\'' +
", addUserName='" + addUserName + '\'' +
", createTime=" + createTime +
'}';
}
}

View File

@ -0,0 +1,134 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* FileApp 表实体类
* @author tajochen
*/
@Entity
@Table(name="file_app")
public class FileAppEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "app_file_seq_gen")
@SequenceGenerator(name = "app_file_seq_gen", sequenceName = "app_file_seq",allocationSize = 1)
private Integer id;
@Column(length = 64, nullable = false, columnDefinition = "varchar(64)")
private String name;
@Column(length = 192 , nullable = false, columnDefinition = "varchar(192)")
private String appPath;
@Column( length = 128, nullable = false,unique = true, columnDefinition = "varchar(128)")
private String versionNumber;
@Column( length = 128, nullable = false, columnDefinition = "varchar(128)")
private String size;
@Column( length = 192, nullable = false, columnDefinition = "varchar(192)")
private String md5;
@Column( length = 192, columnDefinition = "varchar(192)")
private String memo;
@Column( length = 32,nullable = false, columnDefinition = "varchar(32)")
private String addUserName;
private LocalDateTime addTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAppPath() {
return appPath;
}
public void setAppPath(String appPath) {
this.appPath = appPath;
}
public String getVersionNumber() {
return versionNumber;
}
public void setVersionNumber(String versionNumber) {
this.versionNumber = versionNumber;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getAddUserName() {
return addUserName;
}
public void setAddUserName(String addUserName) {
this.addUserName = addUserName;
}
public LocalDateTime getAddTime() {
return addTime;
}
public void setAddTime(LocalDateTime addTime) {
this.addTime = addTime;
}
@Override
public String toString() {
return "FileAppEntity{" +
"id=" + id +
", name='" + name + '\'' +
", appPath='" + appPath + '\'' +
", versionNumber='" + versionNumber + '\'' +
", size='" + size + '\'' +
", md5='" + md5 + '\'' +
", memo='" + memo + '\'' +
", addUserName='" + addUserName + '\'' +
", addTime=" + addTime +
'}';
}
}

View File

@ -0,0 +1,132 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* FileDocument 表实体类
* @author tajochen
*/
@Entity
@Table(name="file_document")
public class FileDocumentEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "file_document_seq_gen")
@SequenceGenerator(name = "file_document_seq_gen", sequenceName = "file_document_seq",allocationSize = 1)
private Integer id;
@Column(length = 64, nullable = false, columnDefinition = "varchar(64)")
private String name;
@Column( nullable = false, columnDefinition = "int4")
private Integer category;
@Column(length = 192 , nullable = false, columnDefinition = "varchar(192)")
private String filePath;
@Column( length = 128, nullable = false, columnDefinition = "varchar(128)")
private String fileSize;
@Column( length = 192, nullable = false, columnDefinition = "varchar(192)")
private String md5;
@Column( length = 128, columnDefinition = "varchar(128)")
private String memo;
@Column( length = 32,nullable = false, columnDefinition = "varchar(32)")
private String addUserName;
private LocalDateTime addTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCategory() {
return category;
}
public void setCategory(Integer category) {
this.category = category;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getAddUserName() {
return addUserName;
}
public void setAddUserName(String addUserName) {
this.addUserName = addUserName;
}
public LocalDateTime getAddTime() {
return addTime;
}
public void setAddTime(LocalDateTime addTime) {
this.addTime = addTime;
}
@Override
public String toString() {
return "FileDocumentEntity{" +
"id=" + id +
", name='" + name + '\'' +
", category=" + category +
", filePath='" + filePath + '\'' +
", fileSize='" + fileSize + '\'' +
", md5='" + md5 + '\'' +
", memo='" + memo + '\'' +
", addUserName=" + addUserName +
", addTime=" + addTime +
'}';
}
}

View File

@ -0,0 +1,151 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* HydrologicalStationEntity 表实体类
* @author tajochen
*/
@Entity
@Table(name="hydrological_station")
public class HydrologicalStationEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "hydrological_station_gen")
@SequenceGenerator(name = "hydrological_station_seq_gen", sequenceName = "hydrological_station_seq",allocationSize = 1)
private Integer id;
@Column( length = 64,nullable = false)
private String name;
private LocalDateTime recordTime;
private Integer countyCode;
@Column( length = 32, nullable = false, columnDefinition = "varchar(32)")
private String countyName;
private Double longitude;
private Double latitude;
private Integer droughtLevel;
private Double drp;
private String remarks;
private LocalDateTime createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDateTime getRecordTime() {
return recordTime;
}
public void setRecordTime(LocalDateTime recordTime) {
this.recordTime = recordTime;
}
public Integer getCountyCode() {
return countyCode;
}
public void setCountyCode(Integer countyCode) {
this.countyCode = countyCode;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Integer getDroughtLevel() {
return droughtLevel;
}
public void setDroughtLevel(Integer droughtLevel) {
this.droughtLevel = droughtLevel;
}
public Double getDrp() {
return drp;
}
public void setDrp(Double drp) {
this.drp = drp;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
@Override
public String toString() {
return "HydrologicalStationEntity{" +
"id=" + id +
", name='" + name + '\'' +
", recordTime=" + recordTime +
", countyCode=" + countyCode +
", countyName='" + countyName + '\'' +
", longitude=" + longitude +
", latitude=" + latitude +
", droughtLevel=" + droughtLevel +
", drp=" + drp +
", remarks='" + remarks + '\'' +
", createTime=" + createTime +
'}';
}
}

View File

@ -0,0 +1,243 @@
package com.xkrs.microservice.model.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.micrometer.core.instrument.util.StringUtils;
import org.geolatte.geom.Geometry;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* IndependentCheckEntity 表实体类
* @author tajochen
*/
@Entity
@Table(name="independent_check")
public class IndependentCheckEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "independent_check_gen")
@SequenceGenerator(name = "independent_check_seq_gen", sequenceName = "independent_check_seq",allocationSize = 1)
private Integer id;
private Integer qxdm;
private String qxmc;
private Integer zwdm;
@Column( length = 32, columnDefinition = "varchar(32)")
private String zwmc;
private Double lai;
private Double swc;
private Integer ggzt;
@Column( length = 512, columnDefinition = "varchar(512)")
private String hczp;
private Integer sfwrj;
private Integer sdcjgp;
private Double xzb;
private Double yzb;
@Column( length = 64, columnDefinition = "varchar(64)")
private String remark;
@Column( length = 32, columnDefinition = "varchar(32)")
private String addUserName;
private LocalDateTime createTime;
private Geometry geom;
@Transient
private String wktGeom;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getQxdm() {
return qxdm;
}
public void setQxdm(Integer qxdm) {
this.qxdm = qxdm;
}
public String getQxmc() {
return qxmc;
}
public void setQxmc(String qxmc) {
this.qxmc = qxmc;
}
public Integer getZwdm() {
return zwdm;
}
public void setZwdm(Integer zwdm) {
this.zwdm = zwdm;
}
public String getZwmc() {
return zwmc;
}
public void setZwmc(String zwmc) {
this.zwmc = zwmc;
}
public Double getLai() {
return lai;
}
public void setLai(Double lai) {
this.lai = lai;
}
public Double getSwc() {
return swc;
}
public void setSwc(Double swc) {
this.swc = swc;
}
public Integer getGgzt() {
return ggzt;
}
public void setGgzt(Integer ggzt) {
this.ggzt = ggzt;
}
public String getHczp() {
return hczp;
}
public void setHczp(String hczp) {
this.hczp = hczp;
}
public Integer getSfwrj() {
return sfwrj;
}
public void setSfwrj(Integer sfwrj) {
this.sfwrj = sfwrj;
}
public Integer getSdcjgp() {
return sdcjgp;
}
public void setSdcjgp(Integer sdcjgp) {
this.sdcjgp = sdcjgp;
}
public Double getXzb() {
return xzb;
}
public void setXzb(Double xzb) {
this.xzb = xzb;
}
public Double getYzb() {
return yzb;
}
public void setYzb(Double yzb) {
this.yzb = yzb;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getAddUserName() {
return addUserName;
}
public void setAddUserName(String addUserName) {
this.addUserName = addUserName;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
@JsonIgnore
public Geometry getGeom() {
return geom;
}
@JsonIgnore
public void setGeom(Geometry geom) {
this.geom = geom;
}
public String getWktGeom() {
if(StringUtils.isNotBlank(wktGeom)){
return wktGeom;
} else if(geom == null){
return "";
} else {
return geom.toString();
}
}
public void setWktGeom(String wktGeom) {
this.wktGeom = wktGeom;
}
@Override
public String toString() {
return "IndependentCheckEntity{" +
"id=" + id +
", qxdm=" + qxdm +
", qxmc='" + qxmc + '\'' +
", zwdm=" + zwdm +
", zwmc='" + zwmc + '\'' +
", lai=" + lai +
", swc=" + swc +
", ggzt=" + ggzt +
", hczp='" + hczp + '\'' +
", sfwrj=" + sfwrj +
", sdcjgp=" + sdcjgp +
", xzb=" + xzb +
", yzb=" + yzb +
", remark='" + remark + '\'' +
", addUserName='" + addUserName + '\'' +
", createTime=" + createTime +
", geom=" + geom +
", wktGeom='" + wktGeom + '\'' +
'}';
}
}

View File

@ -0,0 +1,168 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* IrrigationCheckEntity 表实体类
* @author tajochen
*/
@Entity
@Table(name="irrigation_check")
public class IrrigationCheckEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "irrigation_check_gen")
@SequenceGenerator(name = "irrigation_check_seq_gen", sequenceName = "irrigation_check_seq",allocationSize = 1)
private Integer id;
@Column( length = 32, columnDefinition = "varchar(32)",unique = true, nullable = false)
private String hsbh;
@Column( length = 32, columnDefinition = "varchar(32)", nullable = false)
private String ggbh;
@Column( length = 32, columnDefinition = "varchar(32)", nullable = false)
private String dkbh;
@Column( nullable = false)
private Integer qxbh;
@Column( length = 512, columnDefinition = "varchar(512)")
private String hszp;
@Column( nullable = false)
private Integer hszt;
private Double xzb;
private Double yzb;
@Column( length = 64, columnDefinition = "varchar(64)")
private String remark;
@Column( length = 32, columnDefinition = "varchar(32)")
private String addUserName;
private LocalDateTime createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHsbh() {
return hsbh;
}
public void setHsbh(String hsbh) {
this.hsbh = hsbh;
}
public String getGgbh() {
return ggbh;
}
public void setGgbh(String ggbh) {
this.ggbh = ggbh;
}
public String getDkbh() {
return dkbh;
}
public void setDkbh(String dkbh) {
this.dkbh = dkbh;
}
public Integer getQxbh() {
return qxbh;
}
public void setQxbh(Integer qxbh) {
this.qxbh = qxbh;
}
public String getHszp() {
return hszp;
}
public void setHszp(String hszp) {
this.hszp = hszp;
}
public Integer getHszt() {
return hszt;
}
public void setHszt(Integer hszt) {
this.hszt = hszt;
}
public Double getXzb() {
return xzb;
}
public void setXzb(Double xzb) {
this.xzb = xzb;
}
public Double getYzb() {
return yzb;
}
public void setYzb(Double yzb) {
this.yzb = yzb;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getAddUserName() {
return addUserName;
}
public void setAddUserName(String addUserName) {
this.addUserName = addUserName;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "IrrigationCheckEntity{" +
"id=" + id +
", hsbh='" + hsbh + '\'' +
", ggbh='" + ggbh + '\'' +
", dkbh='" + dkbh + '\'' +
", qxbh=" + qxbh +
", hszp='" + hszp + '\'' +
", hszt=" + hszt +
", xzb=" + xzb +
", yzb=" + yzb +
", remark='" + remark + '\'' +
", addUserName='" + addUserName + '\'' +
", createTime=" + createTime +
'}';
}
}

View File

@ -0,0 +1,157 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* IrrigationRecordEntity 表实体类
* @author tajochen
*/
@Entity
@Table(name="irrigation_record")
public class IrrigationRecordEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "irrigation_record_gen")
@SequenceGenerator(name = "irrigation_record_seq_gen", sequenceName = "irrigation_record_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false)
private Integer countyCode;
@Column( length = 32, nullable = false, columnDefinition = "varchar(32)")
private String countyName;
@Column( length = 16, nullable = false, columnDefinition = "varchar(16)")
private String townCode;
@Column( length = 32, nullable = false, columnDefinition = "varchar(32)")
private String townName;
private LocalDate irrigationDate;
private Double area;
@Column( length = 128, columnDefinition = "varchar(128)")
private String dataSource;
@Column( length = 128, columnDefinition = "varchar(128)")
private String memo;
@Column( length = 32,nullable = false, columnDefinition = "varchar(32)")
private String addUserName;
private LocalDateTime addTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCountyCode() {
return countyCode;
}
public void setCountyCode(Integer countyCode) {
this.countyCode = countyCode;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public LocalDate getIrrigationDate() {
return irrigationDate;
}
public void setIrrigationDate(LocalDate irrigationDate) {
this.irrigationDate = irrigationDate;
}
public Double getArea() {
return area;
}
public void setArea(Double area) {
this.area = area;
}
public String getDataSource() {
return dataSource;
}
public void setDataSource(String dataSource) {
this.dataSource = dataSource;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getAddUserName() {
return addUserName;
}
public void setAddUserName(String addUserName) {
this.addUserName = addUserName;
}
public LocalDateTime getAddTime() {
return addTime;
}
public void setAddTime(LocalDateTime addTime) {
this.addTime = addTime;
}
public String getTownCode() {
return townCode;
}
public void setTownCode(String townCode) {
this.townCode = townCode;
}
public String getTownName() {
return townName;
}
public void setTownName(String townName) {
this.townName = townName;
}
@Override
public String toString() {
return "IrrigationRecordEntity{" +
"id=" + id +
", countyCode=" + countyCode +
", countyName='" + countyName + '\'' +
", townCode='" + townCode + '\'' +
", townName='" + townName + '\'' +
", irrigationDate=" + irrigationDate +
", area=" + area +
", dataSource='" + dataSource + '\'' +
", memo='" + memo + '\'' +
", addUserName='" + addUserName + '\'' +
", addTime=" + addTime +
'}';
}
}

View File

@ -0,0 +1,180 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* IrrigationSarRecordEntity 表实体类
* @author tajochen
*/
@Entity
@Table(name="irrigation_sar_record")
public class IrrigationSarRecordEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "irrigation_sar_record_gen")
@SequenceGenerator(name = "irrigation_sar_record_seq_gen", sequenceName = "irrigation_sar_record_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false)
private Integer countyCode;
@Column( length = 32, nullable = false, columnDefinition = "varchar(32)")
private String countyName;
@Column( length = 16, nullable = false, columnDefinition = "varchar(16)")
private String townCode;
@Column( length = 32, nullable = false, columnDefinition = "varchar(32)")
private String townName;
@Column( length = 32, columnDefinition = "varchar(32)")
private String cropName;
private Integer cropCode;
private LocalDate irrigationDate;
private Double area;
@Column( length = 128, columnDefinition = "varchar(128)")
private String dataSource;
@Column( length = 128, columnDefinition = "varchar(128)")
private String memo;
@Column( length = 32,nullable = false, columnDefinition = "varchar(32)")
private String addUserName;
private LocalDateTime addTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCountyCode() {
return countyCode;
}
public void setCountyCode(Integer countyCode) {
this.countyCode = countyCode;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public LocalDate getIrrigationDate() {
return irrigationDate;
}
public void setIrrigationDate(LocalDate irrigationDate) {
this.irrigationDate = irrigationDate;
}
public Double getArea() {
return area;
}
public void setArea(Double area) {
this.area = area;
}
public String getDataSource() {
return dataSource;
}
public void setDataSource(String dataSource) {
this.dataSource = dataSource;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getAddUserName() {
return addUserName;
}
public void setAddUserName(String addUserName) {
this.addUserName = addUserName;
}
public LocalDateTime getAddTime() {
return addTime;
}
public void setAddTime(LocalDateTime addTime) {
this.addTime = addTime;
}
public String getTownCode() {
return townCode;
}
public void setTownCode(String townCode) {
this.townCode = townCode;
}
public String getTownName() {
return townName;
}
public void setTownName(String townName) {
this.townName = townName;
}
public String getCropName() {
return cropName;
}
public void setCropName(String cropName) {
this.cropName = cropName;
}
public Integer getCropCode() {
return cropCode;
}
public void setCropCode(Integer cropCode) {
this.cropCode = cropCode;
}
@Override
public String toString() {
return "IrrigationSarRecordEntity{" +
"id=" + id +
", countyCode=" + countyCode +
", countyName='" + countyName + '\'' +
", townCode='" + townCode + '\'' +
", townName='" + townName + '\'' +
", cropName='" + cropName + '\'' +
", cropCode=" + cropCode +
", irrigationDate=" + irrigationDate +
", area=" + area +
", dataSource='" + dataSource + '\'' +
", memo='" + memo + '\'' +
", addUserName='" + addUserName + '\'' +
", addTime=" + addTime +
'}';
}
}

View File

@ -0,0 +1,174 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* RelAdmWeatherStationEntity 表实体类
* @author tajochen
*/
@Entity
@Table(name="meteorological_station")
public class MeteorologicalStationEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "rel_adm_weather_station_seq_gen")
@SequenceGenerator(name = "rel_adm_weather_station_seq_gen", sequenceName = "rel_adm_weather_station_seq",allocationSize = 1)
private Integer id;
private Integer code;
@Column(length = 32, nullable = false, columnDefinition = "varchar(32)")
private String name;
private Integer cityCode;
@Column(length = 32, nullable = false, columnDefinition = "varchar(32)")
private String cityName;
private Integer proCode;
@Column(length = 16, nullable = false, columnDefinition = "varchar(16)")
private String proName;
private Integer cityWeatherCode;
private Double height;
private Double lat;
private Double lon;
private Integer stationId;
@Column(length = 128, columnDefinition = "varchar(128)")
private String memo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCityCode() {
return cityCode;
}
public void setCityCode(Integer cityCode) {
this.cityCode = cityCode;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Integer getProCode() {
return proCode;
}
public void setProCode(Integer proCode) {
this.proCode = proCode;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
public Integer getCityWeatherCode() {
return cityWeatherCode;
}
public void setCityWeatherCode(Integer cityWeatherCode) {
this.cityWeatherCode = cityWeatherCode;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Integer getStationId() {
return stationId;
}
public void setStationId(Integer stationId) {
this.stationId = stationId;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
@Override
public String toString() {
return "RelAdmWeatherStationEntity{" +
"id=" + id +
", code=" + code +
", name='" + name + '\'' +
", cityCode=" + cityCode +
", cityName='" + cityName + '\'' +
", proCode=" + proCode +
", proName='" + proName + '\'' +
", cityWeatherCode=" + cityWeatherCode +
", height=" + height +
", lat=" + lat +
", lon=" + lon +
", stationId=" + stationId +
", memo='" + memo + '\'' +
'}';
}
}

View File

@ -0,0 +1,73 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
/**
* DicLandClassify 表实体类
* @author tajochen
*/
@Entity
@Table(name="monitoring_station")
public class MonitoringStationEntity {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dic_crop_classify_seq_gen")
@SequenceGenerator(name = "dic_crop_classify_seq_gen", sequenceName = "dic_crop_classify_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false, columnDefinition = "int4")
private Integer code;
@Column(length = 128, columnDefinition = "varchar(128)")
private String name;
@Column(length = 128, columnDefinition = "varchar(128)")
private String memo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
@Override
public String toString() {
return "DicCropClassifyEntity{" +
"id=" + id +
", code=" + code +
", name='" + name + '\'' +
", memo='" + memo + '\'' +
'}';
}
}

View File

@ -0,0 +1,60 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* RelRoleAuthority 表实体类
* @author tajochen
*/
@Entity
@Table(name="rel_role_authority")
public class RelRoleAuthorityEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "rel_role_authority_seq_gen")
@SequenceGenerator(name = "rel_role_authority_seq_gen", sequenceName = "rel_role_authority_seq",allocationSize = 1)
private Integer id;
@Column(nullable = false)
private Integer roleId;
@Column(nullable = false)
private Integer authorityId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Integer getAuthorityId() {
return authorityId;
}
public void setAuthorityId(Integer authorityId) {
this.authorityId = authorityId;
}
@Override
public String toString() {
return "RelRoleAuthorityEntity{" +
"id=" + id +
", roleId=" + roleId +
", authorityId=" + authorityId +
'}';
}
}

View File

@ -0,0 +1,60 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* RelUserRole 表实体类
* @author tajochen
*/
@Entity
@Table(name="rel_user_role")
public class RelUserRoleEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "rel_user_role_seq_gen")
@SequenceGenerator(name = "rel_user_role_seq_gen", sequenceName = "rel_user_role_seq",allocationSize = 1)
private Integer id;
@Column(nullable = false)
private Long userId;
@Column(nullable = false)
private Integer roleId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "RelUserRoleEntity{" +
"id=" + id +
", userId=" + userId +
", roleId=" + roleId +
'}';
}
}

View File

@ -0,0 +1,142 @@
package com.xkrs.microservice.model.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.micrometer.core.instrument.util.StringUtils;
import org.geolatte.geom.Geometry;
import javax.persistence.*;
import java.io.Serializable;
/**
* ShpCity 表实体类
* @author tajochen
*/
@Entity
@Table(name="shp_city")
public class ShpCityEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "shp_city_seq_gen")
@SequenceGenerator(name = "shp_city_seq_gen", sequenceName = "shp_city_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false, unique = true, columnDefinition = "int4")
private Integer code;
@Column(length = 32, nullable = false, columnDefinition = "varchar(32)")
private String name;
@Column( nullable = false, columnDefinition = "int4")
private Integer proCode;
@Column(length = 16, nullable = false, columnDefinition = "varchar(16)")
private String proName;
private double shapeArea;
@Column( columnDefinition = "varchar(192)")
private String center;
private Geometry geom;
@Transient
private String wktGeom;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getProCode() {
return proCode;
}
public void setProCode(Integer proCode) {
this.proCode = proCode;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
public double getShapeArea() {
return shapeArea;
}
public void setShapeArea(double shapeArea) {
this.shapeArea = shapeArea;
}
public String getCenter() {
return center;
}
public void setCenter(String center) {
this.center = center;
}
@JsonIgnore
public Geometry getGeom() {
return geom;
}
@JsonIgnore
public void setGeom(Geometry geom) {
this.geom = geom;
}
public String getWktGeom() {
if(StringUtils.isNotBlank(wktGeom)){
return wktGeom;
} else if(geom == null){
return "";
} else {
return geom.toString();
}
}
public void setWktGeom(String wktGeom) {
this.wktGeom = wktGeom;
}
@Override
public String toString() {
return "ShpCityEntity{" +
"id=" + id +
", code=" + code +
", name='" + name + '\'' +
", proCode=" + proCode +
", proName='" + proName + '\'' +
", shapeArea=" + shapeArea +
", center='" + center + '\'' +
", geom=" + geom +
", wktGeom='" + wktGeom + '\'' +
'}';
}
}

View File

@ -0,0 +1,177 @@
package com.xkrs.microservice.model.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.micrometer.core.instrument.util.StringUtils;
import org.locationtech.jts.geom.Geometry;
import javax.persistence.*;
import java.io.Serializable;
/**
* ShpCounty 表实体类
* @author tajochen
*/
@Entity
@Table(name="shp_county")
public class ShpCountyEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "shp_county_seq_gen")
@SequenceGenerator(name = "shp_county_seq_gen", sequenceName = "shp_county_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false, unique = true, columnDefinition = "int4")
private Integer code;
@Column(length = 32, nullable = false, columnDefinition = "varchar(32)")
private String name;
@Column( nullable = false, columnDefinition = "int4")
private Integer cityCode;
@Column(length = 32, nullable = false, columnDefinition = "varchar(32)")
private String cityName;
@Column( nullable = false, columnDefinition = "int4")
private Integer proCode;
@Column(length = 16, nullable = false, columnDefinition = "varchar(16)")
private String proName;
private double shapeArea;
@Column( columnDefinition = "varchar(192)")
private String center;
@Column( columnDefinition = "varchar(192)")
private String memo;
private Geometry geom;
@Transient
private String wktGeom;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCityCode() {
return cityCode;
}
public void setCityCode(Integer cityCode) {
this.cityCode = cityCode;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Integer getProCode() {
return proCode;
}
public void setProCode(Integer proCode) {
this.proCode = proCode;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
public double getShapeArea() {
return shapeArea;
}
public void setShapeArea(double shapeArea) {
this.shapeArea = shapeArea;
}
public String getCenter() {
return center;
}
public void setCenter(String center) {
this.center = center;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
@JsonIgnore
public Geometry getGeom() {
return geom;
}
@JsonIgnore
public void setGeom(Geometry geom) {
this.geom = geom;
}
public String getWktGeom() {
if(StringUtils.isNotBlank(wktGeom)){
return wktGeom;
} else if(geom == null){
return "";
} else {
return geom.toString();
}
}
public void setWktGeom(String wktGeom) {
this.wktGeom = wktGeom;
}
@Override
public String toString() {
return "ShpCountyEntity{" +
"id=" + id +
", code=" + code +
", name='" + name + '\'' +
", cityCode=" + cityCode +
", cityName='" + cityName + '\'' +
", proCode=" + proCode +
", proName='" + proName + '\'' +
", shapeArea=" + shapeArea +
", center='" + center + '\'' +
", memo='" + memo + '\'' +
", geom=" + geom +
", wktGeom='" + wktGeom + '\'' +
'}';
}
}

View File

@ -0,0 +1,118 @@
package com.xkrs.microservice.model.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.micrometer.core.instrument.util.StringUtils;
import org.geolatte.geom.Geometry;
import javax.persistence.*;
import java.io.Serializable;
/**
* ShpProvince 表实体类
* @author tajochen
*/
@Entity
@Table(name="shp_province")
public class ShpProvinceEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "shp_province_seq_gen")
@SequenceGenerator(name = "shp_province_seq_gen", sequenceName = "shp_province_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false, unique = true, columnDefinition = "int4")
private Integer code;
@Column(length = 16, nullable = false, columnDefinition = "varchar(16)")
private String name;
private double shapeArea;
@Column( columnDefinition = "varchar(192)")
private String center;
private Geometry geom;
@Transient
private String wktGeom;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getShapeArea() {
return shapeArea;
}
public void setShapeArea(double shapeArea) {
this.shapeArea = shapeArea;
}
public String getCenter() {
return center;
}
public void setCenter(String center) {
this.center = center;
}
@JsonIgnore
public Geometry getGeom() {
return geom;
}
@JsonIgnore
public void setGeom(Geometry geom) {
this.geom = geom;
}
public String getWktGeom() {
if(StringUtils.isNotBlank(wktGeom)){
return wktGeom;
} else if(geom == null){
return "";
} else {
return geom.toString();
}
}
public void setWktGeom(String wktGeom) {
this.wktGeom = wktGeom;
}
@Override
public String toString() {
return "ShpProvinceEntity{" +
"id=" + id +
", code=" + code +
", name='" + name + '\'' +
", shapeArea=" + shapeArea +
", center='" + center + '\'' +
", geom=" + geom +
", wktGeom='" + wktGeom + '\'' +
'}';
}
}

View File

@ -0,0 +1,169 @@
package com.xkrs.microservice.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* StationRecordEntity 表实体类
* @author tajochen
*/
@Entity
@Table(name="station_record")
public class StationRecordEntity implements Serializable {
private static final long serialVersionUID = 4359709211352400087L;
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "station_record_gen")
@SequenceGenerator(name = "station_record_seq_gen", sequenceName = "station_record_seq",allocationSize = 1)
private Integer id;
@Column( nullable = false)
private Integer countyCode;
@Column( length = 32, nullable = false, columnDefinition = "varchar(32)")
private String countyName;
@Column( length = 16, nullable = false, columnDefinition = "varchar(16)")
private String townCode;
@Column( length = 32, nullable = false, columnDefinition = "varchar(32)")
private String townName;
@Column( nullable = false)
private Integer cropCode;
private LocalDate cropDate;
private Long area;
@Column( length = 128, columnDefinition = "varchar(128)")
private String dataSource;
@Column( length = 128, columnDefinition = "varchar(128)")
private String memo;
@Column( length = 32,nullable = false, columnDefinition = "varchar(32)")
private String addUserName;
private LocalDateTime addTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCountyCode() {
return countyCode;
}
public void setCountyCode(Integer countyCode) {
this.countyCode = countyCode;
}
public String getCountyName() {
return countyName;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public String getTownCode() {
return townCode;
}
public void setTownCode(String townCode) {
this.townCode = townCode;
}
public String getTownName() {
return townName;
}
public void setTownName(String townName) {
this.townName = townName;
}
public Integer getCropCode() {
return cropCode;
}
public void setCropCode(Integer cropCode) {
this.cropCode = cropCode;
}
public LocalDate getCropDate() {
return cropDate;
}
public void setCropDate(LocalDate cropDate) {
this.cropDate = cropDate;
}
public Long getArea() {
return area;
}
public void setArea(Long area) {
this.area = area;
}
public String getDataSource() {
return dataSource;
}
public void setDataSource(String dataSource) {
this.dataSource = dataSource;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getAddUserName() {
return addUserName;
}
public void setAddUserName(String addUserName) {
this.addUserName = addUserName;
}
public LocalDateTime getAddTime() {
return addTime;
}
public void setAddTime(LocalDateTime addTime) {
this.addTime = addTime;
}
@Override
public String toString() {
return "CropClassifyRecordEntity{" +
"id=" + id +
", countyCode=" + countyCode +
", countyName='" + countyName + '\'' +
", townCode='" + townCode + '\'' +
", townName='" + townName + '\'' +
", cropCode=" + cropCode +
", cropDate=" + cropDate +
", area=" + area +
", dataSource='" + dataSource + '\'' +
", memo='" + memo + '\'' +
", addUserName='" + addUserName + '\'' +
", addTime=" + addTime +
'}';
}
}

Some files were not shown because too many files have changed in this diff Show More