523096025 3 rokov pred
rodič
commit
614f6833b0
19 zmenil súbory, kde vykonal 1146 pridanie a 0 odobranie
  1. 26 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/config/InterceptorConfig.java
  2. 81 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/config/JWTInterceptor.java
  3. 34 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/exception/ExceptionEnum.java
  4. 6 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/exception/MExceptionEnum.java
  5. 20 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/exception/MiException.java
  6. 20 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/token/TokenConstant.java
  7. 128 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/token/TokenSign.java
  8. 133 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/GeneratorCodeConfig.java
  9. 27 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/GetMD5Str.java
  10. 58 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/HttpUtils.java
  11. 27 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/IpTools.java
  12. 19 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/NumberUtils.java
  13. 79 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/PageFactory.java
  14. 8 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/PageResult.java
  15. 38 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/PlatformException.java
  16. 79 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/Result.java
  17. 41 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/ResultCode.java
  18. 202 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/SnowflakeSequence.java
  19. 120 0
      huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/VerifyUtil.java

+ 26 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/config/InterceptorConfig.java

@@ -0,0 +1,26 @@
+package com.huimv.common.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * @Description: 注册验证tocken的拦截器
+ * @Author
+ * @Date 2021/4/19 20:41
+ * @Version V1.0
+ */
+@Configuration
+public class InterceptorConfig implements WebMvcConfigurer {
+    @Bean
+    public JWTInterceptor jwtInterceptor(){
+        return new JWTInterceptor();
+    }
+
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        registry.addInterceptor(jwtInterceptor()).
+                excludePathPatterns("/my/*","/device/deviceResponse");
+    }
+}

+ 81 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/config/JWTInterceptor.java

@@ -0,0 +1,81 @@
+package com.huimv.common.config;
+
+import com.alibaba.fastjson.JSONObject;
+import com.huimv.common.token.TokenConstant;
+import com.huimv.common.token.TokenSign;
+import io.jsonwebtoken.Claims;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * <p>
+ *  jwt拦截器
+ * </p>
+ * @since 2021/4/19
+ */
+public class JWTInterceptor implements HandlerInterceptor {
+
+
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+        // 如果不是映射到方法,则直接通过
+        if (!(handler instanceof HandlerMethod)) {
+            return true;
+        }
+
+        response.setContentType("application/json;charset=utf-8");
+        // 获取token
+        String token=request.getHeader("accessToken");
+
+
+        if (null==token){
+            Map<String,Object> map=new HashMap<>();
+            map.put("data","token is null");
+            map.put("code","401");
+            response.setStatus(401);
+            response.getWriter().write(JSONObject.toJSONString(map));
+            return false;
+        }else {
+            Claims claims = TokenSign.getClaims(token);
+            if (claims == null){
+                Map<String,Object> map=new HashMap<>();
+                map.put("data","token is overdue");
+                map.put("code","403");
+                response.setStatus(403);
+                response.getWriter().write(JSONObject.toJSONString(map));
+                return false;
+            }
+
+            boolean result= TokenSign.verify(token);
+            if (result){
+                //更新存储的token信息
+                TokenConstant.updateTokenMap(token);
+                return true;
+            }
+            Map<String,Object> map=new HashMap<>();
+            map.put("data","token is null");
+            map.put("code","401");
+            response.setStatus(401);
+            response.getWriter().write(JSONObject.toJSONString(map));
+            return false;
+
+        }
+    }
+
+
+    @Override
+    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
+
+    }
+
+    @Override
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+
+    }
+}

+ 34 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/exception/ExceptionEnum.java

@@ -0,0 +1,34 @@
+package com.huimv.common.exception;
+
+public enum ExceptionEnum implements MExceptionEnum{
+   //自定义的状态码
+   TOKEN_NULL("401","token为空"),
+   TOKEN_OVERDUE("403","token过期"),
+   VERIFCATION_FAID("410","验证码获取失败"),
+   VERIFCATION_OVERDUE("411","验证码获取失败");
+
+
+   //错误码
+   public String code;
+   //提示信息
+   public String message;
+
+   //构造函数
+   ExceptionEnum(String code,String message){
+      this.code = code;
+      this.message = message;
+   }
+
+   //获取状态码
+   @Override
+   public String getCode(){
+      return code;
+   }
+   
+   //获取提示信息
+   @Override
+   public String getMessage(){
+      return message;
+   }
+ 
+}

+ 6 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/exception/MExceptionEnum.java

@@ -0,0 +1,6 @@
+package com.huimv.common.exception;
+
+public interface MExceptionEnum{
+    public String getCode();
+    public String getMessage();
+}

+ 20 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/exception/MiException.java

@@ -0,0 +1,20 @@
+package com.huimv.common.exception;
+
+
+public class MiException extends RuntimeException{
+    private ExceptionEnum exceptionEnum;
+
+    public MiException(ExceptionEnum exceptionEnum){
+        this.exceptionEnum = exceptionEnum;
+    }
+
+    public ExceptionEnum getExceptionEnum(){
+        return exceptionEnum;
+    }
+
+    //用来输出异常信息和状态码
+    public void printException(MiException e){
+        ExceptionEnum exceptionEnum = e.getExceptionEnum();
+        System.out.println("异常代码:" + exceptionEnum.getCode() + ",异常信息:" + exceptionEnum.getMessage());
+    }
+}

+ 20 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/token/TokenConstant.java

@@ -0,0 +1,20 @@
+package com.huimv.common.token;
+ 
+import java.util.HashMap;
+import java.util.Map;
+
+public class TokenConstant {
+ 
+    private static Map<String,String> map=new HashMap();
+ 
+ 
+    public static String getToken(){
+            return map.get("token");
+    }
+ 
+    public static void updateTokenMap(String token){
+        map.put("token",token);
+    }
+ 
+ 
+}

+ 128 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/token/TokenSign.java

@@ -0,0 +1,128 @@
+package com.huimv.common.token;
+
+import io.jsonwebtoken.*;
+import org.springframework.util.StringUtils;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.Date;
+
+public class TokenSign {
+
+    /**
+     * 过期时间60分钟
+     */
+    private static final long EXPIRE_TIME= 24 * 60 * 60 * 1000;
+
+    /**
+     * 私钥,使用它生成token,最好进行下加密
+     */
+    private static final String TOKEN_SECRET="Token";
+    private static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";
+    private static final int REFRESH_TIME = 300;
+
+
+    /**
+     * 产生token
+     * @return
+     */
+    public static String sign(String userName,Integer id){
+
+        String JwtToken = Jwts.builder()
+                //头部信息
+                .setHeaderParam("typ", "JWT")
+                .setHeaderParam("alg", "HS256")
+                .setSubject("hm-user")
+                .setIssuedAt(new Date())
+                //过期时间
+                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
+                //token主体部分,存储用户信息
+                .claim("userName", userName)
+                .claim("id",id)
+                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
+                .compact();
+
+        return JwtToken;
+    }
+
+
+    /**
+     * token校验是否正确
+     * @param token
+     * @return
+     */
+
+    public static boolean verify(String token){
+
+        if (StringUtils.isEmpty(token)) {
+            return false;
+        }
+        try {
+            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return false;
+        }
+        return true;
+
+    }
+
+
+    /**
+     * 根据token获取会员id
+     *
+     * @param request
+     * @return
+     */
+    public static Integer getMemberIdByJwtToken(HttpServletRequest request) {
+        String jwtToken = request.getHeader("accessToken");
+        if (StringUtils.isEmpty(jwtToken)) {
+            return null;
+        }
+        Claims claims = getClaims(jwtToken);
+        return (Integer) claims.get("id");
+    }
+
+    /**
+     * 获取claims对象
+     *
+     * @param jwtToken
+     * @return
+     */
+    public static Claims getClaims(String jwtToken) {
+        try {
+            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
+            return claimsJws.getBody();
+        }catch (ExpiredJwtException e){
+            return null;
+        }
+
+
+    }
+    /**
+     * 是否过期
+     *
+     * @param claims
+     * @return -1:有效,0:有效,1:过期,2:被篡改
+     */
+    public static int verifyToken(Claims claims) {
+        if (claims == null) {
+            return 1;
+        }
+        try {
+            claims.getExpiration()
+                    .before(new Date());
+            // 需要自动刷新TOKEN
+            if ((claims.getExpiration().getTime() - System.currentTimeMillis()) < REFRESH_TIME * 1000) {
+                return -1;
+            } else {
+                return 0;
+            }
+        } catch (ExpiredJwtException ex) {
+            return 1;
+        } catch (Exception e) {
+            return 2;
+        }
+    }
+
+
+}

+ 133 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/GeneratorCodeConfig.java

@@ -0,0 +1,133 @@
+package com.huimv.common.utils;
+
+import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
+import com.baomidou.mybatisplus.core.toolkit.StringUtils;
+import com.baomidou.mybatisplus.generator.AutoGenerator;
+import com.baomidou.mybatisplus.generator.config.*;
+import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
+import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
+
+import java.util.Scanner;
+
+/**
+ * 自动生成mybatisplus的相关代码
+ */
+public class GeneratorCodeConfig {
+
+    public static String scanner(String tip) {
+        Scanner scanner = new Scanner(System.in);
+        StringBuilder help = new StringBuilder();
+        help.append("请输入" + tip + ":");
+        System.out.println(help.toString());
+        if (scanner.hasNext()) {
+            String ipt = scanner.next();
+            if (StringUtils.isNotBlank(ipt)) {
+                return ipt;
+            }
+        }
+        throw new MybatisPlusException("请输入正确的" + tip + "!");
+    }
+
+    public static void main(String[] args) {
+        // 代码生成器
+        AutoGenerator mpg = new AutoGenerator();
+
+        // 全局配置
+        GlobalConfig gc = new GlobalConfig();
+        String projectPath = System.getProperty("user.dir");
+        gc.setOutputDir(projectPath + "/huimv-common/src/main/java");
+        gc.setAuthor("astupidcoder");
+        gc.setOpen(false);
+        //实体属性 Swagger2 注解
+        gc.setSwagger2(false);
+        mpg.setGlobalConfig(gc);
+
+        // 数据源配置
+        DataSourceConfig dsc = new DataSourceConfig();
+        dsc.setUrl("jdbc:mysql://192.168.1.7:3306/huimv_farm_v2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");
+        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
+        dsc.setUsername("root");
+        dsc.setPassword("hm123465");
+        mpg.setDataSource(dsc);
+
+        // 包配置
+        PackageConfig pc = new PackageConfig();
+//        pc.setModuleName(scanner("模块名"));
+        pc.setParent("com.huimv.common.template");
+        pc.setEntity("entity");
+        pc.setMapper("mapper");
+        pc.setService("service");
+        pc.setServiceImpl("service.impl");
+        mpg.setPackageInfo(pc);
+
+        // 自定义配置
+//        InjectionConfig cfg = new InjectionConfig() {
+//            @Override
+//            public void initMap() {
+//                // to do nothing
+//            }
+//        };
+
+        // 如果模板引擎是 freemarker
+//        String templatePath = "/templates/mapper.xml.ftl";
+        // 如果模板引擎是 velocity
+        // String templatePath = "/templates/mapper.xml.vm";
+
+        // 自定义输出配置
+//        List<FileOutConfig> focList = new ArrayList<>();
+        // 自定义配置会被优先输出
+//        focList.add(new FileOutConfig(templatePath) {
+//            @Override
+//            public String outputFile(TableInfo tableInfo) {
+//                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
+//                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+//                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
+//            }
+//        });
+        /*
+        cfg.setFileCreate(new IFileCreate() {
+            @Override
+            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
+                // 判断自定义文件夹是否需要创建
+                checkDir("调用默认方法创建的目录");
+                return false;
+            }
+        });
+        */
+//        cfg.setFileOutConfigList(focList);
+//        mpg.setCfg(cfg);
+
+        // 配置模板
+        TemplateConfig templateConfig = new TemplateConfig();
+
+        // 配置自定义输出模板
+        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
+        // templateConfig.setEntity("templates/entity2.java");
+        // templateConfig.setService();
+        // templateConfig.setController();
+
+        templateConfig.setXml(null);
+        mpg.setTemplate(templateConfig);
+
+        // 策略配置
+        StrategyConfig strategy = new StrategyConfig();
+        strategy.setNaming(NamingStrategy.underline_to_camel);
+        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
+        strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
+        strategy.setEntityLombokModel(true);
+        strategy.setRestControllerStyle(true);
+
+        strategy.setEntityLombokModel(true);
+        // 公共父类
+//        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
+        // 写于父类中的公共字段
+//        strategy.setSuperEntityColumns("id");
+        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
+        strategy.setControllerMappingHyphenStyle(true);
+        strategy.setTablePrefix(pc.getModuleName() + "_");
+//        strategy.setTablePrefix("base_");
+        mpg.setStrategy(strategy);
+        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
+        mpg.execute();
+    }
+}

+ 27 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/GetMD5Str.java

@@ -0,0 +1,27 @@
+package com.huimv.common.utils;
+
+import java.math.BigInteger;
+import java.security.MessageDigest;
+
+public class GetMD5Str {
+    /**
+     * 对字符串md5加密
+     *
+     * @param str
+     * @return
+     * @throws Exception
+     */
+    public static String getMD5Str(String str) throws Exception {
+        try {
+            // 生成一个MD5加密计算摘要
+            MessageDigest md = MessageDigest.getInstance("MD5");
+            // 计算md5函数
+            md.update(str.getBytes());
+            // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
+            // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
+            return new BigInteger(1, md.digest()).toString(16);
+        } catch (Exception e) {
+            throw new Exception("MD5加密出现错误,"+e.toString());
+        }
+    }
+}

+ 58 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/HttpUtils.java

@@ -0,0 +1,58 @@
+package com.huimv.common.utils;
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * http 工具类
+ */
+public class HttpUtils {
+
+    public static String post(String requestUrl, String accessToken, String params) throws Exception {
+        String generalUrl = requestUrl + "?access_token=" + accessToken;
+        URL url = new URL(generalUrl);
+        // 打开和URL之间的连接
+        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+        connection.setRequestMethod("POST");
+        // 设置通用的请求属性
+        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+        connection.setRequestProperty("Connection", "Keep-Alive");
+        connection.setUseCaches(false);
+        connection.setDoOutput(true);
+        connection.setDoInput(true);
+
+        // 得到请求的输出流对象
+        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
+        out.writeBytes(params);
+        out.flush();
+        out.close();
+
+        // 建立实际的连接
+        connection.connect();
+        // 获取所有响应头字段
+        Map<String, List<String>> headers = connection.getHeaderFields();
+        // 遍历所有的响应头字段
+        for (String key : headers.keySet()) {
+            System.out.println(key + "--->" + headers.get(key));
+        }
+        // 定义 BufferedReader输入流来读取URL的响应
+        BufferedReader in = null;
+        if (requestUrl.contains("nlp"))
+            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
+        else
+            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
+        String result = "";
+        String getLine;
+        while ((getLine = in.readLine()) != null) {
+            result += getLine;
+        }
+        in.close();
+        System.out.println("result:" + result);
+        return result;
+    }
+}

+ 27 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/IpTools.java

@@ -0,0 +1,27 @@
+package com.huimv.common.utils;
+
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * @author yejijie
+ * @created 2020年7月17日 上午11:24:20
+*/
+@Component
+public class IpTools {
+
+    public static String getRemoteHost(HttpServletRequest request){
+        String ip = request.getHeader("x-forwarded-for");
+        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
+            ip = request.getHeader("Proxy-Client-IP");
+        }
+        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
+            ip = request.getHeader("WL-Proxy-Client-IP");
+        }
+        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
+            ip = request.getRemoteAddr();
+        }
+        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
+    }
+}

+ 19 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/NumberUtils.java

@@ -0,0 +1,19 @@
+package com.huimv.common.utils;
+
+
+import com.baomidou.mybatisplus.core.toolkit.StringUtils;
+
+import java.text.DecimalFormat;
+import java.util.Date;
+
+public class NumberUtils {
+
+    public static DecimalFormat df = new DecimalFormat("#,##0.00");
+    public static String format(String str) {
+        if (StringUtils.isBlank(str)){
+            return "0.00";
+        }
+        return df.format(Double.valueOf(str));
+    }
+
+}

+ 79 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/PageFactory.java

@@ -0,0 +1,79 @@
+/*
+Copyright [2020] [https://www.xiaonuo.vip]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
+
+1.请不要删除和修改根目录下的LICENSE文件。
+2.请不要删除和修改Snowy源码头部的版权声明。
+3.请保留源码和相关描述文件的项目出处,作者声明等。
+4.分发源码时候,请注明软件出处 https://gitee.com/xiaonuobase/snowy
+5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/xiaonuobase/snowy
+6.若您的项目无法满足以上几点,可申请商业授权,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip
+ */
+package com.huimv.common.utils;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+
+
+/**
+ * 默认分页参数构建
+ *
+ * @author yubaoshan
+ * @date 2017/11/15 13:52
+ */
+public class PageFactory {
+
+    /**
+     * 每页大小(默认20)
+     */
+    private static final String PAGE_SIZE_PARAM_NAME = "pageSize";
+
+    /**
+     * 第几页(从1开始)
+     */
+    private static final String PAGE_NO_PARAM_NAME = "pageNo";
+
+    /**
+     * 默认分页,在使用时PageFactory.defaultPage会自动获取pageSize和pageNo参数
+     *
+     * @author xuyuxiang
+     * @date 2020/3/30 16:42
+     */
+    public static <T> Page<T> defaultPage() {
+
+        int pageSize = 20;
+        int pageNo = 1;
+
+
+        return new Page<>(pageNo, pageSize);
+    }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+ 8 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/PageResult.java

@@ -0,0 +1,8 @@
+package com.huimv.common.utils;
+
+import java.util.List;
+
+public class PageResult<T> {
+    private Long total;
+    private List<T> rows;
+}

+ 38 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/PlatformException.java

@@ -0,0 +1,38 @@
+/**
+ * @Copyright (C), 2014-2020, 杭州慧牧科技有限公司
+ * @ClassName: RobotException
+ * @Author: yejijie
+ * @E-mail: yejijie@huimv.com
+ * @Date: 2020年4月23日
+ * @Version: V1.0
+ * @Description:
+ */
+package com.huimv.common.utils;
+
+/**
+ * @author yejijie
+ *
+ */
+public class PlatformException extends RuntimeException {
+
+	/**
+	 * 
+	 */
+	private static final long serialVersionUID = 6529181147584750288L;
+	private String errCode;
+	private String errMsg;
+	public PlatformException() {
+		super();
+	}
+	public PlatformException(String code, String msg) {
+		super(msg);
+		this.errCode = code;
+		this.errMsg = msg;
+	}
+	public String getErrCode() {
+		return errCode;
+	}
+	public String getErrMsg() {
+		return errMsg;
+	}
+}

+ 79 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/Result.java

@@ -0,0 +1,79 @@
+package com.huimv.common.utils;
+
+import java.io.Serializable;
+
+public class Result implements Serializable {
+
+    private boolean success;
+    private Integer code;
+    private String message;
+
+    public boolean isSuccess() {
+        return success;
+    }
+
+    public void setSuccess(boolean success) {
+        this.success = success;
+    }
+
+    public Integer getCode() {
+        return code;
+    }
+
+    public void setCode(Integer code) {
+        this.code = code;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public void setMessage(String message) {
+        this.message = message;
+    }
+
+    public Object getData() {
+        return data;
+    }
+
+    public void setData(Object data) {
+        this.data = data;
+    }
+
+    private Object data;
+
+    //不需要返回数据时使用
+    public Result(ResultCode code) {
+        this.success = code.success;
+        this.code = code.code;
+        this.message = code.message;
+    }
+
+    public Result(ResultCode code, Object data) {
+        this.success = code.success;
+        this.code = code.code;
+        this.message = code.message;
+        this.data = data;
+    }
+
+    public Result(Integer code, String message, boolean success) {
+        this.code = code;
+        this.message = message;
+        this.success = success;
+    }
+
+    /*
+     * 调用ResultCode类封装常用的返回数据
+     */
+    public static Result SUCCESS(){
+        return new Result(ResultCode.SUCCESS);
+    }
+
+    public static Result ERROR(){
+        return new Result(ResultCode.SERVER_ERROR);
+    }
+
+    public static Result FAIL(){
+        return new Result(ResultCode.FAIL);
+    }
+}

+ 41 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/ResultCode.java

@@ -0,0 +1,41 @@
+package com.huimv.common.utils;
+
+public enum ResultCode {
+    SUCCESS(true,10000,"操作成功!"),
+    //---系统错误返回码-----
+    FAIL(false,10001,"操作失败"),
+    UNAUTHENTICATED(false,10002,"您还未登录"),
+    UNAUTHORISE(false,10003,"权限不足"),
+    SERVER_ERROR(false,99999,"抱歉,系统繁忙,请稍后重试!"),
+
+    //---用户操作返回码  2xxxx----
+    MOBILEORPASSWORDERROR(false,20001,"用户名或密码错误");
+    //---企业操作返回码  3xxxx----
+    //---权限操作返回码----
+    //---其他操作返回码----
+
+    //操作是否成功
+    boolean success;
+    //操作代码
+    int code;
+    //提示信息
+    String message;
+
+    ResultCode(boolean success,int code, String message){
+        this.success = success;
+        this.code = code;
+        this.message = message;
+    }
+
+    public boolean success() {
+        return success;
+    }
+
+    public int code() {
+        return code;
+    }
+
+    public String message() {
+        return message;
+    }
+}

+ 202 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/SnowflakeSequence.java

@@ -0,0 +1,202 @@
+package com.huimv.common.utils;
+
+import java.lang.management.ManagementFactory;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+
+/**
+ * Twitter_Snowflake<br>
+ * SnowFlake的结构如下(每部分用-分开):<br>
+ * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
+ * 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
+ * 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
+ * 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
+ * 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
+ * 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
+ * 加起来刚好64位,为一个Long型。<br>
+ * SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
+ */
+public class SnowflakeSequence {
+    // ==============================Fields===========================================
+    /** 开始时间截 (2017/11/29 18:25:29) */
+    private final long twepoch = 1511951129000L;
+
+    /** 机器id所占的位数 */
+    private final long workerIdBits = 5L;
+
+    /** 数据标识id所占的位数 */
+    private final long datacenterIdBits = 5L;
+
+    /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
+    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
+
+    /** 支持的最大数据标识id,结果是31 */
+    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
+
+    /** 序列在id中占的位数 */
+    private final long sequenceBits = 12L;
+
+    /** 机器ID向左移12位 */
+    private final long workerIdShift = sequenceBits;
+
+    /** 数据标识id向左移17位(12+5) */
+    private final long datacenterIdShift = sequenceBits + workerIdBits;
+
+    /** 时间截向左移22位(5+5+12) */
+    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
+
+    /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
+    private final long sequenceMask = -1L ^ (-1L << sequenceBits);
+
+    /** 工作机器ID(0~31) */
+    private long workerId;
+
+    /** 数据中心ID(0~31) */
+    private long datacenterId;
+
+    /** 毫秒内序列(0~4095) */
+    private long sequence = 0L;
+
+    /** 上次生成ID的时间截 */
+    private long lastTimestamp = -1L;
+
+    //==============================构造函数=====================================
+    //根据mac地址产生datacenterid
+    public SnowflakeSequence() {
+        datacenterId = getDatacenterId(maxDatacenterId);
+        workerId = getMaxWorkerId(datacenterId, maxWorkerId);
+//        System.out.println("datacenterId:" + datacenterId + ",workerId:" + workerId);
+    }
+
+    /**
+     * 构造函数
+     * @param workerId 工作ID (0~31)
+     * @param datacenterId 数据中心ID (0~31)
+     */
+    public SnowflakeSequence(long workerId, long datacenterId) {
+        if (workerId > maxWorkerId || workerId < 0) {
+            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
+        }
+        if (datacenterId > maxDatacenterId || datacenterId < 0) {
+            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
+        }
+        this.workerId = workerId;
+        this.datacenterId = datacenterId;
+    }
+
+    // ==============================Methods==========================================
+    /**
+     * 获得下一个ID (该方法是线程安全的)
+     * @return SnowflakeId
+     */
+    public synchronized long nextId() {
+        long timestamp = timeGen();
+
+        //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
+        if (timestamp < lastTimestamp) {
+            throw new RuntimeException(
+                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
+        }
+
+        //如果是同一时间生成的,则进行毫秒内序列
+        if (lastTimestamp == timestamp) {
+            sequence = (sequence + 1) & sequenceMask;
+            //毫秒内序列溢出
+            if (sequence == 0) {
+                //阻塞到下一个毫秒,获得新的时间戳
+                timestamp = tilNextMillis(lastTimestamp);
+            }
+        }
+        //时间戳改变,毫秒内序列重置
+        else {
+            sequence = 0L;
+        }
+
+        //上次生成ID的时间截
+        lastTimestamp = timestamp;
+
+        //移位并通过或运算拼到一起组成64位的ID
+        return ((timestamp - twepoch) << timestampLeftShift) //
+                | (datacenterId << datacenterIdShift) //
+                | (workerId << workerIdShift) //
+                | sequence;
+    }
+
+    /**
+     * 阻塞到下一个毫秒,直到获得新的时间戳
+     * @param lastTimestamp 上次生成ID的时间截
+     * @return 当前时间戳
+     */
+    protected long tilNextMillis(long lastTimestamp) {
+        long timestamp = timeGen();
+        while (timestamp <= lastTimestamp) {
+            timestamp = timeGen();
+        }
+        return timestamp;
+    }
+
+    /**
+     * 返回以毫秒为单位的当前时间
+     * @return 当前时间(毫秒)
+     */
+    protected long timeGen() {
+        return System.currentTimeMillis();
+    }
+
+    /**
+     * <p>
+     * 数据标识id部分
+     * </p>
+     * @param maxDatacenterId
+     * @return
+     */
+    protected static long getDatacenterId(long maxDatacenterId) {
+        long id = 0L;
+        try {
+            InetAddress ip = InetAddress.getLocalHost();
+            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
+            if (network == null) {
+                id = 1L;
+            } else {
+                byte[] mac = network.getHardwareAddress();
+                if (null != mac) {
+                    id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
+                    id = id % (maxDatacenterId + 1);
+                }
+            }
+        } catch (Exception e) {
+            System.err.println(" getDatacenterId: " + e.getMessage());
+        }
+        return id;
+    }
+
+    /**
+     * 获取 maxWorkerId
+     * @param datacenterId   数据中心id
+     * @param maxWorkerId    机器id
+     * @return  maxWorkerId
+     */
+    protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
+        StringBuilder mpid = new StringBuilder();
+        mpid.append(datacenterId);
+        String name = ManagementFactory.getRuntimeMXBean().getName();
+        if (name != null && "".equals(name)) {
+            // GET jvmPid
+            mpid.append(name.split("@")[0]);
+        }
+        //MAC + PID 的 hashcode 获取16个低位
+        return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
+    }
+
+    //==============================Test=============================================
+    /** 测试 */
+    public static void main(String[] args) {
+//        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
+        SnowflakeSequence idWorker = new SnowflakeSequence();
+        for (int i = 0; i < 10; i++) {
+            long id = idWorker.nextId();
+//            System.out.println(Long.toBinaryString(id));
+            System.out.println(id);
+        }
+    }
+}

+ 120 - 0
huimv-farm-v2/huimv-common/src/main/java/com/huimv/common/utils/VerifyUtil.java

@@ -0,0 +1,120 @@
+package com.huimv.common.utils;
+
+
+import com.huimv.common.exception.ExceptionEnum;
+import com.huimv.common.exception.MiException;
+
+import javax.imageio.ImageIO;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.util.Random;
+
+
+public class VerifyUtil {
+//    public static final String RANDOMCODEKEY = "RANDOMREDISKEY";//放到session中的key
+    private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串
+    private int width = 95;// 图片宽
+    private int height = 50;// 图片高
+    private int lineSize = 40;// 干扰线数量
+    private int stringNum = 4;// 随机产生字符数量
+
+    private Random random = new Random();
+
+    /**
+     * 获得字体
+     */
+    private Font getFont() {
+        return new Font("Fixedsys", Font.CENTER_BASELINE, 25);
+    }
+
+    /**
+     * 获得颜色
+     */
+    private Color getRandColor(int fc, int bc) {
+        if (fc > 255) {
+            fc = 255;
+        }
+        if (bc > 255) {
+            bc = 255;
+        }
+        int r = fc + random.nextInt(bc - fc - 16);
+        int g = fc + random.nextInt(bc - fc - 14);
+        int b = fc + random.nextInt(bc - fc - 18);
+        return new Color(r, g, b);
+    }
+
+    /**
+     * 生成随机图片
+     */
+    public String getRandcode(HttpServletRequest request, HttpServletResponse response) {
+        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
+        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
+        // 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
+        Graphics g = image.getGraphics();
+        //图片大小
+        g.fillRect(0, 0, width, height);
+        //字体大小
+        g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 50));
+        //字体颜色
+        g.setColor(getRandColor(110, 133));
+        // 绘制干扰线
+        for (int i = 0; i <= lineSize; i++) {
+            drowLine(g);
+        }
+        // 绘制随机字符
+        String randomString = "";
+        for (int i = 1; i <= stringNum; i++) {
+            randomString = drowString(g, randomString, i);
+        }
+        //将生成的随机字符串保存到session中
+//        session.removeAttribute(RANDOMCODEKEY);
+//        session.setAttribute(RANDOMCODEKEY, randomString);
+        //设置失效时间1分钟
+//        session.setMaxInactiveInterval(60);
+        g.dispose();
+        try {
+            // 将内存中的图片通过流动形式输出到客户端
+            ImageIO.write(image, "JPEG", response.getOutputStream());
+            return randomString;
+        } catch (Exception e) {
+            throw new MiException(ExceptionEnum.VERIFCATION_FAID);
+        }
+
+    }
+
+    /**
+     * 绘制字符串
+     */
+    private String drowString(Graphics g, String randomString, int i) {
+        g.setFont(getFont());
+        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
+                .nextInt(121)));
+        String rand = String.valueOf(getRandomString(random.nextInt(randString
+                .length())));
+        randomString += rand;
+        g.translate(random.nextInt(3), random.nextInt(3));
+        g.drawString(rand, 13 * i, 33);
+        return randomString;
+    }
+
+    /**
+     * 绘制干扰线
+     */
+    private void drowLine(Graphics g) {
+        int x = random.nextInt(width);
+        int y = random.nextInt(height);
+        int xl = random.nextInt(13);
+        int yl = random.nextInt(15);
+        g.drawLine(x, y, x + xl, y + yl);
+    }
+
+    /**
+     * 获取随机的字符
+     */
+    public String getRandomString(int num) {
+        return String.valueOf(randString.charAt(num));
+    }
+}
+