1
This commit is contained in:
131
common-token-starter/common-token-starter.iml
Normal file
131
common-token-starter/common-token-starter.iml
Normal file
@ -0,0 +1,131 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
|
||||
<component name="FacetManager">
|
||||
<facet type="Spring" name="Spring">
|
||||
<configuration />
|
||||
</facet>
|
||||
<facet type="web" name="Web">
|
||||
<configuration>
|
||||
<webroots />
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
|
||||
<output url="file://$MODULE_DIR$/target/classes" />
|
||||
<output-test url="file://$MODULE_DIR$/target/test-classes" />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="module" module-name="common-base-starter" />
|
||||
<orderEntry type="library" name="Maven: org.apache.velocity:velocity-engine-core:2.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.30" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.springfox:springfox-swagger2:2.8.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.swagger:swagger-annotations:1.5.14" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.swagger:swagger-models:1.5.14" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.springfox:springfox-spi:2.8.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.springfox:springfox-core:2.8.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: net.bytebuddy:byte-buddy:1.7.9" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.springfox:springfox-schema:2.8.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.springfox:springfox-swagger-common:2.8.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.springfox:springfox-spring-web:2.8.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.reflections:reflections:0.9.11" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.javassist:javassist:3.21.0-GA" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.fasterxml:classmate:1.3.4" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.plugin:spring-plugin-core:1.2.0.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.plugin:spring-plugin-metadata:1.2.0.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.mapstruct:mapstruct:1.2.0.Final" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.springfox:springfox-swagger-ui:2.8.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.github.caspar-chen:swagger-ui-layer:1.1.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: cn.hutool:hutool-all:5.7.20" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.belerweb:pinyin4j:2.5.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.alibaba:fastjson:1.2.83" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.12.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.google.guava:guava:29.0-jre" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.google.guava:failureaccess:1.0.1" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.google.code.findbugs:jsr305:3.0.2" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.checkerframework:checker-qual:2.11.1" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.google.errorprone:error_prone_annotations:2.3.4" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.google.j2objc:j2objc-annotations:1.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.github.pagehelper:pagehelper:5.3.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.github.jsqlparser:jsqlparser:4.2" level="project" />
|
||||
<orderEntry type="library" name="Maven: jakarta.validation:jakarta.validation-api:2.0.2" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-boot-starter:3.4.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus:3.4.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.4.5" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-jdbc:2.4.5" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:3.4.5" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-jdbc:5.3.6" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-tx:5.3.6" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-extension:3.4.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-core:3.4.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.baomidou:mybatis-plus-annotation:3.4.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.mybatis:mybatis:3.5.7" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.mybatis:mybatis-spring:2.0.6" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml:4.1.2" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.poi:poi-ooxml-schemas:4.1.2" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.xmlbeans:xmlbeans:3.1.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.commons:commons-compress:1.19" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.github.virtuald:curvesapi:1.06" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.poi:poi:4.1.2" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.commons:commons-collections4:4.4" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.commons:commons-math3:3.6.1" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.zaxxer:SparseBitSet:1.2" level="project" />
|
||||
<orderEntry type="module" module-name="common-redis-starter" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-data-redis:2.3.0.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-redis:2.3.0.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-keyvalue:2.3.0.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-commons:2.3.0.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-oxm:5.2.6.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-context-support:5.2.6.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.lettuce:lettuce-core:5.3.0.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.netty:netty-common:4.1.49.Final" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.netty:netty-handler:4.1.49.Final" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.netty:netty-resolver:4.1.49.Final" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.netty:netty-buffer:4.1.49.Final" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.netty:netty-codec:4.1.49.Final" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.netty:netty-transport:4.1.49.Final" level="project" />
|
||||
<orderEntry type="library" name="Maven: io.projectreactor:reactor-core:3.3.5.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.reactivestreams:reactive-streams:1.0.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-web:2.3.2.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:2.3.2.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:2.3.2.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.3.2.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.13.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.13.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.30" level="project" />
|
||||
<orderEntry type="library" name="Maven: jakarta.annotation:jakarta.annotation-api:1.3.5" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.2.8.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.2.8.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.26" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-json:2.3.2.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.11.1" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.11.1" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-parameter-names:2.11.1" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-tomcat:2.3.2.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-core:9.0.37" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.glassfish:jakarta.el:3.0.3" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-websocket:9.0.37" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-web:5.2.8.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.2.8.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-webmvc:5.2.8.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.2.8.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.2.8.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.alibaba:transmittable-thread-local:2.11.5" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-aop:2.3.2.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.2.8.RELEASE" level="project" />
|
||||
<orderEntry type="library" name="Maven: org.aspectj:aspectjweaver:1.9.6" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.auth0:java-jwt:3.8.1" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.9.9" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.9.0" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.9.9" level="project" />
|
||||
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.12" level="project" />
|
||||
<orderEntry type="library" scope="PROVIDED" name="Maven: org.projectlombok:lombok:1.16.18" level="project" />
|
||||
<orderEntry type="library" name="Maven: com.vividsolutions:jts:1.13" level="project" />
|
||||
</component>
|
||||
</module>
|
84
common-token-starter/pom.xml
Normal file
84
common-token-starter/pom.xml
Normal file
@ -0,0 +1,84 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>mosty-common</artifactId>
|
||||
<groupId>com.mosty</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>common-token-starter</artifactId>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.mosty</groupId>
|
||||
<artifactId>common-base-starter</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${spring-boot-dependencies.version}</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>transmittable-thread-local</artifactId>
|
||||
<version>${transmittable-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
<version>${spring-boot-dependencies.version}</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.auth0</groupId>
|
||||
<artifactId>java-jwt</artifactId>
|
||||
<version>3.8.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.16.18</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.vividsolutions</groupId>
|
||||
<artifactId>jts</artifactId>
|
||||
<version>1.13</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<distributionManagement>
|
||||
<repository>
|
||||
<id>mosty-nexus-releases</id>
|
||||
<name>release version</name>
|
||||
<url>http://10.64.201.126:8081/repository/maven-releases/</url>
|
||||
</repository>
|
||||
<snapshotRepository>
|
||||
<id>mosty-nexus-snapshots</id>
|
||||
<name>snapshots version</name>
|
||||
<url>http://10.64.201.126:8081/repository/maven-snapshots/</url>
|
||||
</snapshotRepository>
|
||||
</distributionManagement>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>2.8.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,60 @@
|
||||
//
|
||||
// Source code recreated from a .class file by IntelliJ IDEA
|
||||
// (powered by FernFlower decompiler)
|
||||
//
|
||||
|
||||
package com.mosty.common.token;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 部门信息
|
||||
*/
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class DeptInfo implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -2608276244908343842L;
|
||||
|
||||
|
||||
@ApiModelProperty(value = "所属部门id")
|
||||
private Long ssbmid;
|
||||
|
||||
@ApiModelProperty(value = "所属部门")
|
||||
private String ssbm;
|
||||
|
||||
@ApiModelProperty(value = "所属部门代码")
|
||||
private String ssbmdm;
|
||||
|
||||
@ApiModelProperty(value = "所属县公安局")
|
||||
private String ssxgaj;
|
||||
|
||||
@ApiModelProperty(value = "所属县公安局id")
|
||||
private Long ssxgajid;
|
||||
|
||||
@ApiModelProperty(value = "所属县公安局代码")
|
||||
private String ssxgajdm;
|
||||
|
||||
@ApiModelProperty(value = "所属市公安局id")
|
||||
private Long sssgajid;
|
||||
|
||||
@ApiModelProperty(value = "所属市公安局")
|
||||
private String sssgaj;
|
||||
|
||||
@ApiModelProperty(value = "所属市公安局代码")
|
||||
private String sssgajdm;
|
||||
|
||||
@ApiModelProperty("权限等级(D_ZDY_SJQX)")
|
||||
private String permissionsLevel;
|
||||
|
||||
@ApiModelProperty("权限过滤条件ids")
|
||||
private String ids;
|
||||
}
|
@ -0,0 +1,102 @@
|
||||
package com.mosty.common.token;
|
||||
|
||||
import cn.hutool.json.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.TokenExpiredException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.auth0.jwt.interfaces.JWTVerifier;
|
||||
import com.mosty.common.base.exception.BusinessException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.ObjectUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import static com.mosty.common.base.constant.SystemConfigConstants.TOKEN_ISSUER;
|
||||
import static com.mosty.common.base.constant.SystemConfigConstants.TOKEN_KEY;
|
||||
|
||||
/**
|
||||
* token工具类
|
||||
*
|
||||
* @author kevin
|
||||
* @date 2022/3/21 11:03 PM
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@Slf4j
|
||||
public class JWTUtil {
|
||||
public JWTUtil() {
|
||||
}
|
||||
|
||||
public static DecodedJWT verify(String token) {
|
||||
try {
|
||||
// 这里不判断token过期状态
|
||||
// Algorithm algorithm = Algorithm.HMAC256(TOKEN_KEY);
|
||||
// JWTVerifier verifier = JWT.require(algorithm).withIssuer(new String[]{TOKEN_ISSUER}).build();
|
||||
// DecodedJWT decodedJWT = verifier.verify(token);
|
||||
//
|
||||
// Date expiresAt = decodedJWT.getExpiresAt();
|
||||
// if (expiresAt.before(new Date())) {
|
||||
// log.info("token已过期");
|
||||
// }
|
||||
//
|
||||
// return expiresAt.after(new Date()) ? decodedJWT : null;
|
||||
if(StringUtils.isNotEmpty(token)){
|
||||
Algorithm algorithm = Algorithm.HMAC256(TOKEN_KEY);
|
||||
JWTVerifier verifier = JWT.require(algorithm).withIssuer(new String[]{TOKEN_ISSUER}).build();
|
||||
return verifier.verify(token);
|
||||
}
|
||||
return null;
|
||||
} catch (TokenExpiredException expiredException) {
|
||||
log.warn("token过期:{}", expiredException.getMessage());
|
||||
throw new BusinessException(HttpStatus.UNAUTHORIZED.value(), "token过期,请重新登陆", null);
|
||||
} catch (Exception var11) {
|
||||
var11.printStackTrace();
|
||||
log.error("解签失败: {}", var11.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* token 泛解析用户信息
|
||||
*
|
||||
* @param token jwt token
|
||||
* @return 用户信息
|
||||
*/
|
||||
public static UserInfo getUserInfo(String token) {
|
||||
DecodedJWT jwt = verify(token);
|
||||
if (jwt == null) {
|
||||
return null;
|
||||
}
|
||||
return new UserInfo(
|
||||
jwt.getClaim("userId").asLong(),
|
||||
jwt.getClaim("userName").asString(),
|
||||
jwt.getClaim("phone").asString(),
|
||||
jwt.getClaim("userLoginName").asString(),
|
||||
jwt.getClaim("inDustRialId").asString(),
|
||||
jwt.getClaim("idEntityCard").asString(),
|
||||
jwt.getClaim("isVirtualUser").asString(),
|
||||
jwt.getClaim("level").asString(),
|
||||
jwt.getClaim("deptId").asLong(),
|
||||
jwt.getClaim("deptName").asString(),
|
||||
jwt.getClaim("deptCode").asString(),
|
||||
jwt.getClaim("fxjDeptId").asLong(),
|
||||
jwt.getClaim("fxjDeptName").asString(),
|
||||
jwt.getClaim("fxjDeptCode").asString(),
|
||||
jwt.getClaim("dszDeptId").asLong(),
|
||||
jwt.getClaim("dszDeptName").asString(),
|
||||
jwt.getClaim("dszDeptCode").asString(),
|
||||
jwt.getClaim("deptLevel").asString(),
|
||||
jwt.getClaim("deptBizType").asString(),
|
||||
JSONObject.parseObject(jwt.getClaim("permissions").asString(), UserPermissionsInfo.class)
|
||||
);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
UserInfo res = getUserInfo("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlzcyI6Inprai1mcG0tc3RvcmVhZG1pbiIsImV4cCI6MTYyODMzMTE1NCwiaWF0IjoxNjI3ODk5MTU0LCJ1c2VySWQiOjUzfQ.hJ25t46zntTUknwjsB0UJzOIFcM5n7IG0DDA6RVP8jM");
|
||||
System.out.println(res);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.mosty.common.token;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 用户信息泛解析标识
|
||||
* @author kevin
|
||||
* @date 2022/2/16 1:17 PM
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.METHOD, ElementType.TYPE})
|
||||
public @interface JwtSysUser {
|
||||
|
||||
/**
|
||||
* 用户realm,方便后续扩展
|
||||
* @return 用户
|
||||
*/
|
||||
String value() default "";
|
||||
}
|
@ -0,0 +1,129 @@
|
||||
package com.mosty.common.token;
|
||||
|
||||
import com.mosty.common.base.exception.BusinessException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* token解析器
|
||||
* @author kevin
|
||||
* @date 2022/3/21 11:12 PM
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@Slf4j
|
||||
@SuppressWarnings("unused")
|
||||
public class SysUserInterceptor implements HandlerInterceptor {
|
||||
public SysUserInterceptor() {
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
}
|
||||
|
||||
public boolean preHandle(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler){
|
||||
if (!(handler instanceof HandlerMethod)) {
|
||||
return true;
|
||||
}else{
|
||||
HandlerMethod handlerMethod =(HandlerMethod)handler;
|
||||
Method method = handlerMethod.getMethod();
|
||||
JwtSysUser sysUser =(JwtSysUser)method.getAnnotation(JwtSysUser.class);
|
||||
|
||||
if(sysUser == null) {
|
||||
sysUser = (JwtSysUser) method.getDeclaringClass().getAnnotation(JwtSysUser.class);
|
||||
}
|
||||
if (sysUser == null) {
|
||||
return true;
|
||||
}else {
|
||||
UserInfo info = this.getUserInfoFromJwtToken(request, sysUser);
|
||||
if(info == null){
|
||||
throw new BusinessException(401,"登录过期,请重新登录!!",(Object)null);
|
||||
} else {
|
||||
UserInfoManager.set(info);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void afterCompletion(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler, Exception ex) {
|
||||
UserInfoManager.clear();
|
||||
}
|
||||
|
||||
private boolean setUserInfo(UserInfo info, JwtSysUser sysUser) {
|
||||
// if (this.mockUserInfo) {
|
||||
// return true;
|
||||
// }
|
||||
|
||||
// UserInfoResp resp = this.userInfoCache.getUserInfo(info.getUserId(), sysUser.value());
|
||||
// if (resp == null) {
|
||||
// return false;
|
||||
// } else {
|
||||
// info.setMerchantId(resp.getMerchantId());
|
||||
// info.setMobile(resp.getMobile());
|
||||
// info.setUsername(resp.getUsername());
|
||||
// info.setAccount(resp.getAccount());
|
||||
// info.setStatus(resp.getStatus());
|
||||
// info.setEmail(resp.getEmail());
|
||||
// info.setSystemType(SystemTypeEnum.toEnum(resp.getSystem()));
|
||||
// info.setUserInfoType(UserInfoTypeEnum.toEnum(resp.getType()));
|
||||
// return true;
|
||||
// }
|
||||
return true;
|
||||
}
|
||||
|
||||
private UserInfo getUserInfoFromJwtToken(HttpServletRequest request, JwtSysUser sysUser) {
|
||||
try {
|
||||
String token = request.getHeader("token");
|
||||
if (token == null) {
|
||||
token = request.getHeader("Authorization");
|
||||
}
|
||||
|
||||
if (!StringUtils.isEmpty(token)) {
|
||||
return JWTUtil.getUserInfo(token);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("解析token异常", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void writeNeedLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
this.assemblyResponse(request, response, "用户未登录!", HttpStatus.UNAUTHORIZED, "BIZ.USER_NOT_LOGIN");
|
||||
}
|
||||
|
||||
private void writeException(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
this.assemblyResponse(request, response, "网络异常,请稍后再试", HttpStatus.OK, "BIZ.BUSSINESS_EXCEPTION");
|
||||
}
|
||||
|
||||
private void assemblyResponse(HttpServletRequest request, HttpServletResponse response, String errorMsg, HttpStatus unauthorized, String userNotLogin) throws IOException {
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.setStatus(unauthorized.value());
|
||||
String origin = request.getHeader("Origin");
|
||||
if (origin == null) {
|
||||
response.addHeader("Access-Control-Allow-Origin", "*");
|
||||
} else {
|
||||
response.addHeader("Access-Control-Allow-Origin", origin);
|
||||
}
|
||||
|
||||
response.addHeader("Access-Control-Allow-Headers", "*");
|
||||
response.addHeader("Access-Control-Allow-Credentials", "true");
|
||||
response.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
|
||||
PrintWriter writer = response.getWriter();
|
||||
// writer.write(JSON.toJSONString(new ResponseResult(userNotLogin, errorMsg)));
|
||||
writer.flush();
|
||||
writer.close();
|
||||
}
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
//
|
||||
// Source code recreated from a .class file by IntelliJ IDEA
|
||||
// (powered by FernFlower decompiler)
|
||||
//
|
||||
|
||||
package com.mosty.common.token;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户信息
|
||||
*
|
||||
* @author kevin
|
||||
* @date 2022/2/16 1:24 PM
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
@AllArgsConstructor
|
||||
public class UserInfo implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -2608276244908343842L;
|
||||
|
||||
@ApiModelProperty(value = "用户id")
|
||||
public final Long userId;
|
||||
|
||||
@ApiModelProperty(value = "用户名")
|
||||
public final String userName;
|
||||
|
||||
@ApiModelProperty(value = "用户电话")
|
||||
public final String phone;
|
||||
|
||||
@ApiModelProperty(value = "用户账号")
|
||||
public final String userLoginName;
|
||||
|
||||
@ApiModelProperty(value = "用户行业号码")
|
||||
public final String inDustRialId;
|
||||
|
||||
@ApiModelProperty(value = "用户身份证号")
|
||||
public final String idEntityCard;
|
||||
|
||||
@ApiModelProperty(value = "是否虚拟用户")
|
||||
public final String isVirtualUser;
|
||||
|
||||
@ApiModelProperty(value = "数据权限范围")
|
||||
public final String level;
|
||||
|
||||
@ApiModelProperty(value = "部门id")
|
||||
public final Long deptId;
|
||||
|
||||
@ApiModelProperty(value = "部门名称")
|
||||
public final String deptName;
|
||||
|
||||
@ApiModelProperty(value = "部门编码")
|
||||
public final String deptCode;
|
||||
|
||||
@ApiModelProperty(value = "分县局部门id")
|
||||
public final Long fxjDeptId;
|
||||
|
||||
@ApiModelProperty(value = "分县局部门名称")
|
||||
public final String fxjDeptName;
|
||||
|
||||
@ApiModelProperty(value = "分县局部门编码")
|
||||
public final String fxjDeptCode;
|
||||
|
||||
@ApiModelProperty(value = "地市州部门id")
|
||||
public final Long dszDeptId;
|
||||
|
||||
@ApiModelProperty(value = "地市州部门名称")
|
||||
public final String dszDeptName;
|
||||
|
||||
@ApiModelProperty(value = "地市州部门编码")
|
||||
public final String dszDeptCode;
|
||||
|
||||
@ApiModelProperty(value = "部门等级")
|
||||
public final String deptLevel;
|
||||
|
||||
@ApiModelProperty(value = "所在部门业务类型代码")
|
||||
public final String deptBizType;
|
||||
|
||||
@ApiModelProperty(value = "用户数据权限SQL")
|
||||
public final UserPermissionsInfo userPermissionsInfo;
|
||||
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
//package com.mosty.common.token;
|
||||
//
|
||||
//import com.google.common.base.Function;
|
||||
//import com.google.common.cache.CacheBuilder;
|
||||
//import com.google.common.cache.CacheLoader;
|
||||
//import com.google.common.cache.LoadingCache;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Map;
|
||||
//import java.util.concurrent.TimeUnit;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//import org.springframework.stereotype.Component;
|
||||
//import org.springframework.util.StringUtils;
|
||||
//
|
||||
//@Component
|
||||
//public class UserInfoCache {
|
||||
// private static final Logger log = LoggerFactory.getLogger(UserInfoCache.class);
|
||||
// private static final String KEY_MID = "_";
|
||||
// private final Map<Integer, Function<Integer, ResponseResult<UserInfoResp>>> func = new HashMap();
|
||||
// private final LoadingCache<String, UserInfoResp> cache;
|
||||
//
|
||||
// public UserInfoCache(StoreUserInfoClient storeUserInfoClient, PlatformUserInfoClient platformUserInfoClient) {
|
||||
// this.cache = CacheBuilder.newBuilder().maximumSize(10000L).expireAfterWrite(3L, TimeUnit.MINUTES).build(new CacheLoader<String, UserInfoResp>() {
|
||||
// public UserInfoResp load(String key) {
|
||||
// if (StringUtils.isEmpty(key)) {
|
||||
// return null;
|
||||
// } else {
|
||||
// String[] vs = key.split("_");
|
||||
// Integer type = Integer.valueOf(vs[0]);
|
||||
// Integer userId = Integer.valueOf(vs[1]);
|
||||
// UserType userType = UserType.toEnum(type);
|
||||
// if (userType == null) {
|
||||
// UserInfoCache.log.error("用户类型正确,type:{},userId:{}", type, userId);
|
||||
// return null;
|
||||
// } else {
|
||||
// ResponseResult<UserInfoResp> result = (ResponseResult)((Function)UserInfoCache.this.func.get(type)).apply(userId);
|
||||
// if (result != null) {
|
||||
// if (result.isSuccess()) {
|
||||
// return (UserInfoResp)result.getData();
|
||||
// }
|
||||
//
|
||||
// UserInfoCache.log.error("调用{}后台用户失败:{},{}", new Object[]{userType.getName(), userId, result.getMessage()});
|
||||
// }
|
||||
//
|
||||
// return null;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// if (storeUserInfoClient != null && platformUserInfoClient != null) {
|
||||
// this.func.put(UserType.store.getValue(), storeUserInfoClient::getUserInfo);
|
||||
// this.func.put(UserType.platform.getValue(), platformUserInfoClient::getUserInfo);
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// public UserInfoResp getUserInfo(Integer userId, UserType userType) {
|
||||
// if (userId != null && userType != null) {
|
||||
// try {
|
||||
// return (UserInfoResp)this.cache.getUnchecked(userType.value + "_" + userId);
|
||||
// } catch (Exception var4) {
|
||||
// log.error("key:{}/{} err", new Object[]{userId, userType, var4});
|
||||
// return null;
|
||||
// }
|
||||
// } else {
|
||||
// return null;
|
||||
// }
|
||||
// }
|
||||
//}
|
@ -0,0 +1,34 @@
|
||||
package com.mosty.common.token;
|
||||
|
||||
import com.alibaba.ttl.TransmittableThreadLocal;
|
||||
import com.mosty.common.base.exception.BusinessException;
|
||||
|
||||
public class UserInfoManager {
|
||||
|
||||
/**
|
||||
* 用户信息
|
||||
*/
|
||||
private static final ThreadLocal<UserInfo> USER_CONTEXT = TransmittableThreadLocal.withInitial(() -> null);
|
||||
|
||||
public UserInfoManager() {}
|
||||
|
||||
public static void set(UserInfo userInfo) {
|
||||
USER_CONTEXT.set(userInfo);
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
USER_CONTEXT.remove();
|
||||
}
|
||||
|
||||
public static UserInfo get() {
|
||||
UserInfo user = USER_CONTEXT.get();
|
||||
if (user == null) {
|
||||
throw new BusinessException("登录信息获取异常,请重新登录!!");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
public static UserInfo getUser() {
|
||||
return USER_CONTEXT.get();
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.mosty.common.token;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
/**
|
||||
* 用户权限信息
|
||||
* @author Lhh
|
||||
* @date 2022/06/27 17:24
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class UserPermissionsInfo {
|
||||
|
||||
@ApiModelProperty("权限过滤条件ids")
|
||||
private String ids;
|
||||
|
||||
@ApiModelProperty("权限过滤条件orgcodes")
|
||||
private String orgcodes;
|
||||
|
||||
@ApiModelProperty("权限等级(D_ZDY_SJQX)")
|
||||
private String permissionsLevel;
|
||||
|
||||
@ApiModelProperty("权限SQL(ssbmid)")
|
||||
private String permissionsSql;
|
||||
|
||||
@ApiModelProperty("权限SQL(ssbmdm)")
|
||||
private String permissionsSqlCode;
|
||||
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
//package com.mosty.common.token;
|
||||
//
|
||||
//import com.aimart.common.base.BaseEnum;
|
||||
//
|
||||
//public enum UserType implements BaseEnum {
|
||||
// store(1, "商家/门店后台"),
|
||||
// platform(2, "平台后台");
|
||||
//
|
||||
// public final int value;
|
||||
// public final String name;
|
||||
//
|
||||
// public int getValue() {
|
||||
// return this.value;
|
||||
// }
|
||||
//
|
||||
// public String getName() {
|
||||
// return this.name;
|
||||
// }
|
||||
//
|
||||
// public static UserType toEnum(Integer value) {
|
||||
// return (UserType)BaseEnum.toEnum(value, UserType.class);
|
||||
// }
|
||||
//
|
||||
// private UserType(int value, String name) {
|
||||
// this.value = value;
|
||||
// this.name = name;
|
||||
// }
|
||||
//}
|
@ -0,0 +1,43 @@
|
||||
package com.mosty.common.token;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
/**
|
||||
* 虚拟用户标识
|
||||
* @author kevin
|
||||
* @date 2022/2/25 9:52 AM
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
public enum VirtualUserEnum {
|
||||
|
||||
/** 正常用户 */
|
||||
NATURE(1, "正常用户"),
|
||||
|
||||
/** 虚拟用户 */
|
||||
VIRTUAL(2, "虚拟状态");
|
||||
|
||||
/** 编码 */
|
||||
public final Integer code;
|
||||
|
||||
/** 描述 */
|
||||
public final String desc;
|
||||
|
||||
/**
|
||||
* 编码匹配 用户类型
|
||||
* @param code 编码
|
||||
* @return 虚拟用户枚举
|
||||
*/
|
||||
public static VirtualUserEnum valueOf(Integer code) {
|
||||
if (code == null) {
|
||||
return null;
|
||||
}
|
||||
for (VirtualUserEnum virtualUserEnum : VirtualUserEnum.values()) {
|
||||
if (virtualUserEnum.code.equals(code)) {
|
||||
return virtualUserEnum;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.mosty.common.util;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
/**
|
||||
* 菜单类型枚举
|
||||
* @author kevin
|
||||
* @date 2022/2/22 12:53 PM
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
public class DataPermissionConstant {
|
||||
|
||||
// 全部数据权限
|
||||
public static final String DATA_SCOPE_ALL = "1";
|
||||
// 市级数据权限
|
||||
public static final String DATA_SCOPE_CITY = "2";
|
||||
// 县级数据权限
|
||||
public static final String DATA_SCOPE_COUNTY = "3";
|
||||
// 部门及以下数据权限
|
||||
public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";
|
||||
// 部门数据权限
|
||||
public static final String DATA_SCOPE_DEPT = "5";
|
||||
// 仅本人数据权限
|
||||
public static final String DATA_SCOPE_SELF = "99";
|
||||
|
||||
}
|
@ -0,0 +1,139 @@
|
||||
package com.mosty.common.util;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author dw
|
||||
* @since 2022/7/19
|
||||
* 经纬度相关工具
|
||||
**/
|
||||
public class GeoHashKit {
|
||||
private static final char[] _base32 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
|
||||
|
||||
private final static Map<Character, Integer> _decodemap = new HashMap<>();
|
||||
|
||||
private static final int[] bits = {16, 8, 4, 2, 1};
|
||||
|
||||
static {
|
||||
int sz = _base32.length;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
_decodemap.put(_base32[i], i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
String gc1 = encode(new BigDecimal("39.916527"), new BigDecimal("116.397128"));
|
||||
System.out.println(gc1);
|
||||
BigDecimal[] gd1 = decode(gc1);
|
||||
System.out.println(gd1[0] + ", " + gd1[1]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 经纬度换算geoHash
|
||||
*
|
||||
* @param lat
|
||||
* @param lon
|
||||
* @return
|
||||
*/
|
||||
public static String encode(BigDecimal lat, BigDecimal lon) {
|
||||
double latitude = lat.doubleValue();
|
||||
double longitude = lon.doubleValue();
|
||||
double[] lat_interval = {-90.0, 90.0};
|
||||
double[] lon_interval = {-180.0, 180.0};
|
||||
StringBuilder geohash = new StringBuilder();
|
||||
boolean is_even = true;
|
||||
int bit = 0, ch = 0;
|
||||
int precision = 12;
|
||||
while (geohash.length() < precision) {
|
||||
double mid;
|
||||
if (is_even) {
|
||||
mid = (lon_interval[0] + lon_interval[1]) / 2;
|
||||
if (longitude > mid) {
|
||||
ch |= bits[bit];
|
||||
lon_interval[0] = mid;
|
||||
} else {
|
||||
lon_interval[1] = mid;
|
||||
}
|
||||
} else {
|
||||
mid = (lat_interval[0] + lat_interval[1]) / 2;
|
||||
if (latitude > mid) {
|
||||
ch |= bits[bit];
|
||||
lat_interval[0] = mid;
|
||||
} else {
|
||||
lat_interval[1] = mid;
|
||||
}
|
||||
}
|
||||
is_even = !is_even;
|
||||
if (bit < 4) {
|
||||
bit++;
|
||||
} else {
|
||||
geohash.append(_base32[ch]);
|
||||
bit = 0;
|
||||
ch = 0;
|
||||
}
|
||||
}
|
||||
return geohash.toString();
|
||||
}
|
||||
|
||||
|
||||
public static BigDecimal[] decode(String geohash) {
|
||||
double[] ge = decode_exactly(geohash);
|
||||
double lat, lon, lat_err, lon_err;
|
||||
lat = ge[0];
|
||||
lon = ge[1];
|
||||
lat_err = ge[2];
|
||||
lon_err = ge[3];
|
||||
double lat_precision = Math.max(1, Math.round(-Math.log10(lat_err))) - 1;
|
||||
double lon_precision = Math.max(1, Math.round(-Math.log10(lon_err))) - 1;
|
||||
lat = getPrecision(lat, lat_precision);
|
||||
lon = getPrecision(lon, lon_precision);
|
||||
return new BigDecimal[]{new BigDecimal(lat), new BigDecimal(lon)};
|
||||
}
|
||||
|
||||
|
||||
public static double[] decode_exactly(String geohash) {
|
||||
double[] lat_interval = {-90.0, 90.0};
|
||||
double[] lon_interval = {-180.0, 180.0};
|
||||
double lat_err = 90.0;
|
||||
double lon_err = 180.0;
|
||||
boolean is_even = true;
|
||||
int sz = geohash.length();
|
||||
int bsz = bits.length;
|
||||
double latitude, longitude;
|
||||
for (int i = 0; i < sz; i++) {
|
||||
int cd = _decodemap.get(geohash.charAt(i));
|
||||
for (int mask : bits) {
|
||||
if (is_even) {
|
||||
lon_err /= 2;
|
||||
if ((cd & mask) != 0) {
|
||||
lon_interval[0] = (lon_interval[0] + lon_interval[1]) / 2;
|
||||
} else {
|
||||
lon_interval[1] = (lon_interval[0] + lon_interval[1]) / 2;
|
||||
}
|
||||
} else {
|
||||
lat_err /= 2;
|
||||
if ((cd & mask) != 0) {
|
||||
lat_interval[0] = (lat_interval[0] + lat_interval[1]) / 2;
|
||||
} else {
|
||||
lat_interval[1] = (lat_interval[0] + lat_interval[1]) / 2;
|
||||
}
|
||||
}
|
||||
is_even = !is_even;
|
||||
}
|
||||
}
|
||||
latitude = (lat_interval[0] + lat_interval[1]) / 2;
|
||||
longitude = (lon_interval[0] + lon_interval[1]) / 2;
|
||||
return new double[]{latitude, longitude, lat_err, lon_err};
|
||||
}
|
||||
|
||||
|
||||
static double getPrecision(double x, double precision) {
|
||||
double base = Math.pow(10, -precision);
|
||||
double diff = x % base;
|
||||
return x - diff;
|
||||
}
|
||||
}
|
@ -0,0 +1,547 @@
|
||||
package com.mosty.common.util;
|
||||
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.util.IOUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import sun.misc.BASE64Encoder;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageReader;
|
||||
import javax.imageio.stream.ImageInputStream;
|
||||
import javax.net.ssl.*;
|
||||
import java.awt.*;
|
||||
import java.awt.color.ColorSpace;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.image.*;
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* 图片处理类<br>
|
||||
*
|
||||
* @author Esacpe
|
||||
* @version 2014-8-22
|
||||
*/
|
||||
|
||||
public class ImageUtils {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
|
||||
|
||||
|
||||
|
||||
public static byte[] getImage(String imagePath)
|
||||
{
|
||||
InputStream is = getFile(imagePath);
|
||||
try
|
||||
{
|
||||
return IOUtils.toByteArray(is);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("图片加载异常 {}", e);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IOUtils.closeQuietly(is);
|
||||
}
|
||||
}
|
||||
|
||||
public static InputStream getFile(String imagePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] result = readFile(imagePath);
|
||||
result = Arrays.copyOf(result, result.length);
|
||||
return new ByteArrayInputStream(result);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("获取图片异常 {}", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件为字节数据
|
||||
*
|
||||
* @param url 地址
|
||||
* @return 字节数据
|
||||
*/
|
||||
public static byte[] readFile(String url)
|
||||
{
|
||||
InputStream in = null;
|
||||
try
|
||||
{
|
||||
// 网络地址
|
||||
URL urlObj = new URL(url);
|
||||
URLConnection urlConnection = urlObj.openConnection();
|
||||
urlConnection.setConnectTimeout(30 * 1000);
|
||||
urlConnection.setReadTimeout(60 * 1000);
|
||||
urlConnection.setDoInput(true);
|
||||
in = urlConnection.getInputStream();
|
||||
return IOUtils.toByteArray(in);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("访问文件异常 {}", e);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IOUtils.closeQuietly(in);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将图片缩放处理方法<br>
|
||||
*
|
||||
* @param source 源图片对象
|
||||
* @param targetW 转换后的宽度
|
||||
* @param targetH 转换后的高度
|
||||
* @param sameScale 是否等比例缩放
|
||||
* @return BufferedImage
|
||||
*/
|
||||
public static BufferedImage resize(BufferedImage source, int targetW,
|
||||
int targetH, boolean sameScale) { // targetW,targetH分别表示目标长和宽
|
||||
int type = source.getType();
|
||||
BufferedImage target = null;
|
||||
double sx = (double) targetW / source.getWidth();
|
||||
double sy = (double) targetH / source.getHeight();
|
||||
if (sameScale) { // 需要等比例缩放
|
||||
if (sx > sy) {
|
||||
sx = sy;
|
||||
targetW = (int) (sx * source.getWidth());
|
||||
} else {
|
||||
sy = sx;
|
||||
targetH = (int) (sy * source.getHeight());
|
||||
}
|
||||
}
|
||||
if (type == BufferedImage.TYPE_CUSTOM) { // handmade
|
||||
ColorModel cm = source.getColorModel();
|
||||
WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
|
||||
targetH);
|
||||
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
|
||||
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
|
||||
} else {
|
||||
target = new BufferedImage(targetW, targetH, type);
|
||||
}
|
||||
Graphics2D g = target.createGraphics();
|
||||
// smoother than exlax:
|
||||
g.setRenderingHint(RenderingHints.KEY_RENDERING,
|
||||
RenderingHints.VALUE_RENDER_QUALITY);
|
||||
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
|
||||
g.dispose();
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将图片放大与缩小<br>
|
||||
*
|
||||
* @param sourceByte 源图片的字节数组
|
||||
* @param width 转换后的宽度
|
||||
* @param height 转换后的高度
|
||||
* @param sameScale 是否等比例缩放
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] convertImageSize(byte[] sourceByte, int width,
|
||||
int height, boolean sameScale) throws Exception {
|
||||
byte[] returnValue = null;
|
||||
if (sourceByte != null && sourceByte.length > 0) {
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(sourceByte);
|
||||
// BufferedImage srcImage = getReadImage(in);
|
||||
BufferedImage srcImage = null;
|
||||
try {
|
||||
srcImage = ImageIO.read(in); // RGB
|
||||
} catch (Exception e) {
|
||||
}
|
||||
if (srcImage != null) {
|
||||
BufferedImage srcImageTarget = resize(srcImage, width, height,
|
||||
sameScale);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
boolean flag = ImageIO.write(srcImageTarget, "JPEG", out);
|
||||
returnValue = out.toByteArray();
|
||||
}
|
||||
}
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将图片放大与缩小后另存<br>
|
||||
*
|
||||
* @param fromFileStr 来源文件名
|
||||
* @param saveToFileStr 目标文件名
|
||||
* @param width 转换后的宽度
|
||||
* @param height 转换后的高度
|
||||
* @param sameScale 是否等比例缩放
|
||||
*/
|
||||
public static void saveImageAsJpg(String fromFileStr, String saveToFileStr,
|
||||
int width, int height, boolean sameScale) throws Exception {
|
||||
String imgType = "JPEG";
|
||||
if (fromFileStr.toLowerCase().endsWith(".png")) {
|
||||
imgType = "PNG";
|
||||
}
|
||||
File saveFile = new File(saveToFileStr);
|
||||
File fromFile = new File(fromFileStr);
|
||||
BufferedImage srcImage = getReadImage(fromFile);
|
||||
if (srcImage != null) {
|
||||
if (width > 0 || height > 0) {
|
||||
srcImage = resize(srcImage, width, height, sameScale);
|
||||
}
|
||||
ImageIO.write(srcImage, imgType, saveFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件取得bufferedImage对象(自动识别RGB与CMYK)<br>
|
||||
*
|
||||
* @param file 来源文件名
|
||||
* @return BufferedImage
|
||||
*/
|
||||
private static BufferedImage getReadImage(File file) throws Exception {
|
||||
BufferedImage srcImage = null;
|
||||
ImageInputStream input = ImageIO.createImageInputStream(file); // 只能接收File或FileInputStream,ByteArrayInputStream无效
|
||||
Iterator readers = ImageIO.getImageReaders(input);
|
||||
if (readers == null || !readers.hasNext()) {
|
||||
throw new RuntimeException("1 No ImageReaders found");
|
||||
}
|
||||
ImageReader reader = (ImageReader) readers.next();
|
||||
reader.setInput(input);
|
||||
String format = reader.getFormatName();
|
||||
if ("JPEG".equalsIgnoreCase(format) || "JPG".equalsIgnoreCase(format)) {
|
||||
try {
|
||||
srcImage = ImageIO.read(file); // RGB
|
||||
} catch (Exception e) {
|
||||
Raster raster = reader.readRaster(0, null);// CMYK
|
||||
srcImage = createJPEG4(raster);
|
||||
}
|
||||
input.close();
|
||||
}
|
||||
return srcImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* RGB彩色空间转换为CMYK<br>
|
||||
*
|
||||
* @param raster
|
||||
* @return BufferedImage
|
||||
*/
|
||||
private static BufferedImage createJPEG4(Raster raster) {
|
||||
int w = raster.getWidth();
|
||||
int h = raster.getHeight();
|
||||
byte[] rgb = new byte[w * h * 3]; // 彩色空间转换
|
||||
float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null);
|
||||
float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null);
|
||||
float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null);
|
||||
float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null);
|
||||
for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) {
|
||||
float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i];
|
||||
double val = y + 1.402 * (cr - 128) - k;
|
||||
val = (val - 128) * .65f + 128;
|
||||
rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff
|
||||
: (byte) (val + 0.5);
|
||||
val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k;
|
||||
val = (val - 128) * .65f + 128;
|
||||
rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff
|
||||
: (byte) (val + 0.5);
|
||||
val = y + 1.772 * (cb - 128) - k;
|
||||
val = (val - 128) * .65f + 128;
|
||||
rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff
|
||||
: (byte) (val + 0.5);
|
||||
}
|
||||
raster = Raster.createInterleavedRaster(new DataBufferByte(rgb,
|
||||
rgb.length), w, h, w * 3, 3, new int[]{0, 1, 2}, null);
|
||||
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
|
||||
ColorModel cm = new ComponentColorModel(cs, false, true,
|
||||
Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
|
||||
return new BufferedImage(cm, (WritableRaster) raster, true, null);
|
||||
}
|
||||
|
||||
public static byte[] encodeImageTobyte(String url) {
|
||||
//打开链接
|
||||
try {
|
||||
URL urls = new URL(url);
|
||||
HttpURLConnection conn = null;
|
||||
|
||||
conn = (HttpURLConnection) urls.openConnection();
|
||||
//设置请求方式为"GET"
|
||||
conn.setRequestMethod("GET");
|
||||
//超时响应时间为5秒
|
||||
conn.setConnectTimeout(5 * 1000);
|
||||
//通过输入流获取图片数据
|
||||
InputStream inStream = conn.getInputStream();
|
||||
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
|
||||
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
|
||||
//创建一个Buffer字符串
|
||||
byte[] buffer = new byte[1024];
|
||||
//每次读取的字符串长度,如果为-1,代表全部读取完毕
|
||||
int len = 0;
|
||||
//使用一个输入流从buffer里把数据读取出来
|
||||
while ((len = inStream.read(buffer)) != -1) {
|
||||
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
//关闭输入流
|
||||
inStream.close();
|
||||
byte[] data = outStream.toByteArray();
|
||||
return data;//返回Base64编码过的字节数组字符串
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 网络图片转成base64 https
|
||||
*
|
||||
* @param url
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static byte[] encodeImageToByteHttps(String url) {
|
||||
byte[] data = null;
|
||||
try {
|
||||
SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
|
||||
sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
|
||||
URL urls = new URL(url);
|
||||
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
|
||||
public boolean verify(String s, SSLSession sslsession) {
|
||||
System.out.println("WARNING: Hostname is not matched for cert.");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
|
||||
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
|
||||
//之后任何Https协议网站皆能正常访问,同第一种情况
|
||||
HttpURLConnection conn = null;
|
||||
|
||||
conn = (HttpURLConnection) urls.openConnection();
|
||||
//设置请求方式为"GET"
|
||||
conn.setRequestMethod("GET");
|
||||
//超时响应时间为5秒
|
||||
conn.setConnectTimeout(5 * 1000);
|
||||
if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
|
||||
String location = conn.getHeaderField("Location");
|
||||
byte[] data1 = encodeImageToByteHttps(location.trim());
|
||||
if (null != data && data1.length > 0) {
|
||||
return data1;
|
||||
}
|
||||
|
||||
} else {
|
||||
//通过输入流获取图片数据
|
||||
InputStream inStream = conn.getInputStream();
|
||||
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
|
||||
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
|
||||
//创建一个Buffer字符串
|
||||
byte[] buffer = new byte[1024];
|
||||
//每次读取的字符串长度,如果为-1,代表全部读取完毕
|
||||
int len = 0;
|
||||
//使用一个输入流从buffer里把数据读取出来
|
||||
while ((len = inStream.read(buffer)) != -1) {
|
||||
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
//关闭输入流
|
||||
inStream.close();
|
||||
data = outStream.toByteArray();
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("解析失败!------》" + e.getMessage());
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 网络图片转成base64 https
|
||||
*
|
||||
* @param url
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String encodeImageToBase64Https(String url) {
|
||||
String base64 = null;
|
||||
try {
|
||||
SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
|
||||
sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
|
||||
URL urls = new URL(url);
|
||||
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
|
||||
public boolean verify(String s, SSLSession sslsession) {
|
||||
System.out.println("WARNING: Hostname is not matched for cert.");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
|
||||
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
|
||||
//之后任何Https协议网站皆能正常访问,同第一种情况
|
||||
HttpURLConnection conn = null;
|
||||
|
||||
conn = (HttpURLConnection) urls.openConnection();
|
||||
//设置请求方式为"GET"
|
||||
conn.setRequestMethod("GET");
|
||||
//超时响应时间为5秒
|
||||
conn.setConnectTimeout(5 * 1000);
|
||||
if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
|
||||
String location = conn.getHeaderField("Location");
|
||||
String s = encodeImageToBase64Https(location.trim());
|
||||
if (StringUtils.isNotBlank(s)) {
|
||||
return s;
|
||||
}
|
||||
|
||||
} else {
|
||||
//通过输入流获取图片数据
|
||||
InputStream inStream = conn.getInputStream();
|
||||
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
|
||||
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
|
||||
//创建一个Buffer字符串
|
||||
byte[] buffer = new byte[1024];
|
||||
//每次读取的字符串长度,如果为-1,代表全部读取完毕
|
||||
int len = 0;
|
||||
//使用一个输入流从buffer里把数据读取出来
|
||||
while ((len = inStream.read(buffer)) != -1) {
|
||||
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
//关闭输入流
|
||||
inStream.close();
|
||||
byte[] data = outStream.toByteArray();
|
||||
//对字节数组Base64编码
|
||||
BASE64Encoder encoder = new BASE64Encoder();
|
||||
base64 = encoder.encode(data).replaceAll("[\\s*\t\n\r]", "");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("解析失败!------》" + e.getMessage());
|
||||
}
|
||||
return base64;
|
||||
}
|
||||
|
||||
/**
|
||||
* 网络图片转成base64
|
||||
*
|
||||
* @param url
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String encodeImageToBase64(String url) throws Exception {
|
||||
//打开链接
|
||||
URL urls = new URL(url);
|
||||
HttpURLConnection conn;
|
||||
try {
|
||||
conn = (HttpURLConnection) urls.openConnection();
|
||||
//设置请求方式为"GET"
|
||||
conn.setRequestMethod("GET");
|
||||
//超时响应时间为5秒
|
||||
conn.setConnectTimeout(5 * 1000);
|
||||
//通过输入流获取图片数据
|
||||
InputStream inStream = conn.getInputStream();
|
||||
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
|
||||
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
|
||||
//创建一个Buffer字符串
|
||||
byte[] buffer = new byte[1024];
|
||||
//每次读取的字符串长度,如果为-1,代表全部读取完毕
|
||||
int len = 0;
|
||||
//使用一个输入流从buffer里把数据读取出来
|
||||
while ((len = inStream.read(buffer)) != -1) {
|
||||
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
//关闭输入流
|
||||
inStream.close();
|
||||
byte[] data = outStream.toByteArray();
|
||||
//对字节数组Base64编码
|
||||
BASE64Encoder encoder = new BASE64Encoder();
|
||||
return encoder.encode(data).replaceAll("[\\s*\t\n\r]", "");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
throw new Exception("解析失败!");
|
||||
}
|
||||
}
|
||||
|
||||
public static String ImageToBase64(String imgPath) {
|
||||
byte[] data = null;
|
||||
try {
|
||||
InputStream in = new FileInputStream(imgPath);
|
||||
data = new byte[in.available()];
|
||||
in.read(data);
|
||||
in.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
// return StringUtils.replaceBlank(StringUtils.getByteToBase64(data));
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 网络图片转成base64
|
||||
*
|
||||
* @param url
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static byte[] encodeImageToByte(String url) throws Exception {
|
||||
//打开链接
|
||||
URL urls = new URL(url);
|
||||
HttpURLConnection conn = null;
|
||||
try {
|
||||
conn = (HttpURLConnection) urls.openConnection();
|
||||
//设置请求方式为"GET"
|
||||
conn.setRequestMethod("GET");
|
||||
//超时响应时间为5秒
|
||||
conn.setConnectTimeout(5 * 1000);
|
||||
//通过输入流获取图片数据
|
||||
InputStream inStream = conn.getInputStream();
|
||||
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
|
||||
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
|
||||
//创建一个Buffer字符串
|
||||
byte[] buffer = new byte[1024];
|
||||
//每次读取的字符串长度,如果为-1,代表全部读取完毕
|
||||
int len = 0;
|
||||
//使用一个输入流从buffer里把数据读取出来
|
||||
while ((len = inStream.read(buffer)) != -1) {
|
||||
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
//关闭输入流
|
||||
inStream.close();
|
||||
byte[] data = outStream.toByteArray();
|
||||
return data;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
throw new Exception("解析失败!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static void main(String argv[]) throws Exception{
|
||||
// ImageUtils.saveImageAsJpg("C:/test.jpg", "c:/test2.jpg", 179, 220,
|
||||
// true);
|
||||
|
||||
// String s = ImageUtils.ImageToBase64("C:\\Users\\admin\\Desktop\\ryxp.jpg");
|
||||
// System.out.println(s);
|
||||
// String str = "normal://repository-builder/20190628/ehlZxEcjZp09UubZQugxug==@11";
|
||||
// //编码加密
|
||||
// String encodeStr = Base64.getEncoder().encodeToString(str.getBytes("UTF-8"));
|
||||
// System.out.println("加密后的字符串为:" + encodeStr);
|
||||
// //解码解密
|
||||
// String decoderStr = new String(Base64.getDecoder().decode(encodeStr), StandardCharsets.UTF_8); //
|
||||
// // 推荐使用StandardCharsets类指定
|
||||
// System.out.println("解密后的字符串为" + decoderStr);
|
||||
|
||||
|
||||
|
||||
String tp="http://10.64.201.128:7266/xlpcAdminNew/requestservice/czrk/ryxp.jpg?sfzh=510502195403065021";
|
||||
String s = ImageUtils.encodeImageToBase64(tp);
|
||||
System.out.println(s);
|
||||
}
|
||||
}
|
@ -0,0 +1,206 @@
|
||||
package com.mosty.common.util;
|
||||
|
||||
import com.vividsolutions.jts.geom.*;
|
||||
import com.vividsolutions.jts.linearref.LengthIndexedLine;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class JtsUtils {
|
||||
private static final double EARTH_RADIUS = 6378137;
|
||||
public static GeometryFactory factory = new GeometryFactory(new PrecisionModel(100000000000d));
|
||||
private static final DecimalFormat df = new DecimalFormat("0.00000000000");
|
||||
private static final DecimalFormat format = new DecimalFormat("0.0000");
|
||||
|
||||
public static String toEwkt(Geometry geom) {
|
||||
if (geom == null) {
|
||||
return null;
|
||||
}
|
||||
String type = geom.getGeometryType().toUpperCase();
|
||||
switch (type) {
|
||||
case "POINT": {
|
||||
Coordinate coor = geom.getCoordinate();
|
||||
return "POINT(" + formatCoordinate(coor) + ")";
|
||||
}
|
||||
case "MULTIPOINT": {
|
||||
return coordinateToEwkt("MULTIPOINT(", geom.getCoordinates(), ")");
|
||||
}
|
||||
case "LINESTRING": {
|
||||
return coordinateToEwkt("LINESTRING(", geom.getCoordinates(), ")");
|
||||
}
|
||||
case "POLYGON": {
|
||||
return coordinateToEwkt("POLYGON((", geom.getCoordinates(), "))");
|
||||
}
|
||||
case "MULTILINESTRING": {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("MULTILINESTRING(");
|
||||
sb.append(multiGeometryFormat(geom));
|
||||
sb.append(")");
|
||||
return sb.toString();
|
||||
}
|
||||
case "MULTIPOLYGON": {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append("MULTIPOLYGON(");
|
||||
sb.append(multiGeometryFormat(geom));
|
||||
sb.append(")");
|
||||
return sb.toString();
|
||||
}
|
||||
case "GEOMETRYCOLLECTION": {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
int num = geom.getNumGeometries();
|
||||
sb.append("GEOMETRYCOLLECTION(");
|
||||
for (int j = 0; j < num; j++) {
|
||||
Geometry element = geom.getGeometryN(j);
|
||||
String subType = element.getGeometryType().toUpperCase();
|
||||
if ("POINT".equals(subType)) {
|
||||
sb.append("POINT(" + formatCoordinate(element.getCoordinate()) + ")");
|
||||
} else if ("LINESTRING".equals(subType)) {
|
||||
sb.append(coordinateToEwkt("LINESTRING(", element.getCoordinates(), ")"));
|
||||
} else if ("POLYGON".equals(subType)) {
|
||||
sb.append(coordinateToEwkt("POLYGON((", element.getCoordinates(), "))"));
|
||||
}
|
||||
if (j < num - 1) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
sb.append(")");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String formatCoordinate(Coordinate coordinate) {
|
||||
return df.format(coordinate.x) + " " + df.format(coordinate.y);
|
||||
}
|
||||
|
||||
public static String coordinateToEwkt(String prefix, Coordinate[] coordinates, String suffix) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append(prefix);
|
||||
boolean append = false;
|
||||
for (Coordinate coordinate : coordinates) {
|
||||
if (append) {
|
||||
sb.append(",");
|
||||
}
|
||||
sb.append(formatCoordinate(coordinate));
|
||||
append = true;
|
||||
}
|
||||
sb.append(suffix);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String multiGeometryFormat(Geometry geom) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
int num = geom.getNumGeometries();
|
||||
for (int i = 0; i < num; i++) {
|
||||
Geometry g = geom.getGeometryN(i);
|
||||
sb.append(coordinateToEwkt("((", g.getCoordinates(), "))"));
|
||||
if (i < num - 1) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取两组成的线的几何中心
|
||||
*
|
||||
* @param s 起始点
|
||||
* @param e 结束点
|
||||
* @return
|
||||
*/
|
||||
public static Coordinate getCentroid(Coordinate s, Coordinate e) {// 获取两点组成的线的图心
|
||||
if (s.x == e.x && s.y == e.y) {
|
||||
return s;
|
||||
}
|
||||
LineString ls = factory.createLineString(new Coordinate[]{s, e});
|
||||
Point cp = ls.getCentroid();
|
||||
return cp.getCoordinate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取多个离散几何点的几何中心
|
||||
*
|
||||
* @param coors
|
||||
* @return
|
||||
*/
|
||||
public static Coordinate getCentroid(Coordinate[] coors) {// 获取多个离散点的图心
|
||||
MultiPoint mp = factory.createMultiPoint(coors);
|
||||
return mp.getCentroid().getCoordinate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取面
|
||||
*
|
||||
* @param list
|
||||
* @return
|
||||
*/
|
||||
public static Polygon getPolygon(List<BigDecimal[]> list) {
|
||||
Coordinate[] coors = new Coordinate[list.size()];
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
BigDecimal[] item = list.get(i);
|
||||
Coordinate coor = new Coordinate();
|
||||
coor.x = item[0].doubleValue();
|
||||
coor.y = item[1].doubleValue();
|
||||
coors[i] = coor;
|
||||
}
|
||||
return factory.createPolygon(coors);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取线
|
||||
*
|
||||
* @param list [[x,y],[x1,y1],[x2,y2]....]
|
||||
* @return
|
||||
*/
|
||||
public static LineString createLine(List<BigDecimal[]> list) {
|
||||
Coordinate[] coors = new Coordinate[list.size() - 1];
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
BigDecimal[] item = list.get(i);
|
||||
Coordinate coor = new Coordinate();
|
||||
coor.x = item[0].doubleValue();
|
||||
coor.y = item[1].doubleValue();
|
||||
coors[i] = coor;
|
||||
}
|
||||
return factory.createLineString(coors);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取点
|
||||
*
|
||||
* @param x
|
||||
* @param y
|
||||
* @return
|
||||
*/
|
||||
public static Point getPoint(BigDecimal x, BigDecimal y) {
|
||||
Coordinate coor = new Coordinate(x.doubleValue(), y.doubleValue());
|
||||
return factory.createPoint(coor);
|
||||
}
|
||||
|
||||
// 解析面类型为经纬度数组
|
||||
public static List<BigDecimal[]> decodePolygon(Polygon pl) {
|
||||
if (pl != null) {
|
||||
List<BigDecimal[]> list = new ArrayList<>();
|
||||
Coordinate[] coors = pl.getCoordinates();
|
||||
if (coors.length > 0) {
|
||||
for (Coordinate coor : coors) {
|
||||
BigDecimal[] temp = new BigDecimal[2];
|
||||
temp[0] = new BigDecimal(coor.x);
|
||||
temp[1] = new BigDecimal(coor.y);
|
||||
list.add(temp);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Coordinate getCenter(LineString line) {
|
||||
LengthIndexedLine indexedLine = new LengthIndexedLine(line);
|
||||
double[] index = indexedLine.indicesOf(line);
|
||||
Coordinate mid = indexedLine.extractPoint((index[0] + index[1]) / 2);
|
||||
return mid;
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.mosty.common.util;
|
||||
|
||||
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
public class MyX509TrustManager implements X509TrustManager {
|
||||
|
||||
// 检查客户端证书
|
||||
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
|
||||
}
|
||||
|
||||
// 检查服务器端证书
|
||||
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
|
||||
}
|
||||
|
||||
// 返回受信任的X509证书数组
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
}
|
@ -0,0 +1,106 @@
|
||||
package com.mosty.common.util;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.mosty.common.base.util.StringUtils;
|
||||
import com.mosty.common.token.DeptInfo;
|
||||
import com.mosty.common.token.UserInfo;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 数据权限获取工具
|
||||
*/
|
||||
public class PermissionsUtil {
|
||||
|
||||
// 根据组织机构ID获取查询权限
|
||||
public static void queryWrapperUtilByDeptInfo(QueryWrapper queryWrapper, DeptInfo deptInfo) {
|
||||
if (deptInfo != null && deptInfo.getPermissionsLevel() != null) {
|
||||
String level = deptInfo.getPermissionsLevel();
|
||||
if ("1".equals(level) || "2".equals(level)) {
|
||||
// do nothing
|
||||
} else if ("3".equals(level)) {
|
||||
queryWrapper.eq("sssgajid", deptInfo.getSssgajid());
|
||||
} else if ("4".equals(level)) {
|
||||
queryWrapper.eq("ssxgajid", deptInfo.getSsxgajid());
|
||||
} else if ("5".equals(level)) {
|
||||
if (StringUtils.isNotEmpty(deptInfo.getIds())) {
|
||||
String[] ids = deptInfo.getIds().split(",");
|
||||
queryWrapper.in("ssbmid", Arrays.asList(ids));
|
||||
}
|
||||
} else if ("6".equals(level)) {
|
||||
queryWrapper.eq("ssbmid", deptInfo.getSsbmid());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 根据组织机构ID获取查询权限
|
||||
public static void queryWrapperUtil(QueryWrapper queryWrapper, UserInfo userInfo) {
|
||||
if (userInfo != null && userInfo.getUserPermissionsInfo() != null) {
|
||||
String level = userInfo.getUserPermissionsInfo().getPermissionsLevel();
|
||||
if ("1".equals(level) || "2".equals(level)) {
|
||||
// do nothing
|
||||
} else if ("3".equals(level)) {
|
||||
queryWrapper.eq("sssgajid", userInfo.getDszDeptId());
|
||||
} else if ("4".equals(level)) {
|
||||
queryWrapper.eq("ssxgajid", userInfo.getFxjDeptId());
|
||||
} else if ("5".equals(level)) {
|
||||
if (userInfo.getUserPermissionsInfo() != null
|
||||
&& StringUtils.isNotEmpty(userInfo.getUserPermissionsInfo().getIds())) {
|
||||
String[] ids = userInfo.getUserPermissionsInfo().getIds().split(",");
|
||||
queryWrapper.in("ssbmid", Arrays.asList(ids));
|
||||
}
|
||||
} else if ("6".equals(level)) {
|
||||
queryWrapper.eq("ssbmid", userInfo.getDeptId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 根据组织机构编码获取查询权限
|
||||
public static void queryWrapperUtilByCode(QueryWrapper queryWrapper, UserInfo userInfo) {
|
||||
if (userInfo != null && userInfo.getUserPermissionsInfo() != null) {
|
||||
String level = userInfo.getUserPermissionsInfo().getPermissionsLevel();
|
||||
if ("1".equals(level) || "2".equals(level)) {
|
||||
// do nothing
|
||||
} else if ("3".equals(level)) {
|
||||
queryWrapper.eq("sssgajdm", userInfo.getDszDeptCode());
|
||||
} else if ("4".equals(level)) {
|
||||
queryWrapper.eq("ssxgajdm", userInfo.getFxjDeptCode());
|
||||
} else if ("5".equals(level)) {
|
||||
String[] orgcodes = userInfo.getUserPermissionsInfo().getOrgcodes().split(",");
|
||||
queryWrapper.in("ssbmdm", Arrays.asList(orgcodes));
|
||||
} else if ("6".equals(level)) {
|
||||
queryWrapper.eq("ssbmdm", userInfo.getDeptId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 表别名(使用ssbmid)
|
||||
public static String createSql(String tableAlias, UserInfo userInfo) {
|
||||
String dataPermissionSql = "";
|
||||
if (userInfo != null && userInfo.userPermissionsInfo != null && !StringUtils.isEmpty(userInfo.userPermissionsInfo.getPermissionsSql())) {
|
||||
String sql = userInfo.userPermissionsInfo.getPermissionsSql().replaceAll("'", "'");
|
||||
if (StringUtils.isEmpty(tableAlias)) {
|
||||
dataPermissionSql = sql.replaceAll("alias.", "");
|
||||
} else {
|
||||
dataPermissionSql = sql.replaceAll("alias", tableAlias);
|
||||
}
|
||||
}
|
||||
return dataPermissionSql;
|
||||
}
|
||||
|
||||
// 表别名(使用ssbmdm)
|
||||
public static String createSqlOfCode(String tableAlias, UserInfo userInfo) {
|
||||
String dataPermissionSql = "";
|
||||
if (userInfo != null && userInfo.userPermissionsInfo != null &&
|
||||
!StringUtils.isEmpty(userInfo.userPermissionsInfo.getPermissionsSqlCode())) {
|
||||
String sql = userInfo.userPermissionsInfo.getPermissionsSqlCode().replaceAll("'", "'");
|
||||
if (StringUtils.isEmpty(tableAlias)) {
|
||||
dataPermissionSql = sql.replaceAll("alias.", "");
|
||||
} else {
|
||||
dataPermissionSql = sql.replaceAll("alias", tableAlias);
|
||||
}
|
||||
}
|
||||
return dataPermissionSql;
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.mosty.common.util;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDGenerator {
|
||||
|
||||
/**
|
||||
* 获取UUID
|
||||
* @return
|
||||
*/
|
||||
public static String getUUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
String str = uuid.toString();
|
||||
// 去掉"-"符号
|
||||
str = str.replace("-", "");
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得指定数量的UUID
|
||||
* @param number 指定数量
|
||||
* @return
|
||||
*/
|
||||
public static String[] getUUID(int number) {
|
||||
if (number < 1) {
|
||||
return null;
|
||||
}
|
||||
String[] ss = new String[number];
|
||||
for (int i = 0; i < number; i++) {
|
||||
ss[i] = getUUID();
|
||||
}
|
||||
return ss;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String[] ss = getUUID(10);
|
||||
for (int i = 0; i < ss.length; i++) {
|
||||
System.out.println("ss[" + i + "]=====" + getUUID());
|
||||
}
|
||||
}
|
||||
}
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -0,0 +1,5 @@
|
||||
#Generated by Maven
|
||||
#Thu Apr 18 12:45:09 CST 2024
|
||||
version=1.0.0-SNAPSHOT
|
||||
groupId=com.mosty
|
||||
artifactId=common-token-starter
|
@ -0,0 +1,17 @@
|
||||
com\mosty\common\token\DeptInfo.class
|
||||
com\mosty\common\token\JwtSysUser.class
|
||||
com\mosty\common\token\VirtualUserEnum.class
|
||||
com\mosty\common\token\UserPermissionsInfo.class
|
||||
com\mosty\common\util\JtsUtils.class
|
||||
com\mosty\common\util\ImageUtils$1.class
|
||||
com\mosty\common\util\DataPermissionConstant.class
|
||||
com\mosty\common\util\PermissionsUtil.class
|
||||
com\mosty\common\token\UserInfoManager.class
|
||||
com\mosty\common\util\MyX509TrustManager.class
|
||||
com\mosty\common\token\SysUserInterceptor.class
|
||||
com\mosty\common\util\ImageUtils.class
|
||||
com\mosty\common\token\JWTUtil.class
|
||||
com\mosty\common\util\ImageUtils$2.class
|
||||
com\mosty\common\token\UserInfo.class
|
||||
com\mosty\common\util\GeoHashKit.class
|
||||
com\mosty\common\util\UUIDGenerator.class
|
@ -0,0 +1,17 @@
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\UserType.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\DeptInfo.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\util\MyX509TrustManager.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\util\DataPermissionConstant.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\UserInfo.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\util\UUIDGenerator.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\util\PermissionsUtil.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\UserPermissionsInfo.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\util\JtsUtils.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\util\ImageUtils.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\util\GeoHashKit.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\UserInfoManager.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\VirtualUserEnum.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\JwtSysUser.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\SysUserInterceptor.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\JWTUtil.java
|
||||
E:\project\zgga\mosty-common\common-token-starter\src\main\java\com\mosty\common\token\UserInfoCache.java
|
Reference in New Issue
Block a user