commit
This commit is contained in:
48
ndplan/doc/readme.txt
Normal file
48
ndplan/doc/readme.txt
Normal file
@@ -0,0 +1,48 @@
|
||||
|
||||
登录页
|
||||
http://localhost:8080/ndplan/view/login.html
|
||||
|
||||
主页
|
||||
http://localhost:8080/ndplan/view/index.jsp
|
||||
|
||||
http://152.136.214.62:9090/ndplan/view/index.jsp
|
||||
http://152.136.214.62:9090/ndplan/view/index_3d.jsp
|
||||
http://152.136.214.62:9090/ndplan/view/index_3d_mainleft.html
|
||||
http://152.136.214.62:9090/ndplan/view/index_3d_mainnew.html
|
||||
|
||||
服务接口测试
|
||||
http://localhost:8080/ndplan/gis/demo
|
||||
|
||||
|
||||
服务地址:
|
||||
http://152.136.214.62:8090/
|
||||
|
||||
http://www.supermapol.com/realspace/services/3D-suofeiya_church/rest/realspace
|
||||
http://www.supermapol.com/realspace/services/3D-suofeiya_church/rest/realspace/scenes/%E6%9C%AA%E5%91%BD%E5%90%8D%E5%9C%BA%E6%99%AF.openrealspace
|
||||
|
||||
http://152.136.214.62:8090/iserver/services/3D-nd/rest/realspace/
|
||||
http://152.136.214.62:8090/iserver/services/3D-nd/rest/realspace/scenes/nd.openrealspace
|
||||
|
||||
http://152.136.214.62:8090/iserver/services/3D-XinWuSuiDao/rest/realspace
|
||||
http://152.136.214.62:8090/iserver/services/3D-XinWuSuiDao/rest/realspace/scenes/%E6%96%B0%E4%B9%8C%E9%9A%A7%E9%81%93.openrealspace
|
||||
|
||||
|
||||
|
||||
|
||||
http://152.136.214.62:8090/iserver/services/3D-nd/rest/realspace
|
||||
|
||||
倾斜目标拾取 viewer.pickEvent
|
||||
http://www.supermapol.com/realspace/services/3D-jinjiang/rest/realspace
|
||||
http://www.supermapol.com/realspace/services/data-jinjiang/rest/data
|
||||
http://192.168.198.21:33333/js/lib/supermap10/examples/editor.html#S3MTiles
|
||||
|
||||
let selecthandler = new Cesium.ScreenSpaceEventHandler(scene.canvas );
|
||||
selecthandler.setInputAction(e => {
|
||||
//点击回调事件
|
||||
scene.pick(e.position);
|
||||
let selectedLayer = scene.layers._selectedLayer;
|
||||
let id = selectedLayer.getSelection()[0];
|
||||
that.$http .get(dataconfig.dataurl + id + ".json").then(result => {
|
||||
let data=result.data
|
||||
})
|
||||
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
|
||||
298
ndplan/pom.xml
Normal file
298
ndplan/pom.xml
Normal file
@@ -0,0 +1,298 @@
|
||||
<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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.tky</groupId>
|
||||
<artifactId>ndplan</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>yard Maven Webapp</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.2.2.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<!-- springboot jar start -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-jdbc</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- 测试相关 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.restdocs</groupId>
|
||||
<artifactId>spring-restdocs-mockmvc</artifactId>
|
||||
<version>2.0.4.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-launcher</artifactId>
|
||||
<version>1.5.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- 测试相关 -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<!-- 保存自动编译jar start -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<!-- 保存自动编译jar end -->
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
<!-- springboot jar end -->
|
||||
|
||||
|
||||
<!-- tomcat发布war包时用start -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat.embed</groupId>
|
||||
<artifactId>tomcat-embed-jasper</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>1.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.taglibs</groupId>
|
||||
<artifactId>taglibs-standard-impl</artifactId>
|
||||
<version>1.2.5</version>
|
||||
</dependency>
|
||||
<!-- tomcat发布war包时用end -->
|
||||
|
||||
<!-- 连接池start -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid</artifactId>
|
||||
<version>1.0.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>c3p0</groupId>
|
||||
<artifactId>c3p0</artifactId>
|
||||
<version>0.9.1.2</version>
|
||||
</dependency>
|
||||
<!-- 连接池end -->
|
||||
|
||||
<!-- mysql -->
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.22</version>
|
||||
</dependency>
|
||||
<!-- <dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency> -->
|
||||
<!-- 整合redis -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.liferay</groupId>
|
||||
<artifactId>org.apache.commons.fileupload</artifactId>
|
||||
<version>1.2.2.LIFERAY-PATCHED-1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.6</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
<version>2.4.2</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- 工具类start -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.5</version>
|
||||
</dependency>
|
||||
<!-- 工具类end -->
|
||||
|
||||
<!-- httpClient -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>4.2.5</version>
|
||||
</dependency>
|
||||
|
||||
<!-- fastjson -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>1.1.33</version>
|
||||
</dependency>
|
||||
|
||||
<!-- gson -->
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.6.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.quartz-scheduler</groupId>
|
||||
<artifactId>quartz</artifactId>
|
||||
<version>2.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context-support</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-ws</artifactId>
|
||||
<version>1.4.6.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<!-- <dependency>
|
||||
<groupId>wsdl4j</groupId>
|
||||
<artifactId>wsdl4j</artifactId>
|
||||
</dependency> -->
|
||||
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-all</artifactId>
|
||||
<version>4.0.12</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-jpamodelgen</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- swaggerui相关依赖 -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>2.9.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>2.9.2</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
|
||||
<dependency>
|
||||
<groupId>commons-beanutils</groupId>
|
||||
<artifactId>commons-beanutils</artifactId>
|
||||
<version>1.8.3</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-httpclient</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
<version>3.1</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.tky</groupId> <!--自定义-->
|
||||
<artifactId>oracleDriver</artifactId> <!--自定义-->
|
||||
<version>1.0</version> <!--自定义-->
|
||||
<scope>system</scope> <!--system,类似provided,需要显式提供依赖的jar以后,Maven就不会在Repository中查找它-->
|
||||
<systemPath>${basedir}/src/main/resources/ojdbc14-10.2.0.2.0.jar</systemPath> <!--项目根目录下的lib文件夹下-->
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.hikvision.ga</groupId>
|
||||
<artifactId>artemis-http-client</artifactId>
|
||||
<version>1.1.2</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- <dependency>
|
||||
<groupId>com.univocity</groupId>
|
||||
<artifactId>univocity-parsers</artifactId>
|
||||
<version>2.5.9</version>
|
||||
</dependency> -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>
|
||||
spring-boot-configuration-processor
|
||||
</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<!-- <build>
|
||||
<finalName>yard</finalName>
|
||||
</build> -->
|
||||
</project>
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.system.business.dictionary;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.SequenceGenerator;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 数据字典
|
||||
* type 类型
|
||||
* item 子项
|
||||
* @author zhangtianlun
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name="t_core_dictionary")
|
||||
@org.hibernate.annotations.Table(appliesTo = "t_core_dictionary", comment = "数据字典")
|
||||
@ApiModel(value="数据字典")
|
||||
public class Dictionary {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ApiModelProperty(value="分类编码")
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '分类编码' ")
|
||||
private String typecode;
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '分类名称' ")
|
||||
private String typename;
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '子项名称' ")
|
||||
private String itemname;
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '子项值' ")
|
||||
private String itemvalue;
|
||||
|
||||
//@Column(columnDefinition = "float COMMENT '优先级' ")
|
||||
private Float priority;
|
||||
|
||||
//@Column(columnDefinition = "integer COMMENT '0删除1使用' ")
|
||||
private Integer useflag;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.system.business.dictionary;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.system.util.json.BaseJSON;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value="/dictionaryController")
|
||||
@Api(tags={"数据字典操作接口DictionaryController"})
|
||||
public class DictionaryController{
|
||||
|
||||
@Autowired
|
||||
public DictionaryServiceImpl dictionaryServiceImpl;
|
||||
|
||||
@ResponseBody
|
||||
@RequestMapping(value="/save",method={RequestMethod.GET,RequestMethod.POST})
|
||||
@ApiOperation(value="保存或修改",httpMethod ="POST",response=Dictionary.class)
|
||||
public String save(Dictionary entity){
|
||||
return BaseJSON.toJSONString(dictionaryServiceImpl.save(entity));
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@RequestMapping(value="/delete",method={RequestMethod.GET})
|
||||
@ApiOperation(value="删除")
|
||||
public String delete(Long id){
|
||||
return BaseJSON.toJSONString(dictionaryServiceImpl.delete(id));
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@RequestMapping(value="/findOne",method={RequestMethod.GET})
|
||||
@ApiOperation(value="查询一条数据")
|
||||
public String findOne(Long id){
|
||||
return BaseJSON.toJSONString(dictionaryServiceImpl.findOne(id));
|
||||
}
|
||||
|
||||
@RequestMapping(value="/findAllType",method={RequestMethod.GET})
|
||||
@ResponseBody
|
||||
@ApiOperation(value="查询一条数据")
|
||||
public String findAllType(){
|
||||
return BaseJSON.toJSONString(dictionaryServiceImpl.findAllType());
|
||||
}
|
||||
|
||||
@RequestMapping(value="/findByTypecode",method={RequestMethod.GET})
|
||||
@ResponseBody
|
||||
@ApiOperation(value="根据typecode查询数据")
|
||||
public String findByTypecode(String typecode){
|
||||
return BaseJSON.toJSONString(dictionaryServiceImpl.findByTypecode(typecode));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.system.business.dictionary;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
//@Repository
|
||||
public interface DictionaryDao extends JpaRepository<Dictionary,Long> ,
|
||||
JpaSpecificationExecutor<Dictionary>{
|
||||
|
||||
@Query(value="from Dictionary where useflag = 1 and (typecode=?1 or typename=?2)")
|
||||
public Dictionary findType(String typecode, String typename);
|
||||
|
||||
@Query(value="from Dictionary where useflag = 1 and typename = ?1 and (typecode=?2 or typename=?3)")
|
||||
public Dictionary findItem(String typename,String itemname, String itemcode);
|
||||
|
||||
@Query(value="from Dictionary where useflag = 1 and itemname is null order by priority")
|
||||
public List<Dictionary> findAllType();
|
||||
|
||||
@Query(value="from Dictionary where useflag = 1 and typecode = ?1 and itemname is not null order by priority")
|
||||
public List<Dictionary> findByTypecode(String typecode);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.system.business.dictionary;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.system.common.ResultBean;
|
||||
import com.system.util.StringUtil;
|
||||
@Service
|
||||
public class DictionaryServiceImpl{
|
||||
|
||||
@Autowired
|
||||
private DictionaryDao dictionaryDao;
|
||||
|
||||
public ResultBean<Dictionary> save(Dictionary entity) {
|
||||
ResultBean<Dictionary> rb = new ResultBean<Dictionary> (0 , "保存成功!" );
|
||||
entity.setUseflag(1);
|
||||
if(StringUtil.isNull(entity.getTypecode())) {
|
||||
return new ResultBean<Dictionary> (-1 , "类型编号不能为空!" );
|
||||
}
|
||||
if(StringUtil.isNull(entity.getTypename())) {
|
||||
return new ResultBean<Dictionary> (-1 , "类型名称不能为空!" );
|
||||
}
|
||||
if(entity.getPriority() == null) {
|
||||
return new ResultBean<Dictionary> (-1 , "排序号不能为空!" );
|
||||
}
|
||||
if(entity.getItemname() == null) { //添加的是类型
|
||||
Dictionary old = dictionaryDao.findType(entity.getTypecode(), entity.getTypename());
|
||||
if(old != null &&
|
||||
// 新增或者不等于它自己
|
||||
(entity.getId() == null || old.getId().longValue() != entity.getId().longValue() ) ) {
|
||||
return new ResultBean<Dictionary> (-1 , "保存失败!类型编号或类型名称已存在!" );
|
||||
}
|
||||
}
|
||||
if(entity.getItemname() != null) { //添加的是子项
|
||||
Dictionary old = dictionaryDao.findItem(
|
||||
entity.getTypename(),entity.getItemname(),entity.getItemvalue());
|
||||
if(old != null &&
|
||||
(entity.getId() == null || old.getId().longValue() != entity.getId().longValue() ) ) {
|
||||
return new ResultBean<Dictionary> (-1 , "保存失败!子项名称或子项值已存在!" );
|
||||
}
|
||||
}
|
||||
dictionaryDao.save(entity);
|
||||
rb.setResult(entity);
|
||||
return rb;
|
||||
}
|
||||
|
||||
public ResultBean<Dictionary> delete(Long id) {
|
||||
ResultBean<Dictionary> rb = new ResultBean<Dictionary> (0 ,"删除成功!");
|
||||
Dictionary old = dictionaryDao.findById(id).orElse(null);
|
||||
old.setUseflag(0);
|
||||
dictionaryDao.save(old);
|
||||
rb.setResult(old);
|
||||
return rb;
|
||||
}
|
||||
|
||||
public ResultBean<Dictionary> findOne(Long id) {
|
||||
ResultBean<Dictionary> rb = new ResultBean<Dictionary> (0 ,"查询成功!");
|
||||
Dictionary old = dictionaryDao.findById(id).orElse(null);
|
||||
rb.setResult(old);
|
||||
return rb;
|
||||
}
|
||||
|
||||
public ResultBean<List<Dictionary>> findAllType() {
|
||||
ResultBean<List<Dictionary>> rb = new ResultBean<List<Dictionary>> (0 ,"查询成功!");
|
||||
List<Dictionary> list = dictionaryDao.findAllType();
|
||||
rb.setResult(list);
|
||||
return rb;
|
||||
}
|
||||
|
||||
public ResultBean<List<Dictionary>> findByTypecode(String typecode) {
|
||||
ResultBean<List<Dictionary>> rb = new ResultBean<List<Dictionary>> (0 ,"查询成功!");
|
||||
List<Dictionary> list = dictionaryDao.findByTypecode(typecode);
|
||||
rb.setResult(list);
|
||||
return rb;
|
||||
}
|
||||
}
|
||||
20
ndplan/src/main/java/com/system/common/BaseTreeNode.java
Normal file
20
ndplan/src/main/java/com/system/common/BaseTreeNode.java
Normal file
@@ -0,0 +1,20 @@
|
||||
package com.system.common;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class BaseTreeNode {
|
||||
private Long id;
|
||||
|
||||
private Integer type;
|
||||
private String text;
|
||||
private Integer anchorstatus;
|
||||
private String state= "open";
|
||||
private String iconCls;
|
||||
private String etext;
|
||||
private String ctext;
|
||||
|
||||
}
|
||||
102
ndplan/src/main/java/com/system/common/PageWrapper.java
Normal file
102
ndplan/src/main/java/com/system/common/PageWrapper.java
Normal file
@@ -0,0 +1,102 @@
|
||||
package com.system.common;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 分页类<br/>
|
||||
* Copyright (c) 2014 , 北京可思云海科技有限公司<br/>
|
||||
* 2014-9-3 下午4:25:23
|
||||
*
|
||||
* @author gyj@kscloud.com
|
||||
* @version V1.0
|
||||
*/
|
||||
|
||||
@NoArgsConstructor
|
||||
public class PageWrapper<T> {
|
||||
|
||||
/**
|
||||
* 数据内容
|
||||
*/
|
||||
private List<T> content;
|
||||
/**
|
||||
* 页码
|
||||
*/
|
||||
private int pageNumber;
|
||||
/**
|
||||
* 每页条数
|
||||
*/
|
||||
private int pageSize;
|
||||
/**
|
||||
* 总页数
|
||||
*/
|
||||
private int totalPage;
|
||||
/**
|
||||
* 记录总条数
|
||||
*/
|
||||
private long totalSize;
|
||||
|
||||
public PageWrapper(int pageNumber, int pageSize, long totalSize, int totalPage, List<T> content) {
|
||||
this.pageNumber = pageNumber;
|
||||
this.pageSize = pageSize;
|
||||
this.totalPage = totalPage;
|
||||
this.totalSize = totalSize;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public List<T> getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(List<T> content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public int getPageNumber() {
|
||||
return pageNumber + 1;
|
||||
}
|
||||
|
||||
public void setPageNumber(int pageNumber) {
|
||||
this.pageNumber = pageNumber;
|
||||
}
|
||||
|
||||
public int getPageSize() {
|
||||
return pageSize;
|
||||
}
|
||||
|
||||
public void setPageSize(int pageSize) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
public int getTotalPage() {
|
||||
return totalPage;
|
||||
}
|
||||
|
||||
public void setTotalPage(int totalPage) {
|
||||
this.totalPage = totalPage;
|
||||
}
|
||||
|
||||
public long getTotalSize() {
|
||||
return totalSize;
|
||||
}
|
||||
|
||||
public void setTotalSize(long totalSize) {
|
||||
this.totalSize = totalSize;
|
||||
}
|
||||
|
||||
public long getTotal(){
|
||||
return this.getTotalSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* 为了解决dataGrid表格的行格式
|
||||
* @Title: getRows
|
||||
* @return
|
||||
* @return List<T> 返回类型
|
||||
* @throws
|
||||
*/
|
||||
public List<T> getRows(){
|
||||
return this.getContent();
|
||||
}
|
||||
}
|
||||
89
ndplan/src/main/java/com/system/common/ResultBean.java
Normal file
89
ndplan/src/main/java/com/system/common/ResultBean.java
Normal file
@@ -0,0 +1,89 @@
|
||||
package com.system.common;
|
||||
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
*
|
||||
* 前后台交互返回借结果规范
|
||||
*/
|
||||
|
||||
@Data
|
||||
@XmlRootElement()
|
||||
@XmlType(name = "", propOrder = {"code", "msg","result" })
|
||||
public class ResultBean<T> {
|
||||
/**
|
||||
* 业务表示代码
|
||||
*/
|
||||
private Integer code;
|
||||
/**
|
||||
* 业务提示信息
|
||||
*/
|
||||
private String msg;
|
||||
|
||||
/**
|
||||
* 业务操作返回结果
|
||||
*/
|
||||
private T result;
|
||||
|
||||
public ResultBean() { }
|
||||
|
||||
public ResultBean(Integer code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public ResultBean(Integer code, String msg, T result) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
|
||||
//解析泛型类Json方法(Gson)
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static ResultBean fromJson(String json, Class clazz) {
|
||||
Gson gson = new Gson();
|
||||
Type objectType = type(ResultBean.class, clazz);
|
||||
return gson.fromJson(json, objectType);
|
||||
}
|
||||
//解析泛型类Json方法(Gson)
|
||||
static ParameterizedType type(@SuppressWarnings("rawtypes") final Class raw, final Type... args) {
|
||||
return new ParameterizedType() {
|
||||
public Type getRawType() {
|
||||
return raw;
|
||||
}
|
||||
|
||||
public Type[] getActualTypeArguments() {
|
||||
return args;
|
||||
}
|
||||
|
||||
public Type getOwnerType() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
//解析泛型类Json方法(Gson)
|
||||
static ParameterizedType typeSgrzJypData(final Class raw, final Type... args) {
|
||||
return new ParameterizedType() {
|
||||
public Type getRawType() {
|
||||
return raw;
|
||||
}
|
||||
|
||||
public Type[] getActualTypeArguments() {
|
||||
return args;
|
||||
}
|
||||
|
||||
public Type getOwnerType() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
42
ndplan/src/main/java/com/system/common/ResultCode.java
Normal file
42
ndplan/src/main/java/com/system/common/ResultCode.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package com.system.common;
|
||||
|
||||
/**
|
||||
* ResultBean中代码规范 <br/>
|
||||
*/
|
||||
|
||||
public class ResultCode {
|
||||
|
||||
public static final Integer SUCCESS = 0;
|
||||
public static final Integer ERROR_SERVE = 100;
|
||||
public static final Integer ERROR_USERNAMEPASSWORD = 200;
|
||||
public static final Integer ILLEGAL_LOGIN = 300;
|
||||
public static final Integer INVALID_PARAM = 400;
|
||||
public static final Integer SESSION_EXPIRED = 500;
|
||||
public static final Integer USER_NO_PERMMSION = 600;
|
||||
public static final Integer SELECT_NON_DATA = 700;
|
||||
|
||||
|
||||
public static final String SUCCESS_STRING= "获取数据成功!";
|
||||
public static final String ERROR_SERVE_STRING = "服务器端错误!";
|
||||
public static final String ERROR_USERNAMEPASSWORD_STRING= "用户名密码错误";
|
||||
public static final String ILLEGAL_LOGIN_STRING = "非法登陆";
|
||||
public static final String INVALID_PARAM_STRING = "参数验证错误";
|
||||
public static final String SESSION_EXPIRED_STRING = "session过期,请重新登陆!";
|
||||
public static final String USER_NO_PERMMSION_STRING = "用户无权限查询数据!";
|
||||
public static final String SELECT_NON_DATA_STRING = "查询无数据!";
|
||||
|
||||
//另一套ResultBean:主要在ScheduleJobServiceImpl中使用
|
||||
public final static Integer SUCCESS_CODE = 0;
|
||||
public final static Integer ERROR_CODE = 100;//数据正常返回 但结果集数据为null
|
||||
public final static Integer SERVER_ERROR_CODE = 500;
|
||||
public final static String CHECKDATA_SUCCESS_STRING = "获取数据成功!";
|
||||
public final static String SERVER_ERROR_STRING = "服务端错误,请联系管理员";
|
||||
|
||||
public final static String CHECKDATA_ERROR_STRING = "获取数据失败,请稍后再试!";
|
||||
public final static String SAVE_SUCCESS_STRING = "保存成功!";
|
||||
public final static String SAVE_ERROR_STRING = "保存失败,请稍后再试!";
|
||||
public final static String UPDATE_ERROR_STRING = "修改失败,请稍后再试!";
|
||||
public final static String DELETE_ERROR_STRING = "删除失败,请稍后再试!";
|
||||
public final static String DELETE_SUCCESS_STRING = "删除成功!";
|
||||
|
||||
}
|
||||
92
ndplan/src/main/java/com/system/common/RowsWrapper.java
Normal file
92
ndplan/src/main/java/com/system/common/RowsWrapper.java
Normal file
@@ -0,0 +1,92 @@
|
||||
package com.system.common;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
|
||||
@NoArgsConstructor
|
||||
public class RowsWrapper<T> {
|
||||
|
||||
/**
|
||||
* 数据内容
|
||||
*/
|
||||
private List<T> rows;
|
||||
/**
|
||||
* 页码
|
||||
*/
|
||||
private int pageNumber;
|
||||
/**
|
||||
* 每页条数
|
||||
*/
|
||||
private int pageSize;
|
||||
/**
|
||||
* 总页数
|
||||
*/
|
||||
private int totalPage;
|
||||
/**
|
||||
* 记录总条数
|
||||
*/
|
||||
private long totalSize;
|
||||
|
||||
public RowsWrapper(int pageNumber, int pageSize, long totalSize, int totalPage, List<T> rows) {
|
||||
this.pageNumber = pageNumber;
|
||||
this.pageSize = pageSize;
|
||||
this.totalPage = totalPage;
|
||||
this.totalSize = totalSize;
|
||||
this.rows = rows;
|
||||
}
|
||||
|
||||
public List<T> getRows() {
|
||||
return rows;
|
||||
}
|
||||
|
||||
public void setContent(List<T> rows) {
|
||||
this.rows = rows;
|
||||
}
|
||||
|
||||
public int getPageNumber() {
|
||||
return pageNumber + 1;
|
||||
}
|
||||
|
||||
public void setPageNumber(int pageNumber) {
|
||||
this.pageNumber = pageNumber;
|
||||
}
|
||||
|
||||
public int getPageSize() {
|
||||
return pageSize;
|
||||
}
|
||||
|
||||
public void setPageSize(int pageSize) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
public int getTotalPage() {
|
||||
return totalPage;
|
||||
}
|
||||
|
||||
public void setTotalPage(int totalPage) {
|
||||
this.totalPage = totalPage;
|
||||
}
|
||||
|
||||
public long getTotalSize() {
|
||||
return totalSize;
|
||||
}
|
||||
|
||||
public void setTotalSize(long totalSize) {
|
||||
this.totalSize = totalSize;
|
||||
}
|
||||
|
||||
public long getTotal(){
|
||||
return this.getTotalSize();
|
||||
}
|
||||
public RowsWrapper(Page<T> page , Integer pageNum , Integer pageSize) {
|
||||
this.totalPage = page.getTotalPages();
|
||||
this.totalSize = page.getTotalElements();
|
||||
this.rows = page.getContent();
|
||||
this.pageNumber = pageNum;
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
}
|
||||
5
ndplan/src/main/java/com/system/module/TypeItem.java
Normal file
5
ndplan/src/main/java/com/system/module/TypeItem.java
Normal file
@@ -0,0 +1,5 @@
|
||||
package com.system.module;
|
||||
|
||||
public class TypeItem {
|
||||
|
||||
}
|
||||
94
ndplan/src/main/java/com/system/util/AESUtils.java
Normal file
94
ndplan/src/main/java/com/system/util/AESUtils.java
Normal file
@@ -0,0 +1,94 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
|
||||
import com.tky.web.config.bean.BasicPlatformConfig;
|
||||
|
||||
public class AESUtils {
|
||||
|
||||
public static String encrypt(String key, String initVector, String value) throws Exception {
|
||||
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
|
||||
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
|
||||
// cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
|
||||
|
||||
byte[] encrypted = cipher.doFinal(value.getBytes());
|
||||
/*
|
||||
* System.out.println("encrypted string: " + +
|
||||
* Base64.encodeBase64String(encrypted));
|
||||
*/
|
||||
// System.out.println(Base64.encodeBase64String(encrypted));
|
||||
return Base64.encodeBase64String(encrypted);
|
||||
|
||||
}
|
||||
|
||||
public static String decrypt(String key, String initVector, String encrypted) throws Exception {
|
||||
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
|
||||
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
|
||||
// cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
|
||||
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
|
||||
|
||||
return new String(original);
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* public static void main(String[] args) throws Exception { String key =
|
||||
* "r93535.com/.!!!!"; // 128 bit key String initVector = "0987654321234567"; //
|
||||
* 16 bytes IV //System.out.println(encrypt(key,initVector,"R93535.com,"));
|
||||
*
|
||||
* //String pwd=encrypt(key,initVector,"QWER1234"); //System.out.println(pwd);
|
||||
*
|
||||
* System.out.println(getLoginInfo("jzxiangxiaoliang","xxl111888")); }
|
||||
*/
|
||||
|
||||
public static String getLoginInfo(String account, String pwd) throws Exception {
|
||||
// 密码加密
|
||||
String key = "r93535.com/.!!!!"; // 128 bit key
|
||||
String initVector = "0987654321234567";
|
||||
pwd = encrypt(key, initVector, pwd);
|
||||
|
||||
// 请求
|
||||
// String url ="http://10.30.1.9:9880/baseservicetest/rest/secret/login?";
|
||||
// String url ="http://www.r93535.com/desb/baseservice/rest/secret/login?";
|
||||
SpringUtil.getBean(BasicPlatformConfig.class).getLoginUrl();
|
||||
String url = SpringUtil.getBean(BasicPlatformConfig.class).getLoginUrl();//"http://10.1.1.50:12003/desb/baseservice/rest/secret/login?";
|
||||
Map<String, String> map = new HashMap();
|
||||
map.put("account", account);
|
||||
map.put("pwd", pwd);
|
||||
String result = HttpUtil.doPost(url, map, "utf-8");
|
||||
System.err.println(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String getLoginInfoCS(String account, String pwd) throws Exception {
|
||||
// 密码加密
|
||||
String key = "r93535.com/.!!!!"; // 128 bit key
|
||||
String initVector = "0987654321234567";
|
||||
pwd = encrypt(key, initVector, pwd);
|
||||
|
||||
// 请求
|
||||
String url = "http://10.30.1.9:9880/baseservicetest/rest/secret/login?";
|
||||
// String url ="http://www.r93535.com/desb/baseservice/rest/secret/login?";
|
||||
// String url = "http://10.1.1.50:12003/desb/baseservice/rest/secret/login?";
|
||||
Map<String, String> map = new HashMap();
|
||||
map.put("account", account);
|
||||
map.put("pwd", pwd);
|
||||
String result = HttpUtil.doPost(url, map, "utf-8");
|
||||
System.err.println(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
79
ndplan/src/main/java/com/system/util/AnnotationUtil.java
Normal file
79
ndplan/src/main/java/com/system/util/AnnotationUtil.java
Normal file
@@ -0,0 +1,79 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class AnnotationUtil {
|
||||
|
||||
|
||||
|
||||
public static Field getField(Class clazz, String fieldName) {
|
||||
Field[] allFields = clazz.getDeclaredFields();// 得到所有定义字段
|
||||
// 得到所有field并存放到一个list中.
|
||||
for (Field field : allFields) {
|
||||
if(fieldName.equals( fieldName )) {
|
||||
field.setAccessible(true); // 禁止访问检查
|
||||
return field;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取实体的所有字段
|
||||
*
|
||||
* @param map
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings({ "rawtypes", "unused" })
|
||||
public static List<Field> getFileds(Class clazz, List<Field> fields,Class annotationClass) {
|
||||
if (fields == null) {
|
||||
fields = new ArrayList<Field>();
|
||||
}
|
||||
|
||||
Field[] allFields = clazz.getDeclaredFields();// 得到所有定义字段
|
||||
// 得到所有field并存放到一个list中.
|
||||
for (Field field : allFields) {
|
||||
if (field.isAnnotationPresent(annotationClass)) {
|
||||
fields.add(field);
|
||||
}
|
||||
}
|
||||
if (clazz.getSuperclass() != null
|
||||
&& !clazz.getSuperclass().equals(Object.class)) {
|
||||
getFileds(clazz.getSuperclass(), fields, annotationClass);
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param clazz
|
||||
* @param fields
|
||||
* @param annotationClass
|
||||
* @return
|
||||
*/
|
||||
public static List<Field> getAnnotationFileds(Class clazz, Class annotationClass) {
|
||||
List<Field> fields = getFileds(clazz, null, annotationClass);
|
||||
/*List<Field> fieldList = new ArrayList<Field>();
|
||||
if(!CollectionUtils.isEmpty(fields)) {
|
||||
fields.stream().forEach( e -> {
|
||||
Object annotation = e.getAnnotation(annotationClass);
|
||||
if(annotation != null)
|
||||
fieldList.add(e);
|
||||
});
|
||||
}
|
||||
*/
|
||||
return fields;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
/*List<Field> fields = getAnnotationFileds(MeasureData.class, CopyAttribute.class);
|
||||
fields.stream().forEach( e -> {
|
||||
System.out.println(e.getName() );
|
||||
});*/
|
||||
}
|
||||
}
|
||||
127
ndplan/src/main/java/com/system/util/Base64Util.java
Normal file
127
ndplan/src/main/java/com/system/util/Base64Util.java
Normal file
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* @Title: Base64Util.java
|
||||
* @Package com.tky.jyp.util
|
||||
* @Description: TODO
|
||||
* Copyright: Copyright (c) 2015
|
||||
* Company:TKY
|
||||
*
|
||||
* @author lwj
|
||||
* @date 2017年6月5日 上午10:22:56
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.system.util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
/**
|
||||
* TODO(用一句话描述这个变量表示什么)
|
||||
*/
|
||||
public class Base64Util {
|
||||
private static final char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
|
||||
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
|
||||
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
|
||||
|
||||
private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60,
|
||||
61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1,
|
||||
-1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 };
|
||||
|
||||
private Base64Util() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组编码为字符串
|
||||
*
|
||||
* @param data
|
||||
*/
|
||||
public static String encode(byte[] data) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
int len = data.length;
|
||||
int i = 0;
|
||||
int b1, b2, b3;
|
||||
|
||||
while (i < len) {
|
||||
b1 = data[i++] & 0xff;
|
||||
if (i == len) {
|
||||
sb.append(base64EncodeChars[b1 >>> 2]);
|
||||
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
|
||||
sb.append("==");
|
||||
break;
|
||||
}
|
||||
b2 = data[i++] & 0xff;
|
||||
if (i == len) {
|
||||
sb.append(base64EncodeChars[b1 >>> 2]);
|
||||
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
|
||||
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
|
||||
sb.append("=");
|
||||
break;
|
||||
}
|
||||
b3 = data[i++] & 0xff;
|
||||
sb.append(base64EncodeChars[b1 >>> 2]);
|
||||
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
|
||||
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
|
||||
sb.append(base64EncodeChars[b3 & 0x3f]);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 灏哹ase64瀛楃涓茶В鐮佷负瀛楄妭鏁扮粍
|
||||
*
|
||||
* @param str
|
||||
*/
|
||||
public static byte[] decode(String str) throws Exception {
|
||||
byte[] data = str.getBytes("GBK");
|
||||
int len = data.length;
|
||||
ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
|
||||
int i = 0;
|
||||
int b1, b2, b3, b4;
|
||||
|
||||
while (i < len) {
|
||||
|
||||
/* b1 */
|
||||
do {
|
||||
b1 = base64DecodeChars[data[i++]];
|
||||
} while (i < len && b1 == -1);
|
||||
if (b1 == -1) {
|
||||
break;
|
||||
}
|
||||
|
||||
/* b2 */
|
||||
do {
|
||||
b2 = base64DecodeChars[data[i++]];
|
||||
} while (i < len && b2 == -1);
|
||||
if (b2 == -1) {
|
||||
break;
|
||||
}
|
||||
buf.write((b1 << 2) | ((b2 & 0x30) >>> 4));
|
||||
|
||||
/* b3 */
|
||||
do {
|
||||
b3 = data[i++];
|
||||
if (b3 == 61) {
|
||||
return buf.toByteArray();
|
||||
}
|
||||
b3 = base64DecodeChars[b3];
|
||||
} while (i < len && b3 == -1);
|
||||
if (b3 == -1) {
|
||||
break;
|
||||
}
|
||||
buf.write(((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2));
|
||||
|
||||
/* b4 */
|
||||
do {
|
||||
b4 = data[i++];
|
||||
if (b4 == 61) {
|
||||
return buf.toByteArray();
|
||||
}
|
||||
b4 = base64DecodeChars[b4];
|
||||
} while (i < len && b4 == -1);
|
||||
if (b4 == -1) {
|
||||
break;
|
||||
}
|
||||
buf.write(((b3 & 0x03) << 6) | b4);
|
||||
}
|
||||
return buf.toByteArray();
|
||||
}
|
||||
}
|
||||
243
ndplan/src/main/java/com/system/util/CacheUtil.java
Normal file
243
ndplan/src/main/java/com/system/util/CacheUtil.java
Normal file
@@ -0,0 +1,243 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.cache.RemovalCause;
|
||||
import com.google.common.cache.RemovalListener;
|
||||
import com.google.common.cache.RemovalNotification;
|
||||
|
||||
import cn.hutool.core.collection.ConcurrentHashSet;
|
||||
/**
|
||||
*
|
||||
* ClassName:CacheUtil
|
||||
* 缓存工具
|
||||
* 建数据缓存到内存中
|
||||
*/
|
||||
public class CacheUtil {
|
||||
/*static LoadingCache<String, Object> cache = CacheBuilder.newBuilder()
|
||||
.maximumSize(10000)//最多存放一万个数据
|
||||
.expireAfterWrite(60, TimeUnit.SECONDS)//缓存60秒,60秒之后进行回收
|
||||
//.recordStats()//开启,记录状态数据功能
|
||||
.build(new CacheLoader<String, Object>() {
|
||||
//数据加载,默认返回-1,也可以是查询操作,如从DB查询
|
||||
@Override
|
||||
public Object load(String key) throws Exception {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
// TODO Auto-generated method stub
|
||||
return super.clone();
|
||||
}
|
||||
});
|
||||
|
||||
public static Object get(String key) {
|
||||
try {
|
||||
return cache.get(key);
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
};
|
||||
public static Object put(String key,Object value) {
|
||||
cache.put(key, value);
|
||||
System.out.println("卡调接收数据:" +cache.size());
|
||||
return value;
|
||||
};
|
||||
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static Set<String> getKeys() {
|
||||
try {
|
||||
return cache.
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
return new HashSet();
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
/** 缓存项最大数量 */
|
||||
private static final long GUAVA_CACHE_SIZE = 100000;
|
||||
|
||||
/** 缓存时间:天 */
|
||||
private static final long GUAVA_CACHE_DAY = 10;
|
||||
|
||||
/** 缓存时间:秒 */
|
||||
private static final long GUAVA_CACHE_SECOND = 120;
|
||||
|
||||
/** 缓存操作对象 */
|
||||
private static LoadingCache<String, Object> GLOBAL_CACHE = null;
|
||||
|
||||
/** 缓存Key */
|
||||
private static Set<String> KEYS = new ConcurrentHashSet<>();
|
||||
|
||||
static {
|
||||
try {
|
||||
GLOBAL_CACHE = loadCache(new CacheLoader <String, Object>() {
|
||||
@Override
|
||||
public Object load(String key) throws Exception {
|
||||
// 处理缓存键不存在缓存值时的处理逻辑
|
||||
return null;
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局缓存设置
|
||||
*
|
||||
* 缓存项最大数量:100000
|
||||
* 缓存有效时间(天):10
|
||||
*
|
||||
*
|
||||
* @param cacheLoader
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
private static LoadingCache<String, Object> loadCache(CacheLoader<String, Object> cacheLoader) throws Exception {
|
||||
LoadingCache<String, Object> cache = CacheBuilder.newBuilder()
|
||||
//缓存池大小,在缓存项接近该大小时, Guava开始回收旧的缓存项
|
||||
.maximumSize(GUAVA_CACHE_SIZE)
|
||||
//设置时间对象没有被读/写访问则对象从内存中删除(在另外的线程里面不定期维护)
|
||||
.expireAfterAccess(GUAVA_CACHE_SECOND, TimeUnit.SECONDS)
|
||||
// 设置缓存在写入之后 设定时间 后失效
|
||||
.expireAfterWrite(GUAVA_CACHE_SECOND, TimeUnit.SECONDS)
|
||||
//移除监听器,缓存项被移除时会触发
|
||||
.removalListener(new RemovalListener <String, Object>() {
|
||||
@Override
|
||||
public void onRemoval(RemovalNotification<String, Object> rn) {
|
||||
if(rn.getCause().ordinal() == RemovalCause.EXPIRED.ordinal()) {
|
||||
System.out.println("移除:" + rn.getKey());
|
||||
KEYS.remove(rn.getKey());
|
||||
}
|
||||
//逻辑操作
|
||||
}
|
||||
})
|
||||
//开启Guava Cache的统计功能
|
||||
.recordStats()
|
||||
.build(cacheLoader);
|
||||
return cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置缓存值
|
||||
* 注: 若已有该key值,则会先移除(会触发removalListener移除监听器),再添加
|
||||
*
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
public static void put(String key, Object value) {
|
||||
try {
|
||||
KEYS.add(key);
|
||||
System.out.println(KEYS);
|
||||
GLOBAL_CACHE.put(key, value);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量设置缓存值
|
||||
*
|
||||
* @param map
|
||||
*/
|
||||
public static void putAll(Map<? extends String, ? extends Object> map) {
|
||||
try {
|
||||
KEYS.addAll(map.keySet());
|
||||
GLOBAL_CACHE.putAll(map);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存值
|
||||
* 注:如果键不存在值,将调用CacheLoader的load方法加载新值到该键中
|
||||
*
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Object get(String key) {
|
||||
Object token = null;
|
||||
try {
|
||||
token = GLOBAL_CACHE.get(key);
|
||||
} catch (Exception e) {
|
||||
//e.printStackTrace();
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除缓存
|
||||
*
|
||||
* @param key
|
||||
*/
|
||||
public static void remove(String key) {
|
||||
try {
|
||||
KEYS.remove(key);
|
||||
GLOBAL_CACHE.invalidate(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量移除缓存
|
||||
*
|
||||
* @param keys
|
||||
*/
|
||||
public static void removeAll(Iterable<String> keys) {
|
||||
try {
|
||||
GLOBAL_CACHE.invalidateAll(keys);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有缓存
|
||||
*/
|
||||
public static void removeAll() {
|
||||
try {
|
||||
GLOBAL_CACHE.invalidateAll();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存项数量
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static long size() {
|
||||
long size = 0;
|
||||
try {
|
||||
size = GLOBAL_CACHE.size();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
|
||||
public static Set<String> keys() {
|
||||
try {
|
||||
return KEYS;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return new ConcurrentHashSet<>() ;
|
||||
}
|
||||
|
||||
public static Map<String,Object> asMap(){
|
||||
return GLOBAL_CACHE.asMap();
|
||||
}
|
||||
}
|
||||
203
ndplan/src/main/java/com/system/util/CacheUtil2.java
Normal file
203
ndplan/src/main/java/com/system/util/CacheUtil2.java
Normal file
@@ -0,0 +1,203 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.cache.RemovalListener;
|
||||
import com.google.common.cache.RemovalNotification;
|
||||
/**
|
||||
*
|
||||
* ClassName:CacheUtil
|
||||
* 缓存工具
|
||||
* 建数据缓存到内存中
|
||||
*/
|
||||
public class CacheUtil2 {
|
||||
/*static LoadingCache<String, Object> cache = CacheBuilder.newBuilder()
|
||||
.maximumSize(10000)//最多存放一万个数据
|
||||
.expireAfterWrite(60, TimeUnit.SECONDS)//缓存10秒,10秒之后进行回收
|
||||
//.recordStats()//开启,记录状态数据功能
|
||||
.build(new CacheLoader<String, Object>() {
|
||||
//数据加载,默认返回-1,也可以是查询操作,如从DB查询
|
||||
@Override
|
||||
public Object load(String key) throws Exception {
|
||||
// TODO Auto-generated method stub
|
||||
return null;
|
||||
}@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
// TODO Auto-generated method stub
|
||||
return super.clone();
|
||||
}
|
||||
});
|
||||
|
||||
public static Object get(String key) {
|
||||
try {
|
||||
return cache.get(key);
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
};
|
||||
public static Object put(String key,Object value) {
|
||||
cache.put(key, value);
|
||||
return value;
|
||||
};
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static Set<String> getKeys() {
|
||||
try {
|
||||
return cache.
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
return new HashSet();
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
/** 缓存项最大数量 */
|
||||
private static final long GUAVA_CACHE_SIZE = 100000;
|
||||
|
||||
/** 缓存时间:天 */
|
||||
private static final long GUAVA_CACHE_DAY = 10;
|
||||
|
||||
/** 缓存操作对象 */
|
||||
private static LoadingCache<Long, String> GLOBAL_CACHE = null;
|
||||
|
||||
static {
|
||||
try {
|
||||
GLOBAL_CACHE = loadCache(new CacheLoader <Long, String>() {
|
||||
@Override
|
||||
public String load(Long key) throws Exception {
|
||||
// 处理缓存键不存在缓存值时的处理逻辑
|
||||
return "";
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局缓存设置
|
||||
*
|
||||
* 缓存项最大数量:100000
|
||||
* 缓存有效时间(天):10
|
||||
*
|
||||
*
|
||||
* @param cacheLoader
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
private static LoadingCache<Long, String> loadCache(CacheLoader<Long, String> cacheLoader) throws Exception {
|
||||
LoadingCache<Long, String> cache = CacheBuilder.newBuilder()
|
||||
//缓存池大小,在缓存项接近该大小时, Guava开始回收旧的缓存项
|
||||
.maximumSize(GUAVA_CACHE_SIZE)
|
||||
//设置时间对象没有被读/写访问则对象从内存中删除(在另外的线程里面不定期维护)
|
||||
.expireAfterAccess(GUAVA_CACHE_DAY, TimeUnit.DAYS)
|
||||
// 设置缓存在写入之后 设定时间 后失效
|
||||
.expireAfterWrite(GUAVA_CACHE_DAY, TimeUnit.DAYS)
|
||||
//移除监听器,缓存项被移除时会触发
|
||||
.removalListener(new RemovalListener <Long, String>() {
|
||||
@Override
|
||||
public void onRemoval(RemovalNotification<Long, String> rn) {
|
||||
//逻辑操作
|
||||
}
|
||||
})
|
||||
//开启Guava Cache的统计功能
|
||||
.recordStats()
|
||||
.build(cacheLoader);
|
||||
return cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置缓存值
|
||||
* 注: 若已有该key值,则会先移除(会触发removalListener移除监听器),再添加
|
||||
*
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
public static void put(Long key, String value) {
|
||||
try {
|
||||
GLOBAL_CACHE.put(key, value);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量设置缓存值
|
||||
*
|
||||
* @param map
|
||||
*/
|
||||
public static void putAll(Map<? extends Long, ? extends String> map) {
|
||||
try {
|
||||
GLOBAL_CACHE.putAll(map);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存值
|
||||
* 注:如果键不存在值,将调用CacheLoader的load方法加载新值到该键中
|
||||
*
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String get(Long key) {
|
||||
String token = "";
|
||||
try {
|
||||
token = GLOBAL_CACHE.get(key);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除缓存
|
||||
*
|
||||
* @param key
|
||||
*/
|
||||
public static void remove(Long key) {
|
||||
try {
|
||||
GLOBAL_CACHE.invalidate(key);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量移除缓存
|
||||
*
|
||||
* @param keys
|
||||
*/
|
||||
public static void removeAll(Iterable<Long> keys) {
|
||||
try {
|
||||
GLOBAL_CACHE.invalidateAll(keys);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有缓存
|
||||
*/
|
||||
public static void removeAll() {
|
||||
try {
|
||||
GLOBAL_CACHE.invalidateAll();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存项数量
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static long size() {
|
||||
long size = 0;
|
||||
try {
|
||||
size = GLOBAL_CACHE.size();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
}
|
||||
37
ndplan/src/main/java/com/system/util/CommonData.java
Normal file
37
ndplan/src/main/java/com/system/util/CommonData.java
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* @Title: CommonData.java
|
||||
* @Package com.tky.jyp.util
|
||||
* @Description: TODO
|
||||
* Copyright: Copyright (c) 2015
|
||||
* Company:TKY
|
||||
*
|
||||
* @author lwj
|
||||
* @date 2017年5月24日 上午8:13:55
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.system.util;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
|
||||
/**
|
||||
* TODO(用一句话描述这个变量表示什么)
|
||||
*/
|
||||
@Component
|
||||
public class CommonData {
|
||||
public static String INTERFACE_PROPERTIES = "interface.properties";
|
||||
public static final String SYSTEM_PROPERTIES = "system.properties";
|
||||
public static final String SELECT_PROPERTIES = "interfaceselect.properties";
|
||||
public static final String APPKEY_PROPERTIES = "appkey.properties";
|
||||
|
||||
@Value("${spring.profiles.active}")
|
||||
public void setProfilesActive(String value) {
|
||||
INTERFACE_PROPERTIES = "interface-"+value+".properties";
|
||||
}
|
||||
|
||||
// 应用ID和秘钥
|
||||
public static final String APP_ID = PropertyUtil.getValue(APPKEY_PROPERTIES, "appid");
|
||||
|
||||
public static final String APP_PASSWORD = PropertyUtil.getValue(APPKEY_PROPERTIES, "appsecret");
|
||||
}
|
||||
55
ndplan/src/main/java/com/system/util/ComplexSqlDao.java
Normal file
55
ndplan/src/main/java/com/system/util/ComplexSqlDao.java
Normal file
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* @Title: ComplexSqlDAO.java
|
||||
* @Package com.tky.sgzz.dao
|
||||
* @Description: 复杂sql查询dao
|
||||
*
|
||||
* @author lwj
|
||||
* @date 2017年5月15日 上午10:49:40
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.system.util;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.Query;
|
||||
|
||||
import org.hibernate.SQLQuery;
|
||||
import org.hibernate.transform.Transformers;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 复杂sql Dao类
|
||||
*/
|
||||
@Component
|
||||
public class ComplexSqlDao {
|
||||
@Autowired
|
||||
@PersistenceContext
|
||||
private EntityManager em;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title: getMapComplexSelectSql
|
||||
* @Description: 复杂sql查询 返回Map
|
||||
* @param objValue 参数值数组
|
||||
* @param sql sql语句 ?和objValue值对应
|
||||
* @return
|
||||
* @return List<Map<String,Object>> 返回类型
|
||||
* @throws
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<Map<String,Object>> getMapComplexSelectSql(Object objValue[], String sql){
|
||||
Query query = em.createNativeQuery(sql);
|
||||
query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
|
||||
for(int i = 0 ; i < objValue.length ; i++){
|
||||
query.setParameter(i + 1, objValue[i]);
|
||||
}
|
||||
List<Map<String,Object>> rows = query.getResultList();
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
400
ndplan/src/main/java/com/system/util/DateUtil.java
Normal file
400
ndplan/src/main/java/com/system/util/DateUtil.java
Normal file
@@ -0,0 +1,400 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import lombok.extern.java.Log;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
/**
|
||||
* 日期相关计算辅助类<br/>
|
||||
*/
|
||||
@Log
|
||||
public class DateUtil {
|
||||
|
||||
public static final String FORMAT_STR = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
/**
|
||||
* 计算年龄
|
||||
*
|
||||
* @param birthDay
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Integer getAge(Date birthDay) {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
if (cal.before(birthDay)) {
|
||||
throw new IllegalArgumentException("出生日期不能在当前日期之后!");
|
||||
}
|
||||
int yearNow = cal.get(Calendar.YEAR);
|
||||
int monthNow = cal.get(Calendar.MONTH) + 1;
|
||||
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
cal.setTime(birthDay);
|
||||
int yearBirth = cal.get(Calendar.YEAR);
|
||||
int monthBirth = cal.get(Calendar.MONTH);
|
||||
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
|
||||
|
||||
int age = yearNow - yearBirth;
|
||||
|
||||
if (monthNow <= monthBirth) {
|
||||
if (monthNow == monthBirth) {
|
||||
if (dayOfMonthNow < dayOfMonthBirth)
|
||||
age--;
|
||||
} else {
|
||||
age--;
|
||||
}
|
||||
}
|
||||
|
||||
return age;
|
||||
}
|
||||
|
||||
|
||||
public static Date getDateByStr(String dateStr){
|
||||
try{
|
||||
return new Date(Long.parseLong(dateStr));
|
||||
}catch (Exception e){
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理开始时间 当天时间的0时0分0秒
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static Date processStartTime(Date start) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(start);
|
||||
c.set(Calendar.HOUR_OF_DAY, 0);
|
||||
c.set(Calendar.MINUTE, 0);
|
||||
c.set(Calendar.SECOND, 0);
|
||||
c.set(Calendar.MILLISECOND, 0);
|
||||
return c.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理结束时间 当天时间的23时59分59秒
|
||||
*
|
||||
* @param endTime
|
||||
* @return
|
||||
*/
|
||||
public static Date processEndTime(Date endTime) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(endTime);
|
||||
c.set(Calendar.HOUR_OF_DAY, 23);
|
||||
c.set(Calendar.MINUTE, 59);
|
||||
c.set(Calendar.SECOND, 59);
|
||||
return c.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析日期
|
||||
* 格式"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm","yyyy-MM-dd HH","yyyy-MM-dd"
|
||||
*
|
||||
* @param dateStr
|
||||
* @return Date
|
||||
*/
|
||||
public static Date parseDate(String dateStr) {
|
||||
String[] dateFormatStr = new String[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH", "yyyy-MM-dd" };
|
||||
if (!StringUtils.isEmpty(dateStr)) {
|
||||
dateStr = dateStr.trim();
|
||||
for (int i = 0; i < dateFormatStr.length; i++) {
|
||||
if (dateStr.length() >= dateFormatStr[i].length()) {
|
||||
return parseDateByFormat(dateStr, dateFormatStr[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Date parseDateByFormat(String dateStr, String dateFormatStr) {
|
||||
try {
|
||||
return DateUtils.parseDate(dateStr, dateFormatStr);
|
||||
} catch (Exception e) {
|
||||
log.warning(e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String formatDate(Date date, String format) {
|
||||
return new SimpleDateFormat(format == null ? "yyyy-MM-dd" : format ).format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过睡眠时间获取所属日睡眠记录的执行日期
|
||||
*
|
||||
* @param date
|
||||
* @return Date
|
||||
*/
|
||||
public static Date getSleepDay(Date date) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(date);
|
||||
if (c.get(Calendar.HOUR_OF_DAY) < 6) {
|
||||
return processStartTime(DateUtils.addDays(date, -1));
|
||||
} else {
|
||||
return processStartTime(date);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取冒号分割的时间字符串
|
||||
*
|
||||
* @param duration
|
||||
* 时长(单位:秒)
|
||||
* @param format
|
||||
* 时间格式
|
||||
* @return String 格式化后的时间字符串
|
||||
*/
|
||||
public static String getTimeStrWithColon(Integer duration, String format) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.set(Calendar.HOUR_OF_DAY, 0);
|
||||
c.set(Calendar.MINUTE, 0);
|
||||
c.set(Calendar.SECOND, 0);
|
||||
c.add(Calendar.SECOND, duration);
|
||||
|
||||
if (GeneralHelper.isTrimStrEmpty(format)) {
|
||||
if (c.get(Calendar.HOUR_OF_DAY) > 0) {
|
||||
format = "HH:mm:ss";
|
||||
} else if (c.get(Calendar.MINUTE) > 0) {
|
||||
format = "mm:ss";
|
||||
} else {
|
||||
format = "ss";
|
||||
}
|
||||
}
|
||||
return GeneralHelper.date2Str(c.getTime(), format);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取汉字分割的时间字符串
|
||||
*
|
||||
* @param duration
|
||||
* 时长(单位:秒)
|
||||
* @param format
|
||||
* 时间格式
|
||||
* @return String 格式化后的时间字符串
|
||||
*/
|
||||
public static String getTimeStrWithChinese(Integer duration, String format) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.set(Calendar.HOUR_OF_DAY, 0);
|
||||
c.set(Calendar.MINUTE, 0);
|
||||
c.set(Calendar.SECOND, 0);
|
||||
c.add(Calendar.SECOND, duration);
|
||||
|
||||
if (GeneralHelper.isTrimStrEmpty(format)) {
|
||||
if (c.get(Calendar.HOUR_OF_DAY) > 0) {
|
||||
format = "HH小时mm分ss秒";
|
||||
} else if (c.get(Calendar.MINUTE) > 0) {
|
||||
format = "mm分ss秒";
|
||||
} else {
|
||||
format = "ss秒";
|
||||
}
|
||||
}
|
||||
return GeneralHelper.date2Str(c.getTime(), format);
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化输出日期
|
||||
*
|
||||
* @param date
|
||||
* @return Date 返回类型
|
||||
*/
|
||||
public static Date getForMatDate(Date date) {
|
||||
return getForMatDate(date, FORMAT_STR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化输出日期
|
||||
*
|
||||
* @param date
|
||||
* @return Date 返回类型
|
||||
*/
|
||||
public static Date getForMatDate(Date date, String pattern) {
|
||||
if (StringUtils.isEmpty(pattern)) {
|
||||
pattern = FORMAT_STR;
|
||||
}
|
||||
SimpleDateFormat fmat = new SimpleDateFormat(pattern);
|
||||
try {
|
||||
return fmat.parse(fmat.format(date));
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return new Date();
|
||||
}
|
||||
|
||||
public static String getDateToString(Date date, String pattern) {
|
||||
try {
|
||||
if (date == null) {
|
||||
return "";
|
||||
}
|
||||
if (StringUtils.isEmpty(pattern)) {
|
||||
pattern = FORMAT_STR;
|
||||
}
|
||||
SimpleDateFormat fmat = new SimpleDateFormat(pattern);
|
||||
return fmat.format(date);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
log.warning(e.getMessage());
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 给定事前是否在服务器规定时间范围内
|
||||
*
|
||||
* @param preTo
|
||||
* @return boolean 返回类型
|
||||
*/
|
||||
public static boolean isValid(Date preTo) {
|
||||
if (preTo == null) {
|
||||
return false;
|
||||
}
|
||||
Date now = new Date();
|
||||
long first = now.getTime() - 24 * 60 * 60 * 1000;
|
||||
long second = preTo.getTime();
|
||||
long third = now.getTime() + 20 * 60 * 1000;
|
||||
if (second >= first && second <= third) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description: 比较睡眠日期是否合法
|
||||
* @param preTo
|
||||
* @return boolean 返回类型
|
||||
*/
|
||||
public static boolean isValidSleep(Date endTime) {
|
||||
if (endTime == null) {
|
||||
return false;
|
||||
}
|
||||
Date now = new Date();
|
||||
long first = now.getTime() - 48 * 60 * 60 * 1000;
|
||||
long second = endTime.getTime();
|
||||
long third = now.getTime() + 24 * 60 * 60 * 1000;
|
||||
if (second >= first && second <= third) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static Date getAddDate(Date now, int day) {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(now);
|
||||
cal.add(Calendar.DATE, day);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
/** 获取两个时间的差值,pattern 为 y代表年,M代表月 */
|
||||
public static String getDatediff(Date d1, Date d2, char pattern) {
|
||||
long timeDeff = d1.getTime() - d2.getTime();
|
||||
if ('y' == pattern)
|
||||
timeDeff = timeDeff / (12 * 30 * 24 * 60 * 60 * 1000);
|
||||
if ('M' == pattern)
|
||||
timeDeff = timeDeff / (30 * 24 * 60 * 60 * 1000L);
|
||||
if ('d' == pattern)
|
||||
timeDeff = timeDeff / (24 * 60 * 60 * 1000);
|
||||
if ('H' == pattern)
|
||||
timeDeff = timeDeff / (60 * 60 * 1000);
|
||||
if ('m' == pattern)
|
||||
timeDeff = timeDeff / (60 * 1000);
|
||||
if ('s' == pattern)
|
||||
timeDeff = timeDeff / (1000);
|
||||
return timeDeff + "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取日期前一个月
|
||||
*
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date getRecentBeforeMonth(Date date) {
|
||||
Date temp = (date.getDay() == 1) ? date : DateUtils.addMonths(date, -1);
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取日期后一个月
|
||||
*
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date getRecentAfterMonth(Date date) {
|
||||
Date temp = (DateUtils.addDays(date, 1).getDay() == 1) ? date : DateUtils.addMonths(date, 1);
|
||||
return temp;
|
||||
}
|
||||
|
||||
public static int getDays(Date d1, Date d2) {
|
||||
return (int) (Math.abs(d1.getTime() - d2.getTime()) / (24 * 60 * 60 * 1000));
|
||||
}
|
||||
|
||||
public static Date getFirstDate(Date d1, int unit) {
|
||||
Date date = DateUtils.addMonths(d1, 1);
|
||||
try {
|
||||
date = DateUtils.parseDate(formatDate(date, "yyyy-MM"), "yyyy-MM");
|
||||
if (getDays(d1, date) > (30 * unit / 2)) {
|
||||
return date;
|
||||
} else {
|
||||
return DateUtils.addMonths(date, unit);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warning(e.getMessage());
|
||||
}
|
||||
return d1;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param dateStr 源日期字符串
|
||||
* @param obj 运算对象
|
||||
* @param type 运算类型
|
||||
* @param value 运算量
|
||||
* @return
|
||||
*/
|
||||
public static String DateArithmetic(Date date,String obj,String type,Integer value){
|
||||
Calendar rightNow = Calendar.getInstance();
|
||||
rightNow.setTime(date);
|
||||
if(obj.equals("year")){
|
||||
if(type.equals("plus")){
|
||||
rightNow.add(Calendar.YEAR,value);
|
||||
}else{
|
||||
rightNow.add(Calendar.YEAR,-value);
|
||||
}
|
||||
}else if(obj.equals("month")){
|
||||
if(type.equals("plus")){
|
||||
rightNow.add(Calendar.MONTH,value);
|
||||
}else{
|
||||
rightNow.add(Calendar.MONTH,-value);
|
||||
}
|
||||
}else if(obj.equals("day")){
|
||||
if(type.equals("plus")){
|
||||
rightNow.add(Calendar.DAY_OF_MONTH,value);
|
||||
}else{
|
||||
rightNow.add(Calendar.DAY_OF_MONTH,-value);
|
||||
}
|
||||
}
|
||||
Date dt=rightNow.getTime();
|
||||
String dateStr=DateUtil.formatDate(dt, "yyyy-MM-dd'T'HH:mm:ss.SSS");
|
||||
System.out.println(dateStr);
|
||||
|
||||
return dateStr;
|
||||
}
|
||||
|
||||
|
||||
public static String getYesterday(String format){
|
||||
if(StringUtils.isEmpty(format)){
|
||||
format = "yyyy-MM-dd";
|
||||
}
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.add(Calendar.DATE, -1);
|
||||
String yesterday = new SimpleDateFormat( format).format(cal.getTime());
|
||||
return yesterday;
|
||||
}
|
||||
|
||||
}
|
||||
39
ndplan/src/main/java/com/system/util/DoubleUtil.java
Normal file
39
ndplan/src/main/java/com/system/util/DoubleUtil.java
Normal file
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @Title: NumberUtil.java
|
||||
* @Package com.tky.sanwei.util
|
||||
* @Description: TODO
|
||||
* Copyright: Copyright (c) 2015
|
||||
* Company:TKY
|
||||
*
|
||||
* @author vicene
|
||||
* @date 2017年7月28日 下午4:05:02
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.system.util;
|
||||
|
||||
import java.text.NumberFormat;
|
||||
|
||||
/**
|
||||
* TODO(用一句话描述这个变量表示什么)
|
||||
*/
|
||||
public class DoubleUtil {
|
||||
/**
|
||||
*
|
||||
* @Title: getRoundDoubleByDouble
|
||||
* @Description: 四舍五入保留两位小数
|
||||
* @param d
|
||||
* @return
|
||||
* @return Double 返回类型
|
||||
* @throws
|
||||
*/
|
||||
public static Double getRoundSave2DoubleByDouble(Double d){
|
||||
if(d == null){
|
||||
throw new RuntimeException("传入参数不能为空");
|
||||
}
|
||||
return (double)Math.round(d*100)/100;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(getRoundSave2DoubleByDouble(1919.017));
|
||||
}
|
||||
}
|
||||
540
ndplan/src/main/java/com/system/util/FileUtil.java
Normal file
540
ndplan/src/main/java/com/system/util/FileUtil.java
Normal file
@@ -0,0 +1,540 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileChannel.MapMode;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
|
||||
|
||||
public class FileUtil {
|
||||
|
||||
/**
|
||||
* 单个文件上传
|
||||
* @param is
|
||||
* @param fileName
|
||||
* @param filePath
|
||||
*/
|
||||
public static boolean upFile(MultipartFile uploadFile,String fileName,String filePath){
|
||||
FileOutputStream fos = null;
|
||||
BufferedOutputStream bos = null;
|
||||
FileInputStream is = null;
|
||||
BufferedInputStream bis = null;
|
||||
File file = new File(filePath);
|
||||
if(!file.exists()){
|
||||
file.mkdirs();
|
||||
}
|
||||
File f = new File(filePath+"/"+fileName);
|
||||
try {
|
||||
InputStream inputStream = uploadFile.getInputStream();
|
||||
//is = new FileInputStream(uploadFile);
|
||||
bis = new BufferedInputStream(inputStream);
|
||||
fos = new FileOutputStream(f);
|
||||
bos = new BufferedOutputStream(fos);
|
||||
byte[] bt = new byte[4096];
|
||||
int len = 0;
|
||||
while((len = bis.read(bt))>0){
|
||||
bos.write(bt, 0, len);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}finally {
|
||||
|
||||
try {
|
||||
if(null != bos){
|
||||
bos.close();
|
||||
bos = null;
|
||||
}
|
||||
if(null != fos){
|
||||
fos.close();
|
||||
fos= null;
|
||||
}
|
||||
if(null != is){
|
||||
is.close();
|
||||
is=null;
|
||||
}
|
||||
|
||||
if (null != bis) {
|
||||
bis.close();
|
||||
bis = null;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 文件下载
|
||||
* @param response
|
||||
* @param downloadFile
|
||||
*/
|
||||
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String downloadFile, String fileName) {
|
||||
|
||||
BufferedInputStream bis = null;
|
||||
InputStream is = null;
|
||||
OutputStream os = null;
|
||||
BufferedOutputStream bos = null;
|
||||
try {
|
||||
File file=new File(downloadFile); //文件的声明
|
||||
is = new FileInputStream(file); //文件流的声明
|
||||
os = response.getOutputStream(); //重点突出(特别注意),通过response获取的输出流,作为服务端往客户端浏览器输出内容的一个通道
|
||||
// 为了提高效率使用缓冲区流
|
||||
bis = new BufferedInputStream(is);
|
||||
bos = new BufferedOutputStream(os);
|
||||
// 处理下载文件名的乱码问题
|
||||
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
|
||||
fileName = new String(fileName.getBytes("GB2312"),"ISO-8859-1");
|
||||
} else {
|
||||
// 对文件名进行编码处理中文问题
|
||||
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
|
||||
fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
|
||||
}
|
||||
response.reset(); // 重点突出
|
||||
response.setCharacterEncoding("UTF-8"); // 重点突出
|
||||
response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
|
||||
// inline在浏览器中直接显示,不提示用户下载
|
||||
// attachment弹出对话框,提示用户进行下载保存本地
|
||||
// 默认为inline方式
|
||||
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
|
||||
// response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出
|
||||
int bytesRead = 0;
|
||||
byte[] buffer = new byte[1024];
|
||||
while ((bytesRead = bis.read(buffer)) != -1){ //重点
|
||||
bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex.getMessage());
|
||||
} finally {
|
||||
// 特别重要
|
||||
// 1. 进行关闭是为了释放资源
|
||||
// 2. 进行关闭会自动执行flush方法清空缓冲区内容
|
||||
try {
|
||||
if (null != bis) {
|
||||
bis.close();
|
||||
bis = null;
|
||||
}
|
||||
if (null != bos) {
|
||||
bos.close();
|
||||
bos = null;
|
||||
}
|
||||
if (null != is) {
|
||||
is.close();
|
||||
is = null;
|
||||
}
|
||||
if (null != os) {
|
||||
os.close();
|
||||
os = null;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 文件下载
|
||||
* @param response
|
||||
* @param downloadFile
|
||||
*/
|
||||
public static void downloadFile(HttpServletResponse response, String downloadFile, String showFileName) {
|
||||
|
||||
BufferedInputStream bis = null;
|
||||
InputStream is = null;
|
||||
OutputStream os = null;
|
||||
BufferedOutputStream bos = null;
|
||||
try {
|
||||
File file=new File(downloadFile); //:文件的声明
|
||||
String fileName=file.getName();
|
||||
is = new FileInputStream(file); //:文件流的声明
|
||||
os = response.getOutputStream(); // 重点突出
|
||||
bis = new BufferedInputStream(is);
|
||||
bos = new BufferedOutputStream(os);
|
||||
// 对文件名进行编码处理中文问题
|
||||
fileName = java.net.URLEncoder.encode(showFileName, "UTF-8");// 处理中文文件名的问题
|
||||
fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
|
||||
response.reset(); // 重点突出
|
||||
response.setCharacterEncoding("UTF-8"); // 重点突出
|
||||
response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
|
||||
// inline在浏览器中直接显示,不提示用户下载
|
||||
// attachment弹出对话框,提示用户进行下载保存本地
|
||||
// 默认为inline方式
|
||||
response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出
|
||||
int bytesRead = 0;
|
||||
byte[] buffer = new byte[1024];
|
||||
while ((bytesRead = bis.read(buffer)) != -1){ //重点
|
||||
bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex.getMessage());
|
||||
} finally {
|
||||
// 特别重要
|
||||
// 1. 进行关闭是为了释放资源
|
||||
// 2. 进行关闭会自动执行flush方法清空缓冲区内容
|
||||
try {
|
||||
if (null != bis) {
|
||||
bis.close();
|
||||
bis = null;
|
||||
}
|
||||
if (null != bos) {
|
||||
bos.close();
|
||||
bos = null;
|
||||
}
|
||||
if (null != is) {
|
||||
is.close();
|
||||
is = null;
|
||||
}
|
||||
if (null != os) {
|
||||
os.close();
|
||||
os = null;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 文件下载
|
||||
* @param response
|
||||
* @param downloadFile
|
||||
*/
|
||||
public static void downloadPDFFile(HttpServletResponse response, String showFileName, byte[] data) {
|
||||
|
||||
OutputStream os = null;
|
||||
BufferedOutputStream bos = null;
|
||||
try {
|
||||
// 对文件名进行编码处理中文问题
|
||||
/*showFileName = URLEncoder.encode(showFileName, "UTF-8");
|
||||
if (showFileName.length() > 150) {
|
||||
String guessCharset = "gb2312"; 根据request的locale 得出可能的编码,中文操作系统通常是gb2312
|
||||
showFileName = new String(showFileName.getBytes("gb2312"), "ISO8859-1");
|
||||
} */
|
||||
|
||||
showFileName = new String(showFileName.getBytes("utf-8"),"iso8859-1");
|
||||
|
||||
os = response.getOutputStream(); // 重点突出
|
||||
bos = new BufferedOutputStream(os);
|
||||
// 对文件名进行编码处理中文问题
|
||||
response.reset(); // 重点突出
|
||||
response.setHeader("Accept-Ranges", "bytes");
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.setHeader("Content-Length", data.length + "");
|
||||
response.setHeader("Content-Type", "application/pdf");
|
||||
//response.setHeader("X-Application-Context","application:8080");
|
||||
response.setCharacterEncoding("UTF-8"); // 重点突出
|
||||
//response.setContentType("application/pdf");// 不同类型的文件对应不同的MIME类型 // 重点突出
|
||||
// inline在浏览器中直接显示,不提示用户下载
|
||||
// attachment弹出对话框,提示用户进行下载保存本地
|
||||
// 默认为inline方式
|
||||
//attachment;filename= attachment;浏览器会自动下载
|
||||
//response.setHeader("Content-Disposition", "filename=9999"); // 重点突出
|
||||
bos.write(data);
|
||||
bos.flush();
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex.getMessage());
|
||||
} finally {
|
||||
try {
|
||||
if (null != bos) {
|
||||
bos.close();
|
||||
bos = null;
|
||||
}
|
||||
if (null != os) {
|
||||
os.close();
|
||||
os = null;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException(ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 将文本文件转换成2进制
|
||||
* @param is
|
||||
* @param fileName
|
||||
* @param filePath
|
||||
*/
|
||||
public static byte[] convertFile2Byte(MultipartFile uploadFile){
|
||||
try {
|
||||
if(uploadFile == null){
|
||||
return null;
|
||||
}
|
||||
return uploadFile.getBytes();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title: convertFile2Base64Str
|
||||
* @Description: 将上传文件解析成base64字符串
|
||||
* @param uploadFile
|
||||
* @return
|
||||
* @return String 返回类型
|
||||
* @throws
|
||||
*/
|
||||
public static String convertFile2Base64Str(MultipartFile uploadFile){
|
||||
try {
|
||||
return Base64Util.encode(convertFile2Byte(uploadFile));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static String txt2String(File file){
|
||||
StringBuilder result = new StringBuilder();
|
||||
try{
|
||||
InputStreamReader ir =new InputStreamReader(new FileInputStream(file), "utf-8");
|
||||
BufferedReader br = new BufferedReader(ir);//构造一个BufferedReader类来读取文件
|
||||
String s = null;
|
||||
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
|
||||
result.append(new String(s.getBytes()));
|
||||
}
|
||||
br.close();
|
||||
}catch(Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String ReadFile(String Path){
|
||||
BufferedReader reader = null;
|
||||
String laststr = "";
|
||||
try{
|
||||
FileInputStream fileInputStream = new FileInputStream(Path);
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");
|
||||
reader = new BufferedReader(inputStreamReader);
|
||||
String tempString = null;
|
||||
while((tempString = reader.readLine()) != null){
|
||||
laststr += tempString;
|
||||
}
|
||||
reader.close();
|
||||
}catch(IOException e){
|
||||
e.printStackTrace();
|
||||
}finally{
|
||||
if(reader != null){
|
||||
try {
|
||||
reader.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return laststr;
|
||||
}
|
||||
|
||||
|
||||
public static List<String> ReadLine(String Path){
|
||||
BufferedReader reader = null;
|
||||
List<String> lines = new ArrayList<String>();
|
||||
try{
|
||||
FileInputStream fileInputStream = new FileInputStream(Path);
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");
|
||||
reader = new BufferedReader(inputStreamReader);
|
||||
|
||||
String line = null;
|
||||
while((line = reader.readLine()) != null){
|
||||
lines.add(line);
|
||||
}
|
||||
reader.close();
|
||||
}catch(IOException e){
|
||||
e.printStackTrace();
|
||||
}finally{
|
||||
if(reader != null){
|
||||
try {
|
||||
reader.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title: toByteArray3
|
||||
* @Description: TODO
|
||||
* @param filename
|
||||
* @return
|
||||
* @throws IOException
|
||||
* @return byte[] 返回类型
|
||||
* @throws
|
||||
*/
|
||||
@SuppressWarnings("resource")
|
||||
public static byte[] file2ByteArray(String filename) throws IOException {
|
||||
|
||||
FileChannel fc = null;
|
||||
try {
|
||||
fc = new RandomAccessFile(filename, "r").getChannel();
|
||||
MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();
|
||||
byte[] result = new byte[(int) fc.size()];
|
||||
if (byteBuffer.remaining() > 0) {
|
||||
byteBuffer.get(result, 0, byteBuffer.remaining());
|
||||
}
|
||||
return result;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
throw e;
|
||||
} finally {
|
||||
try {
|
||||
fc.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static byte[] getFileToByte(File file) {
|
||||
InputStream is = null;
|
||||
ByteArrayOutputStream bytestream = null;
|
||||
byte[] by = new byte[(int) file.length()];
|
||||
try {
|
||||
is = new FileInputStream(file);
|
||||
bytestream = new ByteArrayOutputStream();
|
||||
byte[] bb = new byte[2048];
|
||||
int ch;
|
||||
ch = is.read(bb);
|
||||
while (ch != -1) {
|
||||
bytestream.write(bb, 0, ch);
|
||||
ch = is.read(bb);
|
||||
}
|
||||
by = bytestream.toByteArray();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}finally {
|
||||
try {
|
||||
|
||||
if(is != null) is.close();
|
||||
if(bytestream != null) bytestream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return by;
|
||||
}
|
||||
|
||||
public static byte[] getFileToByte(String filename) {
|
||||
File file = new File(filename);
|
||||
if(!file.exists()) throw new RuntimeException("文件不存在");
|
||||
return getFileToByte( file);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* writeData: 将数据写入指定的文件中
|
||||
*
|
||||
* @param filePath
|
||||
* @param data
|
||||
* @return boolean 是否写入成功
|
||||
*/
|
||||
public static boolean writeData(String filePath, byte[] data){
|
||||
FileOutputStream fos = null;
|
||||
try {
|
||||
File file = new File(filePath);
|
||||
if(file.exists()){
|
||||
file.delete();
|
||||
}
|
||||
file.createNewFile();
|
||||
fos =new FileOutputStream(file);
|
||||
fos.write(data);
|
||||
fos.close();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}finally{
|
||||
if(fos != null){
|
||||
try {
|
||||
fos.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param filePath
|
||||
* @param data
|
||||
* @param nextLine
|
||||
* @return boolean 是否写入成功
|
||||
*/
|
||||
public static boolean append(String filePath, String data, boolean nextLine ){
|
||||
try {
|
||||
try {
|
||||
File file = new File(filePath);
|
||||
if(!file.exists()){
|
||||
file.createNewFile();
|
||||
}
|
||||
FileOutputStream fos = new FileOutputStream(file, true);
|
||||
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
|
||||
if(nextLine) {
|
||||
data = data + System.lineSeparator();
|
||||
}
|
||||
osw.write(data);
|
||||
osw.flush();
|
||||
osw.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}finally{
|
||||
}
|
||||
|
||||
}
|
||||
public static void main(String[] args) throws IOException {
|
||||
FileUtil.append("D:\\aa.txt", "12323",true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
1319
ndplan/src/main/java/com/system/util/GeneralHelper.java
Normal file
1319
ndplan/src/main/java/com/system/util/GeneralHelper.java
Normal file
File diff suppressed because it is too large
Load Diff
211
ndplan/src/main/java/com/system/util/HttpUtil.java
Normal file
211
ndplan/src/main/java/com/system/util/HttpUtil.java
Normal file
File diff suppressed because one or more lines are too long
86
ndplan/src/main/java/com/system/util/JsonUtil.java
Normal file
86
ndplan/src/main/java/com/system/util/JsonUtil.java
Normal file
@@ -0,0 +1,86 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JavaType;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
|
||||
public class JsonUtil {
|
||||
private static final ObjectMapper objectMapper;
|
||||
static {
|
||||
objectMapper = new ObjectMapper();
|
||||
// 去掉默认的时间戳格式
|
||||
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
|
||||
// 设置为中国上海时区
|
||||
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
|
||||
objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
|
||||
// 空值不序列化
|
||||
/* objectMapper.setSerializationInclusion(Include.NON_NULL); */
|
||||
// 反序列化时,属性不存在的兼容处理
|
||||
objectMapper.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
// 序列化时,日期的统一格式
|
||||
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
|
||||
|
||||
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
|
||||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
// 单引号处理
|
||||
objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
|
||||
}
|
||||
|
||||
public static <T> T toObject(String json, Class<T> clazz) {
|
||||
try {
|
||||
return objectMapper.readValue(json, clazz);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static <T> String toJson(T entity) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(entity);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static <T> T toCollection(String json, TypeReference<T> typeReference) {
|
||||
try {
|
||||
return objectMapper.readValue(json, typeReference);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取泛型的Collection Type
|
||||
*
|
||||
* @param collectionClass 泛型的Collection
|
||||
* @param elementClasses 元素类
|
||||
* @return JavaType Java类型
|
||||
* @since 1.0
|
||||
*/
|
||||
public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
|
||||
return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
|
||||
}
|
||||
|
||||
public static <T> List<T> toCollection(String json, Class<T> clazz) {
|
||||
try {
|
||||
JavaType javaType = getCollectionType(ArrayList.class, clazz);
|
||||
List<T> list = objectMapper.readValue(json, javaType);
|
||||
return list;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
47
ndplan/src/main/java/com/system/util/MD5Util.java
Normal file
47
ndplan/src/main/java/com/system/util/MD5Util.java
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* @Title: MD5Util.java
|
||||
* @Package com.tky.gis.util
|
||||
* @Description: MD5Util加密工具类
|
||||
* Copyright: Copyright (c) 2015
|
||||
* Company:TKY
|
||||
*
|
||||
* @author lwj
|
||||
* @date 2016年9月21日 上午11:25:28
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.system.util;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
/**
|
||||
* TODOMD5Util加密工具类
|
||||
*/
|
||||
public class MD5Util {
|
||||
public static String getMD5(String str) {
|
||||
StringBuffer buffer;
|
||||
try {
|
||||
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
|
||||
byte[] b = messageDigest.digest(str.getBytes());
|
||||
buffer = new StringBuffer(b.length * 2);
|
||||
int i;
|
||||
for (i = 0; i < b.length; i++) {
|
||||
int k = ((int) b[i] & 0xff);
|
||||
if (k < 0x10)// 小于十前面补零
|
||||
buffer.append("0");
|
||||
buffer.append(Long.toString((int) b[i] & 0xff, 16));
|
||||
}
|
||||
//System.out.println(buffer.toString());
|
||||
return buffer.toString();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(getMD5("chenjiang20170628"));
|
||||
System.out.println(getMD5("dzyb20170628"));
|
||||
System.out.println(getMD5("xxjk20170629"));
|
||||
}
|
||||
}
|
||||
29
ndplan/src/main/java/com/system/util/NullUtil.java
Normal file
29
ndplan/src/main/java/com/system/util/NullUtil.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.system.util;
|
||||
|
||||
public class NullUtil {
|
||||
public static String getString(Object obj,String value){
|
||||
return obj == null ? null : value;
|
||||
}
|
||||
|
||||
public static String getString(Object obj){
|
||||
return getString(obj, obj.toString());
|
||||
}
|
||||
|
||||
|
||||
public static Boolean getStringEquals(Object obj1,Object obj2,boolean defualt){
|
||||
return obj1 == null ? defualt : obj1.toString().equals(obj2);
|
||||
}
|
||||
|
||||
public static Boolean getBoolean(Boolean obj,boolean defualt){
|
||||
return obj == null ? defualt : obj;
|
||||
}
|
||||
|
||||
public static Boolean getBooleanFalse(Boolean obj){
|
||||
return obj == null ? false : obj;
|
||||
}
|
||||
|
||||
public static Boolean getBooleanTrue(Boolean obj){
|
||||
return obj == null ? true : obj;
|
||||
}
|
||||
|
||||
}
|
||||
39
ndplan/src/main/java/com/system/util/PageHelper.java
Normal file
39
ndplan/src/main/java/com/system/util/PageHelper.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
/**
|
||||
*
|
||||
* @author 页面帮助类
|
||||
*
|
||||
*/
|
||||
public class PageHelper {
|
||||
|
||||
public static <T> PageWrapper<T> toPage(Page<T> page){
|
||||
return new PageWrapper<T>(page.getNumber(), page.getSize(), page.getTotalElements(), page.getTotalPages(), page.getContent());
|
||||
}
|
||||
|
||||
public static <T> PageWrapper<T> toPage(Page<T> page ,List<T> contents){
|
||||
return new PageWrapper<T>(page.getNumber(), page.getSize(), page.getTotalElements(), page.getTotalPages(), contents);
|
||||
}
|
||||
|
||||
public static <T> PageWrapper<T> toPage(int pageNumber ,int pageSize , Long totalElement, int totalPages ,List<T> contents){
|
||||
return new PageWrapper<T>(pageNumber, pageSize, totalElement, totalPages, contents);
|
||||
}
|
||||
|
||||
|
||||
public static PageRequest buildPageRequest(int pageNumber, int pageSize,
|
||||
String sortDirection, String sortFiled) {
|
||||
Sort sort=null;
|
||||
if("DESC".equalsIgnoreCase(sortDirection)){
|
||||
sort=Sort.by(Direction.DESC,sortFiled);
|
||||
}else if("ASC".equalsIgnoreCase(sortDirection)){
|
||||
sort=Sort.by(Direction.ASC,sortFiled);
|
||||
}
|
||||
return PageRequest.of(pageNumber-1, pageSize, sort);
|
||||
}
|
||||
}
|
||||
25
ndplan/src/main/java/com/system/util/PageUtil.java
Normal file
25
ndplan/src/main/java/com/system/util/PageUtil.java
Normal file
@@ -0,0 +1,25 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class PageUtil<T> {
|
||||
|
||||
private int total;
|
||||
private List<T> rows;
|
||||
|
||||
|
||||
public int getTotal() {
|
||||
return total;
|
||||
}
|
||||
public void setTotal(int total) {
|
||||
this.total = total;
|
||||
}
|
||||
public List<T> getRows() {
|
||||
return rows;
|
||||
}
|
||||
public void setRows(List<T> rows) {
|
||||
this.rows = rows;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
102
ndplan/src/main/java/com/system/util/PageWrapper.java
Normal file
102
ndplan/src/main/java/com/system/util/PageWrapper.java
Normal file
@@ -0,0 +1,102 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 分页类<br/>
|
||||
* Copyright (c) 2014 , 北京可思云海科技有限公司<br/>
|
||||
* 2014-9-3 下午4:25:23
|
||||
*
|
||||
* @author gyj@kscloud.com
|
||||
* @version V1.0
|
||||
*/
|
||||
|
||||
@NoArgsConstructor
|
||||
public class PageWrapper<T> {
|
||||
|
||||
/**
|
||||
* 数据内容
|
||||
*/
|
||||
private List<T> content;
|
||||
/**
|
||||
* 页码
|
||||
*/
|
||||
private int pageNumber;
|
||||
/**
|
||||
* 每页条数
|
||||
*/
|
||||
private int pageSize;
|
||||
/**
|
||||
* 总页数
|
||||
*/
|
||||
private int totalPage;
|
||||
/**
|
||||
* 记录总条数
|
||||
*/
|
||||
private long totalSize;
|
||||
|
||||
public PageWrapper(int pageNumber, int pageSize, long totalSize, int totalPage, List<T> content) {
|
||||
this.pageNumber = pageNumber;
|
||||
this.pageSize = pageSize;
|
||||
this.totalPage = totalPage;
|
||||
this.totalSize = totalSize;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public List<T> getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(List<T> content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public int getPageNumber() {
|
||||
return pageNumber + 1;
|
||||
}
|
||||
|
||||
public void setPageNumber(int pageNumber) {
|
||||
this.pageNumber = pageNumber;
|
||||
}
|
||||
|
||||
public int getPageSize() {
|
||||
return pageSize;
|
||||
}
|
||||
|
||||
public void setPageSize(int pageSize) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
public int getTotalPage() {
|
||||
return totalPage;
|
||||
}
|
||||
|
||||
public void setTotalPage(int totalPage) {
|
||||
this.totalPage = totalPage;
|
||||
}
|
||||
|
||||
public long getTotalSize() {
|
||||
return totalSize;
|
||||
}
|
||||
|
||||
public void setTotalSize(long totalSize) {
|
||||
this.totalSize = totalSize;
|
||||
}
|
||||
|
||||
public long getTotal(){
|
||||
return this.getTotalSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* 为了解决dataGrid表格的行格式
|
||||
* @Title: getRows
|
||||
* @return
|
||||
* @return List<T> 返回类型
|
||||
* @throws
|
||||
*/
|
||||
public List<T> getRows(){
|
||||
return this.getContent();
|
||||
}
|
||||
}
|
||||
190
ndplan/src/main/java/com/system/util/PropertyUtil.java
Normal file
190
ndplan/src/main/java/com/system/util/PropertyUtil.java
Normal file
@@ -0,0 +1,190 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
public class PropertyUtil {
|
||||
|
||||
private static String[] getKeys(String packagePath){
|
||||
InputStream is = null;
|
||||
Properties prop = null;
|
||||
try{
|
||||
String filePath = PropertyUtil.class.getClassLoader().getResource(packagePath).getPath();
|
||||
is = new FileInputStream(filePath);
|
||||
prop = new Properties();
|
||||
prop.load(is);
|
||||
String fieldSort = prop.getProperty("field.sort");
|
||||
String[] keys = fieldSort.split(",");
|
||||
for (int i = 0; i < keys.length; i++) {
|
||||
keys[i] = keys[i].trim();
|
||||
}
|
||||
return keys;
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}finally{
|
||||
close(is);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static String[] getKeys(String packagePath,String fields){
|
||||
InputStream is = null;
|
||||
Properties prop = null;
|
||||
try{
|
||||
String filePath = PropertyUtil.class.getClassLoader().getResource(packagePath).getPath();
|
||||
is = new FileInputStream(filePath);
|
||||
prop = new Properties();
|
||||
prop.load(is);
|
||||
String fieldSort = prop.getProperty((null == fields) ? "field.sort" : fields);
|
||||
String[] keys = fieldSort.split(",");
|
||||
for (int i = 0; i < keys.length; i++) {
|
||||
keys[i] = keys[i].trim();
|
||||
}
|
||||
return keys;
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}finally{
|
||||
close(is);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getValue(String filename,String key){
|
||||
InputStream is = null;
|
||||
Properties prop = null;
|
||||
try{
|
||||
String filePath = PropertyUtil.class.getClassLoader().getResource(filename).getPath();
|
||||
is = new FileInputStream(filePath);
|
||||
prop = new Properties();
|
||||
prop.load(is);
|
||||
return prop.getProperty(key);
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}finally{
|
||||
close(is);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static String[] getKeysByValues(String packagePath , String fields, String[] values ){
|
||||
if(null == values || values.length < 0)
|
||||
return null;
|
||||
InputStream is = null;
|
||||
Properties prop = null;
|
||||
List<String> keyList = new ArrayList<String>();
|
||||
try{
|
||||
String filePath = PropertyUtil.class.getClassLoader().getResource(packagePath).getPath();
|
||||
is = new FileInputStream(filePath);
|
||||
prop = new Properties();
|
||||
prop.load(is);
|
||||
String[] keystemp = getKeys(packagePath);
|
||||
String[] valuestemp = getValues(packagePath, fields);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
for (int j = 0; j < valuestemp.length; j++) {
|
||||
if(values[i].equals(valuestemp[j])){
|
||||
keyList.add(keystemp[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
String[] keys = keyList.toArray(new String[keyList.size()]);
|
||||
return keys;
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}finally{
|
||||
close(is);
|
||||
}
|
||||
}
|
||||
public static String[] getValues(String packagePath , String fields) {
|
||||
String filePath = PropertyUtil.class.getClassLoader().getResource(packagePath).getPath();
|
||||
InputStream is = null;
|
||||
Properties prop = null;
|
||||
try{
|
||||
is = new FileInputStream(filePath);
|
||||
prop = new Properties();
|
||||
prop.load(is);
|
||||
String[] keys = getKeys(packagePath,fields);
|
||||
String[] values = new String[keys.length];
|
||||
for (int i = 0; i < keys.length; i++) {
|
||||
String value = prop.getProperty(keys[i]);
|
||||
values[i] = new String(value.getBytes("ISO8859-1"), "utf-8");
|
||||
values[i] = values[i].trim();
|
||||
}
|
||||
return values;
|
||||
}catch(Exception e){
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}finally{
|
||||
close(is);
|
||||
}
|
||||
}
|
||||
public static void setValueByKey(String packagePath, String key, String upDatevalue) {
|
||||
//获取绝对路径
|
||||
//String filePath = PropertyUtil.class.getClassLoader().getResource(packagePath).getPath();
|
||||
|
||||
Properties prop = new Properties();
|
||||
try {
|
||||
File file = new File(packagePath);
|
||||
if (!file.exists())
|
||||
file.createNewFile();
|
||||
InputStream fis =PropertyUtil.class.getResourceAsStream("config.properties");
|
||||
prop.load(fis);
|
||||
//一定要在修改值之前关闭fis
|
||||
fis.close();
|
||||
OutputStream fos = new FileOutputStream(packagePath);
|
||||
prop.setProperty(key, upDatevalue);
|
||||
//保存,并加入注释
|
||||
prop.store(fos, "Update '" + key + "' value");
|
||||
fos.close();
|
||||
} catch (IOException e) {
|
||||
System.err.println("Visit " + packagePath + " for updating " + upDatevalue + " value error");
|
||||
}
|
||||
}
|
||||
public static void close(InputStream is){
|
||||
if( null != is ){
|
||||
try {
|
||||
is.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void print(String[] values){
|
||||
if (null == values || values.length == 0) {
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
System.out.print( values[i] + "\t");
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String path = "com/tky/tunnel/entity/DayReport.properties";
|
||||
// String[] keys= getKeys(path, "field.import");
|
||||
|
||||
setValueByKey("nodeLevel.properties","userExpression","0 3/5 * * * ?");
|
||||
//String[] values= getValues("/nodeLevel.properties", "userExpression");
|
||||
//getKeysByValues(path, values);
|
||||
// print(keys);
|
||||
// print(values);
|
||||
// print(getKeysByValues(path, "field.export" ,values));
|
||||
//System.out.println(keys[0]);
|
||||
//System.out.println(values[0]);
|
||||
//System.out.println(values.length);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
524
ndplan/src/main/java/com/system/util/RedisUtil.java
Normal file
524
ndplan/src/main/java/com/system/util/RedisUtil.java
Normal file
@@ -0,0 +1,524 @@
|
||||
package com.system.util;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
public class RedisUtil {
|
||||
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
//=============================common============================
|
||||
/**
|
||||
* 指定缓存失效时间
|
||||
* @param key 键
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean expire(String key,long time){
|
||||
try {
|
||||
if(time>0){
|
||||
redisTemplate.expire(key, time, TimeUnit.SECONDS);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据key 获取过期时间
|
||||
* @param key 键 不能为null
|
||||
* @return 时间(秒) 返回0代表为永久有效
|
||||
*/
|
||||
public long getExpire(String key){
|
||||
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断key是否存在
|
||||
* @param key 键
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean hasKey(String key){
|
||||
try {
|
||||
return redisTemplate.hasKey(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缓存
|
||||
* @param key 可以传一个值 或多个
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public void del(String ... key){
|
||||
if(key!=null&&key.length>0){
|
||||
if(key.length==1){
|
||||
redisTemplate.delete(key[0]);
|
||||
}else{
|
||||
redisTemplate.delete(CollectionUtils.arrayToList(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//============================String=============================
|
||||
/**
|
||||
* 普通缓存获取
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public Object get(String key){
|
||||
return key==null?null:redisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通缓存放入
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return true成功 false失败
|
||||
*/
|
||||
public boolean set(String key,Object value) {
|
||||
try {
|
||||
redisTemplate.opsForValue().set(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通缓存放入并设置时间
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
|
||||
* @return true成功 false 失败
|
||||
*/
|
||||
public boolean set(String key,Object value,long time){
|
||||
try {
|
||||
if(time>0){
|
||||
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
|
||||
}else{
|
||||
set(key, value);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递增
|
||||
* @param key 键
|
||||
* @param by 要增加几(大于0)
|
||||
* @return
|
||||
*/
|
||||
public long incr(String key, long delta){
|
||||
if(delta<0){
|
||||
throw new RuntimeException("递增因子必须大于0");
|
||||
}
|
||||
return redisTemplate.opsForValue().increment(key, delta);
|
||||
}
|
||||
|
||||
/**
|
||||
* 递减
|
||||
* @param key 键
|
||||
* @param by 要减少几(小于0)
|
||||
* @return
|
||||
*/
|
||||
public long decr(String key, long delta){
|
||||
if(delta<0){
|
||||
throw new RuntimeException("递减因子必须大于0");
|
||||
}
|
||||
return redisTemplate.opsForValue().increment(key, -delta);
|
||||
}
|
||||
|
||||
//================================Map=================================
|
||||
/**
|
||||
* HashGet
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 不能为null
|
||||
* @return 值
|
||||
*/
|
||||
public Object hget(String key,String item){
|
||||
return redisTemplate.opsForHash().get(key, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取hashKey对应的所有键值
|
||||
* @param key 键
|
||||
* @return 对应的多个键值
|
||||
*/
|
||||
public Map<Object,Object> hmget(String key){
|
||||
return redisTemplate.opsForHash().entries(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* HashSet
|
||||
* @param key 键
|
||||
* @param map 对应多个键值
|
||||
* @return true 成功 false 失败
|
||||
*/
|
||||
public boolean hmset(String key, Map<String,Object> map){
|
||||
try {
|
||||
redisTemplate.opsForHash().putAll(key, map);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HashSet 并设置时间
|
||||
* @param key 键
|
||||
* @param map 对应多个键值
|
||||
* @param time 时间(秒)
|
||||
* @return true成功 false失败
|
||||
*/
|
||||
public boolean hmset(String key, Map<String,Object> map, long time){
|
||||
try {
|
||||
redisTemplate.opsForHash().putAll(key, map);
|
||||
if(time>0){
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向一张hash表中放入数据,如果不存在将创建
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param value 值
|
||||
* @return true 成功 false失败
|
||||
*/
|
||||
public boolean hset(String key,String item,Object value) {
|
||||
try {
|
||||
redisTemplate.opsForHash().put(key, item, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向一张hash表中放入数据,如果不存在将创建
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param value 值
|
||||
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
|
||||
* @return true 成功 false失败
|
||||
*/
|
||||
public boolean hset(String key,String item,Object value,long time) {
|
||||
try {
|
||||
redisTemplate.opsForHash().put(key, item, value);
|
||||
if(time>0){
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除hash表中的值
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 可以使多个 不能为null
|
||||
*/
|
||||
public void hdel(String key, Object... item){
|
||||
redisTemplate.opsForHash().delete(key,item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断hash表中是否有该项的值
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 不能为null
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean hHasKey(String key, String item){
|
||||
return redisTemplate.opsForHash().hasKey(key, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param by 要增加几(大于0)
|
||||
* @return
|
||||
*/
|
||||
public double hincr(String key, String item,double by){
|
||||
return redisTemplate.opsForHash().increment(key, item, by);
|
||||
}
|
||||
|
||||
/**
|
||||
* hash递减
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param by 要减少记(小于0)
|
||||
* @return
|
||||
*/
|
||||
public double hdecr(String key, String item,double by){
|
||||
return redisTemplate.opsForHash().increment(key, item,-by);
|
||||
}
|
||||
|
||||
//============================set=============================
|
||||
/**
|
||||
* 根据key获取Set中的所有值
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public Set<Object> sGet(String key){
|
||||
try {
|
||||
return redisTemplate.opsForSet().members(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据value从一个set中查询,是否存在
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean sHasKey(String key,Object value){
|
||||
try {
|
||||
return redisTemplate.opsForSet().isMember(key, value);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据放入set缓存
|
||||
* @param key 键
|
||||
* @param values 值 可以是多个
|
||||
* @return 成功个数
|
||||
*/
|
||||
public long sSet(String key, Object...values) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().add(key, values);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将set数据放入缓存
|
||||
* @param key 键
|
||||
* @param time 时间(秒)
|
||||
* @param values 值 可以是多个
|
||||
* @return 成功个数
|
||||
*/
|
||||
public long sSetAndTime(String key,long time,Object...values) {
|
||||
try {
|
||||
Long count = redisTemplate.opsForSet().add(key, values);
|
||||
if(time>0) expire(key, time);
|
||||
return count;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取set缓存的长度
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public long sGetSetSize(String key){
|
||||
try {
|
||||
return redisTemplate.opsForSet().size(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除值为value的
|
||||
* @param key 键
|
||||
* @param values 值 可以是多个
|
||||
* @return 移除的个数
|
||||
*/
|
||||
public long setRemove(String key, Object ...values) {
|
||||
try {
|
||||
Long count = redisTemplate.opsForSet().remove(key, values);
|
||||
return count;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
//===============================list=================================
|
||||
|
||||
/**
|
||||
* 获取list缓存的内容
|
||||
* @param key 键
|
||||
* @param start 开始
|
||||
* @param end 结束 0 到 -1代表所有值
|
||||
* @return
|
||||
*/
|
||||
public List<Object> lGet(String key,long start, long end){
|
||||
try {
|
||||
return redisTemplate.opsForList().range(key, start, end);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取list缓存的长度
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public long lGetListSize(String key){
|
||||
try {
|
||||
return redisTemplate.opsForList().size(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过索引 获取list中的值
|
||||
* @param key 键
|
||||
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
|
||||
* @return
|
||||
*/
|
||||
public Object lGetIndex(String key,long index){
|
||||
try {
|
||||
return redisTemplate.opsForList().index(key, index);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPush(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, Object value, long time) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPush(key, value);
|
||||
if (time > 0) expire(key, time);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, List<Object> value) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPushAll(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, List<Object> value, long time) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPushAll(key, value);
|
||||
if (time > 0) expire(key, time);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据索引修改list中的某条数据
|
||||
* @param key 键
|
||||
* @param index 索引
|
||||
* @param value 值
|
||||
* @return
|
||||
*/
|
||||
public boolean lUpdateIndex(String key, long index,Object value) {
|
||||
try {
|
||||
redisTemplate.opsForList().set(key, index, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除N个值为value
|
||||
* @param key 键
|
||||
* @param count 移除多少个
|
||||
* @param value 值
|
||||
* @return 移除的个数
|
||||
*/
|
||||
public long lRemove(String key,long count,Object value) {
|
||||
try {
|
||||
Long remove = redisTemplate.opsForList().remove(key, count, value);
|
||||
return remove;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
53
ndplan/src/main/java/com/system/util/ResultBeanUtil.java
Normal file
53
ndplan/src/main/java/com/system/util/ResultBeanUtil.java
Normal file
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* @Title: ResultBeanUtil.java
|
||||
* @Package com.tky.gis.util
|
||||
* @Description: TODO
|
||||
* Copyright: Copyright (c) 2015
|
||||
* Company:TKY
|
||||
*
|
||||
* @author lwj
|
||||
* @date 2016年9月23日 下午1:46:03
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.system.util;
|
||||
|
||||
import com.system.common.ResultBean;
|
||||
import com.system.common.ResultCode;
|
||||
|
||||
|
||||
/**
|
||||
* TODO处理泛型对象返回值为json数据
|
||||
*/
|
||||
public class ResultBeanUtil {
|
||||
public static ResultBean getResultBeanByJsonAndClass(String json,Class clz){
|
||||
ResultBean re = ResultBean.fromJson(json, clz);
|
||||
return re;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title: getResultBeanByCode
|
||||
* @Description: 过滤接口返回的数据(与各个子系统约定) [除了梁场]
|
||||
* ResultBean code == 0 && result !=null 正常返回数据
|
||||
* ResultBean code == 0 && result ==null 调用接口正常 查不到数据
|
||||
* ResultBean code != 0 接口异常返回的数据 code为-1
|
||||
* @param resultBean
|
||||
* @return
|
||||
* @return ResultBean 返回类型
|
||||
* @throws
|
||||
*/
|
||||
public static ResultBean getResultBeanByCode(ResultBean resultBean){
|
||||
if(resultBean.getCode() == 0){
|
||||
if(resultBean.getResult() != null){
|
||||
return resultBean;
|
||||
}
|
||||
return new ResultBean(ResultCode.SELECT_NON_DATA,ResultCode.SELECT_NON_DATA_STRING);
|
||||
}else{
|
||||
return new ResultBean(ResultCode.ERROR_SERVE,ResultCode.ERROR_SERVE_STRING);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
44
ndplan/src/main/java/com/system/util/SpringContextUtil.java
Normal file
44
ndplan/src/main/java/com/system/util/SpringContextUtil.java
Normal file
@@ -0,0 +1,44 @@
|
||||
|
||||
/**
|
||||
* @Title: SpringContextUtil.java
|
||||
* @Package com.tky.sgzz.util
|
||||
* @Description: TODO(用一句话描述该文件做什么)
|
||||
* @author CMB
|
||||
* @date 2017年5月25日 下午7:23:56
|
||||
* @version V1.0
|
||||
*/
|
||||
|
||||
package com.system.util;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SpringContextUtil implements ApplicationContextAware {
|
||||
private static ApplicationContext applicationContext; // Spring应用上下文环境
|
||||
|
||||
/*
|
||||
* 实现了ApplicationContextAware 接口,必须实现该方法;
|
||||
* 通过传递applicationContext参数初始化成员变量applicationContext
|
||||
*/
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
SpringContextUtil.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public static ApplicationContext getApplicationContext() {
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T getBean(String name) throws BeansException {
|
||||
return (T) applicationContext.getBean(name);
|
||||
}
|
||||
|
||||
public static <T> T getBean(Class<T> clazz) throws BeansException {
|
||||
System.out.println(applicationContext);
|
||||
return (T) applicationContext.getBean(clazz);
|
||||
}
|
||||
}
|
||||
46
ndplan/src/main/java/com/system/util/SpringUtil.java
Normal file
46
ndplan/src/main/java/com/system/util/SpringUtil.java
Normal file
@@ -0,0 +1,46 @@
|
||||
package com.system.util;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 通类可以通过调用SpringUtils工具类获取spring中的bean实体
|
||||
*
|
||||
* @author zhangtianlun
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class SpringUtil implements ApplicationContextAware {
|
||||
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
if(SpringUtil.applicationContext == null) {
|
||||
SpringUtil.applicationContext = applicationContext;
|
||||
}
|
||||
}
|
||||
|
||||
//获取applicationContext
|
||||
public static ApplicationContext getApplicationContext() {
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
//通过name获取 Bean.
|
||||
public static Object getBean(String name){
|
||||
return getApplicationContext().getBean(name);
|
||||
}
|
||||
|
||||
//通过class获取Bean.
|
||||
public static <T> T getBean(Class<T> clazz){
|
||||
return getApplicationContext().getBean(clazz);
|
||||
}
|
||||
|
||||
//通过name,以及Clazz返回指定的Bean
|
||||
public static <T> T getBean(String name,Class<T> clazz){
|
||||
return getApplicationContext().getBean(name, clazz);
|
||||
}
|
||||
|
||||
}
|
||||
130
ndplan/src/main/java/com/system/util/StringUtil.java
Normal file
130
ndplan/src/main/java/com/system/util/StringUtil.java
Normal file
@@ -0,0 +1,130 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* 对一些常用数据进行操作的工具类
|
||||
*
|
||||
*/
|
||||
public class StringUtil {
|
||||
public static boolean isNotNull(String str) {
|
||||
if (null != str && !"".equals(str)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isNull(String str) {
|
||||
if (null == str || "".equals(str)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static int parseInt(String str) {
|
||||
if (isNotNull(str)) {
|
||||
return Integer.parseInt(str);
|
||||
} else {
|
||||
throw new RuntimeException("字符串为空,不能转换成数字");
|
||||
}
|
||||
}
|
||||
|
||||
public static String formatFloat(String value) {
|
||||
if (isNotNull(value)) {
|
||||
return formatFloat(Float.parseFloat(value));
|
||||
} else {
|
||||
return "0";
|
||||
}
|
||||
}
|
||||
|
||||
public static String formatFloat(float value) {
|
||||
DecimalFormat formator = null;
|
||||
if (value < 10) {
|
||||
formator = new DecimalFormat("0.00");
|
||||
return formator.format(value);
|
||||
} else if (value < 100) {
|
||||
formator = new DecimalFormat("00.00");
|
||||
return formator.format(value);
|
||||
} else if (value < 1000) {
|
||||
formator = new DecimalFormat("000.00");
|
||||
return formator.format(value);
|
||||
} else {
|
||||
return value + "";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static String formatInt(String value) {
|
||||
if (isNotNull(value)) {
|
||||
return formatInt(Float.parseFloat(value));
|
||||
} else {
|
||||
return "0";
|
||||
}
|
||||
}
|
||||
|
||||
public static String formatInt(float value) {
|
||||
DecimalFormat formator = new DecimalFormat("");
|
||||
return formator.format(value);
|
||||
}
|
||||
|
||||
// 过滤0
|
||||
public static String formatNumber(String str) {
|
||||
if (str == null || str.equals("")) {
|
||||
return "0";
|
||||
}
|
||||
if (str.contains(".")) {
|
||||
if (str.contains("%")) {
|
||||
String substr = str.substring(0, str.length() - 1);
|
||||
String[] split = substr.split("\\.");
|
||||
if (split[1].length() == 2) {
|
||||
if (split[1].equals("00")) {
|
||||
return substr.substring(0, substr.length() - 3) + "%";
|
||||
} else if (!split[1].substring(0, 1).equals("0") && split[1].substring(1).equals("0")) {
|
||||
return substr.substring(0, substr.length() - 1) + "%";
|
||||
}
|
||||
} else if (split[1].length() == 1) {
|
||||
if (split[1].equals("0")) {
|
||||
return substr.substring(0, substr.length() - 2) + "%";
|
||||
}
|
||||
}
|
||||
}
|
||||
String[] split = str.split("\\.");
|
||||
if (split[1].length() == 2) {
|
||||
if (split[1].equals("00")) {
|
||||
return str.substring(0, str.length() - 3);
|
||||
} else if (!split[1].substring(0, 1).equals("0") && split[1].substring(1).equals("0")) {
|
||||
return str.substring(0, str.length() - 1);
|
||||
}
|
||||
} else if (split[1].length() == 1) {
|
||||
if (split[1].equals("0")) {
|
||||
return str.substring(0, str.length() - 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
// 保留2位
|
||||
public static String formatDouble(double value) {
|
||||
if (value == 0) {
|
||||
return "0";
|
||||
}
|
||||
DecimalFormat df = new DecimalFormat(".##");
|
||||
String str = df.format(value);
|
||||
return str;
|
||||
}
|
||||
|
||||
//首字母大写
|
||||
public static String firstUpperCase(String str) {
|
||||
return str.substring(0, 1).toUpperCase() + str.substring(1);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
231
ndplan/src/main/java/com/system/util/StringUtils.java
Normal file
231
ndplan/src/main/java/com/system/util/StringUtils.java
Normal file
@@ -0,0 +1,231 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import org.apache.commons.lang3.CharUtils;
|
||||
|
||||
import lombok.extern.java.Log;
|
||||
|
||||
@Log
|
||||
public class StringUtils {
|
||||
/**
|
||||
* 根据数据库里程长度转换成DKxxx+xxx.x格式
|
||||
*
|
||||
* @param mileage
|
||||
* @return
|
||||
*/
|
||||
public static String getMileageByInt(Integer mileage) {
|
||||
String strMileage = "";
|
||||
strMileage = "DK" + (mileage / 10000) + "+" + StringUtils.DecimalFormat2(((double) (mileage % 10000)) / 10, "000.0");
|
||||
return strMileage;
|
||||
}
|
||||
/***/
|
||||
public static String getStringByObject(Object object){
|
||||
return object == null ? null : object.toString();
|
||||
}
|
||||
/**
|
||||
* 根据数据库长度转换成实际长度,数据库长度比实际长度小10倍
|
||||
*
|
||||
* @param leng
|
||||
* @return
|
||||
*/
|
||||
public static String getLengByInt(Integer leng) {
|
||||
if (StringUtils.isNotEmpty("" + leng) && !"null".equals("" + leng)) {
|
||||
return "" + (double) (leng) / 10;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据double长度返回固定格式format,如不够千位数补0,format=000.0
|
||||
*
|
||||
* @param dou
|
||||
* @param format
|
||||
* @return 返回补0后的字符串
|
||||
*/
|
||||
public static String DecimalFormat2(Double dou, String format) {
|
||||
DecimalFormat df = new DecimalFormat(format);
|
||||
String str = df.format(dou);
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串是否为空,如果为空返回false,否则返回true
|
||||
*
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static boolean isNotEmpty(String str) {
|
||||
if (null == str || "".equals(str) || str.isEmpty()) {
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 判断字符串是否为空,如果为空返回false,否则返回true
|
||||
*
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static boolean isEmptyOrBlank(String str) {
|
||||
if (null == str || "".equals(str.trim())) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 首字母大写
|
||||
public static String captureName(String name) {
|
||||
char[] cs = name.toCharArray();
|
||||
cs[0] -= 32;
|
||||
return String.valueOf(cs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据实际长度转换成数据库长度,数据库长度比实际长度小10倍
|
||||
*
|
||||
* @param leng
|
||||
* @return
|
||||
*/
|
||||
public static int getStringByLong(String leng) {
|
||||
if (StringUtils.isNotEmpty(leng) && !"null".equals(leng)) {
|
||||
double d = Double.parseDouble(leng);
|
||||
BigDecimal b1 = new BigDecimal(Double.valueOf(d));
|
||||
BigDecimal b2 = new BigDecimal(Double.valueOf(10));
|
||||
double value = b1.multiply(b2).doubleValue();
|
||||
return (int) value;
|
||||
}
|
||||
return (Integer) null;
|
||||
}
|
||||
|
||||
// 将里程为D2K123+456.0db转换为123456.0
|
||||
public static String converter2str(String value) {
|
||||
|
||||
if (value == null || "".equals(value))
|
||||
return "0";
|
||||
try{
|
||||
if (value.contains("+")) {
|
||||
String str1 = value.split("\\+")[0];
|
||||
String str2 = value.split("\\+")[1];
|
||||
String str = "";
|
||||
for(int i =0;i < str2.length(); i++){
|
||||
char c = str2.charAt(i);
|
||||
if (46 == c || (48 <= c && c <= 57)) { //小数点或数字
|
||||
str += c;
|
||||
}
|
||||
}
|
||||
for (int i = str1.length() - 1; i >= 0; i--) {
|
||||
char c = str1.charAt(i);
|
||||
if (48 <= c && c <= 57) {
|
||||
str = c + str;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return str;
|
||||
} else {
|
||||
String str1 = "";
|
||||
for (int i = value.length() - 1; i >= 0; i--) {
|
||||
char c = value.charAt(i);
|
||||
if (48 <= c && c <= 57) {
|
||||
str1 = c + str1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return str1;
|
||||
}
|
||||
}catch(Exception e){
|
||||
log.log(Level.SEVERE, e.getMessage());
|
||||
}
|
||||
return "0";
|
||||
}
|
||||
/**将里程为D2K123+456.0转换为1234560
|
||||
*
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static Integer mileStong2int(String str) {
|
||||
List<String> list = getGe2NumStr(str);
|
||||
if(list.size()==0){
|
||||
log.warning("没有数字字符串");
|
||||
return 0;
|
||||
}else{
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for(String s:list){
|
||||
|
||||
if(s.length()>3){
|
||||
return Integer.parseInt(s)*10;
|
||||
}else{
|
||||
sb.append(s);
|
||||
}
|
||||
}
|
||||
return Integer.parseInt(sb.toString())*10;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取字符串中的大于两位的数字串
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static List<String> getGe2NumStr(String str) {
|
||||
List<String> list = new LinkedList<String>();
|
||||
if(org.apache.commons.lang3.StringUtils.isEmpty(str)||str.length()<2){
|
||||
return list;
|
||||
}else{
|
||||
StringBuffer sb = new StringBuffer();
|
||||
boolean isNum = false;
|
||||
for(int i=0;i<str.length();i++){
|
||||
if(CharUtils.isAsciiNumeric(str.charAt(i))){
|
||||
sb.append(str.charAt(i));
|
||||
isNum = true;
|
||||
}else{
|
||||
if(sb.length()>=2){
|
||||
list.add(sb.toString());
|
||||
}
|
||||
if(sb.length()>0){
|
||||
sb = new StringBuffer();
|
||||
}
|
||||
isNum = false;
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
public static Double formatDK2Mile(String str){
|
||||
return Double.valueOf(converter2str(str));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* gbk与utf-8互转
|
||||
* 利用BASE64Encoder/BASE64Decoder实现互转
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static String charsetConvert(String str, String charset) {
|
||||
try {
|
||||
str = new sun.misc.BASE64Encoder().encode(str.getBytes(charset));
|
||||
byte[] bytes = new sun.misc.BASE64Decoder().decodeBuffer(str);
|
||||
str = new String(bytes, charset);
|
||||
} catch(IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(formatDK2Mile("DK64+400.0"));
|
||||
}
|
||||
}
|
||||
138
ndplan/src/main/java/com/system/util/TreeUtil.java
Normal file
138
ndplan/src/main/java/com/system/util/TreeUtil.java
Normal file
@@ -0,0 +1,138 @@
|
||||
package com.system.util;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.system.util.json.BaseJSON;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 主节点操作工具类型
|
||||
* 将list数组转换成一棵树
|
||||
* @author zhangtianlun
|
||||
*
|
||||
*/
|
||||
public class TreeUtil {
|
||||
/**
|
||||
* 将一个list转换成一个树
|
||||
* @param data list数据
|
||||
* @param valueMethod 获取当前节点值的方法名称
|
||||
* @param pvalueMethod 获取父节点值的方法名称
|
||||
* @param childFiled 子节点的字段
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
static public <T> List<T> listToTree(List<T> data, String valueMethod,
|
||||
String pvalueMethod, String childFiled) throws Exception {
|
||||
|
||||
List<T> result = new ArrayList<T>();
|
||||
if(data == null || data.size() == 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
for (T t : data) {
|
||||
boolean isroot = listToTree2(data, t, valueMethod, pvalueMethod, childFiled);
|
||||
if(isroot ) {
|
||||
result.add(t);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将一个list转换成一个树
|
||||
* @param data list数据
|
||||
* @param object 当前节点
|
||||
* @param valueMethod 获取当前节点值的方法名称
|
||||
* @param pvalueMethod 获取父节点值的方法名称
|
||||
* @param childFiled 子节点的字段
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
static public <T> boolean listToTree2(List<T> data , T object, String valueMethod,
|
||||
String pvalueMethod, String childFiled) throws Exception {
|
||||
// 当前节点是根节点吗?找到了父节点,就不是根节点,没有找到就是。
|
||||
boolean isroot = true;
|
||||
|
||||
Method vmethod = object.getClass().getMethod(valueMethod);
|
||||
Method pmethod = object.getClass().getMethod(pvalueMethod);
|
||||
Method cgetmethod = object.getClass().getMethod("get" + StringUtil.firstUpperCase(childFiled));
|
||||
Method csetmethod = object.getClass().
|
||||
getMethod("set" + StringUtil.firstUpperCase(childFiled), List.class);
|
||||
|
||||
Object pvalue = pmethod.invoke(object, null); // 父值
|
||||
for (T ptree : data) {
|
||||
Object value = vmethod.invoke(ptree, null);
|
||||
// 节点是本节点
|
||||
if(ptree== object)
|
||||
continue;
|
||||
//System.out.println(BaseJSON.toJSONString(ptree));
|
||||
if(value.equals(pvalue)) {
|
||||
// 父节点的孩子节点
|
||||
List<T> child = (List<T>) cgetmethod.invoke(ptree, null);
|
||||
if(child == null) {
|
||||
child = new ArrayList<T>();
|
||||
}
|
||||
child.add(object);
|
||||
csetmethod.invoke(ptree,child );
|
||||
// 当前节点有了父节点,就不是根节点
|
||||
isroot = false;
|
||||
}
|
||||
}
|
||||
|
||||
return isroot;
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
List<TreeTest> list = Lists.newArrayList();
|
||||
TreeTest t1 = new TreeTest();
|
||||
t1.setPid(null);
|
||||
t1.setId(1L);
|
||||
t1.setName("0");
|
||||
TreeTest t2 = new TreeTest();
|
||||
t2.setPid(1L);
|
||||
t2.setId(2L);
|
||||
t2.setName("2");
|
||||
TreeTest t3 = new TreeTest();
|
||||
t3.setPid(1L);
|
||||
t3.setId(3L);
|
||||
t3.setName("3");
|
||||
TreeTest t4 = new TreeTest();
|
||||
t3.setPid(2L);
|
||||
t3.setId(4L);
|
||||
t3.setName("4");
|
||||
list.add(t1);
|
||||
list.add(t2);
|
||||
list.add(t3);
|
||||
|
||||
System.out.println(BaseJSON.toJSONString(TreeUtil.listToTree(list, "getId", "getPid", "child")));
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
static private class TreeTest {
|
||||
public Long id;
|
||||
public Long pid;
|
||||
public String name;
|
||||
public List<TreeTest> child;
|
||||
|
||||
/*public void TreeTreeTest(Long id, Long pid, String name) {
|
||||
this.id = id;
|
||||
this.pid = pid;
|
||||
this.name = name;
|
||||
}*/
|
||||
|
||||
public void setChild(List<TreeTest> child) {
|
||||
this.child = child;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
|
||||
/**
|
||||
* @Title: OperationLog.java
|
||||
* @Package com.tky.sgzz.util.annotation
|
||||
* @Description: TODO(用一句话描述该文件做什么)
|
||||
* @author CMB
|
||||
* @date 2017年5月23日 上午9:36:09
|
||||
* @version V1.0
|
||||
*/
|
||||
|
||||
package com.system.util.annoatation;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* @ClassName: OperationLog
|
||||
* @Description:此注解作为标记用于记录用户操作日志
|
||||
* @author CMB
|
||||
* @date 2017年5月23日 上午9:36:09
|
||||
*
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.TYPE})//运行机制
|
||||
@Retention(RetentionPolicy.RUNTIME)//保留机制,此处为运行时保留
|
||||
@Documented
|
||||
public @interface OperationLog {
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title: description
|
||||
* @Description: 操作描述
|
||||
* @param @return 参数
|
||||
* @return String 返回类型
|
||||
* @throws
|
||||
* @author CMB
|
||||
* @date 2017年5月23日 上午10:47:50
|
||||
*/
|
||||
String description() default "";
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.system.util.annoatation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Target({ElementType.METHOD, ElementType.TYPE})//运行机制
|
||||
@Retention(RetentionPolicy.RUNTIME)//保留机制,此处为运行时保留
|
||||
@Documented
|
||||
public @interface RequestDescMapping {
|
||||
|
||||
String mappingName() default "fieldName";
|
||||
}
|
||||
27
ndplan/src/main/java/com/system/util/bean/BeanProperty.java
Normal file
27
ndplan/src/main/java/com/system/util/bean/BeanProperty.java
Normal file
@@ -0,0 +1,27 @@
|
||||
package com.system.util.bean;
|
||||
|
||||
/**
|
||||
* Bean属性
|
||||
*
|
||||
* @author L.cm
|
||||
*/
|
||||
public class BeanProperty {
|
||||
private String name;
|
||||
private Class<?> type;
|
||||
|
||||
public BeanProperty() {
|
||||
}
|
||||
|
||||
public BeanProperty(String name, Class<?> type) {
|
||||
this.name = name;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Class<?> getType() {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
300
ndplan/src/main/java/com/system/util/bean/BeanUtils.java
Normal file
300
ndplan/src/main/java/com/system/util/bean/BeanUtils.java
Normal file
@@ -0,0 +1,300 @@
|
||||
package com.system.util.bean;
|
||||
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.cglib.beans.BeanCopier;
|
||||
import org.springframework.cglib.beans.BeanGenerator;
|
||||
import org.springframework.cglib.beans.BeanMap;
|
||||
|
||||
/**
|
||||
* 基于CGlib
|
||||
* 实体工具类,目前copy不支持map、list
|
||||
*
|
||||
* @author L.cm
|
||||
* email: 596392912@qq.com
|
||||
* site:http://www.dreamlu.net
|
||||
* @date 2015年4月26日下午5:10:42
|
||||
*/
|
||||
public final class BeanUtils extends org.springframework.beans.BeanUtils {
|
||||
private BeanUtils() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 实例化对象
|
||||
*
|
||||
* @param clazz 类
|
||||
* @return 对象
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T newInstance(Class<?> clazz) {
|
||||
return (T) instantiate(clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* 实例化对象
|
||||
*
|
||||
* @param clazzStr 类名
|
||||
* @return 对象
|
||||
*/
|
||||
public static <T> T newInstance(String clazzStr) {
|
||||
try {
|
||||
Class<?> clazz = Class.forName(clazzStr);
|
||||
return newInstance(clazz);
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Bean的属性
|
||||
*
|
||||
* @param bean bean
|
||||
* @param propertyName 属性名
|
||||
* @return 属性值
|
||||
*/
|
||||
public static Object getProperty(Object bean, String propertyName) {
|
||||
PropertyDescriptor pd = getPropertyDescriptor(bean.getClass(), propertyName);
|
||||
if (pd == null) {
|
||||
throw new RuntimeException("Could not read property '" + propertyName + "' from bean PropertyDescriptor is null");
|
||||
}
|
||||
Method readMethod = pd.getReadMethod();
|
||||
if (readMethod == null) {
|
||||
throw new RuntimeException("Could not read property '" + propertyName + "' from bean readMethod is null");
|
||||
}
|
||||
if (!readMethod.isAccessible()) {
|
||||
readMethod.setAccessible(true);
|
||||
}
|
||||
try {
|
||||
return readMethod.invoke(bean);
|
||||
} catch (Throwable ex) {
|
||||
throw new RuntimeException("Could not read property '" + propertyName + "' from bean", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置Bean属性
|
||||
*
|
||||
* @param bean bean
|
||||
* @param propertyName 属性名
|
||||
* @param value 属性值
|
||||
*/
|
||||
public static void setProperty(Object bean, String propertyName, Object value) {
|
||||
PropertyDescriptor pd = getPropertyDescriptor(bean.getClass(), propertyName);
|
||||
if (pd == null) {
|
||||
throw new RuntimeException("Could not set property '" + propertyName + "' to bean PropertyDescriptor is null");
|
||||
}
|
||||
Method writeMethod = pd.getWriteMethod();
|
||||
if (writeMethod == null) {
|
||||
throw new RuntimeException("Could not set property '" + propertyName + "' to bean writeMethod is null");
|
||||
}
|
||||
if (!writeMethod.isAccessible()) {
|
||||
writeMethod.setAccessible(true);
|
||||
}
|
||||
try {
|
||||
writeMethod.invoke(bean, value);
|
||||
} catch (Throwable ex) {
|
||||
throw new RuntimeException("Could not set property '" + propertyName + "' to bean", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 给一个Bean添加字段
|
||||
*
|
||||
* @param superBean 父级Bean
|
||||
* @param props 新增属性
|
||||
* @return {Object}
|
||||
*/
|
||||
public static Object generator(Object superBean, BeanProperty... props) {
|
||||
Class<?> superclass = superBean.getClass();
|
||||
Object genBean = generator(superclass, props);
|
||||
BeanUtils.copy(superBean, genBean);
|
||||
return genBean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 给一个class添加字段
|
||||
*
|
||||
* @param superclass 父级
|
||||
* @param props 新增属性
|
||||
* @return {Object}
|
||||
*/
|
||||
public static Object generator(Class<?> superclass, BeanProperty... props) {
|
||||
BeanGenerator generator = new BeanGenerator();
|
||||
generator.setSuperclass(superclass);
|
||||
generator.setUseCache(true);
|
||||
for (BeanProperty prop : props) {
|
||||
generator.addProperty(prop.getName(), prop.getType());
|
||||
}
|
||||
return generator.create();
|
||||
}
|
||||
|
||||
/**
|
||||
* copy 对象属性到另一个对象,默认不使用Convert
|
||||
*
|
||||
* @param src
|
||||
* @param clazz 类名
|
||||
* @return T
|
||||
*/
|
||||
public static <T> T copy(Object src, Class<T> clazz) {
|
||||
BeanCopier copier = BeanCopier.create(src.getClass(), clazz, false);
|
||||
|
||||
T to = newInstance(clazz);
|
||||
copier.copy(src, to, null);
|
||||
return to;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拷贝对象
|
||||
*
|
||||
* @param src 源对象
|
||||
* @param dist 需要赋值的对象
|
||||
*/
|
||||
public static void copy(Object src, Object dist) {
|
||||
BeanCopier copier = BeanCopier
|
||||
.create(src.getClass(), dist.getClass(), false);
|
||||
|
||||
copier.copy(src, dist, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象装成map形式
|
||||
*
|
||||
* @param src
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static BeanMap toMap(Object src) {
|
||||
return BeanMap.create(src);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将map 转为 bean
|
||||
*/
|
||||
public static <T> T toBean(Map<String, Object> beanMap, Class<T> valueType) {
|
||||
T bean = BeanUtils.newInstance(valueType);
|
||||
PropertyDescriptor[] beanPds = getPropertyDescriptors(valueType);
|
||||
for (PropertyDescriptor propDescriptor : beanPds) {
|
||||
String propName = propDescriptor.getName();
|
||||
// 过滤class属性
|
||||
if (propName.equals("class")) {
|
||||
continue;
|
||||
}
|
||||
if (beanMap.containsKey(propName)) {
|
||||
Method writeMethod = propDescriptor.getWriteMethod();
|
||||
if (null == writeMethod) {
|
||||
continue;
|
||||
}
|
||||
Object value = beanMap.get(propName);
|
||||
if (!writeMethod.isAccessible()) {
|
||||
writeMethod.setAccessible(true);
|
||||
}
|
||||
try {
|
||||
writeMethod.invoke(bean, value);
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Could not set property '" + propName + "' to bean", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字段转换成字符串
|
||||
* @param filed
|
||||
* @return
|
||||
*/
|
||||
public static String convertToString(Object filed) {
|
||||
if(filed == null)
|
||||
return null;
|
||||
if(filed instanceof Integer) {
|
||||
return ((Integer) filed).toString();
|
||||
}else if(filed instanceof String) {
|
||||
return (String) filed;
|
||||
}else if(filed instanceof Double) {
|
||||
return ((Double) filed).toString();
|
||||
}else if(filed instanceof Float) {
|
||||
return ((Float) filed).toString();
|
||||
}else if(filed instanceof Long) {
|
||||
return ((Long) filed).toString();
|
||||
}else if(filed instanceof Boolean) {
|
||||
return ((Boolean) filed).toString();
|
||||
}else if(filed instanceof Date) {
|
||||
Date d = (Date) filed;
|
||||
return d.toString();
|
||||
}else {
|
||||
return filed.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将String转换成对象
|
||||
* @param filed
|
||||
* @return
|
||||
*/
|
||||
public static Object string2Object(String value, Class clazz) {
|
||||
if(clazz == Integer.class) {
|
||||
|
||||
return Integer.parseInt(value);
|
||||
|
||||
}else if(clazz == Float.class) {
|
||||
|
||||
return Float.parseFloat(value);
|
||||
|
||||
}else if(clazz == Double.class) {
|
||||
|
||||
return Double.parseDouble(value);
|
||||
|
||||
}else if(clazz == Integer.class) {
|
||||
|
||||
return Integer.parseInt(value);
|
||||
|
||||
}else if(clazz == Boolean.class) {
|
||||
|
||||
return Boolean.parseBoolean(value);
|
||||
|
||||
}else if(clazz == Short.class) {
|
||||
|
||||
return Short.parseShort(value);
|
||||
|
||||
}else {
|
||||
return value;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static String toString(Object bean, String prefix, String suffix) {
|
||||
String str ="";
|
||||
if(bean == null) return str;
|
||||
Map<String, Object> map = BeanUtils.toMap(bean);
|
||||
for (String key: map.keySet()) {
|
||||
str += prefix + BeanUtils.convertToString(map.get(key))+ suffix;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
public static String toString(Map<String,String> bean, String prefix, String suffix) {
|
||||
String str ="";
|
||||
if(bean == null) return str;
|
||||
|
||||
for (String key: bean.keySet()) {
|
||||
str += prefix + bean.get(key)+ suffix;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
public static String merge( Object field, String prefix, String suffix) {
|
||||
String str ="";
|
||||
if(field == null) return str;
|
||||
str += prefix + BeanUtils.convertToString(field)+ suffix;
|
||||
return str;
|
||||
}
|
||||
|
||||
}
|
||||
11
ndplan/src/main/java/com/system/util/bean/CopyAttribute.java
Normal file
11
ndplan/src/main/java/com/system/util/bean/CopyAttribute.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.system.util.bean;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target( { java.lang.annotation.ElementType.FIELD })
|
||||
public @interface CopyAttribute {
|
||||
|
||||
}
|
||||
252
ndplan/src/main/java/com/system/util/bean/CopyUtil.java
Normal file
252
ndplan/src/main/java/com/system/util/bean/CopyUtil.java
Normal file
@@ -0,0 +1,252 @@
|
||||
package com.system.util.bean;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.BeanWrapper;
|
||||
import org.springframework.beans.BeanWrapperImpl;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import com.system.util.AnnotationUtil;
|
||||
|
||||
public class CopyUtil {
|
||||
|
||||
/**
|
||||
* 获取一个对象的属性值为空的属性集合
|
||||
* @param source
|
||||
* @return
|
||||
*/
|
||||
public static Set<String> getNullPropertyNames (Object source) {
|
||||
final BeanWrapper src = new BeanWrapperImpl(source);
|
||||
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
|
||||
|
||||
Set<String> emptyNames = new HashSet<String>();
|
||||
for(java.beans.PropertyDescriptor pd : pds) {
|
||||
Object srcValue = src.getPropertyValue(pd.getName());
|
||||
if (srcValue == null) emptyNames.add(pd.getName());
|
||||
}
|
||||
String[] result = new String[emptyNames.size()];
|
||||
return emptyNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将object中只用了CopyAttribute注解的属性复制到target,
|
||||
* 如果target为空,创建一个新对象
|
||||
* @param Object
|
||||
* @param target
|
||||
* @return
|
||||
*/
|
||||
//@SuppressWarnings("unchecked")
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T copyObject(T object, T target) {
|
||||
return copyObject(object,target, null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 1.如果target为空,创建一个新对象
|
||||
* 2.将object中只用了CopyAttribute注解的属性复制到target
|
||||
* 3.默认是【非空复制】, 属性的值为null,就不复制,除非使用了CopyAttribute
|
||||
* 4.noIgnoreProperties 不可忽略的字段,null也要替换
|
||||
* @param Object ,如果target为空,创建一个新对象
|
||||
* @param target
|
||||
* @param noIgnoreProperties 不可忽略的字段,null也要替换
|
||||
* @return
|
||||
*/
|
||||
//@SuppressWarnings("unchecked")
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T copyObject(T object, T target, Set<String> noIgnoreProperties) {
|
||||
if(object == null ) {
|
||||
return target;
|
||||
}
|
||||
if (target == null) {
|
||||
try {
|
||||
target = (T) object.getClass().newInstance();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// 调用spring的复制代码,解决habernateDAO的问题
|
||||
try {
|
||||
|
||||
Set<String> ignoreProperties = new HashSet<>();
|
||||
|
||||
Field[] allFieldList = object.getClass().getDeclaredFields();
|
||||
List<Field> fieldList = AnnotationUtil.getAnnotationFileds(object.getClass(), CopyAttribute.class);
|
||||
// 有CopyAttribute注解的字段
|
||||
Set<String> fieldSet = new HashSet<>();
|
||||
|
||||
// 值为空的字段,获取对象中的空值字段,然后忽略掉字段
|
||||
Set<String> nullSet = getNullPropertyNames(object);
|
||||
if(!CollectionUtils.isEmpty(fieldList)) {
|
||||
for (int i = 0; i < allFieldList.length; i++) {
|
||||
//忽略所有字段
|
||||
ignoreProperties.add(allFieldList[i].getName());
|
||||
}
|
||||
}
|
||||
|
||||
if(!CollectionUtils.isEmpty(fieldList)) {
|
||||
for (int i = 0; i < fieldList.size(); i++) {
|
||||
fieldSet.add(fieldList.get(i).getName());
|
||||
}
|
||||
}
|
||||
|
||||
ignoreProperties.remove(fieldSet);
|
||||
nullSet.remove(fieldSet);
|
||||
ignoreProperties.addAll(nullSet);
|
||||
|
||||
// 指定的字段要进行复制
|
||||
if( ignoreProperties != null && ignoreProperties.size() > 0
|
||||
&& noIgnoreProperties != null && noIgnoreProperties.size() > 0 ) {
|
||||
ignoreProperties.removeAll(noIgnoreProperties);
|
||||
}
|
||||
|
||||
String[] array = new String[ignoreProperties.size()];
|
||||
int i = 0;
|
||||
for (String e : ignoreProperties) {
|
||||
array[i++] = e;
|
||||
}
|
||||
|
||||
BeanUtils.copyProperties(object, target,array);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 1.如果target为空,创建一个新对象
|
||||
* 2.将object中只用了CopyAttribute注解的属性复制到target
|
||||
* 3.默认是【全复制】, 属性的值为null,也要复制,除非字段是NoCopyAttribute
|
||||
* 4.noIgnoreProperties 不可忽略的字段,null也要替换
|
||||
* @param Object ,如果target为空,创建一个新对象
|
||||
* @param target
|
||||
* @param noIgnoreProperties 不可忽略的字段,null也要替换
|
||||
* @return
|
||||
*/
|
||||
//@SuppressWarnings("unchecked")
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T copyAll(T object, T target, Set<String> noIgnoreProperties) {
|
||||
if(object == null ) {
|
||||
return target;
|
||||
}
|
||||
if (target == null) {
|
||||
try {
|
||||
target = (T) object.getClass().newInstance();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
List<Field> fieldList = AnnotationUtil.getAnnotationFileds(object.getClass(), NoCopyAttribute.class);
|
||||
|
||||
String[] array = new String[fieldList.size()];
|
||||
for (int i = 0; i < fieldList.size(); i++) {
|
||||
array[i] = fieldList.get(i).getName();
|
||||
}
|
||||
|
||||
BeanUtils.copyProperties(object, target,array);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> List<T> copyObjects(List<T> objects, List<T> targets) {
|
||||
if(objects == null || objects.size() == 0 ) {
|
||||
if(targets == null || targets.size() == 0 ) {
|
||||
return new ArrayList<T>();
|
||||
}else {
|
||||
return targets;
|
||||
}
|
||||
}
|
||||
if(targets == null || targets.size() == 0) {
|
||||
targets = new ArrayList<T>();
|
||||
}
|
||||
for (int i = 0; i < objects.size(); i++) {
|
||||
T item = objects.get(i);
|
||||
if( i < targets.size()) {
|
||||
targets.set(i, copyObject(item, targets.get(i)) );
|
||||
}else {
|
||||
targets.add(copyObject(item, null));
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> List<T> copyObjects(List<T> objects, List<T> targets, String fieldName) {
|
||||
|
||||
|
||||
if(objects == null || objects.size() == 0 ) {
|
||||
if(targets == null || targets.size() == 0 ) {
|
||||
return new ArrayList<T>();
|
||||
}else {
|
||||
return targets;
|
||||
}
|
||||
}
|
||||
if(targets == null || targets.size() == 0) {
|
||||
targets = new ArrayList<T>();
|
||||
}
|
||||
|
||||
Field field= AnnotationUtil.getField(objects.get(0).getClass(), fieldName);
|
||||
if(field == null) {
|
||||
|
||||
}
|
||||
for (int i = 0; i < objects.size(); i++) {
|
||||
T item = objects.get(i);
|
||||
|
||||
for (int j = 0; j < targets.size(); i++) {
|
||||
T target = targets.get(j);
|
||||
|
||||
}
|
||||
|
||||
if( i < targets.size()) {
|
||||
targets.set(i, copyObject(item, targets.get(i)) );
|
||||
}else {
|
||||
targets.add(copyObject(item, null));
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
/*CommonObject object = new CommonObject();
|
||||
object.setId(1L);
|
||||
object.setName("1");
|
||||
|
||||
CommonObject target = new CommonObject();
|
||||
target.setId(2L);
|
||||
target.setName("2");
|
||||
target = CopyUtil.copyObject(object, target);
|
||||
System.out.println(target.getId());
|
||||
System.out.println(target.getName());*/
|
||||
|
||||
|
||||
|
||||
/*List<CommonObject> objects = new ArrayList<CommonObject>();
|
||||
objects.add(object);
|
||||
System.out.println(copyObjects(objects, null));*/
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.system.util.bean;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target( { java.lang.annotation.ElementType.FIELD })
|
||||
public @interface NoCopyAttribute {
|
||||
|
||||
}
|
||||
111
ndplan/src/main/java/com/system/util/jpa/Condition.java
Normal file
111
ndplan/src/main/java/com/system/util/jpa/Condition.java
Normal file
@@ -0,0 +1,111 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import com.system.util.json.JSONFilter;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 条件表达式
|
||||
*/
|
||||
@Data
|
||||
public class Condition {
|
||||
|
||||
|
||||
/**
|
||||
* 过滤条件
|
||||
*/
|
||||
private Expression express;
|
||||
/**
|
||||
* 排序条件
|
||||
*/
|
||||
private List<OrderCondition> orderConditions;
|
||||
|
||||
/**
|
||||
* jpa的排序条件
|
||||
*/
|
||||
@JSONFilter
|
||||
private Sort sort;
|
||||
/**
|
||||
* jpa的查询条件
|
||||
*/
|
||||
@JSONFilter
|
||||
private Specification specification;
|
||||
|
||||
public Condition() {
|
||||
}
|
||||
|
||||
/*private void addFilter(FilterCondition fc, int direct) {
|
||||
if (CollectionUtils.isEmpty(this.express)) {
|
||||
this.express = new LinkedList<FilterCondition>();
|
||||
fc.setSortNo(1);
|
||||
} else {
|
||||
int destNo = 0;
|
||||
FilterCondition destFc = null;
|
||||
int pos = 0;
|
||||
for (FilterCondition temp : this.express) {
|
||||
if(pos==0){
|
||||
destFc = temp;
|
||||
}else{
|
||||
if (direct > 0) {
|
||||
if (temp.getSortNo() > destNo) {
|
||||
destNo = temp.getSortNo();
|
||||
destFc = temp;
|
||||
}
|
||||
} else {
|
||||
if (temp.getSortNo() < destNo) {
|
||||
destNo = temp.getSortNo();
|
||||
destFc = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
pos++;
|
||||
}
|
||||
if(direct<=0){
|
||||
// destFc.setConditionRelate(fc.getConditionRelate());
|
||||
}
|
||||
fc.setSortNo(destNo + direct);
|
||||
}
|
||||
this.express.add(fc);
|
||||
}*/
|
||||
|
||||
public void addLastOrder(OrderCondition oc) {
|
||||
this.addOrder(oc, 1);
|
||||
}
|
||||
|
||||
public void addFirstOrder(OrderCondition oc) {
|
||||
this.addOrder(oc, -1);
|
||||
}
|
||||
|
||||
private void addOrder(OrderCondition oc, int direct) {
|
||||
if (CollectionUtils.isEmpty(this.orderConditions)) {
|
||||
this.orderConditions = new LinkedList<OrderCondition>();
|
||||
oc.setSortNo(1);
|
||||
} else {
|
||||
int destNo = 0;
|
||||
for (OrderCondition temp : this.orderConditions) {
|
||||
if (direct > 0) {
|
||||
if (temp.getSortNo() > destNo) {
|
||||
destNo = temp.getSortNo();
|
||||
}
|
||||
} else {
|
||||
if (temp.getSortNo() < destNo) {
|
||||
destNo = temp.getSortNo();
|
||||
}
|
||||
}
|
||||
}
|
||||
oc.setSortNo(destNo + 1);
|
||||
}
|
||||
this.orderConditions.add(oc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
/**
|
||||
* 条件表达式之间的关系
|
||||
*/
|
||||
public enum ConditionRelate {
|
||||
and, or
|
||||
}
|
||||
104
ndplan/src/main/java/com/system/util/jpa/ConditionUtil.java
Normal file
104
ndplan/src/main/java/com/system/util/jpa/ConditionUtil.java
Normal file
@@ -0,0 +1,104 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.data.domain.Sort.Order;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
|
||||
import com.system.common.ResultBean;
|
||||
import com.system.common.ResultCode;
|
||||
import com.system.util.json.BaseJSON;
|
||||
|
||||
import lombok.val;
|
||||
import lombok.extern.java.Log;
|
||||
|
||||
|
||||
|
||||
|
||||
@val
|
||||
@Log
|
||||
public class ConditionUtil {
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @param jsonStr
|
||||
* @param clazz
|
||||
* @return ResultBean<Condition>
|
||||
*/
|
||||
public static <T> ResultBean<Condition> buildCondition(String jsonStr,Class clazz){
|
||||
if(!StringUtils.isEmpty(jsonStr)){
|
||||
Condition condition = BaseJSON.parseObject(jsonStr, Condition.class);
|
||||
try{
|
||||
Specification<T> specification =JsonDynamicSpecifications.builder(condition, clazz);
|
||||
condition.setSpecification(specification);
|
||||
if (condition != null && condition.getOrderConditions() != null && condition.getOrderConditions().size() > 0) {
|
||||
Collections.sort(condition.getOrderConditions(), new Comparator<OrderCondition>() {
|
||||
@Override
|
||||
public int compare(OrderCondition o1, OrderCondition o2) {
|
||||
if (o1.getSortNo() < o2.getSortNo()) {
|
||||
return -1;
|
||||
} else if (o1.getSortNo() == o2.getSortNo()) {
|
||||
return 0;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if(condition.getOrderConditions()!=null&&condition.getOrderConditions().size()>0){
|
||||
List<Order> orderList = new ArrayList<Sort.Order>();
|
||||
for(OrderCondition orderCondition :condition.getOrderConditions()){
|
||||
Order order = new Order("DESC".equalsIgnoreCase(orderCondition.getOrder())?Direction.DESC:Direction.ASC, orderCondition.getAttrName());
|
||||
orderList.add(order);
|
||||
}
|
||||
//condition.setSort(Sort.by(orderList));
|
||||
}
|
||||
}catch (Exception e){
|
||||
log.warning(e.getMessage());
|
||||
}
|
||||
val resultBean = new ResultBean<Condition>(ResultCode.SUCCESS,"",condition);
|
||||
return resultBean;
|
||||
}else{
|
||||
return new ResultBean<Condition>(ResultCode.SUCCESS,"输入字符串为空!",new Condition());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把json字符串转换为Condition对象
|
||||
* @param condition
|
||||
* @return Condition
|
||||
*/
|
||||
public static Condition parseCondition(String condition){
|
||||
if(GeneralHelper.isTrimStrNotEmpty(condition)){
|
||||
return BaseJSON.parseObject(condition, Condition.class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
// public static <T> Condition buildCondition(TreeNode treeNode,Class clazz){
|
||||
// /*if(treeNode!=null){
|
||||
// Condition condition = new Condition();
|
||||
// if(treeNode.getSub().size()==1){
|
||||
// Expression expre = new Expression(ConditionRelate.or,null,null);
|
||||
// int i = 1;
|
||||
// expre.getSubCons().put(i++, value)
|
||||
// }
|
||||
// return condition;
|
||||
// }else{
|
||||
// return null;
|
||||
// }*/
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Path;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
import org.apache.commons.lang3.ClassUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
|
||||
import com.system.util.DateUtil;
|
||||
|
||||
import lombok.extern.java.Log;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @author yongjie Gu 2013-10-11
|
||||
* specificationn.详述, 规格, 说明书, 规范
|
||||
*/
|
||||
@Log
|
||||
public class DynamicSpecifications {
|
||||
|
||||
/**
|
||||
* Specification的创建方法
|
||||
* 应用jpa组合查询条件(or的条件用括号括起来,and的也是,而这两组条件通过or进行连接)
|
||||
* @param searchParams
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
public static <T> Specification<T> builder(final Map<String, Object> searchParams, final Class<T> clazz) {
|
||||
|
||||
/**获取查询的条件*/
|
||||
final Map<Integer, SearchFilter> map= parseParam(searchParams);
|
||||
final Class<T> c = clazz;
|
||||
|
||||
return new Specification<T>() {
|
||||
/**重写谓词方法
|
||||
* 使用 CriteriaBuilder来构建标准的谓词
|
||||
*/
|
||||
@Override
|
||||
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
Predicate resultPredicate = builder.conjunction();
|
||||
if (map.size()>0) {
|
||||
for(int i=1;i<=map.size();i++){
|
||||
Predicate tempPredicate = builder.conjunction();
|
||||
SearchFilter sf = map.get(i);
|
||||
String[] names = StringUtils.split(sf.fieldName, ".");
|
||||
Path expression = root.get(names[0]);
|
||||
Class curClass = clazz;
|
||||
for (int j = 1; j < names.length; j++) {
|
||||
expression = expression.get(names[j]);
|
||||
}
|
||||
try {
|
||||
if (names.length > 1) {
|
||||
curClass = getCurrentClass(names, curClass);
|
||||
}
|
||||
tempPredicate = buildSearchFilter(sf, expression, curClass, builder);
|
||||
} catch (Exception e) {
|
||||
log.warning("查询字段" + sf.fieldName + "语法错误:" + e.getMessage());
|
||||
log.warning(e.getMessage());
|
||||
}
|
||||
|
||||
if (i == 0) {
|
||||
resultPredicate = tempPredicate;
|
||||
} else {
|
||||
if ("or".equalsIgnoreCase(sf.operator)) {
|
||||
resultPredicate = builder.or(resultPredicate, tempPredicate);
|
||||
} else {
|
||||
resultPredicate = builder.and(resultPredicate, tempPredicate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* int flag = 0; while (iter.hasNext()) { Predicate subPredicate
|
||||
* = builder.conjunction(); FilterCondition filterCondition =
|
||||
* iter.next(); String[] names =
|
||||
* StringUtils.split(filterCondition.getAttrName(), "."); Class
|
||||
* curClass = clazz; Path expression = root.get(names[0]); for
|
||||
* (int j = 1; j < names.length; j++) { expression =
|
||||
* expression.get(names[j]); } try { if (names.length > 1) {
|
||||
* curClass = getCurrentClass(names, curClass); } subPredicate =
|
||||
* buildFilterConditon(filterCondition, expression, curClass,
|
||||
* builder); } catch (Exception e) { log.error("查询字段" +
|
||||
* filterCondition.getAttrName() + "语法错误:" + e.getMessage()); }
|
||||
* if (flag != 0) { if
|
||||
* (ConditionRelate.or.toString().equalsIgnoreCase
|
||||
* (filterCondition.getConditionRelate())) { resultPredicate =
|
||||
* builder.or(resultPredicate, subPredicate); } else {
|
||||
* resultPredicate = builder.and(resultPredicate, subPredicate);
|
||||
* } } else { resultPredicate = subPredicate; }
|
||||
*
|
||||
* flag++; }
|
||||
*/
|
||||
return resultPredicate;
|
||||
}
|
||||
private Class getCurrentClass(String[] names, Class clazz) throws Exception {
|
||||
Field field = clazz.getDeclaredField(names[0]);
|
||||
Class res = field.getType();
|
||||
if (names.length == 2) {
|
||||
return res;
|
||||
} else {
|
||||
return getCurrentClass(Arrays.copyOfRange(names, 1, names.length), res);
|
||||
}
|
||||
}
|
||||
|
||||
private Predicate buildSearchFilter(final SearchFilter sf, final Path expression, Class<T> clazz, final CriteriaBuilder builder) throws Exception {
|
||||
Predicate predicate = builder.conjunction();
|
||||
String filedName = sf.fieldName;
|
||||
int pos = filedName.lastIndexOf(".");
|
||||
if (pos > 0) {
|
||||
filedName = filedName.substring(pos + 1);
|
||||
}
|
||||
Field field = clazz.getDeclaredField(filedName);
|
||||
Class fieldClass = field.getType();
|
||||
|
||||
if (ClassUtils.isPrimitiveOrWrapper(fieldClass)) {
|
||||
if(fieldClass.getName().endsWith("Long")){
|
||||
switch (Operation.valueOf(sf.operator)) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, sf.value);
|
||||
break;
|
||||
case gt:
|
||||
predicate = builder.gt(expression, Long.parseLong(sf.value));
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.ge(expression, Long.parseLong(sf.value));
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lt(expression, Long.parseLong(sf.value));
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.le(expression, Long.parseLong(sf.value));
|
||||
break;
|
||||
case like:
|
||||
throw new Exception("数字类型字段不能相似操作!");
|
||||
case eq:
|
||||
predicate = builder.equal(expression, Long.parseLong(sf.value));
|
||||
break;
|
||||
case linr:
|
||||
predicate.in(sf.value);
|
||||
break;
|
||||
}
|
||||
}else{
|
||||
switch (Operation.valueOf(sf.operator)) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, sf.value);
|
||||
break;
|
||||
case gt:
|
||||
predicate = builder.gt(expression, NumberUtils.createNumber(sf.value));
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.ge(expression, NumberUtils.createNumber(sf.value));
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lt(expression, NumberUtils.createNumber(sf.value));
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.le(expression, NumberUtils.createNumber(sf.value));
|
||||
break;
|
||||
case like:
|
||||
throw new Exception("数字类型字段不能相似操作!");
|
||||
case eq:
|
||||
predicate = builder.equal(expression, NumberUtils.createNumber(sf.value));
|
||||
break;
|
||||
case linr:
|
||||
predicate.in(sf.value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} else if (fieldClass.getName().endsWith("Date")) {
|
||||
// 日期处理
|
||||
switch (Operation.valueOf(String.valueOf(sf.operator))) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, DateUtil.parseDate(sf.value));
|
||||
break;
|
||||
case gt:
|
||||
predicate = builder.greaterThan(expression, (Comparable) DateUtil.parseDate(sf.value));
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(sf.value));
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lessThan(expression, (Comparable) DateUtil.parseDate(sf.value));
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.lessThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(sf.value));
|
||||
break;
|
||||
case like:
|
||||
throw new Exception("日期类型字段不能相似操作!");
|
||||
case eq:
|
||||
predicate = builder.equal(expression, sf.value);
|
||||
case emp:
|
||||
predicate = builder.isNull(expression);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
switch (Operation.valueOf(String.valueOf(sf.operator))) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, sf.value);
|
||||
break;
|
||||
|
||||
case gt:
|
||||
predicate = builder.greaterThan(expression, (Comparable) sf.value);
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) sf.value);
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lessThan(expression, (Comparable) sf.value);
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.lessThanOrEqualTo(expression, (Comparable) sf.value);
|
||||
break;
|
||||
case like:
|
||||
predicate = builder.like(expression, "%" + sf.value + "%");
|
||||
break;
|
||||
case llike:
|
||||
predicate = builder.like(expression, "%" + sf.value);
|
||||
break;
|
||||
case rlike:
|
||||
predicate = builder.like(expression, sf.value + "%");
|
||||
break;
|
||||
case eq:
|
||||
predicate = builder.equal(expression, sf.value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return predicate;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 搜索过滤器
|
||||
*/
|
||||
static class SearchFilter {
|
||||
|
||||
public String fieldName;
|
||||
public String value;
|
||||
public String operator;
|
||||
public String relation;
|
||||
|
||||
private SearchFilter(String fieldName, String operator, String value, String relation) {
|
||||
this.fieldName = fieldName;
|
||||
this.value = value;
|
||||
this.operator = operator;
|
||||
this.relation = relation;
|
||||
}
|
||||
|
||||
public static SearchFilter newInstance(String fieldName, String operator, String value) {
|
||||
return new SearchFilter(fieldName, operator, value, null);
|
||||
}
|
||||
|
||||
public static SearchFilter newInstance(String fieldName, String operator, String value, String relation) {
|
||||
return new SearchFilter(fieldName, operator, value, relation);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把查询条件解析为结构化数据 operation_field_sortNo_relation:eq_id_1_and
|
||||
* @param searchParams
|
||||
* @return
|
||||
*/
|
||||
private static Map<Integer, SearchFilter> parseParam(Map<String, Object> searchParams) {
|
||||
Map<Integer, SearchFilter> resultMap = new HashMap<Integer, DynamicSpecifications.SearchFilter>();
|
||||
if (searchParams == null || searchParams.size() == 0)
|
||||
return resultMap;
|
||||
for (Entry<String, Object> entry : searchParams.entrySet()) {
|
||||
// 过滤掉空值
|
||||
String key = entry.getKey();
|
||||
if(key.indexOf("_")==-1){
|
||||
continue;
|
||||
}
|
||||
Object value = entry.getValue();
|
||||
// 如果value是数组,则使用(String)value会报错,所以修改为使用toString()方法代替。
|
||||
if (value == null || StringUtils.isBlank(value.toString())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String[] vals = new String[1];
|
||||
String val = value.toString();
|
||||
vals[0] = val;
|
||||
/*if(vals.length==1){*/
|
||||
// /value = vals[0];
|
||||
/*}*/
|
||||
// 拆分operator与filedAttribute
|
||||
String[] names = StringUtils.split(key, "_");
|
||||
if (names.length < 2) {
|
||||
log.info(key + " is not a valid search filter name");
|
||||
continue;
|
||||
}
|
||||
if (names.length == 2) {
|
||||
String filedName = names[1];
|
||||
SearchFilter filter = new SearchFilter(filedName, names[0], vals[0], null);
|
||||
resultMap.put(1, filter);
|
||||
} else {
|
||||
resultMap.put(Integer.parseInt(names[2]), SearchFilter.newInstance(names[1], names[0], vals[0], names[3]));
|
||||
}
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
}
|
||||
85
ndplan/src/main/java/com/system/util/jpa/Expression.java
Normal file
85
ndplan/src/main/java/com/system/util/jpa/Expression.java
Normal file
@@ -0,0 +1,85 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @Title: Expression.java
|
||||
* @Package com.tky.tunnel.util.jpa
|
||||
* @Description: where查询表达式
|
||||
*
|
||||
* @author jassengu@163.com
|
||||
* @date 2015年11月10日 下午3:09:07
|
||||
* @version V1.0
|
||||
* @Copyright: TKY.BIM Copyright (c) 2015
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class Expression {
|
||||
/**
|
||||
* 子表达式或者条件队列的关系
|
||||
*/
|
||||
private ConditionRelate relation = ConditionRelate.and;
|
||||
/**
|
||||
* 子表达式
|
||||
*/
|
||||
private Map<String, Expression> subExpress = new HashMap<String, Expression>();
|
||||
/**
|
||||
* 过滤条件序列
|
||||
*/
|
||||
private Map<String, FilterCondition> subCons = new HashMap<String, FilterCondition>();
|
||||
|
||||
public void setRelation(String relation) {
|
||||
this.relation = ConditionRelate.valueOf(relation);
|
||||
}
|
||||
|
||||
public Expression(ConditionRelate relation,Map<String, Expression> subExpress,Map<String, FilterCondition> subCons){
|
||||
this.relation = relation;
|
||||
if(subCons!=null){
|
||||
this.subCons = subCons;
|
||||
}
|
||||
if(subExpress!=null){
|
||||
this.subExpress = subExpress;
|
||||
}
|
||||
}
|
||||
|
||||
public Expression and(Expression express){
|
||||
boolean isAnd = ConditionRelate.and==express.getRelation()&&this.relation==ConditionRelate.and;
|
||||
boolean isLeaf = this.subExpress.size()==0&&express.getSubExpress().size()==0;
|
||||
if(isAnd&&isLeaf){
|
||||
for(int i=1;i<=express.subCons.size();i++ ){
|
||||
this.subCons.put(String.valueOf(this.subCons.size()+1), express.getSubCons().get(String.valueOf(i)));
|
||||
}
|
||||
return this;
|
||||
}else{
|
||||
Expression res = new Expression(ConditionRelate.and, null, null);
|
||||
res.getSubExpress().put("1", this);
|
||||
res.getSubExpress().put("2", express);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
public Expression or(Expression express){
|
||||
boolean isOr = ConditionRelate.or==express.getRelation()&&this.relation==ConditionRelate.or;
|
||||
boolean isLeaf = this.subExpress.size()==0&&express.getSubExpress().size()==0;
|
||||
if(isOr&&isLeaf){
|
||||
for(int i=1;i<=express.subCons.size();i++ ){
|
||||
this.subCons.put(String.valueOf(this.subCons.size()+1), express.getSubCons().get(String.valueOf(i)));
|
||||
}
|
||||
return this;
|
||||
}else{
|
||||
Expression res = new Expression(ConditionRelate.or, null, null);
|
||||
res.getSubExpress().put("1", this);
|
||||
res.getSubExpress().put("2", express);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
// public static Expression oper(ConditionRelate rlation,Expression ... expresses){
|
||||
//
|
||||
// }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title: FilterCondition.java
|
||||
* @Package com.tky.tunnel.util.jpa
|
||||
* @Description: 条件表达式 表达式加括号后再与其它表达式进行运算
|
||||
*
|
||||
* @author jassengu@163.com
|
||||
* @date 2015年11月10日 下午3:05:05
|
||||
* @version V1.0
|
||||
* @Copyright: TKY.BIM Copyright (c) 2015
|
||||
*/
|
||||
@Data
|
||||
public class FilterCondition {
|
||||
|
||||
/**
|
||||
* 要过滤的属性名称
|
||||
*/
|
||||
private String attrName;
|
||||
/**
|
||||
* 条件关系符 当有多个FilterCondition时,标识它们之间的关系。
|
||||
*/
|
||||
// private String conditionRelate;
|
||||
/**
|
||||
* 条件结束值 对于区间值,记录区间的结束值
|
||||
*/
|
||||
private String endVal;
|
||||
/**
|
||||
* 操作符 当为一元操作符时,操作值在val中; 当为二元操作符时,操作值分别在startVal及endVal值中
|
||||
*/
|
||||
private String operation;
|
||||
/**
|
||||
* 顺序号 表示条件的先后顺序。数字越小越靠前
|
||||
*/
|
||||
// private Integer sortNo;
|
||||
/**
|
||||
* 条件开始值 对于区间值,记录区间的开始值
|
||||
*/
|
||||
private String startVal;
|
||||
/**
|
||||
* 条件值 对于一元操作符,记录单一条件值。
|
||||
*/
|
||||
private String val;
|
||||
/**
|
||||
* 分组序号
|
||||
*/
|
||||
// private Integer group;
|
||||
|
||||
// private String groupRelate;
|
||||
|
||||
public FilterCondition() {
|
||||
}
|
||||
|
||||
public FilterCondition(String val, String attrName, String operation) {
|
||||
this.val = val;
|
||||
this.attrName = attrName;
|
||||
this.operation = operation;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public FilterCondition(String startVal, String endVal, String attrName, String operation) {
|
||||
this.startVal = startVal;
|
||||
this.endVal = endVal;
|
||||
this.operation = operation;
|
||||
this.attrName = attrName;
|
||||
}
|
||||
|
||||
}
|
||||
1319
ndplan/src/main/java/com/system/util/jpa/GeneralHelper.java
Normal file
1319
ndplan/src/main/java/com/system/util/jpa/GeneralHelper.java
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,551 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Path;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
import org.apache.commons.lang3.ClassUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
|
||||
import com.system.util.DateUtil;
|
||||
|
||||
import lombok.extern.java.Log;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@Log
|
||||
public class JsonDynamicSpecifications {
|
||||
|
||||
/**
|
||||
* 应用jpa组合查询条件(or的条件用括号括起来,and的也是,而这两组条件通过or进行连接)
|
||||
*
|
||||
* @param c
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
public static <T> Specification<T> builder(final Condition c, final Class<T> clazz) throws Exception {
|
||||
|
||||
return new Specification<T>() {
|
||||
|
||||
private Predicate buildSubSpec(Root<T> root, Expression express, CriteriaBuilder builder) {
|
||||
Predicate resultPredicate = builder.conjunction();
|
||||
if (express.getSubCons().size() > 0) {
|
||||
for (int i = 1; i <= express.getSubCons().size(); i++) {
|
||||
FilterCondition fc = express.getSubCons().get(String.valueOf(i));
|
||||
Predicate tempPredicate = builder.conjunction();
|
||||
String[] names = StringUtils.split(fc.getAttrName(), ".");
|
||||
Class curClass = clazz;
|
||||
Path expression = root.get(names[0]);
|
||||
for (int j = 1; j < names.length; j++) {
|
||||
expression = expression.get(names[j]);
|
||||
}
|
||||
try {
|
||||
if (names.length > 1) {
|
||||
curClass = getCurrentClass(names, curClass);
|
||||
}
|
||||
tempPredicate = buildFilterConditon(fc, expression, curClass, builder);
|
||||
} catch (Exception e) {
|
||||
log.warning("查询字段" + fc.getAttrName() + "语法错误:" + e.getMessage());
|
||||
}
|
||||
if (express.getRelation() == ConditionRelate.and) {
|
||||
resultPredicate = builder.and(resultPredicate, tempPredicate);
|
||||
} else {
|
||||
resultPredicate = builder.or(resultPredicate, tempPredicate);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (express.getSubExpress().size() > 0) {
|
||||
for (int i = 1; i <= express.getSubExpress().size(); i++) {
|
||||
if (express.getRelation() == ConditionRelate.and) {
|
||||
resultPredicate = builder.and(resultPredicate, buildSubSpec(root, express.getSubExpress().get(String.valueOf(i)), builder));
|
||||
} else {
|
||||
resultPredicate = builder.or(resultPredicate, buildSubSpec(root, express.getSubExpress().get(String.valueOf(i)), builder));
|
||||
}
|
||||
}
|
||||
}
|
||||
return resultPredicate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
|
||||
Predicate resultPredicate = builder.conjunction();
|
||||
if (c.getExpress() != null) {
|
||||
resultPredicate = buildSubSpec(root, c.getExpress(), builder);
|
||||
}
|
||||
|
||||
/*
|
||||
* if (c != null && c.getFilterCondition() != null &&
|
||||
* c.getFilterCondition().size() > 0) {
|
||||
* Collections.sort(c.getFilterCondition(), new
|
||||
* Comparator<FilterCondition>() {
|
||||
*
|
||||
* @Override public int compare(FilterCondition o1,
|
||||
* FilterCondition o2) { if (o1.getSortNo() < o2.getSortNo()) {
|
||||
* return -1; } else if (o1.getSortNo() == o2.getSortNo()) {
|
||||
* return 0; } else { return 1; } } }); } else { return
|
||||
* resultPredicate; } Hashtable<Integer, List<FilterCondition>>
|
||||
* map = new Hashtable<Integer, List<FilterCondition>>();
|
||||
* Iterator<FilterCondition> iter =
|
||||
* c.getFilterCondition().iterator(); while (iter.hasNext()) {
|
||||
* FilterCondition fc = iter.next(); if (fc.getGroup() == null)
|
||||
* {
|
||||
*
|
||||
* fc.setGroup(0); } List<FilterCondition> list =
|
||||
* map.get(fc.getGroup()); if (list == null) { list = new
|
||||
* LinkedList<FilterCondition>(); map.put(fc.getGroup(), list);
|
||||
* } list.add(fc); } for (int i = 0; i <= 10; i++) {
|
||||
* List<FilterCondition> subList = map.get(i); if (subList !=
|
||||
* null && subList.size() > 0) { int flag = 0;
|
||||
* Iterator<FilterCondition> subIterator = subList.iterator();
|
||||
* Predicate subPredicate = builder.conjunction(); while
|
||||
* (subIterator.hasNext()) { Predicate tempPredicate =
|
||||
* builder.conjunction(); FilterCondition filterCondition =
|
||||
* subIterator.next(); String[] names =
|
||||
* StringUtils.split(filterCondition.getAttrName(), "."); Class
|
||||
* curClass = clazz; Path expression = root.get(names[0]); for
|
||||
* (int j = 1; j < names.length; j++) { expression =
|
||||
* expression.get(names[j]); } try { if (names.length > 1) {
|
||||
* curClass = getCurrentClass(names, curClass); } tempPredicate
|
||||
* = buildFilterConditon(filterCondition, expression, curClass,
|
||||
* builder); } catch (Exception e) { log.warning("查询字段" +
|
||||
* filterCondition.getAttrName() + "语法错误:" + e.getMessage()); }
|
||||
*
|
||||
* if (flag != 0) { if
|
||||
* (ConditionRelate.or.toString().equalsIgnoreCase
|
||||
* (filterCondition.getConditionRelate())) { subPredicate =
|
||||
* builder.or(subPredicate, tempPredicate); } else {
|
||||
* subPredicate = builder.and(subPredicate, tempPredicate); } }
|
||||
* else { subPredicate = tempPredicate; } flag++; } if (i == 0)
|
||||
* { resultPredicate = subPredicate; } else { if
|
||||
* ("or".equalsIgnoreCase(subList.get(0).getGroupRelate())) {
|
||||
* resultPredicate = builder.or(resultPredicate, subPredicate);
|
||||
* } else { resultPredicate = builder.and(resultPredicate,
|
||||
* subPredicate); } } }
|
||||
*
|
||||
* }
|
||||
*/
|
||||
/*
|
||||
* int flag = 0; while (iter.hasNext()) { Predicate subPredicate
|
||||
* = builder.conjunction(); FilterCondition filterCondition =
|
||||
* iter.next(); String[] names =
|
||||
* StringUtils.split(filterCondition.getAttrName(), "."); Class
|
||||
* curClass = clazz; Path expression = root.get(names[0]); for
|
||||
* (int j = 1; j < names.length; j++) { expression =
|
||||
* expression.get(names[j]); } try { if (names.length > 1) {
|
||||
* curClass = getCurrentClass(names, curClass); } subPredicate =
|
||||
* buildFilterConditon(filterCondition, expression, curClass,
|
||||
* builder); } catch (Exception e) { log.error("查询字段" +
|
||||
* filterCondition.getAttrName() + "语法错误:" + e.getMessage()); }
|
||||
* if (flag != 0) { if
|
||||
* (ConditionRelate.or.toString().equalsIgnoreCase
|
||||
* (filterCondition.getConditionRelate())) { resultPredicate =
|
||||
* builder.or(resultPredicate, subPredicate); } else {
|
||||
* resultPredicate = builder.and(resultPredicate, subPredicate);
|
||||
* } } else { resultPredicate = subPredicate; }
|
||||
*
|
||||
* flag++; }
|
||||
*/
|
||||
return resultPredicate;
|
||||
}
|
||||
|
||||
private Class getCurrentClass(String[] names, Class clazz) throws Exception {
|
||||
Field field = clazz.getDeclaredField(names[0]);
|
||||
Class res = field.getType();
|
||||
if (names.length == 2) {
|
||||
return res;
|
||||
} else {
|
||||
return getCurrentClass(Arrays.copyOfRange(names, 1, names.length), res);
|
||||
}
|
||||
}
|
||||
|
||||
private Predicate buildFilterConditon(final FilterCondition fc, final Path expression, Class<T> clazz, final CriteriaBuilder builder) throws Exception {
|
||||
Predicate predicate = builder.conjunction();
|
||||
String filedName = fc.getAttrName();
|
||||
int pos = filedName.lastIndexOf(".");
|
||||
if (pos > 0) {
|
||||
filedName = filedName.substring(pos + 1);
|
||||
}
|
||||
Field field = clazz.getDeclaredField(filedName);
|
||||
Class fieldClass = field.getType();
|
||||
|
||||
if (ClassUtils.isPrimitiveOrWrapper(fieldClass)) {
|
||||
switch (Operation.valueOf(fc.getOperation())) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, fc.getVal());
|
||||
break;
|
||||
case in:
|
||||
predicate = builder.gt(expression, NumberUtils.createNumber(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lt(expression, NumberUtils.createNumber(fc.getEndVal())));
|
||||
break;
|
||||
case inr:
|
||||
predicate = builder.gt(expression, NumberUtils.createNumber(fc.getStartVal()));
|
||||
predicate = builder.and(builder.le(expression, NumberUtils.createNumber(fc.getEndVal())));
|
||||
break;
|
||||
case linr:
|
||||
predicate = builder.ge(expression, NumberUtils.createNumber(fc.getStartVal()));
|
||||
predicate = builder.and(builder.le(expression, NumberUtils.createNumber(fc.getEndVal())));
|
||||
break;
|
||||
case lin:
|
||||
predicate = builder.ge(expression, NumberUtils.createNumber(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lt(expression, NumberUtils.createNumber(fc.getEndVal())));
|
||||
break;
|
||||
case gt:
|
||||
predicate = builder.gt(expression, NumberUtils.createNumber(fc.getVal()));
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.ge(expression, NumberUtils.createNumber(fc.getVal()));
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lt(expression, NumberUtils.createNumber(fc.getVal()));
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.le(expression, NumberUtils.createNumber(fc.getVal()));
|
||||
break;
|
||||
case like:
|
||||
throw new Exception("数字类型字段不能相似操作!");
|
||||
case eq:
|
||||
predicate = builder.equal(expression, fc.getVal());
|
||||
break;
|
||||
}
|
||||
} else if (fieldClass.getName().endsWith("Date")) {
|
||||
// 日期处理
|
||||
switch (Operation.valueOf(String.valueOf(fc.getOperation()))) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case in:
|
||||
predicate = builder.greaterThan(expression, (Comparable) DateUtil.parseDate(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lessThan(expression, (Comparable) DateUtil.parseDate(fc.getEndVal())));
|
||||
break;
|
||||
case inr:
|
||||
predicate = builder.greaterThan(expression, (Comparable) DateUtil.parseDate(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lessThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getEndVal())));
|
||||
break;
|
||||
case linr:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lessThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getEndVal())));
|
||||
break;
|
||||
case lin:
|
||||
predicate = builder.greaterThan(expression, (Comparable) DateUtil.parseDate(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lessThan(expression, (Comparable) DateUtil.parseDate(fc.getEndVal())));
|
||||
break;
|
||||
case gt:
|
||||
predicate = builder.greaterThan(expression, (Comparable) DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lessThan(expression, (Comparable) DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.lessThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case like:
|
||||
throw new Exception("日期类型字段不能相似操作!");
|
||||
case eq:
|
||||
predicate = builder.equal(expression, fc.getVal());
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
switch (Operation.valueOf(String.valueOf(fc.getOperation()))) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, fc.getVal());
|
||||
break;
|
||||
case in:
|
||||
predicate = builder.greaterThan(expression, (Comparable) fc.getStartVal());
|
||||
predicate = builder.and(builder.lessThan(expression, (Comparable) fc.getEndVal()));
|
||||
break;
|
||||
case inr:
|
||||
predicate = builder.greaterThan(expression, (Comparable) fc.getStartVal());
|
||||
predicate = builder.and(builder.lessThanOrEqualTo(expression, (Comparable) fc.getEndVal()));
|
||||
break;
|
||||
case linr:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) fc.getStartVal());
|
||||
predicate = builder.and(builder.lessThanOrEqualTo(expression, (Comparable) fc.getEndVal()));
|
||||
break;
|
||||
case lin:
|
||||
predicate = builder.greaterThan(expression, (Comparable) fc.getStartVal());
|
||||
predicate = builder.and(builder.lessThan(expression, (Comparable) fc.getEndVal()));
|
||||
break;
|
||||
case gt:
|
||||
predicate = builder.greaterThan(expression, (Comparable) fc.getVal());
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) fc.getVal());
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lessThan(expression, (Comparable) fc.getVal());
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.lessThanOrEqualTo(expression, (Comparable) fc.getVal());
|
||||
break;
|
||||
case like:
|
||||
predicate = builder.like(expression, "%" + fc.getVal() + "%");
|
||||
break;
|
||||
case llike:
|
||||
predicate = builder.like(expression, "%" + fc.getVal());
|
||||
break;
|
||||
case rlike:
|
||||
predicate = builder.like(expression, fc.getVal() + "%");
|
||||
break;
|
||||
case eq:
|
||||
predicate = builder.equal(expression, fc.getVal());
|
||||
break;
|
||||
}
|
||||
}
|
||||
return predicate;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static class SearchFilter {
|
||||
|
||||
public String fieldName;
|
||||
public Object value;
|
||||
public String operator;
|
||||
|
||||
private SearchFilter(String fieldName, String operator, Object value) {
|
||||
this.fieldName = fieldName;
|
||||
this.value = value;
|
||||
this.operator = operator;
|
||||
}
|
||||
|
||||
public static SearchFilter newInstance(String fieldName, String operator, Object value) {
|
||||
return new SearchFilter(fieldName, operator, value);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> Specification<T> builderWithSpecification(final Specification spec, final Condition c, final Class<T> clazz) throws Exception {
|
||||
|
||||
return new Specification<T>() {
|
||||
|
||||
private Predicate buildSubSpec(Root<T> root, Expression express, CriteriaBuilder builder) {
|
||||
Predicate resultPredicate = null;
|
||||
if (express.getSubCons().size() > 0) {
|
||||
for (int i = 1; i <= express.getSubCons().size(); i++) {
|
||||
FilterCondition fc = express.getSubCons().get(String.valueOf(i));
|
||||
Predicate tempPredicate = builder.conjunction();
|
||||
String[] names = StringUtils.split(fc.getAttrName(), ".");
|
||||
Class curClass = clazz;
|
||||
Path expression = root.get(names[0]);
|
||||
for (int j = 1; j < names.length; j++) {
|
||||
expression = expression.get(names[j]);
|
||||
}
|
||||
try {
|
||||
if (names.length > 1) {
|
||||
curClass = getCurrentClass(names, curClass);
|
||||
}
|
||||
tempPredicate = buildFilterConditon(fc, expression, curClass, builder);
|
||||
} catch (Exception e) {
|
||||
log.warning("查询字段" + fc.getAttrName() + "语法错误:" + e.getMessage());
|
||||
}
|
||||
if (express.getRelation() == ConditionRelate.and) {
|
||||
if (resultPredicate == null) {
|
||||
resultPredicate = tempPredicate;
|
||||
} else {
|
||||
resultPredicate = builder.and(resultPredicate, tempPredicate);
|
||||
}
|
||||
} else {
|
||||
if (resultPredicate == null) {
|
||||
resultPredicate = tempPredicate;
|
||||
} else {
|
||||
resultPredicate = builder.or(resultPredicate, tempPredicate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (express.getSubExpress().size() > 0) {
|
||||
for (int i = 1; i <= express.getSubExpress().size(); i++) {
|
||||
if (express.getRelation() == ConditionRelate.and) {
|
||||
if (resultPredicate == null) {
|
||||
resultPredicate = buildSubSpec(root, express.getSubExpress().get(String.valueOf(i)), builder);
|
||||
} else {
|
||||
resultPredicate = builder.and(resultPredicate, buildSubSpec(root, express.getSubExpress().get(String.valueOf(i)), builder));
|
||||
}
|
||||
} else {
|
||||
if (resultPredicate == null) {
|
||||
resultPredicate = buildSubSpec(root, express.getSubExpress().get(String.valueOf(i)), builder);
|
||||
} else {
|
||||
resultPredicate = builder.or(resultPredicate, buildSubSpec(root, express.getSubExpress().get(String.valueOf(i)), builder));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return resultPredicate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
|
||||
Predicate resultPredicate = builder.conjunction();
|
||||
if (c.getExpress() != null) {
|
||||
resultPredicate = buildSubSpec(root, c.getExpress(), builder);
|
||||
}
|
||||
return builder.and(spec.toPredicate(root, query, builder), resultPredicate);
|
||||
}
|
||||
|
||||
private Class getCurrentClass(String[] names, Class clazz) throws Exception {
|
||||
Field field = clazz.getDeclaredField(names[0]);
|
||||
Class res = field.getType();
|
||||
if (names.length == 2) {
|
||||
return res;
|
||||
} else {
|
||||
return getCurrentClass(Arrays.copyOfRange(names, 1, names.length), res);
|
||||
}
|
||||
}
|
||||
|
||||
private Predicate buildFilterConditon(final FilterCondition fc, final Path expression, Class<T> clazz, final CriteriaBuilder builder) throws Exception {
|
||||
Predicate predicate = builder.conjunction();
|
||||
String filedName = fc.getAttrName();
|
||||
int pos = filedName.lastIndexOf(".");
|
||||
if (pos > 0) {
|
||||
filedName = filedName.substring(pos + 1);
|
||||
}
|
||||
Field field = clazz.getDeclaredField(filedName);
|
||||
Class fieldClass = field.getType();
|
||||
|
||||
if (ClassUtils.isPrimitiveOrWrapper(fieldClass)) {
|
||||
switch (Operation.valueOf(fc.getOperation())) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, fc.getVal());
|
||||
break;
|
||||
case in:
|
||||
predicate = builder.gt(expression, NumberUtils.createNumber(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lt(expression, NumberUtils.createNumber(fc.getEndVal())));
|
||||
break;
|
||||
case inr:
|
||||
predicate = builder.gt(expression, NumberUtils.createNumber(fc.getStartVal()));
|
||||
predicate = builder.and(builder.le(expression, NumberUtils.createNumber(fc.getEndVal())));
|
||||
break;
|
||||
case linr:
|
||||
predicate = builder.ge(expression, NumberUtils.createNumber(fc.getStartVal()));
|
||||
predicate = builder.and(builder.le(expression, NumberUtils.createNumber(fc.getEndVal())));
|
||||
break;
|
||||
case lin:
|
||||
predicate = builder.ge(expression, NumberUtils.createNumber(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lt(expression, NumberUtils.createNumber(fc.getEndVal())));
|
||||
break;
|
||||
case gt:
|
||||
predicate = builder.gt(expression, NumberUtils.createNumber(fc.getVal()));
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.ge(expression, NumberUtils.createNumber(fc.getVal()));
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lt(expression, NumberUtils.createNumber(fc.getVal()));
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.le(expression, NumberUtils.createNumber(fc.getVal()));
|
||||
break;
|
||||
case like:
|
||||
throw new Exception("数字类型字段不能相似操作!");
|
||||
case eq:
|
||||
predicate = builder.equal(expression, fc.getVal());
|
||||
break;
|
||||
}
|
||||
} else if (fieldClass.getName().endsWith("Date")) {
|
||||
// 日期处理
|
||||
switch (Operation.valueOf(String.valueOf(fc.getOperation()))) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case in:
|
||||
predicate = builder.greaterThan(expression, (Comparable) DateUtil.parseDate(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lessThan(expression, (Comparable) DateUtil.parseDate(fc.getEndVal())));
|
||||
break;
|
||||
case inr:
|
||||
predicate = builder.greaterThan(expression, (Comparable) DateUtil.parseDate(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lessThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getEndVal())));
|
||||
break;
|
||||
case linr:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lessThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getEndVal())));
|
||||
break;
|
||||
case lin:
|
||||
predicate = builder.greaterThan(expression, (Comparable) DateUtil.parseDate(fc.getStartVal()));
|
||||
predicate = builder.and(builder.lessThan(expression, (Comparable) DateUtil.parseDate(fc.getEndVal())));
|
||||
break;
|
||||
case gt:
|
||||
predicate = builder.greaterThan(expression, (Comparable) DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lessThan(expression, (Comparable) DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.lessThanOrEqualTo(expression, (Comparable) DateUtil.parseDate(fc.getVal()));
|
||||
break;
|
||||
case like:
|
||||
throw new Exception("日期类型字段不能相似操作!");
|
||||
case eq:
|
||||
predicate = builder.equal(expression, fc.getVal());
|
||||
case emp:
|
||||
predicate = builder.isNull(expression);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
switch (Operation.valueOf(String.valueOf(fc.getOperation()))) {
|
||||
case neq:
|
||||
predicate = builder.notEqual(expression, fc.getVal());
|
||||
break;
|
||||
case in:
|
||||
predicate = builder.greaterThan(expression, (Comparable) fc.getStartVal());
|
||||
predicate = builder.and(builder.lessThan(expression, (Comparable) fc.getEndVal()));
|
||||
break;
|
||||
case inr:
|
||||
predicate = builder.greaterThan(expression, (Comparable) fc.getStartVal());
|
||||
predicate = builder.and(builder.lessThanOrEqualTo(expression, (Comparable) fc.getEndVal()));
|
||||
break;
|
||||
case linr:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) fc.getStartVal());
|
||||
predicate = builder.and(builder.lessThanOrEqualTo(expression, (Comparable) fc.getEndVal()));
|
||||
break;
|
||||
case lin:
|
||||
predicate = builder.greaterThan(expression, (Comparable) fc.getStartVal());
|
||||
predicate = builder.and(builder.lessThan(expression, (Comparable) fc.getEndVal()));
|
||||
break;
|
||||
case gt:
|
||||
predicate = builder.greaterThan(expression, (Comparable) fc.getVal());
|
||||
break;
|
||||
case ge:
|
||||
predicate = builder.greaterThanOrEqualTo(expression, (Comparable) fc.getVal());
|
||||
break;
|
||||
case lt:
|
||||
predicate = builder.lessThan(expression, (Comparable) fc.getVal());
|
||||
break;
|
||||
case le:
|
||||
predicate = builder.lessThanOrEqualTo(expression, (Comparable) fc.getVal());
|
||||
break;
|
||||
case like:
|
||||
predicate = builder.like(expression, "%" + fc.getVal() + "%");
|
||||
break;
|
||||
case llike:
|
||||
predicate = builder.like(expression, "%" + fc.getVal());
|
||||
break;
|
||||
case rlike:
|
||||
predicate = builder.like(expression, fc.getVal() + "%");
|
||||
break;
|
||||
case eq:
|
||||
predicate = builder.equal(expression, fc.getVal());
|
||||
break;
|
||||
}
|
||||
}
|
||||
return predicate;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
26
ndplan/src/main/java/com/system/util/jpa/Operation.java
Normal file
26
ndplan/src/main/java/com/system/util/jpa/Operation.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
/**
|
||||
*
|
||||
* 查询操作标识
|
||||
*
|
||||
*/
|
||||
public enum Operation {
|
||||
linr, // 区间包括两点,
|
||||
in, // 区间不包括两点,
|
||||
lin, // 区间包括起始不包括终点,
|
||||
inr, // 区间不包括起始包括终点,
|
||||
eq, // 相等,
|
||||
/**
|
||||
* like 操作符
|
||||
*/
|
||||
like, // 相似,%+fieldValue+%
|
||||
llike, // 左相似,%+fieldValue
|
||||
rlike, // 右边相似,fieldValue+%
|
||||
lt, // 小于,
|
||||
le, // 小于等于,
|
||||
gt, // 大于,
|
||||
ge, // 大于等于,
|
||||
neq,// 不等于
|
||||
emp // 等于NULL
|
||||
}
|
||||
15
ndplan/src/main/java/com/system/util/jpa/Order.java
Normal file
15
ndplan/src/main/java/com/system/util/jpa/Order.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
/**
|
||||
* 排序<br/>
|
||||
*/
|
||||
public enum Order {
|
||||
/**
|
||||
* 顺序 取文字
|
||||
*/
|
||||
asc,
|
||||
/**
|
||||
* 倒序 取文字
|
||||
*/
|
||||
desc
|
||||
}
|
||||
35
ndplan/src/main/java/com/system/util/jpa/OrderCondition.java
Normal file
35
ndplan/src/main/java/com/system/util/jpa/OrderCondition.java
Normal file
@@ -0,0 +1,35 @@
|
||||
package com.system.util.jpa;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 排序条件<br/>
|
||||
*/
|
||||
@Data
|
||||
public class OrderCondition {
|
||||
|
||||
/**
|
||||
* 要排序的属性名称
|
||||
*/
|
||||
private String attrName;
|
||||
/**
|
||||
* 排序方向
|
||||
* 来源:Order
|
||||
*/
|
||||
private String order;
|
||||
/**
|
||||
* 排序号
|
||||
* 当前属性排序位置,数字越小,越靠前
|
||||
*/
|
||||
private Integer sortNo;
|
||||
|
||||
public OrderCondition() {
|
||||
}
|
||||
|
||||
public OrderCondition(String attrName,String order,Integer sortNo ){
|
||||
this.attrName = attrName;
|
||||
this.order = order;
|
||||
this.sortNo = sortNo;
|
||||
}
|
||||
|
||||
}
|
||||
967
ndplan/src/main/java/com/system/util/json/BaseJSON.java
Normal file
967
ndplan/src/main/java/com/system/util/json/BaseJSON.java
Normal file
@@ -0,0 +1,967 @@
|
||||
package com.system.util.json;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONAware;
|
||||
import com.alibaba.fastjson.JSONException;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alibaba.fastjson.JSONStreamAware;
|
||||
import com.alibaba.fastjson.TypeReference;
|
||||
import com.alibaba.fastjson.parser.DefaultJSONParser;
|
||||
import com.alibaba.fastjson.parser.DefaultJSONParser.ResolveTask;
|
||||
import com.alibaba.fastjson.parser.Feature;
|
||||
import com.alibaba.fastjson.parser.JSONLexer;
|
||||
import com.alibaba.fastjson.parser.JSONToken;
|
||||
import com.alibaba.fastjson.parser.ParserConfig;
|
||||
import com.alibaba.fastjson.parser.deserializer.FieldDeserializer;
|
||||
import com.alibaba.fastjson.serializer.NameFilter;
|
||||
import com.alibaba.fastjson.serializer.PropertyFilter;
|
||||
import com.alibaba.fastjson.serializer.PropertyPreFilter;
|
||||
import com.alibaba.fastjson.serializer.SerializeConfig;
|
||||
import com.alibaba.fastjson.serializer.SerializeFilter;
|
||||
import com.alibaba.fastjson.serializer.SerializeWriter;
|
||||
import com.alibaba.fastjson.serializer.SerializerFeature;
|
||||
import com.alibaba.fastjson.serializer.ValueFilter;
|
||||
import com.alibaba.fastjson.util.FieldInfo;
|
||||
import com.alibaba.fastjson.util.IOUtils;
|
||||
import com.alibaba.fastjson.util.ThreadLocalCache;
|
||||
import com.alibaba.fastjson.util.TypeUtils;
|
||||
|
||||
public abstract class BaseJSON implements JSONStreamAware, JSONAware {
|
||||
|
||||
public static String DEFAULT_TYPE_KEY = "@type";
|
||||
private static Logger Log = LoggerFactory.getLogger(BaseJSON.class);
|
||||
|
||||
public static int DEFAULT_PARSER_FEATURE;
|
||||
static {
|
||||
int features = 0;
|
||||
features |= Feature.AutoCloseSource.getMask();
|
||||
features |= Feature.InternFieldNames.getMask();
|
||||
features |= Feature.UseBigDecimal.getMask();
|
||||
features |= Feature.AllowUnQuotedFieldNames.getMask();
|
||||
features |= Feature.AllowSingleQuotes.getMask();
|
||||
features |= Feature.AllowArbitraryCommas.getMask();
|
||||
features |= Feature.SortFeidFastMatch.getMask();
|
||||
features |= Feature.IgnoreNotMatch.getMask();
|
||||
DEFAULT_PARSER_FEATURE = features;
|
||||
}
|
||||
|
||||
public static String DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
public static int DEFAULT_GENERATE_FEATURE;
|
||||
static {
|
||||
int features = 0;
|
||||
features |= com.alibaba.fastjson.serializer.SerializerFeature.QuoteFieldNames
|
||||
.getMask();
|
||||
features |= com.alibaba.fastjson.serializer.SerializerFeature.SkipTransientField
|
||||
.getMask();
|
||||
features |= com.alibaba.fastjson.serializer.SerializerFeature.WriteEnumUsingToString
|
||||
.getMask();
|
||||
features |= com.alibaba.fastjson.serializer.SerializerFeature.SortField
|
||||
.getMask();
|
||||
// features |=
|
||||
// com.alibaba.fastjson.serializer.SerializerFeature.WriteSlashAsSpecial.getMask();
|
||||
DEFAULT_GENERATE_FEATURE = features;
|
||||
}
|
||||
|
||||
public static final Object parse(String text) {
|
||||
return parse(text, DEFAULT_PARSER_FEATURE);
|
||||
}
|
||||
|
||||
public static final Object parse(String text, int features) {
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
DefaultJSONParser parser = new DefaultJSONParser(text,
|
||||
ParserConfig.getGlobalInstance(), features);
|
||||
Object value = parser.parse();
|
||||
|
||||
handleResovleTask(parser, value);
|
||||
|
||||
parser.close();
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public static final Object parse(byte[] input, Feature... features) {
|
||||
return parse(input, 0, input.length, ThreadLocalCache.getUTF8Decoder(),
|
||||
features);
|
||||
}
|
||||
|
||||
public static final Object parse(byte[] input, int off, int len,
|
||||
CharsetDecoder charsetDecoder, Feature... features) {
|
||||
if (input == null || input.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int featureValues = DEFAULT_PARSER_FEATURE;
|
||||
for (Feature featrue : features) {
|
||||
featureValues = Feature.config(featureValues, featrue, true);
|
||||
}
|
||||
|
||||
return parse(input, off, len, charsetDecoder, featureValues);
|
||||
}
|
||||
|
||||
public static final Object parse(byte[] input, int off, int len,
|
||||
CharsetDecoder charsetDecoder, int features) {
|
||||
charsetDecoder.reset();
|
||||
|
||||
int scaleLength = (int) (len * (double) charsetDecoder
|
||||
.maxCharsPerByte());
|
||||
char[] chars = ThreadLocalCache.getChars(scaleLength);
|
||||
|
||||
ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len);
|
||||
CharBuffer charBuf = CharBuffer.wrap(chars);
|
||||
IOUtils.decode(charsetDecoder, byteBuf, charBuf);
|
||||
|
||||
int position = charBuf.position();
|
||||
|
||||
DefaultJSONParser parser = new DefaultJSONParser(chars, position,
|
||||
ParserConfig.getGlobalInstance(), features);
|
||||
Object value = parser.parse();
|
||||
|
||||
handleResovleTask(parser, value);
|
||||
|
||||
parser.close();
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public static final Object parse(String text, Feature... features) {
|
||||
int featureValues = DEFAULT_PARSER_FEATURE;
|
||||
for (Feature featrue : features) {
|
||||
featureValues = Feature.config(featureValues, featrue, true);
|
||||
}
|
||||
|
||||
return parse(text, featureValues);
|
||||
}
|
||||
|
||||
public static final JSONObject parseObject(String text, Feature... features) {
|
||||
return (JSONObject) parse(text, features);
|
||||
}
|
||||
|
||||
public static final JSONObject parseObject(String text) {
|
||||
Object obj = parse(text);
|
||||
if (obj instanceof JSONObject) {
|
||||
return (JSONObject) obj;
|
||||
}
|
||||
|
||||
return (JSONObject) BaseJSON.toJSON(obj);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> T parseObject(String text, TypeReference<T> type,
|
||||
Feature... features) {
|
||||
return (T) parseObject(text, type.getType(),
|
||||
ParserConfig.getGlobalInstance(), DEFAULT_PARSER_FEATURE,
|
||||
features);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> T parseObject(String text, Class<T> clazz,
|
||||
Feature... features) {
|
||||
return (T) parseObject(text, (Type) clazz,
|
||||
ParserConfig.getGlobalInstance(), DEFAULT_PARSER_FEATURE,
|
||||
features);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> T parseObject(String input, Type clazz,
|
||||
Feature... features) {
|
||||
return (T) parseObject(input, clazz, ParserConfig.getGlobalInstance(),
|
||||
DEFAULT_PARSER_FEATURE, features);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> T parseObject(String input, Type clazz,
|
||||
int featureValues, Feature... features) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (Feature featrue : features) {
|
||||
featureValues = Feature.config(featureValues, featrue, true);
|
||||
}
|
||||
|
||||
DefaultJSONParser parser = new DefaultJSONParser(input,
|
||||
ParserConfig.getGlobalInstance(), featureValues);
|
||||
T value = (T) parser.parseObject(clazz);
|
||||
|
||||
handleResovleTask(parser, value);
|
||||
|
||||
parser.close();
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> T parseObject(String input, Type clazz,
|
||||
ParserConfig config, int featureValues, Feature... features) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (Feature featrue : features) {
|
||||
featureValues = Feature.config(featureValues, featrue, true);
|
||||
}
|
||||
|
||||
DefaultJSONParser parser = new DefaultJSONParser(input, config,
|
||||
featureValues);
|
||||
T value = (T) parser.parseObject(clazz);
|
||||
|
||||
handleResovleTask(parser, value);
|
||||
|
||||
parser.close();
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public static <T> int handleResovleTask(DefaultJSONParser parser, T value) {
|
||||
int size = parser.getResolveTaskList().size();
|
||||
for (int i = 0; i < size; ++i) {
|
||||
ResolveTask task = parser.getResolveTaskList().get(i);
|
||||
FieldDeserializer fieldDeser = task.getFieldDeserializer();
|
||||
|
||||
Object object = null;
|
||||
if (task.getOwnerContext() != null) {
|
||||
object = task.getOwnerContext().getObject();
|
||||
}
|
||||
|
||||
String ref = task.getReferenceValue();
|
||||
Object refValue;
|
||||
if (ref.startsWith("$")) {
|
||||
refValue = parser.getObject(ref);
|
||||
} else {
|
||||
refValue = task.getContext().getObject();
|
||||
}
|
||||
fieldDeser.setValue(object, refValue);
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> T parseObject(byte[] input, Type clazz,
|
||||
Feature... features) {
|
||||
return (T) parseObject(input, 0, input.length,
|
||||
ThreadLocalCache.getUTF8Decoder(), clazz, features);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> T parseObject(byte[] input, int off, int len,
|
||||
CharsetDecoder charsetDecoder, Type clazz, Feature... features) {
|
||||
charsetDecoder.reset();
|
||||
|
||||
int scaleLength = (int) (len * (double) charsetDecoder
|
||||
.maxCharsPerByte());
|
||||
char[] chars = ThreadLocalCache.getChars(scaleLength);
|
||||
|
||||
ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len);
|
||||
CharBuffer charByte = CharBuffer.wrap(chars);
|
||||
IOUtils.decode(charsetDecoder, byteBuf, charByte);
|
||||
|
||||
int position = charByte.position();
|
||||
|
||||
return (T) parseObject(chars, position, clazz, features);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> T parseObject(char[] input, int length, Type clazz,
|
||||
Feature... features) {
|
||||
if (input == null || input.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int featureValues = DEFAULT_PARSER_FEATURE;
|
||||
for (Feature featrue : features) {
|
||||
featureValues = Feature.config(featureValues, featrue, true);
|
||||
}
|
||||
|
||||
DefaultJSONParser parser = new DefaultJSONParser(input, length,
|
||||
ParserConfig.getGlobalInstance(), featureValues);
|
||||
T value = (T) parser.parseObject(clazz);
|
||||
|
||||
handleResovleTask(parser, value);
|
||||
|
||||
parser.close();
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public static final <T> T parseObject(String text, Class<T> clazz) {
|
||||
return parseObject(text, clazz, new Feature[0]);
|
||||
}
|
||||
|
||||
public static final JSONArray parseArray(String text) {
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
DefaultJSONParser parser = new DefaultJSONParser(text,
|
||||
ParserConfig.getGlobalInstance());
|
||||
|
||||
JSONArray array;
|
||||
|
||||
JSONLexer lexer = parser.getLexer();
|
||||
if (lexer.token() == JSONToken.NULL) {
|
||||
lexer.nextToken();
|
||||
array = null;
|
||||
} else if (lexer.token() == JSONToken.EOF) {
|
||||
array = null;
|
||||
} else {
|
||||
array = new JSONArray();
|
||||
parser.parseArray(array);
|
||||
|
||||
handleResovleTask(parser, array);
|
||||
}
|
||||
|
||||
parser.close();
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
public static final <T> List<T> parseArray(String text, Class<T> clazz) {
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<T> list;
|
||||
|
||||
DefaultJSONParser parser = new DefaultJSONParser(text,
|
||||
ParserConfig.getGlobalInstance());
|
||||
JSONLexer lexer = parser.getLexer();
|
||||
if (lexer.token() == JSONToken.NULL) {
|
||||
lexer.nextToken();
|
||||
list = null;
|
||||
} else {
|
||||
list = new ArrayList<T>();
|
||||
parser.parseArray(clazz, list);
|
||||
|
||||
handleResovleTask(parser, list);
|
||||
}
|
||||
|
||||
parser.close();
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static final List<Object> parseArray(String text, Type[] types) {
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<Object> list;
|
||||
|
||||
DefaultJSONParser parser = new DefaultJSONParser(text,
|
||||
ParserConfig.getGlobalInstance());
|
||||
Object[] objectArray = parser.parseArray(types);
|
||||
if (objectArray == null) {
|
||||
list = null;
|
||||
} else {
|
||||
list = Arrays.asList(objectArray);
|
||||
}
|
||||
|
||||
handleResovleTask(parser, list);
|
||||
|
||||
parser.close();
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
// ======================
|
||||
|
||||
public static final String toJSONString(Object object) {
|
||||
return toJSONString(object, new SerializerFeature[0]);
|
||||
}
|
||||
|
||||
public static final String toJSONString(Object object,
|
||||
SerializerFeature... features) {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out);
|
||||
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
|
||||
serializer.getPropertyFilters().add(filter);
|
||||
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
|
||||
serializer.config(feature, true);
|
||||
}
|
||||
|
||||
serializer.write(object);
|
||||
|
||||
return out.toString();
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 1.1.14
|
||||
*/
|
||||
public static final String toJSONStringWithDateFormat(Object object,
|
||||
String dateFormat, SerializerFeature... features) {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out);
|
||||
serializer.getPropertyFilters().add(filter);
|
||||
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
|
||||
serializer.config(feature, true);
|
||||
}
|
||||
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
|
||||
if (dateFormat != null) {
|
||||
serializer.setDateFormat(dateFormat);
|
||||
}
|
||||
serializer.write(object);
|
||||
|
||||
return out.toString();
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static final String toJSONString(Object object,
|
||||
SerializeFilter filter, SerializerFeature... features) {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out);
|
||||
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
|
||||
serializer.config(feature, true);
|
||||
}
|
||||
|
||||
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
|
||||
serializer.setDateFormat(DATEFORMATE);
|
||||
if (filter != null) {
|
||||
if (filter instanceof PropertyPreFilter) {
|
||||
serializer.getPropertyPreFilters().add(
|
||||
(PropertyPreFilter) filter);
|
||||
}
|
||||
|
||||
if (filter instanceof NameFilter) {
|
||||
serializer.getNameFilters().add((NameFilter) filter);
|
||||
}
|
||||
|
||||
if (filter instanceof ValueFilter) {
|
||||
serializer.getValueFilters().add((ValueFilter) filter);
|
||||
}
|
||||
|
||||
if (filter instanceof PropertyFilter) {
|
||||
serializer.getPropertyFilters()
|
||||
.add((PropertyFilter) filter);
|
||||
}
|
||||
}
|
||||
|
||||
serializer.write(object);
|
||||
|
||||
return out.toString();
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤object的属性值 <br/>
|
||||
* 如A:{b:{name:"",no:""},name:""} 序列化A的实例时只序列号a和b的名称 表达式:{name,b{name}}
|
||||
*
|
||||
* @param object
|
||||
* @param filterStr
|
||||
* @return String
|
||||
*/
|
||||
public static final String toJSONString(Object object, String filterStr) {
|
||||
return toJSONString(object, filterStr, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤object的属性值 <br/>
|
||||
* 如A:{b:{name:"",no:""},name:""} 序列化A的实例时过滤a和b的名称 表达式:{name,b{name}}
|
||||
*
|
||||
* @param object
|
||||
* @param filterStr
|
||||
* @param flag
|
||||
* 过滤开关
|
||||
* @return String
|
||||
*/
|
||||
public static final String toJSONString(Object object, String filterStr,
|
||||
boolean flag) {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out);
|
||||
|
||||
if (filter != null) {
|
||||
if (filter instanceof PropertyPreFilter) {
|
||||
serializer.getPropertyPreFilters().add(
|
||||
(PropertyPreFilter) filter);
|
||||
}
|
||||
|
||||
if (filter instanceof NameFilter) {
|
||||
serializer.getNameFilters().add((NameFilter) filter);
|
||||
}
|
||||
|
||||
if (filter instanceof ValueFilter) {
|
||||
serializer.getValueFilters().add((ValueFilter) filter);
|
||||
}
|
||||
|
||||
if (filter instanceof PropertyFilter) {
|
||||
serializer.getPropertyFilters()
|
||||
.add((PropertyFilter) filter);
|
||||
}
|
||||
}
|
||||
if (!StringUtils.isEmpty(filterStr)) {
|
||||
String[] strs = parseFillterJson(filterStr, flag);
|
||||
if (flag == true) {
|
||||
strs = processFillterJson(strs);
|
||||
}
|
||||
|
||||
serializer.getPropertyPreFilters().add(
|
||||
new BasePropertyPreFilter(strs, flag));
|
||||
}
|
||||
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
|
||||
serializer.config(SerializerFeature.WriteNullStringAsEmpty, true);
|
||||
serializer.config(SerializerFeature.PrettyFormat, true);
|
||||
serializer.setDateFormat(DATEFORMATE);
|
||||
// serializer.config(SerializerFeature.PrettyFormat, true);
|
||||
// for (com.alibaba.fastjson.serializer.SerializerFeature feature :
|
||||
// features) {
|
||||
// }
|
||||
serializer.write(object);
|
||||
|
||||
return out.toString();
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static final String toFilterJSONString(Object object,
|
||||
String filterStr, SerializerFeature... features) {
|
||||
return toFilterJSONString(object, filterStr, true, features);
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤object的属性值 <br/>
|
||||
* 如A:{b:{name:"",no:""},name:""} 序列化A的实例时过滤a和b的名称 表达式:{name,b{name}}
|
||||
*
|
||||
* @param object
|
||||
* @param filterStr
|
||||
* @param flag true 只留下序列化A的实例时过滤a和b的名称 false 与true相反
|
||||
* @param features
|
||||
* @return String
|
||||
*/
|
||||
public static final String toFilterJSONString(Object object,
|
||||
String filterStr, boolean flag, SerializerFeature... features) {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out);
|
||||
|
||||
if (filter != null) {
|
||||
if (filter instanceof PropertyPreFilter) {
|
||||
serializer.getPropertyPreFilters().add(
|
||||
(PropertyPreFilter) filter);
|
||||
}
|
||||
|
||||
if (filter instanceof NameFilter) {
|
||||
serializer.getNameFilters().add((NameFilter) filter);
|
||||
}
|
||||
|
||||
if (filter instanceof ValueFilter) {
|
||||
serializer.getValueFilters().add((ValueFilter) filter);
|
||||
}
|
||||
|
||||
if (filter instanceof PropertyFilter) {
|
||||
serializer.getPropertyFilters()
|
||||
.add((PropertyFilter) filter);
|
||||
}
|
||||
}
|
||||
|
||||
if (!StringUtils.isEmpty(filterStr)) {
|
||||
String[] strs = parseFillterJson(filterStr, flag);
|
||||
if (flag == true) {
|
||||
strs = processFillterJson(strs);
|
||||
}
|
||||
|
||||
serializer.getPropertyPreFilters().add(
|
||||
new BasePropertyPreFilter(strs, flag));
|
||||
}
|
||||
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
|
||||
serializer.config(feature, true);
|
||||
}
|
||||
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
|
||||
serializer.config(SerializerFeature.WriteNullStringAsEmpty, true);
|
||||
// serializer.config(SerializerFeature.PrettyFormat, true);
|
||||
serializer.setDateFormat(DATEFORMATE);
|
||||
// serializer.config(SerializerFeature.PrettyFormat, true);
|
||||
// for (com.alibaba.fastjson.serializer.SerializerFeature feature :
|
||||
// features) {
|
||||
// }
|
||||
serializer.write(object);
|
||||
|
||||
return out.toString();
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static final byte[] toJSONBytes(Object object,
|
||||
SerializerFeature... features) {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out);
|
||||
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
|
||||
serializer.config(feature, true);
|
||||
}
|
||||
|
||||
serializer.write(object);
|
||||
|
||||
return out.toBytes("UTF-8");
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static final String toJSONString(Object object,
|
||||
SerializeConfig config, SerializerFeature... features) {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out, config);
|
||||
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
|
||||
serializer.config(feature, true);
|
||||
}
|
||||
|
||||
serializer.write(object);
|
||||
|
||||
return out.toString();
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static final String toJSONStringZ(Object object,
|
||||
SerializeConfig mapping, SerializerFeature... features) {
|
||||
SerializeWriter out = new SerializeWriter(features);
|
||||
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out, mapping);
|
||||
|
||||
serializer.write(object);
|
||||
|
||||
return out.toString();
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static final byte[] toJSONBytes(Object object,
|
||||
SerializeConfig config, SerializerFeature... features) {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out, config);
|
||||
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
|
||||
serializer.config(feature, true);
|
||||
}
|
||||
|
||||
serializer.write(object);
|
||||
|
||||
return out.toBytes("UTF-8");
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
public static final String toJSONString(Object object, boolean prettyFormat) {
|
||||
if (!prettyFormat) {
|
||||
return toJSONString(object);
|
||||
}
|
||||
|
||||
return toJSONString(object, SerializerFeature.PrettyFormat);
|
||||
}
|
||||
|
||||
public static final void writeJSONStringTo(Object object, Writer writer,
|
||||
SerializerFeature... features) {
|
||||
SerializeWriter out = new SerializeWriter(writer);
|
||||
|
||||
try {
|
||||
BaseJSONSerializer serializer = new BaseJSONSerializer(out);
|
||||
for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
|
||||
serializer.config(feature, true);
|
||||
}
|
||||
|
||||
serializer.write(object);
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
// ======================================
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return toJSONString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toJSONString() {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
try {
|
||||
new BaseJSONSerializer(out).write(this);
|
||||
return out.toString();
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeJSONString(Appendable appendable) {
|
||||
SerializeWriter out = new SerializeWriter();
|
||||
try {
|
||||
new BaseJSONSerializer(out).write(this);
|
||||
appendable.append(out.toString());
|
||||
} catch (IOException e) {
|
||||
throw new JSONException(e.getMessage(), e);
|
||||
} finally {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
// ///////
|
||||
|
||||
public static final Object toJSON(Object javaObject) {
|
||||
return toJSON(javaObject, ParserConfig.getGlobalInstance());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final Object toJSON(Object javaObject, ParserConfig mapping) {
|
||||
if (javaObject == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (javaObject instanceof BaseJSON) {
|
||||
return javaObject;
|
||||
}
|
||||
|
||||
if (javaObject instanceof Map) {
|
||||
Map<Object, Object> map = (Map<Object, Object>) javaObject;
|
||||
|
||||
JSONObject json = new JSONObject(map.size());
|
||||
|
||||
for (Map.Entry<Object, Object> entry : map.entrySet()) {
|
||||
Object key = entry.getKey();
|
||||
String jsonKey = TypeUtils.castToString(key);
|
||||
Object jsonValue = toJSON(entry.getValue());
|
||||
json.put(jsonKey, jsonValue);
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
if (javaObject instanceof Collection) {
|
||||
Collection<Object> collection = (Collection<Object>) javaObject;
|
||||
|
||||
JSONArray array = new JSONArray(collection.size());
|
||||
|
||||
for (Object item : collection) {
|
||||
Object jsonValue = toJSON(item);
|
||||
array.add(jsonValue);
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
Class<?> clazz = javaObject.getClass();
|
||||
|
||||
if (clazz.isEnum()) {
|
||||
return ((Enum<?>) javaObject).name();
|
||||
}
|
||||
|
||||
if (clazz.isArray()) {
|
||||
int len = Array.getLength(javaObject);
|
||||
|
||||
JSONArray array = new JSONArray(len);
|
||||
|
||||
for (int i = 0; i < len; ++i) {
|
||||
Object item = Array.get(javaObject, i);
|
||||
Object jsonValue = toJSON(item);
|
||||
array.add(jsonValue);
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
if (mapping.isPrimitive(clazz)) {
|
||||
return javaObject;
|
||||
}
|
||||
|
||||
try {
|
||||
List<FieldInfo> getters = TypeUtils.computeGetters(clazz, null);
|
||||
|
||||
JSONObject json = new JSONObject(getters.size());
|
||||
|
||||
for (FieldInfo field : getters) {
|
||||
Object value = field.get(javaObject);
|
||||
Object jsonValue = toJSON(value);
|
||||
|
||||
json.put(field.getName(), jsonValue);
|
||||
}
|
||||
|
||||
return json;
|
||||
} catch (Exception e) {
|
||||
throw new JSONException("toJSON error", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static final <T> T toJavaObject(BaseJSON json, Class<T> clazz) {
|
||||
return TypeUtils.cast(json, clazz, ParserConfig.getGlobalInstance());
|
||||
}
|
||||
|
||||
public final static String VERSION = "1.1.33";
|
||||
public final static String DATEFORMATE = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
private static ValueFilter valueFilter = new ValueFilter() {
|
||||
|
||||
@Override
|
||||
public Object process(Object source, String name, Object value) {
|
||||
if (value == null) {
|
||||
return false;
|
||||
} else if ("java.lang.Object".equals(value.getClass().getName())) {
|
||||
if (StringUtils.isEmpty(value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
private static PropertyFilter filter = new PropertyFilter() {
|
||||
@Override
|
||||
public boolean apply(Object source, String name, Object value) {
|
||||
boolean result = true;
|
||||
try {
|
||||
if (Map.class.isInstance(source)) {
|
||||
return true;
|
||||
} else {
|
||||
Field field = null;
|
||||
Field[] fields = source.getClass().getDeclaredFields();
|
||||
if (!"java.lang.Object".equals(source.getClass()
|
||||
.getSuperclass().getName())) {
|
||||
fields = ArrayUtils.addAll(fields, source.getClass()
|
||||
.getSuperclass().getDeclaredFields());
|
||||
}
|
||||
|
||||
if (fields != null && fields.length > 0) {
|
||||
for (Field f : fields) {
|
||||
if (f.getName().equals(name)) {
|
||||
field = f;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (field != null
|
||||
&& field.isAnnotationPresent(JSONFilter.class)) {
|
||||
result = false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.error("error:" + name + ":" + value);
|
||||
// Log.error(Exceptions.getStackTraceAsString(e));
|
||||
}
|
||||
return result;
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
public static String[] parseFillterJson(String str, boolean flag) {
|
||||
List<String> res = new LinkedList<String>();
|
||||
String path = "";
|
||||
char[] chs = str.toCharArray();
|
||||
StringBuffer temp = new StringBuffer();
|
||||
for (int i = 0; i < chs.length; i++) {
|
||||
if (chs[i] == '{') {
|
||||
if (i == 0) {
|
||||
continue;
|
||||
}
|
||||
if (path.length() > 0) {
|
||||
path = path + "." + temp.toString().trim();
|
||||
if (flag) {
|
||||
res.add(path);
|
||||
}
|
||||
} else {
|
||||
path = temp.toString().trim();
|
||||
}
|
||||
temp = new StringBuffer();
|
||||
} else if (chs[i] == '}') {
|
||||
if (temp.toString().trim().length() > 0) {
|
||||
if (path.length() > 0) {
|
||||
res.add(path + "." + temp.toString().trim());
|
||||
} else {
|
||||
res.add(temp.toString().trim());
|
||||
}
|
||||
}
|
||||
if (path.lastIndexOf(".") > 0) {
|
||||
path = path.substring(0, path.lastIndexOf("."));
|
||||
} else {
|
||||
path = "";
|
||||
}
|
||||
temp = new StringBuffer();
|
||||
} else if (chs[i] == ',') {
|
||||
if (temp.toString().trim().length() > 0) {
|
||||
if (path.length() > 0) {
|
||||
res.add(path + "." + temp.toString().trim());
|
||||
} else {
|
||||
res.add(temp.toString().trim());
|
||||
}
|
||||
}
|
||||
temp = new StringBuffer();
|
||||
} else {
|
||||
temp.append(chs[i]);
|
||||
}
|
||||
}
|
||||
return res.toArray(new String[] {});
|
||||
}
|
||||
|
||||
public static String[] processFillterJson(String[] strs) {
|
||||
HashSet<String> set = new HashSet<String>();
|
||||
for (String str : strs) {
|
||||
int pos = str.lastIndexOf(".");
|
||||
if (pos > 0) {
|
||||
set.add(str.substring(0, pos));
|
||||
}
|
||||
set.add(str);
|
||||
}
|
||||
return set.toArray(new String[] {});
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static final <T> T toObject(String text, Class<T> clazz) {
|
||||
return (T)JSON.parseObject(text, clazz);
|
||||
}
|
||||
|
||||
public static final <T> List<T> toArray(String text, Class<T> clazz) {
|
||||
return (List<T>)JSON.parseArray(text, clazz);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
package com.system.util.json;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.charset.Charset;
|
||||
import java.sql.Clob;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONAware;
|
||||
import com.alibaba.fastjson.JSONStreamAware;
|
||||
import com.alibaba.fastjson.serializer.AppendableSerializer;
|
||||
import com.alibaba.fastjson.serializer.ArraySerializer;
|
||||
import com.alibaba.fastjson.serializer.AutowiredObjectSerializer;
|
||||
import com.alibaba.fastjson.serializer.CalendarSerializer;
|
||||
import com.alibaba.fastjson.serializer.CharsetSerializer;
|
||||
import com.alibaba.fastjson.serializer.ClobSeriliazer;
|
||||
import com.alibaba.fastjson.serializer.CollectionSerializer;
|
||||
import com.alibaba.fastjson.serializer.DateSerializer;
|
||||
import com.alibaba.fastjson.serializer.EnumSerializer;
|
||||
import com.alibaba.fastjson.serializer.EnumerationSeriliazer;
|
||||
import com.alibaba.fastjson.serializer.ExceptionSerializer;
|
||||
import com.alibaba.fastjson.serializer.JSONAwareSerializer;
|
||||
import com.alibaba.fastjson.serializer.JSONSerializer;
|
||||
import com.alibaba.fastjson.serializer.JSONSerializerMap;
|
||||
import com.alibaba.fastjson.serializer.JSONStreamAwareSerializer;
|
||||
import com.alibaba.fastjson.serializer.ListSerializer;
|
||||
import com.alibaba.fastjson.serializer.MapSerializer;
|
||||
import com.alibaba.fastjson.serializer.NameFilter;
|
||||
import com.alibaba.fastjson.serializer.ObjectSerializer;
|
||||
import com.alibaba.fastjson.serializer.PropertyFilter;
|
||||
import com.alibaba.fastjson.serializer.PropertyPreFilter;
|
||||
import com.alibaba.fastjson.serializer.SerialContext;
|
||||
import com.alibaba.fastjson.serializer.SerializeConfig;
|
||||
import com.alibaba.fastjson.serializer.SerializeWriter;
|
||||
import com.alibaba.fastjson.serializer.SerializerFeature;
|
||||
import com.alibaba.fastjson.serializer.TimeZoneSerializer;
|
||||
import com.alibaba.fastjson.serializer.ValueFilter;
|
||||
import com.alibaba.fastjson.util.ServiceLoader;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class BaseJSONSerializer extends JSONSerializer{
|
||||
|
||||
private final SerializeConfig config;
|
||||
|
||||
private final SerializeWriter out;
|
||||
|
||||
private List<PropertyFilter> propertyFilters = null;
|
||||
private List<ValueFilter> valueFilters = null;
|
||||
private List<NameFilter> nameFilters = null;
|
||||
private List<PropertyPreFilter> propertyPreFilters = null;
|
||||
|
||||
private int indentCount = 0;
|
||||
private String indent = "\t";
|
||||
|
||||
private String dateFormatPattern;
|
||||
private DateFormat dateFormat;
|
||||
|
||||
private IdentityHashMap<Object, SerialContext> references = null;
|
||||
private SerialContext context;
|
||||
|
||||
public BaseJSONSerializer(){
|
||||
this(new SerializeWriter(), SerializeConfig.getGlobalInstance());
|
||||
}
|
||||
|
||||
public BaseJSONSerializer(SerializeWriter out){
|
||||
this(out, SerializeConfig.getGlobalInstance());
|
||||
}
|
||||
|
||||
public BaseJSONSerializer(SerializeConfig config){
|
||||
this(new SerializeWriter(), config);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public BaseJSONSerializer(JSONSerializerMap mapping){
|
||||
this(new SerializeWriter(), mapping);
|
||||
}
|
||||
|
||||
public BaseJSONSerializer(SerializeWriter out, SerializeConfig config){
|
||||
this.out = out;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public String getDateFormatPattern() {
|
||||
if (dateFormat instanceof SimpleDateFormat) {
|
||||
return ((SimpleDateFormat) dateFormat).toPattern();
|
||||
}
|
||||
return dateFormatPattern;
|
||||
}
|
||||
|
||||
public DateFormat getDateFormat() {
|
||||
if (dateFormat == null) {
|
||||
if (dateFormatPattern != null) {
|
||||
dateFormat = new SimpleDateFormat(dateFormatPattern);
|
||||
}
|
||||
}
|
||||
|
||||
return dateFormat;
|
||||
}
|
||||
|
||||
public void setDateFormat(DateFormat dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
if (dateFormatPattern != null) {
|
||||
dateFormatPattern = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void setDateFormat(String dateFormat) {
|
||||
this.dateFormatPattern = dateFormat;
|
||||
if (this.dateFormat != null) {
|
||||
this.dateFormat = null;
|
||||
}
|
||||
}
|
||||
|
||||
public SerialContext getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
public void setContext(SerialContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public void setContext(SerialContext parent, Object object, Object fieldName) {
|
||||
if (isEnabled(SerializerFeature.DisableCircularReferenceDetect)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.context = new SerialContext(parent, object, fieldName);
|
||||
if (references == null) {
|
||||
references = new IdentityHashMap<Object, SerialContext>();
|
||||
}
|
||||
this.references.put(object, context);
|
||||
}
|
||||
|
||||
public void setContext(Object object, Object fieldName) {
|
||||
this.setContext(context, object, fieldName);
|
||||
}
|
||||
|
||||
public void popContext() {
|
||||
if (context != null) {
|
||||
this.context = this.context.getParent();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public SerialContext getSerialContext(Object object) {
|
||||
if (references == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return references.get(object);
|
||||
}
|
||||
|
||||
public boolean containsReference(Object value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void writeReference(Object object) {
|
||||
SerialContext context = this.getContext();
|
||||
Object current = context.getObject();
|
||||
|
||||
if (object == current) {
|
||||
out.write("{\"$ref\":\"@\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
SerialContext parentContext = context.getParent();
|
||||
|
||||
if (parentContext != null) {
|
||||
if (object == parentContext.getObject()) {
|
||||
out.write("{\"$ref\":\"..\"}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
SerialContext rootContext = context;
|
||||
for (;;) {
|
||||
if (rootContext.getParent() == null) {
|
||||
break;
|
||||
}
|
||||
rootContext = rootContext.getParent();
|
||||
}
|
||||
|
||||
if (object == rootContext.getObject()) {
|
||||
out.write("{\"$ref\":\"$\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
SerialContext refContext = this.getSerialContext(object);
|
||||
|
||||
String path = refContext.getPath();
|
||||
|
||||
out.write("{\"$ref\":\"");
|
||||
out.write(path);
|
||||
out.write("\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
public List<ValueFilter> getValueFilters() {
|
||||
if (valueFilters == null) {
|
||||
valueFilters = new ArrayList<ValueFilter>();
|
||||
}
|
||||
|
||||
return valueFilters;
|
||||
}
|
||||
|
||||
public List<ValueFilter> getValueFiltersDirect() {
|
||||
return valueFilters;
|
||||
}
|
||||
|
||||
public int getIndentCount() {
|
||||
return indentCount;
|
||||
}
|
||||
|
||||
public void incrementIndent() {
|
||||
indentCount++;
|
||||
}
|
||||
|
||||
public void decrementIdent() {
|
||||
indentCount--;
|
||||
}
|
||||
|
||||
public void println() {
|
||||
out.write('\n');
|
||||
for (int i = 0; i < indentCount; ++i) {
|
||||
out.write(indent);
|
||||
}
|
||||
}
|
||||
|
||||
public List<NameFilter> getNameFilters() {
|
||||
if (nameFilters == null) {
|
||||
nameFilters = new ArrayList<NameFilter>();
|
||||
}
|
||||
|
||||
return nameFilters;
|
||||
}
|
||||
|
||||
public List<NameFilter> getNameFiltersDirect() {
|
||||
return nameFilters;
|
||||
}
|
||||
|
||||
public List<PropertyPreFilter> getPropertyPreFilters() {
|
||||
if (propertyPreFilters == null) {
|
||||
propertyPreFilters = new ArrayList<PropertyPreFilter>();
|
||||
}
|
||||
|
||||
return propertyPreFilters;
|
||||
}
|
||||
|
||||
public List<PropertyPreFilter> getPropertyPreFiltersDirect() {
|
||||
return propertyPreFilters;
|
||||
}
|
||||
|
||||
public List<PropertyFilter> getPropertyFilters() {
|
||||
if (propertyFilters == null) {
|
||||
propertyFilters = new ArrayList<PropertyFilter>();
|
||||
}
|
||||
|
||||
return propertyFilters;
|
||||
}
|
||||
|
||||
public List<PropertyFilter> getPropertyFiltersDirect() {
|
||||
return propertyFilters;
|
||||
}
|
||||
|
||||
public SerializeWriter getWriter() {
|
||||
return out;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
public void config(SerializerFeature feature, boolean state) {
|
||||
out.config(feature, state);
|
||||
}
|
||||
|
||||
public boolean isEnabled(SerializerFeature feature) {
|
||||
return out.isEnabled(feature);
|
||||
}
|
||||
|
||||
public void writeNull() {
|
||||
this.out.writeNull();
|
||||
}
|
||||
|
||||
public SerializeConfig getMapping() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public ObjectSerializer getObjectWriter(Class<?> clazz) {
|
||||
ObjectSerializer writer = config.get(clazz);
|
||||
|
||||
if (writer == null) {
|
||||
try {
|
||||
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
|
||||
for (Object o : ServiceLoader.load(AutowiredObjectSerializer.class, classLoader)) {
|
||||
if (!(o instanceof AutowiredObjectSerializer)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AutowiredObjectSerializer autowired = (AutowiredObjectSerializer) o;
|
||||
for (Type forType : autowired.getAutowiredFor()) {
|
||||
config.put(forType, autowired);
|
||||
}
|
||||
}
|
||||
} catch (ClassCastException ex) {
|
||||
// skip
|
||||
}
|
||||
|
||||
writer = config.get(clazz);
|
||||
}
|
||||
|
||||
if (writer == null) {
|
||||
final ClassLoader classLoader = JSON.class.getClassLoader();
|
||||
if (classLoader != Thread.currentThread().getContextClassLoader()) {
|
||||
try {
|
||||
for (Object o : ServiceLoader.load(AutowiredObjectSerializer.class, classLoader)) {
|
||||
|
||||
if (!(o instanceof AutowiredObjectSerializer)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
AutowiredObjectSerializer autowired = (AutowiredObjectSerializer) o;
|
||||
for (Type forType : autowired.getAutowiredFor()) {
|
||||
config.put(forType, autowired);
|
||||
}
|
||||
}
|
||||
} catch (ClassCastException ex) {
|
||||
// skip
|
||||
}
|
||||
|
||||
writer = config.get(clazz);
|
||||
}
|
||||
}
|
||||
|
||||
if (writer == null) {
|
||||
if (Map.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, MapSerializer.instance);
|
||||
} else if (List.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, ListSerializer.instance);
|
||||
} else if (Collection.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, CollectionSerializer.instance);
|
||||
} else if (Date.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, DateSerializer.instance);
|
||||
} else if (JSONAware.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, JSONAwareSerializer.instance);
|
||||
} else if (JSONStreamAware.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, JSONStreamAwareSerializer.instance);
|
||||
} else if (clazz.isEnum() || (clazz.getSuperclass() != null && clazz.getSuperclass().isEnum())) {
|
||||
config.put(clazz, EnumSerializer.instance);
|
||||
} else if (clazz.isArray()) {
|
||||
Class<?> componentType = clazz.getComponentType();
|
||||
ObjectSerializer compObjectSerializer = getObjectWriter(componentType);
|
||||
config.put(clazz, new ArraySerializer(componentType, compObjectSerializer));
|
||||
} else if (Throwable.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, new ExceptionSerializer(clazz));
|
||||
} else if (TimeZone.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, TimeZoneSerializer.instance);
|
||||
} else if (Appendable.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, AppendableSerializer.instance);
|
||||
} else if (Charset.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, CharsetSerializer.instance);
|
||||
} else if (Enumeration.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, EnumerationSeriliazer.instance);
|
||||
} else if (Calendar.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, CalendarSerializer.instance);
|
||||
} else if (Clob.class.isAssignableFrom(clazz)) {
|
||||
config.put(clazz, ClobSeriliazer.instance);
|
||||
} else {
|
||||
boolean isCglibProxy = false;
|
||||
boolean isJavassistProxy = false;
|
||||
for (Class<?> item : clazz.getInterfaces()) {
|
||||
if (item.getName().equals("net.sf.cglib.proxy.Factory")) {
|
||||
isCglibProxy = true;
|
||||
break;
|
||||
} else if (item.getName().equals("javassist.util.proxy.ProxyObject")) {
|
||||
isJavassistProxy = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (isCglibProxy || isJavassistProxy) {
|
||||
Class<?> superClazz = clazz.getSuperclass();
|
||||
|
||||
ObjectSerializer superWriter = getObjectWriter(superClazz);
|
||||
config.put(clazz, superWriter);
|
||||
return superWriter;
|
||||
}
|
||||
|
||||
if (Proxy.isProxyClass(clazz)) {
|
||||
config.put(clazz, config.createJavaBeanSerializer(clazz));
|
||||
} else {
|
||||
config.put(clazz, config.createJavaBeanSerializer(clazz));
|
||||
}
|
||||
}
|
||||
|
||||
writer = config.get(clazz);
|
||||
}
|
||||
return writer;
|
||||
}
|
||||
|
||||
public void close() {
|
||||
this.out.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.system.util.json;
|
||||
|
||||
import com.alibaba.fastjson.serializer.JSONSerializer;
|
||||
import com.alibaba.fastjson.serializer.PropertyPreFilter;
|
||||
import com.alibaba.fastjson.serializer.SerialContext;
|
||||
|
||||
|
||||
public class BasePropertyPreFilter implements PropertyPreFilter {
|
||||
|
||||
/**
|
||||
* 要过滤的表达式数组
|
||||
*/
|
||||
String[] filterProperties;
|
||||
/**
|
||||
* 符合过滤表达式的字段是否要json序列号
|
||||
*/
|
||||
boolean flag = false;
|
||||
|
||||
public BasePropertyPreFilter(String[] filterProperties, boolean flag) {
|
||||
this.filterProperties = filterProperties;
|
||||
this.flag = flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断过滤表达式中是否含有此属性值
|
||||
*
|
||||
* @param ss
|
||||
* @param s
|
||||
* @return boolean
|
||||
*/
|
||||
private static boolean containInclude(String[] ss, String s) {
|
||||
if (ss == null || ss.length == 0 || s == null){
|
||||
// System.out.println("false");
|
||||
return false;
|
||||
}
|
||||
for (String st : ss){
|
||||
if (st.equalsIgnoreCase(s)) {
|
||||
// System.out.println("true");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// System.out.println("false");
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取处理当前元素的路径表达式
|
||||
* 如:Object.name
|
||||
*
|
||||
* @param serialContext
|
||||
* @return String
|
||||
*/
|
||||
private static String getLinkPath(SerialContext serialContext) {
|
||||
// System.out.println(String.valueOf(serialContext.getFieldName()));
|
||||
if (serialContext.getParent() == null) {
|
||||
return null;
|
||||
} else {
|
||||
if (serialContext.getParent().getFieldName() instanceof Integer) {
|
||||
String parentPath = getLinkPath(serialContext.getParent().getParent());
|
||||
return parentPath == null ? String.valueOf(serialContext.getFieldName()) : (parentPath + "." + String.valueOf(serialContext.getFieldName()));
|
||||
} else {
|
||||
String parentPath = getLinkPath(serialContext.getParent());
|
||||
return parentPath == null ? String.valueOf(serialContext.getFieldName()) : (parentPath + "." + String.valueOf(serialContext.getFieldName()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 过滤条件的判断
|
||||
* </p>
|
||||
*
|
||||
* @param serializer
|
||||
* @param source
|
||||
* @param name
|
||||
* @return
|
||||
* @see com.alibaba.fastjson.serializer.PropertyPreFilter#apply(com.alibaba.fastjson.serializer.JSONSerializer, java.lang.Object, java.lang.String)
|
||||
*/
|
||||
@Override
|
||||
public boolean apply(JSONSerializer serializer, Object source, String name) {
|
||||
SerialContext nowContext = new SerialContext(serializer.getContext(), source, name);
|
||||
String nowPath = getLinkPath(nowContext);
|
||||
// System.out.println("path->" + nowPath);
|
||||
if(this.flag==true){
|
||||
return containInclude(filterProperties, nowPath);
|
||||
}else{
|
||||
return (!containInclude(filterProperties, nowPath));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
16
ndplan/src/main/java/com/system/util/json/JSONFilter.java
Normal file
16
ndplan/src/main/java/com/system/util/json/JSONFilter.java
Normal file
@@ -0,0 +1,16 @@
|
||||
package com.system.util.json;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
|
||||
public @interface JSONFilter {
|
||||
String value() default "true";
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.system.util.pack;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Create by zhangpe0312@qq.com on 2018/6/3.
|
||||
*
|
||||
* 用来保存扫描到的注解集合
|
||||
*/
|
||||
public class KeepAnnotation {
|
||||
|
||||
/**
|
||||
* 类
|
||||
*/
|
||||
private Class classzz;
|
||||
/**
|
||||
* 类上面的注解
|
||||
*/
|
||||
private Annotation classzzAnnotation;
|
||||
|
||||
|
||||
/**
|
||||
* 类上面所有方法上的注解
|
||||
*/
|
||||
private Map<String,Annotation> methodAnnotation;
|
||||
|
||||
public KeepAnnotation(Class classzz) {
|
||||
this.classzz = classzz;
|
||||
}
|
||||
|
||||
public Class getClasszz() {
|
||||
return classzz;
|
||||
}
|
||||
|
||||
public void setClasszz(Class classzz) {
|
||||
this.classzz = classzz;
|
||||
}
|
||||
|
||||
public Annotation getClasszzAnnotation() {
|
||||
return classzzAnnotation;
|
||||
}
|
||||
|
||||
public void setClasszzAnnotation(Annotation classzzAnnotation) {
|
||||
this.classzzAnnotation = classzzAnnotation;
|
||||
}
|
||||
|
||||
public Map<String, Annotation> getMethodAnnotation() {
|
||||
return methodAnnotation;
|
||||
}
|
||||
|
||||
public void setMethodAnnotation(Map<String, Annotation> methodAnnotation) {
|
||||
this.methodAnnotation = methodAnnotation;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "KeepAnnotation{" +
|
||||
"classzz=" + classzz +
|
||||
", classzzAnnotation=" + classzzAnnotation +
|
||||
", methodAnnotation=" + methodAnnotation +
|
||||
'}';
|
||||
}
|
||||
|
||||
}
|
||||
172
ndplan/src/main/java/com/system/util/pack/PackageUtil.java
Normal file
172
ndplan/src/main/java/com/system/util/pack/PackageUtil.java
Normal file
@@ -0,0 +1,172 @@
|
||||
package com.system.util.pack;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileFilter;
|
||||
import java.io.IOException;
|
||||
import java.net.JarURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
|
||||
public class PackageUtil {
|
||||
private PackageUtil(){
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从包package中获取所有的Class
|
||||
*
|
||||
* @param pack 指定扫描的包
|
||||
* @return 包里面的所有文件
|
||||
*/
|
||||
public static Set<Class<?>> getClasses(String pack) {
|
||||
|
||||
// 第一个class类的集合
|
||||
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
|
||||
// 是否循环迭代
|
||||
boolean recursive = true;
|
||||
// 获取包的名字 并进行替换
|
||||
String packageName = pack;
|
||||
String packageDirName = packageName.replace('.', '/');
|
||||
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
|
||||
Enumeration<URL> dirs;
|
||||
try {
|
||||
dirs = Thread.currentThread().getContextClassLoader().getResources(
|
||||
packageDirName);
|
||||
// 循环迭代下去
|
||||
while (dirs.hasMoreElements()) {
|
||||
// 获取下一个元素
|
||||
URL url = dirs.nextElement();
|
||||
// 得到协议的名称
|
||||
String protocol = url.getProtocol();
|
||||
// 如果是以文件的形式保存在服务器上
|
||||
if ("file".equals(protocol)) {
|
||||
System.err.println("file类型的扫描");
|
||||
// 获取包的物理路径
|
||||
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
|
||||
// 以文件的方式扫描整个包下的文件 并添加到集合中
|
||||
findAndAddClassesInPackageByFile(packageName, filePath,
|
||||
recursive, classes);
|
||||
} else if ("jar".equals(protocol)) {
|
||||
// 如果是jar包文件
|
||||
// 定义一个JarFile
|
||||
System.err.println("jar类型的扫描");
|
||||
JarFile jar;
|
||||
try {
|
||||
// 获取jar
|
||||
jar = ((JarURLConnection) url.openConnection()).getJarFile();
|
||||
// 从此jar包 得到一个枚举类
|
||||
Enumeration<JarEntry> entries = jar.entries();
|
||||
// 同样的进行循环迭代
|
||||
while (entries.hasMoreElements()) {
|
||||
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
|
||||
JarEntry entry = entries.nextElement();
|
||||
String name = entry.getName();
|
||||
// 如果是以/开头的
|
||||
if (name.charAt(0) == '/') {
|
||||
// 获取后面的字符串
|
||||
name = name.substring(1);
|
||||
}
|
||||
// 如果前半部分和定义的包名相同
|
||||
if (name.startsWith(packageDirName)) {
|
||||
int idx = name.lastIndexOf('/');
|
||||
// 如果以"/"结尾 是一个包
|
||||
if (idx != -1) {
|
||||
// 获取包名 把"/"替换成"."
|
||||
packageName = name.substring(0, idx)
|
||||
.replace('/', '.');
|
||||
}
|
||||
// 如果可以迭代下去 并且是一个包
|
||||
if ((idx != -1) || recursive) {
|
||||
// 如果是一个.class文件 而且不是目录
|
||||
if (name.endsWith(".class")
|
||||
&& !entry.isDirectory()) {
|
||||
// 去掉后面的".class" 获取真正的类名
|
||||
String className = name.substring(packageName.length() + 1, name.length() - 6);
|
||||
try {
|
||||
// 添加到classes
|
||||
classes.add(Class.forName(packageName + '.' + className));
|
||||
} catch (ClassNotFoundException e) {
|
||||
// log
|
||||
// .error("添加用户自定义视图类错误 找不到此类的.class文件");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
packageName = pack;
|
||||
} catch (IOException e) {
|
||||
// log.error("在扫描用户定义视图时从jar包获取文件出错");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("包扫描执行完毕....");
|
||||
return classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 以文件的形式来获取包下的所有Class
|
||||
*
|
||||
* @param packageName 包的名字
|
||||
* @param packagePath 包的路径
|
||||
* @param recursive
|
||||
* @param classes 文件列表
|
||||
*/
|
||||
private static void findAndAddClassesInPackageByFile(String packageName,
|
||||
String packagePath,
|
||||
final boolean recursive,
|
||||
Set<Class<?>> classes) {
|
||||
// 获取此包的目录 建立一个File
|
||||
File dir = new File(packagePath);
|
||||
// 如果不存在或者 也不是目录就直接返回
|
||||
if (!dir.exists() || !dir.isDirectory()) {
|
||||
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
|
||||
return;
|
||||
}
|
||||
// 如果存在 就获取包下的所有文件 包括目录
|
||||
File[] dirfiles = dir.listFiles(new FileFilter() {
|
||||
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
|
||||
public boolean accept(File file) {
|
||||
return (recursive && file.isDirectory())
|
||||
|| (file.getName().endsWith(".class"));
|
||||
}
|
||||
});
|
||||
// 循环所有文件
|
||||
for (File file : dirfiles) {
|
||||
// 如果是目录 则继续扫描
|
||||
if (file.isDirectory()) {
|
||||
findAndAddClassesInPackageByFile(packageName + "."
|
||||
+ file.getName(), file.getAbsolutePath(), recursive,
|
||||
classes);
|
||||
} else {
|
||||
// 如果是java类文件 去掉后面的.class 只留下类名
|
||||
String className = file.getName().substring(0,
|
||||
file.getName().length() - 6);
|
||||
try {
|
||||
// 添加到集合中去
|
||||
//classes.add(Class.forName(packageName + '.' + className));
|
||||
//经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净
|
||||
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
|
||||
} catch (ClassNotFoundException e) {
|
||||
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
//System.out.println( ScanPack.getClasses("com.tky.") );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.system.util.pack;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class ScanAnnotation {
|
||||
|
||||
/**
|
||||
* 查询指定包中的类的所有注解
|
||||
* @param packagePath 指定包路径
|
||||
* @param annotation 需要查询的注解
|
||||
* @param checkRepeat 是否查重
|
||||
* @return 注解集合
|
||||
* @throws Exception 如果有两个方法上的两个注解完全相同时则抛出异常
|
||||
*/
|
||||
public static List<KeepAnnotation> getAnnotationByPackage(String packagePath
|
||||
, Class<? extends Annotation> annotation
|
||||
, boolean checkRepeat) throws Exception {
|
||||
|
||||
Set<Class<?>> classes = PackageUtil.getClasses(packagePath);
|
||||
List<KeepAnnotation> keepAnnotations = new ArrayList<KeepAnnotation>(classes.size());
|
||||
|
||||
for (Class classzz : classes) {
|
||||
KeepAnnotation keepAnnotation = getAnnotationByClass(classzz, annotation, checkRepeat);
|
||||
keepAnnotations.add(keepAnnotation);
|
||||
}
|
||||
return keepAnnotations;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找一个类上的所有注解
|
||||
*
|
||||
* @param classzz 指定查找的类
|
||||
* @param annotation 需要获取的注解
|
||||
* @param checkRepeat 是否查找重复的注解
|
||||
* @return 注解集合
|
||||
* @throws Exception 如果有两个方法上的两个注解完全相同时则抛出异常
|
||||
*/
|
||||
public static KeepAnnotation getAnnotationByClass(Class<?> classzz
|
||||
, Class<? extends Annotation> annotation
|
||||
, boolean checkRepeat) throws Exception {
|
||||
|
||||
KeepAnnotation KeepAnnotation = new KeepAnnotation(classzz);
|
||||
|
||||
// 获取到类上的注解
|
||||
Annotation classzzAnnotation = classzz.getAnnotation(annotation);
|
||||
if (classzzAnnotation != null) KeepAnnotation.setClasszzAnnotation(classzzAnnotation);
|
||||
|
||||
// 获取到方法上的注解
|
||||
Map<String,Annotation> methodAnnotations = new HashMap<String, Annotation>();
|
||||
Method[] methods = classzz.getMethods();
|
||||
for (Method method : methods) {
|
||||
Annotation methodAnnotation = method.getAnnotation(annotation);
|
||||
if (methodAnnotation != null) {
|
||||
// 如果需要检查重复则检查否则不检测注解值是否重复
|
||||
if (checkRepeat && methodAnnotations.containsValue(methodAnnotation))
|
||||
throw new Exception(classzz.getName() + " \n" + method.getName() + " \n"
|
||||
+ methodAnnotation.toString() + " have repeat value");
|
||||
else {
|
||||
methodAnnotations.put(method.getName(),methodAnnotation);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
KeepAnnotation.setMethodAnnotation(methodAnnotations);
|
||||
return KeepAnnotation;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
//Set<Class<?>> classes = ScanPack.getClasses("");
|
||||
//KeepAnnotation KeepAnnotation = getAnnotationByClass(LineSlopeController.class, RequestMapping.class, false);
|
||||
//System.out.println(KeepAnnotation);
|
||||
}
|
||||
}
|
||||
|
||||
56
ndplan/src/main/java/com/system/util/role/MenuItem.java
Normal file
56
ndplan/src/main/java/com/system/util/role/MenuItem.java
Normal file
@@ -0,0 +1,56 @@
|
||||
package com.system.util.role;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
|
||||
/**
|
||||
* 用在Controller类或方法上面
|
||||
* @author zhangtianlun
|
||||
* 注解在类上:
|
||||
* @MenuItem(name="科研成果管理", type= MenuType.MENU, path="/subject", pathMethod="GET", sort= 1)
|
||||
* 注解在方法上:
|
||||
* @MenuItem(name="科研成果管理-添加和修改", type= MenuType.BUTTON, path="/subject/save", pathMethod="GET/POST", sort= 1)
|
||||
*
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target( { ElementType.METHOD, ElementType.TYPE })
|
||||
public @interface MenuItem {
|
||||
|
||||
/**
|
||||
* 模块名称,如"腕臂预配/系统管理"
|
||||
*/
|
||||
public abstract String moduleName() default "";
|
||||
|
||||
/**
|
||||
* 菜单的名称
|
||||
*/
|
||||
public abstract String name() default "";
|
||||
|
||||
/**
|
||||
* 菜单类型
|
||||
*/
|
||||
public abstract MenuType type() default MenuType.MENU;
|
||||
|
||||
/**
|
||||
* 排序号
|
||||
*/
|
||||
public abstract int sort() default 0;
|
||||
|
||||
/**
|
||||
* 菜单的路径
|
||||
*/
|
||||
public abstract String path() default "";
|
||||
|
||||
/**
|
||||
* 菜单的路径请求方法
|
||||
*/
|
||||
public abstract String pathMethod() default "";
|
||||
|
||||
/**
|
||||
* 设定菜单的名称
|
||||
*/
|
||||
public String value() default "";
|
||||
}
|
||||
8
ndplan/src/main/java/com/system/util/role/MenuType.java
Normal file
8
ndplan/src/main/java/com/system/util/role/MenuType.java
Normal file
@@ -0,0 +1,8 @@
|
||||
package com.system.util.role;
|
||||
|
||||
public enum MenuType {
|
||||
MENU, //菜单类型
|
||||
BUTTON, //按钮类型
|
||||
DATA_INTERFACE, //数据接口
|
||||
ADMIN //数据接口
|
||||
}
|
||||
69
ndplan/src/main/java/com/system/util/role/RoleUtil.java
Normal file
69
ndplan/src/main/java/com/system/util/role/RoleUtil.java
Normal file
@@ -0,0 +1,69 @@
|
||||
package com.system.util.role;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import com.system.util.pack.KeepAnnotation;
|
||||
import com.system.util.pack.PackageUtil;
|
||||
import com.system.util.pack.ScanAnnotation;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
|
||||
public class RoleUtil {
|
||||
|
||||
private static final Logger log = (Logger) LoggerFactory.getLogger(RoleUtil.class);
|
||||
|
||||
//解析Controller上的注解
|
||||
public static Map<MenuItem, Set<MenuItem>> pasreMenu() {
|
||||
// key是Class上的菜单, value是方法上的菜单
|
||||
Map<MenuItem, Set<MenuItem>> menuMap = new HashMap<MenuItem, Set<MenuItem>>();
|
||||
// 获取项目上面的所有class
|
||||
Set<Class<?>> classes = PackageUtil.getClasses("com.tky");
|
||||
|
||||
|
||||
// 获取到方法上的注解
|
||||
if(! CollectionUtils.isEmpty(classes)) {
|
||||
for (Class<?> clazz : classes) {
|
||||
System.out.println(clazz.getName() + "=============");
|
||||
try {
|
||||
KeepAnnotation annotation = ScanAnnotation.getAnnotationByClass(clazz, MenuItem.class, false);
|
||||
// 解析Class上Menu
|
||||
Annotation classzzAnnotation = annotation.getClasszzAnnotation();
|
||||
if(classzzAnnotation != null
|
||||
&& MenuItem.class.getName().equals(classzzAnnotation.annotationType().getName() )) {
|
||||
|
||||
MenuItem menu = (MenuItem) classzzAnnotation;
|
||||
log.info(menu.toString());
|
||||
//解析方法上Menu
|
||||
Map<String, Annotation> methodAnnotation = annotation.getMethodAnnotation();
|
||||
Set<MenuItem> menuItemSet = new HashSet<MenuItem>();
|
||||
if(methodAnnotation != null) {
|
||||
for(String key : methodAnnotation.keySet()) {
|
||||
MenuItem menuItem = (MenuItem) methodAnnotation.get(key);
|
||||
menuItemSet.add(menuItem);
|
||||
log.info(menuItem.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// 添加
|
||||
menuMap.put(menu, menuItemSet);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return menuMap;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
pasreMenu();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.system.util.scheduler;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.quartz.Job;
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.quartz.JobExecutionException;
|
||||
|
||||
/**
|
||||
* 作业
|
||||
* 实现一个作业继承JobServce,实现execute方法
|
||||
*
|
||||
*/
|
||||
public class JobServce implements Job {
|
||||
@Override
|
||||
public void execute(JobExecutionContext context) throws JobExecutionException {
|
||||
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "★★★★★★★★★★★");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.system.util.scheduler;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.quartz.JobExecutionException;
|
||||
|
||||
/**
|
||||
*
|
||||
* 作业
|
||||
* 实现一个作业
|
||||
*
|
||||
*/
|
||||
public class QuartzJobExample extends JobServce {
|
||||
@Override
|
||||
public void execute(JobExecutionContext context) throws JobExecutionException {
|
||||
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "★★★★★★★★★★★");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.system.util.scheduler;
|
||||
|
||||
|
||||
import org.quartz.CronScheduleBuilder;
|
||||
import org.quartz.CronTrigger;
|
||||
import org.quartz.JobBuilder;
|
||||
import org.quartz.JobDetail;
|
||||
import org.quartz.JobKey;
|
||||
import org.quartz.Scheduler;
|
||||
import org.quartz.Trigger;
|
||||
import org.quartz.TriggerBuilder;
|
||||
import org.quartz.TriggerKey;
|
||||
|
||||
/**
|
||||
* Quartz调度管理器
|
||||
*
|
||||
* 用于启动、停止、调度和管理作业
|
||||
* @author Administrator
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
<!-- Quartz依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.quartz-scheduler</groupId>
|
||||
<artifactId>quartz</artifactId>
|
||||
<version>2.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.quartz-scheduler</groupId>
|
||||
<artifactId>quartz-jobs</artifactId>
|
||||
<version>2.2.1</version>
|
||||
</dependency>
|
||||
*/
|
||||
public class QuartzManager {
|
||||
private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";
|
||||
private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";
|
||||
|
||||
/**
|
||||
* @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
|
||||
*
|
||||
* @param sched 调度器
|
||||
* @param jobName 任务名
|
||||
* @param cls 任务类
|
||||
* @param time 时间设置,参考quartz说明文档
|
||||
*
|
||||
*/
|
||||
public static void addJob(Scheduler sched, String jobName, @SuppressWarnings("rawtypes") Class jobClass, String time) {
|
||||
addJob( sched, jobName, JOB_GROUP_NAME,
|
||||
jobName, TRIGGER_GROUP_NAME, jobClass, time);
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description: 添加一个定时任务
|
||||
*
|
||||
* @param sched 调度器
|
||||
* @param jobName 任务名
|
||||
* @param jobGroupName 任务组名
|
||||
* @param triggerName 触发器名
|
||||
* @param triggerGroupName 触发器组名
|
||||
* @param jobClass 任务
|
||||
* @param time 时间设置,参考quartz说明文档
|
||||
*/
|
||||
public static void addJob(Scheduler sched, String jobName, String jobGroupName,
|
||||
String triggerName, String triggerGroupName, @SuppressWarnings("rawtypes") Class jobClass, String time) {
|
||||
try {
|
||||
// 作业
|
||||
JobKey jobKey = new JobKey(jobName, jobGroupName);// 任务名,任务组
|
||||
@SuppressWarnings("unchecked")
|
||||
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobKey).build();
|
||||
|
||||
// 触发器
|
||||
TriggerKey triggerKey = new TriggerKey(jobName, triggerGroupName);// 触发器名,触发器组
|
||||
Trigger trigger = TriggerBuilder.newTrigger()
|
||||
.withIdentity(triggerKey)
|
||||
.withSchedule(CronScheduleBuilder.cronSchedule(time))
|
||||
.build();// 触发器时间设定
|
||||
|
||||
sched.scheduleJob(jobDetail, trigger);
|
||||
// 启动
|
||||
if (!sched.isShutdown()) {
|
||||
sched.start();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
|
||||
*
|
||||
* @param sched 调度器
|
||||
* @param jobName 任务名
|
||||
* @param time 时间设置,参考quartz说明文档
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static void modifyJobTime(Scheduler sched, String jobName, String time) {
|
||||
try {
|
||||
TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
|
||||
CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
|
||||
if (trigger == null) {
|
||||
return;
|
||||
}
|
||||
String oldTime = trigger.getCronExpression();
|
||||
if (!oldTime.equalsIgnoreCase(time)) {
|
||||
JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
|
||||
JobDetail jobDetail = sched.getJobDetail(jobKey);
|
||||
Class objJobClass = jobDetail.getJobClass();
|
||||
removeJob(sched, jobName);
|
||||
System.out.println("修改任务:"+jobName);
|
||||
addJob(sched, jobName, objJobClass, time);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description: 修改一个任务的触发时间
|
||||
*
|
||||
* @param sched 调度器
|
||||
* @param triggerName 触发器名称
|
||||
* @param triggerGroupName 触发器组名称
|
||||
* @param time 时间设置,参考quartz说明文档
|
||||
*
|
||||
*/
|
||||
public static void modifyJobTime(Scheduler sched, String triggerName, String triggerGroupName, String time) {
|
||||
try {
|
||||
TriggerKey triggerKey = new TriggerKey(triggerName,
|
||||
triggerGroupName);
|
||||
CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
|
||||
if (trigger == null) {
|
||||
return;
|
||||
}
|
||||
String oldTime = trigger.getCronExpression();
|
||||
if (!oldTime.equalsIgnoreCase(time)) {
|
||||
// 修改时间
|
||||
trigger.getTriggerBuilder().withSchedule(CronScheduleBuilder.cronSchedule(time));
|
||||
// 重启触发器
|
||||
sched.resumeTrigger(triggerKey);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
|
||||
*
|
||||
* @param sched 调度器
|
||||
* @param jobName 任务名称
|
||||
*/
|
||||
public static void removeJob(Scheduler sched, String jobName) {
|
||||
try {
|
||||
TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
|
||||
sched.pauseTrigger(triggerKey);// 停止触发器
|
||||
sched.unscheduleJob(triggerKey);// 移除触发器
|
||||
JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
|
||||
sched.deleteJob(jobKey);// 删除任务
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description: 移除一个任务
|
||||
*
|
||||
* @param sched 调度器
|
||||
* @param jobName 任务名
|
||||
* @param jobGroupName 任务组名
|
||||
* @param triggerName 触发器名
|
||||
* @param triggerGroupName 触发器组名
|
||||
*
|
||||
*/
|
||||
public static void removeJob(Scheduler sched, String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
|
||||
try {
|
||||
TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
|
||||
sched.pauseTrigger(triggerKey);// 停止触发器
|
||||
sched.unscheduleJob(triggerKey);// 移除触发器
|
||||
JobKey jobKey = new JobKey(jobName, jobGroupName);
|
||||
sched.deleteJob(jobKey);// 删除任务
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description: 启动所有定时任务
|
||||
*
|
||||
* @param sched 调度器
|
||||
*/
|
||||
public static void startJobs(Scheduler sched) {
|
||||
try {
|
||||
sched.start();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description:关闭所有定时任务
|
||||
*
|
||||
* @param sched 调度器
|
||||
*/
|
||||
public static void shutdownJobs(Scheduler sched) {
|
||||
try {
|
||||
if (!sched.isShutdown()) {
|
||||
sched.shutdown();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.system.util.scheduler;
|
||||
|
||||
import org.quartz.Scheduler;
|
||||
import org.quartz.SchedulerException;
|
||||
import org.quartz.SchedulerFactory;
|
||||
import org.quartz.impl.StdSchedulerFactory;
|
||||
|
||||
/**
|
||||
* QuartzPool Quartz池
|
||||
*
|
||||
* 把定时器扔池中运行
|
||||
*
|
||||
*/
|
||||
public class QuartzPool {
|
||||
// 调度器工厂
|
||||
private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();
|
||||
// 调度器
|
||||
@SuppressWarnings("unused")
|
||||
private static Scheduler sched = null;
|
||||
|
||||
static {
|
||||
try {
|
||||
sched = schedulerFactory.getScheduler();
|
||||
} catch (SchedulerException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void addJob(String jobName, @SuppressWarnings("rawtypes") Class jobClass, String time) {
|
||||
QuartzManager.addJob(sched, jobName, jobClass, time);
|
||||
}
|
||||
|
||||
|
||||
public static void addJob(String jobName, String jobGroupName,
|
||||
String triggerName, String triggerGroupName, @SuppressWarnings("rawtypes") Class jobClass, String time) {
|
||||
QuartzManager.addJob(sched, jobName, jobGroupName, triggerName, triggerGroupName, jobClass, time);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static void modifyJobTime(String jobName, String time) {
|
||||
QuartzManager.modifyJobTime(sched, jobName, time);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static void modifyJobTime(String triggerName, String triggerGroupName, String time) {
|
||||
QuartzManager.modifyJobTime(sched, triggerName, triggerGroupName, time);
|
||||
}
|
||||
|
||||
|
||||
public static void removeJob(String jobName) {
|
||||
QuartzManager.removeJob(sched, jobName);
|
||||
}
|
||||
|
||||
|
||||
public static void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
|
||||
QuartzManager.removeJob(sched, jobName, jobGroupName, triggerName, triggerGroupName);
|
||||
}
|
||||
|
||||
}
|
||||
53
ndplan/src/main/java/com/system/util/tomcat/MBeans.java
Normal file
53
ndplan/src/main/java/com/system/util/tomcat/MBeans.java
Normal file
@@ -0,0 +1,53 @@
|
||||
package com.system.util.tomcat;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.management.JMException;
|
||||
import javax.management.MBeanServer;
|
||||
import javax.management.MalformedObjectNameException;
|
||||
import javax.management.ObjectName;
|
||||
|
||||
public class MBeans {
|
||||
|
||||
// Java Management Extensions (JMXTM) API 是一个用于管理和监视的标准 API。
|
||||
// 典型用途包括: 查询并更改应用程序配置 累积有关应用程序行为的统计并使其可用 通知状态更改及错误状况。
|
||||
private final MBeanServer mbeanServer;
|
||||
|
||||
MBeans() {
|
||||
this(getPlatformMBeanServer());
|
||||
}
|
||||
|
||||
private MBeans(MBeanServer mbeanServer) {
|
||||
super();
|
||||
this.mbeanServer = mbeanServer;
|
||||
}
|
||||
static MBeanServer getPlatformMBeanServer() {
|
||||
return ManagementFactory.getPlatformMBeanServer();
|
||||
}
|
||||
Set<ObjectName> getTomcatThreadPools() throws MalformedObjectNameException {
|
||||
return mbeanServer.queryNames(new ObjectName("*:type=ThreadPool,*"), null);
|
||||
}
|
||||
|
||||
Set<ObjectName> getTomcatGlobalRequestProcessors() throws MalformedObjectNameException {
|
||||
return mbeanServer.queryNames(new ObjectName("*:type=GlobalRequestProcessor,*"), null);
|
||||
}
|
||||
|
||||
Set<ObjectName> getTomcatManager() throws MalformedObjectNameException {
|
||||
ObjectName managerObjName = new ObjectName("*:type=Manager,*");
|
||||
Set<ObjectName> objectNames = mbeanServer.queryNames(managerObjName, null);
|
||||
/* for (ObjectName obj : s) {
|
||||
System.out.println("应用名:" + obj.getKeyProperty("path"));
|
||||
ObjectName objname = new ObjectName(obj.getCanonicalName());
|
||||
System.out.println("最大会话数:" + mbeanServer.getAttribute(objname, "maxActiveSessions"));
|
||||
System.out.println("会话数:" + mbeanServer.getAttribute(objname, "activeSessions"));
|
||||
System.out.println("活动会话数:" + mbeanServer.getAttribute(objname, "sessionCounter"));
|
||||
} */
|
||||
return objectNames;
|
||||
}
|
||||
|
||||
Object getAttribute(ObjectName name, String attribute) throws JMException {
|
||||
return mbeanServer.getAttribute(name, attribute);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package com.system.util.tomcat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.management.AttributeNotFoundException;
|
||||
import javax.management.InstanceNotFoundException;
|
||||
import javax.management.JMException;
|
||||
import javax.management.MalformedObjectNameException;
|
||||
import javax.management.ObjectName;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* tomcat信息
|
||||
*/
|
||||
@Data
|
||||
public class TomcatInformations {
|
||||
|
||||
private static final boolean TOMCAT_USED = System.getProperty("catalina.home") != null;
|
||||
|
||||
private static final long serialVersionUID = -6145865427461051370L;
|
||||
|
||||
@SuppressWarnings("all")
|
||||
private static final List<ObjectName> THREAD_POOLS = new ArrayList<ObjectName>();
|
||||
@SuppressWarnings("all")
|
||||
private static final List<ObjectName> GLOBAL_REQUEST_PROCESSORS = new ArrayList<ObjectName>();
|
||||
|
||||
private final String name;
|
||||
private final int maxThreads;
|
||||
private final int currentThreadCount;
|
||||
private static int currentThreadsBusy=0;
|
||||
private final long bytesReceived;
|
||||
private final long bytesSent;
|
||||
private final int requestCount;
|
||||
private final int errorCount;
|
||||
private final long processingTime;
|
||||
private final long maxTime;
|
||||
|
||||
|
||||
|
||||
private TomcatInformations(MBeans mBeans, ObjectName threadPool) throws JMException {
|
||||
super();
|
||||
name = threadPool.getKeyProperty("name");
|
||||
maxThreads = (Integer) mBeans.getAttribute(threadPool, "maxThreads");
|
||||
currentThreadCount = (Integer) mBeans.getAttribute(threadPool, "currentThreadCount");
|
||||
currentThreadsBusy = (Integer) mBeans.getAttribute(threadPool, "currentThreadsBusy");
|
||||
ObjectName grp = null;
|
||||
for (final ObjectName globalRequestProcessor : GLOBAL_REQUEST_PROCESSORS) {
|
||||
if (name.equals(globalRequestProcessor.getKeyProperty("name"))) {
|
||||
grp = globalRequestProcessor;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (grp != null) {
|
||||
bytesReceived = (Long) mBeans.getAttribute(grp, "bytesReceived");
|
||||
bytesSent = (Long) mBeans.getAttribute(grp, "bytesSent");
|
||||
requestCount = (Integer) mBeans.getAttribute(grp, "requestCount");
|
||||
errorCount = (Integer) mBeans.getAttribute(grp, "errorCount");
|
||||
processingTime = (Long) mBeans.getAttribute(grp, "processingTime");
|
||||
maxTime = (Long) mBeans.getAttribute(grp, "maxTime");
|
||||
} else {
|
||||
bytesReceived = 0;
|
||||
bytesSent = 0;
|
||||
requestCount = 0;
|
||||
errorCount = 0;
|
||||
processingTime = 0;
|
||||
maxTime = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<TomcatInformations> buildTomcatInformationsList() {
|
||||
if (!TOMCAT_USED) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
try {
|
||||
synchronized (THREAD_POOLS) {
|
||||
if (THREAD_POOLS.isEmpty() || GLOBAL_REQUEST_PROCESSORS.isEmpty()) {
|
||||
initMBeans();
|
||||
}
|
||||
}
|
||||
final MBeans mBeans = new MBeans();
|
||||
final List<TomcatInformations> tomcatInformationsList = new ArrayList<TomcatInformations>(
|
||||
THREAD_POOLS.size());
|
||||
for (final ObjectName threadPool : THREAD_POOLS) {
|
||||
tomcatInformationsList.add(new TomcatInformations(mBeans, threadPool));
|
||||
}
|
||||
return tomcatInformationsList;
|
||||
} catch (final InstanceNotFoundException e) {
|
||||
return Collections.emptyList();
|
||||
} catch (final AttributeNotFoundException e) {
|
||||
return Collections.emptyList();
|
||||
} catch (final JMException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void initMBeans() throws MalformedObjectNameException {
|
||||
final MBeans mBeans = new MBeans();
|
||||
THREAD_POOLS.clear();
|
||||
GLOBAL_REQUEST_PROCESSORS.clear();
|
||||
THREAD_POOLS.addAll(mBeans.getTomcatThreadPools());
|
||||
GLOBAL_REQUEST_PROCESSORS.addAll(mBeans.getTomcatGlobalRequestProcessors());
|
||||
}
|
||||
|
||||
public static long getCurrentThreadsBusy(){
|
||||
buildTomcatInformationsList();
|
||||
return currentThreadsBusy;
|
||||
}
|
||||
|
||||
// 获取tomcat的线程信息
|
||||
public static Map<String,Map<String,String>> getInformation() {
|
||||
final MBeans mBeans = new MBeans();
|
||||
Map<String,Map<String,String>> data= new HashMap<>();
|
||||
try {
|
||||
for(ObjectName threadPool : mBeans.getTomcatThreadPools()) {
|
||||
Map<String,String> map= new HashMap<>();
|
||||
|
||||
String name = threadPool.getKeyProperty("name");
|
||||
String type = threadPool.getKeyProperty("type");
|
||||
int maxThreads = (Integer) mBeans.getAttribute(threadPool, "maxThreads");
|
||||
int currentThreadCount = (Integer) mBeans.getAttribute(threadPool, "currentThreadCount");
|
||||
int currentThreadsBusy = (Integer) mBeans.getAttribute(threadPool, "currentThreadsBusy");
|
||||
/*long bytesReceived = (Long) mBeans.getAttribute(threadPool, "bytesReceived");
|
||||
long bytesSent = (Long) mBeans.getAttribute(threadPool, "bytesSent");
|
||||
int requestCount = (Integer) mBeans.getAttribute(threadPool, "requestCount");
|
||||
int errorCount = (Integer) mBeans.getAttribute(threadPool, "errorCount");
|
||||
long processingTime = (Long) mBeans.getAttribute(threadPool, "processingTime");
|
||||
long maxTime = (Long) mBeans.getAttribute(threadPool, "maxTime");*/
|
||||
|
||||
|
||||
map.put("name", name);
|
||||
map.put("type", type +"");
|
||||
map.put("maxThreads", maxThreads +"");
|
||||
map.put("currentThreadCount", currentThreadCount +"");
|
||||
map.put("currentThreadsBusy", currentThreadsBusy +"");
|
||||
/*data.put("bytesReceived", bytesReceived +"");
|
||||
data.put("bytesSent", bytesSent +"");
|
||||
data.put("requestCount", requestCount +"");
|
||||
data.put("errorCount", errorCount +"");
|
||||
data.put("processingTime", processingTime +"");
|
||||
data.put("maxTime", maxTime +"");*/
|
||||
|
||||
data.put(name, map);
|
||||
// data.put("bbbb",threadPool.getKeyPropertyList());
|
||||
}
|
||||
|
||||
// ======session=======
|
||||
for(ObjectName objname : mBeans.getTomcatManager()) {
|
||||
Map<String,String> map= new HashMap<>();
|
||||
// 应用名
|
||||
String context = objname.getKeyProperty("context");
|
||||
// 类型
|
||||
String type = objname.getKeyProperty("type");
|
||||
// 最大会话数
|
||||
int maxActiveSessions = (Integer) mBeans.getAttribute(objname, "maxActiveSessions");
|
||||
// 会话数
|
||||
long sessionCounter = (Long) mBeans.getAttribute(objname, "sessionCounter");
|
||||
// 活动会话数
|
||||
int activeSessions = (Integer) mBeans.getAttribute(objname, "activeSessions");
|
||||
map.put("context", "" + context);
|
||||
map.put("type", "" + type);
|
||||
map.put("maxActiveSessions", "" + maxActiveSessions);
|
||||
map.put("activeSessions", "" + activeSessions);
|
||||
map.put("sessionCounter", "" + sessionCounter);
|
||||
|
||||
data.put(context, map);
|
||||
|
||||
// data.put("aaa",objname.getKeyPropertyList());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
17
ndplan/src/main/java/com/tky/web/ServletCustomizer.java
Normal file
17
ndplan/src/main/java/com/tky/web/ServletCustomizer.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package com.tky.web;
|
||||
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
|
||||
import org.springframework.boot.web.server.MimeMappings;
|
||||
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ServletCustomizer
|
||||
implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
|
||||
@Override
|
||||
public void customize(TomcatServletWebServerFactory factory) {
|
||||
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
|
||||
mappings.add("wasm", "application/wasm");
|
||||
factory.setMimeMappings(mappings);
|
||||
}
|
||||
}
|
||||
13
ndplan/src/main/java/com/tky/web/ServletInitializer.java
Normal file
13
ndplan/src/main/java/com/tky/web/ServletInitializer.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package com.tky.web;
|
||||
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
public class ServletInitializer extends SpringBootServletInitializer {
|
||||
|
||||
@Override
|
||||
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
|
||||
return application.sources(WebApplication.class);
|
||||
}
|
||||
|
||||
}
|
||||
65
ndplan/src/main/java/com/tky/web/WebApplication.java
Normal file
65
ndplan/src/main/java/com/tky/web/WebApplication.java
Normal file
@@ -0,0 +1,65 @@
|
||||
package com.tky.web;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@EnableScheduling
|
||||
@SpringBootApplication()
|
||||
@ComponentScan(
|
||||
basePackages = {"com.system.business", "com.system.util", "com.tky", "com.tky.web.controller"})
|
||||
@EnableJpaRepositories(basePackages = {"com.system.business", "com.system.util", "com.tky"})
|
||||
@EntityScan(basePackages = {"com.system.business", "com.system.util", "com.tky"})
|
||||
@EnableSwagger2
|
||||
public class WebApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate() {
|
||||
return new RestTemplate();
|
||||
}
|
||||
|
||||
@Autowired private Environment env;
|
||||
|
||||
// 连接池
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
DruidDataSource dataSource = new DruidDataSource();
|
||||
dataSource.setUrl(env.getProperty("spring.datasource.url"));
|
||||
dataSource.setUsername(env.getProperty("spring.datasource.username")); // 用户名
|
||||
dataSource.setPassword(env.getProperty("spring.datasource.password")); // 密码
|
||||
dataSource.setInitialSize(2);
|
||||
dataSource.setMaxActive(20);
|
||||
dataSource.setMinIdle(0);
|
||||
dataSource.setMaxWait(60000);
|
||||
dataSource.setValidationQuery("SELECT 1 FROM DUAL");
|
||||
dataSource.setTestOnBorrow(false);
|
||||
dataSource.setTestWhileIdle(true);
|
||||
dataSource.setPoolPreparedStatements(false);
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
/* @Bean
|
||||
public GPSUDPReceiveRunner gpsUDPReceiveRunner() {
|
||||
return new GPSUDPReceiveRunner();
|
||||
}
|
||||
*/
|
||||
/*@Bean
|
||||
public JobRunner jobRunner() {
|
||||
return new JobRunner();
|
||||
}*/
|
||||
}
|
||||
85
ndplan/src/main/java/com/tky/web/XmlOperationTest.java
Normal file
85
ndplan/src/main/java/com/tky/web/XmlOperationTest.java
Normal file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* All rights Reserved, Designed By cheng
|
||||
* @Title: XmlOperationTest.java
|
||||
* @Package com.tky.sanwei
|
||||
* @Description: TODO(用一句话描述该文件做什么)
|
||||
* @author: cheng
|
||||
* @date: 2019年5月30日 下午2:21:15
|
||||
* @version V1.0
|
||||
* @Copyright: 2019 All rights reserved.
|
||||
*/
|
||||
package com.tky.web;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.dom4j.Attribute;
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.DocumentException;
|
||||
import org.dom4j.Element;
|
||||
import org.dom4j.io.SAXReader;
|
||||
|
||||
/**
|
||||
* @ClassName: XmlOperationTest
|
||||
* @Description:TODO(这里用一句话描述这个类的作用)
|
||||
* @author: cheng
|
||||
* @date: 2019年5月30日 下午2:21:15
|
||||
*
|
||||
* @Copyright: 2019 All rights reserved.
|
||||
*/
|
||||
public class XmlOperationTest {
|
||||
|
||||
public static void main(String[] args) {
|
||||
getXmlFile();
|
||||
}
|
||||
|
||||
public static void getXmlFile() {
|
||||
// TODO Auto-generated method stub
|
||||
// 解析JXCJ_Seg1_QH_Bridge_01JHZQ.xml文件
|
||||
// 创建SAXReader的对象reader
|
||||
SAXReader reader = new SAXReader();
|
||||
try {
|
||||
// 通过reader对象的read方法加载JXCJ_Seg1_QH_Bridge_01JHZQ.xml文件,获取docuemnt对象。
|
||||
Document document = reader.read(new File("D:\\test_file\\JXCJ_Seg1_QH_Bridge_01JHZQ.xml"));
|
||||
// 通过document对象获取根节点
|
||||
Element node = document.getRootElement();
|
||||
// 遍历所有的元素节点
|
||||
listNodes(node);
|
||||
|
||||
} catch (DocumentException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历当前节点元素下面的所有(元素的)子节点
|
||||
*
|
||||
* @param node
|
||||
*/
|
||||
public static void listNodes(Element node) {
|
||||
System.out.println("---------------------------------------------------------------");
|
||||
System.out.println("当前节点的名称::" + node.getName());
|
||||
// 获取当前节点的所有属性节点
|
||||
List<Attribute> list = node.attributes();
|
||||
// 遍历属性节点
|
||||
for (Attribute attr : list) {
|
||||
System.out.println(attr.getText() + "--属性名:--" + attr.getName() + "--属性值:--" + attr.getValue());
|
||||
}
|
||||
|
||||
if (!(node.getTextTrim().equals(""))) {
|
||||
System.out.println("文本内容::::" + node.getText());
|
||||
}
|
||||
|
||||
// 当前节点下面子节点迭代器
|
||||
Iterator<Element> it = node.elementIterator();
|
||||
// 遍历
|
||||
while (it.hasNext()) {
|
||||
// 获取某个子节点对象
|
||||
Element e = it.next();
|
||||
// 对子节点进行遍历
|
||||
listNodes(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* @Title: LoginAop.java
|
||||
* @Package com.tky.bbs.configuration.aop
|
||||
* @Description: TODO
|
||||
* Copyright: Copyright (c) 2015
|
||||
* Company:TKY
|
||||
*
|
||||
* @author vicene
|
||||
* @date 2017年7月7日 下午3:43:31
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.tky.web.config.aop;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.After;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
|
||||
/**
|
||||
* TODO(用一句话描述这个变量表示什么)
|
||||
*/
|
||||
@Component
|
||||
@Aspect
|
||||
public class OperateLoggerAop {
|
||||
|
||||
/*
|
||||
// 登陆后
|
||||
@After("execution(* com.tky.web.action.connect.LoginControl.login(..))")
|
||||
public void afterLoginMethod(JoinPoint joinPoint) {
|
||||
List<Object> args = Arrays.asList(joinPoint.getArgs());
|
||||
for (Object o : args) {
|
||||
if (o instanceof HttpSession) {
|
||||
HttpSession session = (HttpSession) o;
|
||||
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.tky.web.config.bean;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "basic-platform")
|
||||
public class BasicPlatformConfig {
|
||||
private String loginUrl;
|
||||
private String getUserByLoginAccountUrl;
|
||||
private String getUserByIdUrl;
|
||||
private String getDepartpartmentsByUserId;
|
||||
private String getProjectAreaByUserId;
|
||||
private String getBdInfo;
|
||||
private String getProjectSectionByUserId;
|
||||
private String getProjectinfoByUserId;
|
||||
private String getAllArea;
|
||||
private String getProjectInfosByCategoryItemId;
|
||||
private String getProjectSectionByProjectInfoId;
|
||||
private String getSGByJL;
|
||||
private String getBuildByProjectSectionId;
|
||||
private String getProjectSiteListById;
|
||||
private String getBbsBySiteId;
|
||||
private String getSSOUserInfoByToken;
|
||||
|
||||
}
|
||||
24
ndplan/src/main/java/com/tky/web/config/bean/BeanConfig.java
Normal file
24
ndplan/src/main/java/com/tky/web/config/bean/BeanConfig.java
Normal file
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* @Title: BeanConfig.java
|
||||
* @Package com.tky.sanwei.config.bean
|
||||
* @Description: TODO
|
||||
* Copyright: Copyright (c) 2015
|
||||
* Company:TKY
|
||||
*
|
||||
* @author vicene
|
||||
* @date 2017年6月30日 上午9:13:46
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.tky.web.config.bean;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class BeanConfig {
|
||||
|
||||
//定时器调度配置
|
||||
/*@Bean
|
||||
public SchedulerFactoryBean schedulerFactoryBean(){
|
||||
return new SchedulerFactoryBean();
|
||||
}*/
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.tky.web.config.bean;
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.SocketException;
|
||||
|
||||
|
||||
public class GPSUDPReceive {
|
||||
public static void main(String[] args) {
|
||||
DatagramSocket datagramSocket=null;
|
||||
try {
|
||||
//监视8081端口的内容
|
||||
datagramSocket=new DatagramSocket(8081);
|
||||
while(true){
|
||||
byte[] buf=new byte[1024];
|
||||
|
||||
//定义接收数据的数据包
|
||||
DatagramPacket datagramPacket=new DatagramPacket(buf, 0, buf.length);
|
||||
datagramSocket.receive(datagramPacket);
|
||||
//从接收数据包取出数据
|
||||
String data=new String(datagramPacket.getData() , 0 ,datagramPacket.getLength());
|
||||
|
||||
System.out.println("test---------------------------------------------");
|
||||
System.out.println("hahahha--->"+data);
|
||||
}
|
||||
} catch (SocketException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
datagramSocket.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package com.tky.web.config.bean;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.SocketException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.core.Ordered;
|
||||
|
||||
import com.system.util.CacheUtil;
|
||||
import com.system.util.FileUtil;
|
||||
|
||||
/**
|
||||
* GPS监听卡调数据
|
||||
* @author zhangtianlun
|
||||
*
|
||||
*/
|
||||
public class GPSUDPReceiveRunner implements ApplicationRunner, Ordered {
|
||||
private static final Logger logger = (Logger) LoggerFactory.getLogger(GPSUDPReceiveRunner.class);
|
||||
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
/*
|
||||
电文类型 Char 4 电文类型暂时有三个值分别是01,02。01代表定位数据、02代表调度数据
|
||||
电文发送日期时间 Char 20 日期时间格式(yyyy-MM-dd HH:mm:ss)
|
||||
设备编号 Char 4
|
||||
设备类型 Char 4 01卡车 02电铲
|
||||
03 钻机 04钩机
|
||||
设备型号 Char 20
|
||||
司机名称 Char 20
|
||||
经度 Char 12
|
||||
纬度 Char 12
|
||||
速度 Char 12
|
||||
高度 Char 12
|
||||
GPS状态时间 Char 20 日期时间格式(yyyy-MM-dd HH:mm:ss)
|
||||
*/
|
||||
|
||||
(new Thread(
|
||||
new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
DatagramSocket datagramSocket=null;
|
||||
try {
|
||||
//监视8081端口的内容
|
||||
datagramSocket=new DatagramSocket(8081);
|
||||
//System.out.println("卡调UDP启动----------------");
|
||||
while(true){
|
||||
byte[] buf=new byte[1024];
|
||||
//定义接收数据的数据包
|
||||
DatagramPacket datagramPacket=new DatagramPacket(buf, 0, buf.length);
|
||||
datagramSocket.receive(datagramPacket);
|
||||
|
||||
//从接收数据包取出数据
|
||||
String data=new String(datagramPacket.getData() , 0 ,datagramPacket.getLength(),"UTF-8");
|
||||
//data =new String(data.getBytes("UTF-8"), "UTF-8");
|
||||
// data = "01 2019-09-21 21:40:18 1021 01 TR100 孔祥匿 117.290042 49.430657 0.00 722.00 2019-09-21 21:39:56 ";
|
||||
// 数据保存到缓存中
|
||||
System.out.println("卡调接收原始数据:\r\n" +data);
|
||||
if(data!=null&&data.length()>28
|
||||
&& "01".equals(data.substring(0,2) ) // 调车数据
|
||||
&& "01 ".equals(data.substring(32,36)) //设备类型是卡车
|
||||
){
|
||||
try {
|
||||
|
||||
data = data.replaceAll("\0",""); // 去掉 \0字符
|
||||
//FileUtil.append("C:\\kadiao.txt", data , true);
|
||||
// 保存数据到缓存中
|
||||
//CacheUtil.put(data.substring(24,28), data);
|
||||
System.out.println("卡调接收数据:" +data+"卡调名称:"+data.substring(24,28));
|
||||
// ----------------解析数据------------
|
||||
// 电文类型
|
||||
String dwlx = data.substring(0,4).trim();
|
||||
// 电文发送日期时间
|
||||
String dwfsrqsj = data.substring(4,24).trim();
|
||||
// 设备编号
|
||||
String sbbh = data.substring(24,32).trim();
|
||||
// 设备类型
|
||||
String sblx = data.substring(32,36).trim();
|
||||
// 设备型号
|
||||
String sbxh = data.substring(36,56).trim();
|
||||
// 司机名称
|
||||
String sjmc = data.substring(56,70).trim();
|
||||
|
||||
//56位个字符串: 117.267717 49.419899 0.00 698.00 2019-11-19 22:45:26
|
||||
// 经度
|
||||
//String lon = data.substring(data.le,82).trim();
|
||||
String lon = data.substring(data.length()-68,data.length() - 56).trim();
|
||||
// 纬度
|
||||
//String lat = data.substring(82,94).trim();
|
||||
String lat = data.substring(data.length()-56,data.length() - 44).trim();
|
||||
// 速度
|
||||
//String speed = data.substring(94,106).trim();
|
||||
String speed = data.substring(data.length()-44,data.length() - 32).trim();
|
||||
// 高度
|
||||
//String height = data.substring(106,118).trim();
|
||||
String height = data.substring(data.length()-32,data.length() - 20).trim();
|
||||
// GPS状态时间
|
||||
//String gpsTime = data.substring(118,138).trim();
|
||||
String gpsTime = data.substring(data.length()-20,data.length()).trim();
|
||||
|
||||
if("01".equals(sblx)) sblx = "卡车";
|
||||
if("02".equals(sblx))sblx = "电铲";
|
||||
if("03".equals(sblx))sblx = "钻机";
|
||||
if("04".equals(sblx)) sblx = "钩机";
|
||||
// ----------------保存数据到缓存中------------
|
||||
Map<String,String> map = new HashMap<String,String>();
|
||||
map.put("dwlx", dwlx);
|
||||
map.put("dwfsrqsj", dwfsrqsj);
|
||||
map.put("sbbh", sbbh);
|
||||
map.put("sblx", sblx);
|
||||
map.put("sbxh", sbxh);
|
||||
map.put("sjmc", sjmc);
|
||||
map.put("lon", lon);
|
||||
map.put("lat", lat);
|
||||
map.put("speed", speed);
|
||||
map.put("height", height);
|
||||
map.put("gpsTime", gpsTime);
|
||||
// 保存数据到缓存中
|
||||
CacheUtil.put(sbbh, map);
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}//--if
|
||||
|
||||
} //while
|
||||
} catch (SocketException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
datagramSocket.close();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
)).start();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
/*
|
||||
卡调真实数据:
|
||||
|
||||
01 2019-11-19 22:45:28 1058 01 TR100 衡正 117.267717 49.419899 0.00 698.00 2019-11-19 22:45:26
|
||||
01 2019-11-19 22:45:28 1008 01 TR100 朱宝富 117.266452 49.421816 0.00 725.00 2019-11-19 22:45:26
|
||||
01 2019-11-19 22:45:29 1010 01 TR100 张春雷 117.281472 49.415455 21.00 792.00 2019-11-19 22:45:26
|
||||
01 2019-11-19 22:45:29 1003 01 TR100 张春宝 117.302462 49.430329 31.00 753.00 2019-11-19 22:45:26
|
||||
01 2019-11-19 22:45:29 1051 01 TR100 刘世海 117.273850 49.416181 17.00 731.00 2019-11-19 22:45:27
|
||||
01 2019-11-19 22:45:29 1059 01 TR100 郭八虎 117.296886 49.430011 26.00 707.00 2019-11-19 22:45:27
|
||||
01 2019-11-19 22:45:29 1012 01 TR100 于革辉 117.278530 49.415482 17.00 779.00 2019-11-19 22:45:27
|
||||
01 2019-11-19 22:45:29 1063 01 TR100 徐志勇 117.301252 49.425573 41.00 679.00 2019-11-19 22:45:27
|
||||
01 2019-11-19 22:45:30 1005 01 TR100 张立军 117.299206 49.405808 19.00 869.00 2019-11-19 22:45:27
|
||||
01 2019-11-19 22:45:30 2913 02 12号700 康长利 117.284252 49.422656 0.00 738.00 2019-11-19 22:45:28
|
||||
01 2019-11-19 22:45:30 1066 01 TR100 姜学生 117.295217 49.429476 0.00 690.00 2019-11-19 22:45:28
|
||||
01 2019-11-19 22:45:30 2713 02 13号700 谢俊才 117.297809 49.423414 12.00 620.00 2019-11-19 22:45:28
|
||||
01 2019-11-19 22:45:30 1060 01 TR100 陈祥均 117.301205 49.417908 19.00 824.00 2019-11-19 22:45:28
|
||||
01 2019-11-19 22:45:30 1062 01 TR100 王维友 117.297630 49.429831 25.00 706.00 2019-11-19 22:45:28
|
||||
01 2019-11-19 22:45:30 1069 01 TR100 李生北 117.301469 49.415189 0.00 837.00 2019-11-19 22:45:28
|
||||
01 2019-11-19 22:45:31 1068 01 TR100 韩志江 117.302424 49.419029 27.00 814.00 2019-11-19 22:45:28
|
||||
01 2019-11-19 22:45:31 1026 01 TR100 赵振林 117.302765 49.417150 0.00 829.00 2019-11-19 22:45:29
|
||||
01 2019-11-19 22:45:31 1011 01 TR100 马万全 117.267843 49.417647 0.00 707.00 2019-11-19 22:45:29
|
||||
01 2019-11-19 22:45:31 1065 01 TR100 靳桂峰 117.297990 49.420709 0.00 648.00 2019-11-19 22:45:29
|
||||
01 2019-11-19 22:45:31 2915 02 15号700 高世伟 117.297753 49.427781 0.00 652.00 2019-11-19 22:45:29
|
||||
01 2019-11-19 22:45:31 1050 01 TR100 孙振清 117.298911 49.421012 20.00 647.00 2019-11-19 22:45:29
|
||||
01 2019-11-19 22:45:32 1019 01 TR100 罗军 117.295570 49.429312 15.00 694.00 2019-11-19 22:45:29
|
||||
01 2019-11-19 22:45:32 1006 01 TR100 邹成宝 117.299276 49.406296 28.00 853.00 2019-11-19 22:45:30
|
||||
01 2019-11-19 22:45:32 1053 01 TR100 117.297994 49.431218 16.00 732.00 2019-11-19 22:45:30
|
||||
01 2019-11-19 22:45:33 1013 01 TR100 翟永林 117.280557 49.403219 19.00 867.00 2019-11-19 22:45:30
|
||||
01 2019-11-19 22:45:33 1021 01 TR100 李艳宝 117.301473 49.415413 0.00 832.00 2019-11-19 22:45:30
|
||||
01 2019-11-19 22:45:33 1057 01 TR100 胡国友 117.295048 49.429597 4.00 691.00 2019-11-19 22:45:30
|
||||
01 2019-11-19 22:45:33 1023 01 TR100 赵占平 117.301332 49.417892 25.00 821.00 2019-11-19 22:45:31
|
||||
01 2019-11-19 22:38:42 2005 02 5号电铲 李春天 117.000000 49.000000 0.00 0.00 2019-11-19 22:38:42
|
||||
01 2019-11-19 22:45:33 1028 01 TR100 陈国福 117.283016 49.422100 30.00 755.00 2019-11-19 22:45:31
|
||||
01 2019-11-19 22:45:33 1022 01 TR100 117.297227 49.416144 22.00 825.00 2019-11-19 22:45:31
|
||||
01 2019-11-19 22:45:33 1009 01 TR100 宫建军 117.275131 49.414965 16.00 756.00 2019-11-19 22:45:31
|
||||
01 2019-11-19 22:45:33 1027 01 TR100 王喜民 117.272203 49.415024 18.00 752.00 2019-11-19 22:45:31
|
||||
01 2019-11-19 22:45:34 1008 01 TR100 朱宝富 117.266451 49.421816 0.00 725.00 2019-11-19 22:45:31
|
||||
01 2019-11-19 22:45:34 1010 01 TR100 张春雷 117.281843 49.415310 24.00 792.00 2019-11-19 22:45:31
|
||||
01 2019-11-19 22:45:34 1001 01 TR100 孙红伟 117.301199 49.430908 23.00 735.00 2019-11-19 22:45:32
|
||||
01 2019-11-19 22:45:34 1051 01 TR100 刘世海 117.274230 49.416211 16.00 733.00 2019-11-19 22:45:32
|
||||
01 2019-11-19 22:45:34 1056 01 TR100 唐风生 117.301362 49.415782 0.00 829.00 2019-11-19 22:45:32
|
||||
01 2019-11-19 22:45:34 1012 01 TR100 于革辉 117.278865 49.415517 19.00 780.00 2019-11-19 22:45:32
|
||||
01 2019-11-19 22:45:35 1005 01 TR100 张立军 117.299374 49.405567 24.00 870.00 2019-11-19 22:45:32
|
||||
01 2019-11-19 22:45:35 1052 01 TR100 钟占胜 117.301268 49.417948 21.00 821.00 2019-11-19 22:45:33
|
||||
01 2019-11-19 22:45:35 1055 01 TR100 117.299554 49.421082 19.00 646.00 2019-11-19 22:45:33
|
||||
01 2019-11-19 22:45:35 2713 02 13号700 谢俊才 117.297809 49.423414 12.00 620.00 2019-11-19 22:45:33
|
||||
01 2019-11-19 22:45:35 1058 01 TR100 衡正 117.267713 49.419895 0.00 697.00 2019-11-19 22:45:33
|
||||
01 2019-11-19 22:45:35 1060 01 TR100 陈祥均 117.300935 49.417751 19.00 826.00 2019-11-19 22:45:33
|
||||
01 2019-11-19 22:45:35 1003 01 TR100 张春宝 117.301826 49.430659 31.00 748.00 2019-11-19 22:45:33
|
||||
01 2019-11-19 22:45:35 1062 01 TR100 王维友 117.297171 49.429918 25.00 706.00 2019-11-19 22:45:33
|
||||
01 2019-11-19 22:45:36 1059 01 TR100 郭八虎 117.296378 49.430185 24.00 707.00 2019-11-19 22:45:33
|
||||
01 2019-11-19 22:45:36 1063 01 TR100 徐志勇 117.301080 49.425032 35.00 677.00 2019-11-19 22:45:33
|
||||
01 2019-11-19 22:45:36 1065 01 TR100 靳桂峰 117.297988 49.420709 0.00 648.00 2019-11-19 22:45:34
|
||||
01 2019-11-19 22:45:36 2915 02 15号700 高世伟 117.297753 49.427781 0.00 652.00 2019-11-19 22:45:34
|
||||
01 2019-11-19 22:45:36 1050 01 TR100 孙振清 117.298646 49.420942 12.00 642.00 2019-11-19 22:45:34
|
||||
01 2019-11-19 22:45:37 1066 01 TR100 姜学生 117.295217 49.429476 0.00 690.00 2019-11-19 22:45:34
|
||||
01 2019-11-19 22:45:37 1019 01 TR100 罗军 117.295873 49.429282 17.00 693.00 2019-11-19 22:45:34
|
||||
01 2019-11-19 22:45:37 1006 01 TR100 邹成宝 117.299263 49.406709 36.00 851.00 2019-11-19 22:45:35
|
||||
01 2019-11-19 22:45:37 1067 01 TR100 王连伍 117.272671 49.415002 29.00 749.00 2019-11-19 22:45:35
|
||||
01 2019-11-19 22:45:37 1069 01 TR100 李生北 117.301467 49.415186 0.00 837.00 2019-11-19 22:45:35
|
||||
01 2019-11-19 22:45:37 1068 01 TR100 韩志江 117.302148 49.418645 23.00 817.00 2019-11-19 22:45:35
|
||||
01 2019-11-19 22:45:38 1011 01 TR100 马万全 117.267842 49.417647 0.00 707.00 2019-11-19 22:45:35
|
||||
01 2019-11-19 22:45:38 1057 01 TR100 胡国友 117.295026 49.429664 4.00 691.00 2019-11-19 22:45:36
|
||||
01 2019-11-19 22:38:47 2005 02 5号电铲 李春天 117.000000 49.000000 0.00 0.00 2019-11-19 22:38:47
|
||||
01 2019-11-19 22:45:38 1023 01 TR100 赵占平 117.301707 49.418145 27.00 820.00 2019-11-19 22:45:36
|
||||
01 2019-11-19 22:45:38 1028 01 TR100 陈国福 117.282521 49.422364 35.00 750.00 2019-11-19 22:45:36
|
||||
01 2019-11-19 22:45:39 1009 01 TR100 宫建军 117.275413 49.415026 15.00 759.00 2019-11-19 22:45:36
|
||||
01 2019-11-19 22:45:39 1008 01 TR100 朱宝富 117.266450 49.421813 0.00 725.00 2019-11-19 22:45:36
|
||||
01 2019-11-19 22:45:39 1053 01 TR100 117.298415 49.431169 16.00 733.00 2019-11-19 22:45:37
|
||||
01 2019-11-19 22:45:39 1010 01 TR100 张春雷 117.282215 49.415014 26.00 792.00 2019-11-19 22:45:37
|
||||
01 2019-11-19 22:45:39 1051 01 TR100 刘世海 117.274518 49.416233 16.00 735.00 2019-11-19 22:45:37
|
||||
01 2019-11-19 22:45:39 1012 01 TR100 于革辉 117.279258 49.415543 22.00 780.00 2019-11-19 22:45:37
|
||||
01 2019-11-19 22:45:39 1021 01 TR100 李艳宝 117.301440 49.415426 0.00 834.00 2019-11-19 22:45:37
|
||||
01 2019-11-19 22:45:39 1020 01 TR100 117.285456 49.414710 38.00 791.00 2019-11-19 22:45:37
|
||||
01 2019-11-19 22:45:40 1022 01 TR100 117.297910 49.416165 28.00 826.00 2019-11-19 22:45:38
|
||||
01 2019-11-19 22:45:40 1005 01 TR100 张立军 117.299413 49.405202 25.00 871.00 2019-11-19 22:45:38
|
||||
01 2019-11-19 22:45:40 1027 01 TR100 王喜民 117.272748 49.414879 27.00 751.00 2019-11-19 22:45:38
|
||||
01 2019-11-19 22:45:40 2913 02 12号700 康长利 117.284248 49.422652 0.00 738.00 2019-11-19 22:45:38
|
||||
01 2019-11-19 22:45:40 2713 02 13号700 谢俊才 117.297809 49.423414 12.00 620.00 2019-11-19 22:45:38
|
||||
01 2019-11-19 22:45:40 1001 01 TR100 孙红伟 117.301593 49.430734 19.00 738.00 2019-11-19 22:45:38
|
||||
01 2019-11-19 22:45:40 1060 01 TR100 陈祥均 117.300663 49.417602 18.00 827.00 2019-11-19 22:45:38
|
||||
01 2019-11-19 22:45:41 1056 01 TR100 唐风生 117.301362 49.415784 0.00 830.00 2019-11-19 22:45:38
|
||||
01 2019-11-19 22:45:41 1062 01 TR100 王维友 117.296727 49.430039 25.00 705.00 2019-11-19 22:45:38
|
||||
01 2019-11-19 22:45:41 1065 01 TR100 靳桂峰 117.297987 49.420709 0.00 648.00 2019-11-19 22:45:39
|
||||
01 2019-11-19 22:45:41 2878 02 9号870 杨传超 117.266297 49.421868 1.00 727.00 2019-11-19 22:45:39
|
||||
01 2019-11-19 22:45:41 2915 02 15号700 高世伟 117.297753 49.427781 0.00 652.00 2019-11-19 22:45:39
|
||||
01 2019-11-19 22:45:41 1052 01 TR100 钟占胜 117.300858 49.417712 20.00 824.00 2019-11-19 22:45:39
|
||||
01 2019-11-19 22:45:42 1050 01 TR100 孙振清 117.298481 49.420822 9.00 635.00 2019-11-19 22:45:39
|
||||
01 2019-11-19 22:45:42 1058 01 TR100 衡正 117.267705 49.419887 0.00 696.00 2019-11-19 22:45:40
|
||||
01 2019-11-19 22:45:42 1019 01 TR100 罗军 117.296267 49.429260 17.00 693.00 2019-11-19 22:45:40
|
||||
01 2019-11-19 22:45:42 1059 01 TR100 郭八虎 117.295799 49.430421 25.00 706.00 2019-11-19 22:45:40
|
||||
01 2019-11-19 22:45:42 1063 01 TR100 徐志勇 117.300981 49.424419 37.00 673.00 2019-11-19 22:45:40
|
||||
01 2019-11-19 22:45:43 1057 01 TR100 胡国友 117.295009 49.429683 0.00 690.00 2019-11-19 22:45:41
|
||||
01 2019-11-19 22:38:52 2005 02 5号电铲 李春天 117.000000 49.000000 0.00 0.00 2019-11-19 22:38:52
|
||||
01 2019-11-19 22:45:43 1023 01 TR100 赵占平 117.302016 49.418403 26.00 817.00 2019-11-19 22:45:41
|
||||
01 2019-11-19 22:45:43 1016 01 TR100 王贵兴 117.267986 49.417755 0.00 707.00 2019-11-19 22:45:41
|
||||
01 2019-11-19 22:45:43 1028 01 TR100 陈国福 117.281985 49.422668 38.00 746.00 2019-11-19 22:45:41
|
||||
01 2019-11-19 22:45:43 1066 01 TR100 姜学生 117.295219 49.429476 0.00 690.00 2019-11-19 22:45:41
|
||||
01 2019-11-19 22:45:44 1009 01 TR100 宫建军 117.275661 49.415068 13.00 762.00 2019-11-19 22:45:41
|
||||
01 2019-11-19 22:45:44 1067 01 TR100 王连伍 117.272255 49.415224 19.00 749.00 2019-11-19 22:45:41
|
||||
01 2019-11-19 22:45:44 1008 01 TR100 朱宝富 117.266450 49.421815 0.00 726.00 2019-11-19 22:45:42
|
||||
01 2019-11-19 22:45:44 1069 01 TR100 李生北 117.301473 49.415183 0.00 837.00 2019-11-19 22:45:42
|
||||
01 2019-11-19 22:38:53 2003 02 3号电铲 赵金新 117.295168 49.429745 0.00 702.00 2019-11-19 22:38:53
|
||||
01 2019-11-19 22:45:44 1010 01 TR100 张春雷 117.282490 49.414708 29.00 790.00 2019-11-19 22:45:42
|
||||
01 2019-11-19 22:45:44 1068 01 TR100 韩志江 117.301828 49.418324 21.00 820.00 2019-11-19 22:45:42
|
||||
01 2019-11-19 22:45:44 1051 01 TR100 刘世海 117.274837 49.416167 21.00 736.00 2019-11-19 22:45:42
|
||||
01 2019-11-19 22:45:44 1012 01 TR100 于革辉 117.279658 49.415543 20.00 782.00 2019-11-19 22:45:42
|
||||
01 2019-11-19 22:45:45 1005 01 TR100 张立军 117.299453 49.404879 27.00 871.00 2019-11-19 22:45:43
|
||||
01 2019-11-19 22:45:45 2913 02 12号700 康长利 117.284249 49.422649 0.00 738.00 2019-11-19 22:45:43
|
||||
01 2019-11-19 22:45:45 2713 02 13号700 谢俊才 117.297809 49.423414 12.00 620.00 2019-11-19 22:45:43
|
||||
01 2019-11-19 22:45:46 1060 01 TR100 陈祥均 117.300389 49.417457 20.00 828.00 2019-11-19 22:45:43
|
||||
01 2019-11-19 22:45:46 1053 01 TR100 117.298794 49.431131 17.00 735.00 2019-11-19 22:45:43
|
||||
01 2019-11-19 22:45:46 1062 01 TR100 王维友 117.296309 49.430197 26.00 704.00 2019-11-19 22:45:43
|
||||
01 2019-11-19 22:45:46 1026 01 TR100 赵振林 117.302755 49.417143 0.00 830.00 2019-11-19 22:45:44
|
||||
01 2019-11-19 22:45:46 1065 01 TR100 靳桂峰 117.297987 49.420710 0.00 648.00 2019-11-19 22:45:44
|
||||
01 2019-11-19 22:45:46 1021 01 TR100 李艳宝 117.301419 49.415432 0.00 835.00 2019-11-19 22:45:44
|
||||
01 2019-11-19 22:45:46 2915 02 15号700 高世伟 117.297753 49.427779 0.00 652.00 2019-11-19 22:45:44
|
||||
01 2019-11-19 22:45:47 1022 01 TR100 117.298592 49.416166 31.00 827.00 2019-11-19 22:45:44
|
||||
01 2019-11-19 22:45:47 1050 01 TR100 孙振清 117.298401 49.420794 1.00 633.00 2019-11-19 22:45:44
|
||||
01 2019-11-19 22:45:47 1019 01 TR100 罗军 117.296609 49.429248 18.00 693.00 2019-11-19 22:45:45
|
||||
01 2019-11-19 22:45:47 1001 01 TR100 孙红伟 117.302003 49.430588 16.00 740.00 2019-11-19 22:45:45
|
||||
01 2019-11-19 22:45:48 1056 01 TR100 唐风生 117.301362 49.415786 0.00 830.00 2019-11-19 22:45:45
|
||||
01 2019-11-19 22:45:48 1015 01 TR100 李忠山 117.270441 49.417144 36.00 713.00 2019-11-19 22:45:46
|
||||
01 2019-11-19 22:38:57 2005 02 5号电铲 李春天 117.000000 49.000000 0.00 0.00 2019-11-19 22:38:57
|
||||
01 2019-11-19 22:45:48 1052 01 TR100 钟占胜 117.300447 49.417499 20.00 826.00 2019-11-19 22:45:46
|
||||
01 2019-11-19 22:45:48 1023 01 TR100 赵占平 117.302218 49.418739 27.00 813.00 2019-11-19 22:45:46
|
||||
01 2019-11-19 22:45:49 1058 01 TR100 衡正 117.267694 49.419890 0.00 695.00 2019-11-19 22:45:46
|
||||
*/
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.tky.web.config.bean;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
|
||||
import com.hikvision.artemis.sdk.config.ArtemisConfig;
|
||||
|
||||
public class GetCameraPreviewURL {
|
||||
|
||||
public static String GetCameraPreviewURL() {
|
||||
|
||||
/**
|
||||
* STEP1:设置平台参数,根据实际情况,设置host appkey appsecret 三个参数.
|
||||
*/
|
||||
ArtemisConfig.host = "192.168.15.9:443"; // artemis网关服务器ip端口
|
||||
ArtemisConfig.appKey = "25546701"; // 秘钥appkey
|
||||
ArtemisConfig.appSecret = "PJsKRawg2bCLeVVnnW2S";// 秘钥appSecret
|
||||
|
||||
/**
|
||||
* STEP2:设置OpenAPI接口的上下文
|
||||
*/
|
||||
final String ARTEMIS_PATH = "/artemis";
|
||||
|
||||
/**
|
||||
* STEP3:设置接口的URI地址
|
||||
*/
|
||||
final String previewURLsApi = ARTEMIS_PATH + "/api/video/v1/cameras/previewURLs";
|
||||
Map<String, String> path = new HashMap<String, String>(2) {
|
||||
{
|
||||
put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* STEP4:设置参数提交方式
|
||||
*/
|
||||
String contentType = "application/json";
|
||||
|
||||
/**
|
||||
* STEP5:组装请求参数
|
||||
*/
|
||||
JSONObject jsonBody = new JSONObject();
|
||||
jsonBody.put("cameraIndexCode", "818888e4d54c4db2b7ff3d5ddb6b9067");
|
||||
jsonBody.put("streamType", 0);
|
||||
jsonBody.put("protocol", "rtsp");
|
||||
jsonBody.put("transmode", 1);
|
||||
jsonBody.put("expand", "streamform=ps");
|
||||
String body = jsonBody.toJSONString();
|
||||
/**
|
||||
* STEP6:调用接口
|
||||
*/
|
||||
String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType , null);// post请求application/json类型参数
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String result = GetCameraPreviewURL();
|
||||
System.setProperty("javax.net.debug", "ssl");
|
||||
System.out.println("result结果示例: " + result);
|
||||
}
|
||||
}
|
||||
36
ndplan/src/main/java/com/tky/web/config/bean/JobRunner.java
Normal file
36
ndplan/src/main/java/com/tky/web/config/bean/JobRunner.java
Normal file
@@ -0,0 +1,36 @@
|
||||
package com.tky.web.config.bean;
|
||||
|
||||
|
||||
import org.quartz.Scheduler;
|
||||
import org.quartz.SchedulerFactory;
|
||||
import org.quartz.impl.StdSchedulerFactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.core.Ordered;
|
||||
|
||||
/**
|
||||
* 运行定时器任务
|
||||
* @author zhangtianlun
|
||||
*
|
||||
*/
|
||||
public class JobRunner implements ApplicationRunner, Ordered {
|
||||
private static final Logger logger = (Logger) LoggerFactory.getLogger(JobRunner.class);
|
||||
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
|
||||
Scheduler sche = gSchedulerFactory.getScheduler();
|
||||
String job_name = "动态任务调度";
|
||||
|
||||
//QuartzManager.addJob(sche, job_name, SideSlopeQuartzJob.class, "0 */50 * * * ?");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* @Title: SystemApp.java
|
||||
* @Package com.tky.dzgcrz.dto
|
||||
* @Description: TODO
|
||||
* Copyright: Copyright (c) 2015
|
||||
* Company:TKY
|
||||
*
|
||||
* @author vicene
|
||||
* @date 2017年8月12日 下午3:14:42
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.tky.web.config.bean;
|
||||
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
|
||||
/**
|
||||
* TODO系统应用appid和秘钥
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "system-app")
|
||||
public class SystemAppConfig {
|
||||
private String appid;
|
||||
private String appsecret;
|
||||
private String tokenurl;
|
||||
private String loginurl;
|
||||
private String userinfobyidurl;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.tky.web.config.swagger;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Optional;
|
||||
import com.google.common.base.Predicate;
|
||||
|
||||
import springfox.documentation.RequestHandler;
|
||||
import springfox.documentation.builders.ApiInfoBuilder;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.service.Contact;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
|
||||
@Configuration
|
||||
@EnableSwagger2
|
||||
public class SwaggerConfig {
|
||||
@Bean
|
||||
public Docket createRestApi() {
|
||||
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
|
||||
.select()
|
||||
.apis(basePackage("com.tky.web;com.system"))
|
||||
.paths(PathSelectors.any()).build();
|
||||
}
|
||||
|
||||
private ApiInfo apiInfo() {
|
||||
return new ApiInfoBuilder().title("Manage Swagger RESTful APIs")
|
||||
.description("矿山三维系统")
|
||||
.termsOfServiceUrl("http://swagger.io/")
|
||||
.contact(new Contact("liuteng", "127.0.0.1", "liuteng@hotmail.com"))
|
||||
.version("1.0")
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
public static Predicate<RequestHandler> basePackage(final String basePackage) {
|
||||
return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
|
||||
}
|
||||
|
||||
private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
|
||||
return input -> {
|
||||
// 循环判断匹配
|
||||
for (String strPackage : basePackage.split(";")) {
|
||||
boolean isMatch = input.getPackage().getName().startsWith(strPackage);
|
||||
if (isMatch) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
|
||||
return Optional.fromNullable(input.declaringClass());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.tky.web.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/gis")
|
||||
public class GISController {
|
||||
|
||||
@RequestMapping("/demo")
|
||||
public String Hello() {
|
||||
System.out.println("Hello springboot");
|
||||
return "hello,this is a gis service api!~";
|
||||
}
|
||||
}
|
||||
18
ndplan/src/main/java/com/tky/web/dao/EnterpriseDao.java
Normal file
18
ndplan/src/main/java/com/tky/web/dao/EnterpriseDao.java
Normal file
@@ -0,0 +1,18 @@
|
||||
package com.tky.web.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import com.tky.web.entity.Enterprise;
|
||||
|
||||
public interface EnterpriseDao extends JpaRepository<Enterprise,Long> , JpaSpecificationExecutor<Enterprise>{
|
||||
@Query(value="select * from aq_bs_enterprise where useflag = 1 ORDER BY num ", nativeQuery=true)
|
||||
public List<Enterprise> findAll();
|
||||
|
||||
|
||||
@Query(value="select * from aq_bs_enterprise where useflag = 1 ORDER BY nlssort(abbr,'NLS_SORT=SCHINESE_PINYIN_M')", nativeQuery=true)
|
||||
public List<Enterprise> findAllOrderByAbbr();
|
||||
}
|
||||
12
ndplan/src/main/java/com/tky/web/dao/UserDao.java
Normal file
12
ndplan/src/main/java/com/tky/web/dao/UserDao.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.tky.web.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import com.tky.web.entity.User;
|
||||
|
||||
public interface UserDao extends JpaRepository<User,Long> , JpaSpecificationExecutor<User>{
|
||||
}
|
||||
37
ndplan/src/main/java/com/tky/web/dto/TreeNode.java
Normal file
37
ndplan/src/main/java/com/tky/web/dto/TreeNode.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.tky.web.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class TreeNode {
|
||||
public static String TREENODESTATE_OPEN = "open";
|
||||
public static String TREENODESTATE_CLOSED = "closed";
|
||||
|
||||
private Long id;
|
||||
private Integer type;
|
||||
private String typestr;
|
||||
private String text;
|
||||
private String name;
|
||||
private String state = TREENODESTATE_OPEN;
|
||||
private String iconCls;
|
||||
private String iconType; // 图标类型
|
||||
private Object source;
|
||||
private List<TreeNode> children;
|
||||
private Double lon;
|
||||
private Double lat;
|
||||
private Double height;
|
||||
public TreeNode(Long id, Integer type, String text, String state) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.type = type;
|
||||
this.text = text;
|
||||
this.name = text;
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
52
ndplan/src/main/java/com/tky/web/entity/Enterprise.java
Normal file
52
ndplan/src/main/java/com/tky/web/entity/Enterprise.java
Normal file
@@ -0,0 +1,52 @@
|
||||
package com.tky.web.entity;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
/**
|
||||
* 企业
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name="aq_bs_enterprise") // 安全_基础_企业
|
||||
@org.hibernate.annotations.Table(appliesTo = "aq_bs_enterprise", comment = "企业")
|
||||
public class Enterprise {
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="aq_bs_enterprise_ID_SEQ")
|
||||
@SequenceGenerator(name="aq_bs_enterprise_ID_SEQ",sequenceName="aq_bs_enterprise_ID_SEQ",allocationSize=1)
|
||||
private Long id;
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '企业编号' ")
|
||||
private String code;
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '企业名称' ")
|
||||
private String name;
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '企业简称' ")
|
||||
private String abbr;
|
||||
|
||||
//@Column(columnDefinition = "double COMMENT '经度' ")
|
||||
private Double lon;
|
||||
|
||||
//@Column(columnDefinition = "double COMMENT '纬度' ")
|
||||
private Double lat;
|
||||
|
||||
//@Column(columnDefinition = "double COMMENT '高度' ")
|
||||
private Double height;
|
||||
|
||||
//@Column(columnDefinition = "varchar(50) COMMENT '企业类型' ")
|
||||
private String type;
|
||||
|
||||
//@Column(columnDefinition = "varchar(50) COMMENT '企业性质' ")
|
||||
private String quality;
|
||||
|
||||
//@Column(columnDefinition = "int COMMENT '排序' ")
|
||||
private Integer num;
|
||||
|
||||
//@Column(columnDefinition = "integer COMMENT '是否使用,1是,0删除'")
|
||||
private Integer useflag;
|
||||
|
||||
}
|
||||
46
ndplan/src/main/java/com/tky/web/entity/User.java
Normal file
46
ndplan/src/main/java/com/tky/web/entity/User.java
Normal file
@@ -0,0 +1,46 @@
|
||||
package com.tky.web.entity;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 用户
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name="t_user")
|
||||
@org.hibernate.annotations.Table(appliesTo = "t_user", comment = "用户")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '账号名称' ")
|
||||
private String username;
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '密码' ")
|
||||
private String password;
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '单位名称' ")
|
||||
private String company;
|
||||
|
||||
//@Column(columnDefinition = "varchar(255) COMMENT '角色' ")
|
||||
private String role;
|
||||
|
||||
//@Column(columnDefinition = "timestamp COMMENT '上传时间' ")
|
||||
private Date createtime;
|
||||
|
||||
//@Column(columnDefinition = "integer COMMENT '是否使用,1是,0删除'")
|
||||
private Integer useflag;
|
||||
|
||||
}
|
||||
3
ndplan/src/main/resources/appkey.properties
Normal file
3
ndplan/src/main/resources/appkey.properties
Normal file
@@ -0,0 +1,3 @@
|
||||
appid=7b59450e7a
|
||||
appsecret=b327cb45ab17b59450e7a2d340a5ae44
|
||||
jypappid=1510562287779048
|
||||
25
ndplan/src/main/resources/application-local.yml
Normal file
25
ndplan/src/main/resources/application-local.yml
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://152.136.214.62/kssw?useUnicode=true&characterEncoding=utf-8&useSSL=false
|
||||
username: root
|
||||
password: 1qazxsw2
|
||||
driver-class-name: com.mysql.jdbc.Driver
|
||||
|
||||
basicPlatform:
|
||||
loginUrl: http://10.30.1.9:9880/baseservicetest/rest/secret/login
|
||||
getSSOUserInfoByToken: http://10.30.1.9:9300/servicesapitest/users/getSSOUserInfoByToken/
|
||||
getDepartpartmentsByUserId: http://10.30.1.9:9300/servicesapitest/users/getJSDeptsByUserId/{userid}
|
||||
getProjectinfoByUserId: http://10.30.1.9:9300/servicesapitest/users/getProjectinfoByUserId/{id}
|
||||
getAllArea: http://10.30.1.9:9300/servicesapitest/categoryItems/getCategoryItems
|
||||
getUserByLoginAccountUrl: http://10.30.1.9:9300/servicesapitest/users/getUserByAccount/
|
||||
getUserByIdUrl: http://10.30.1.9:9300/servicesapitest/users/getUserById/
|
||||
getProjectAreaByUserId: http://10.30.1.9:9300/servicesapitest/users/getProjectAreaByUserId/{userid}
|
||||
getBdInfo: http://10.30.1.9:9300/servicesapitest/projectSection/getProjectSectionById/{id}
|
||||
getProjectSectionByUserId: http://10.30.1.9:9300/servicesapitest/users/getProjectSectionByUserId/{userid}
|
||||
getProjectInfosByCategoryItemId: http://10.30.1.9:9300/servicesapitest/categoryItems/getProjectInfoItemId/{categoryItemId}
|
||||
getProjectSectionByProjectInfoId: http://10.30.1.9:9300/servicesapitest/projectInfo/getProjectSectionByInfoId/
|
||||
getSGByJL: http://10.30.1.9:9300/servicesapitest/projectSection/getProjectSectionList/
|
||||
getBuildByProjectSectionId: http://10.30.1.9:9300/servicesapitest/projectSection/getBuildList/
|
||||
getProjectSiteListById: http://10.30.1.9:9300/servicesapitest/build/getProjectSiteListById/w'w
|
||||
getBbsBySiteId: http://10.1.0.157:8080/gcstfj/bbsinterface/getDataOnebyOne?
|
||||
52
ndplan/src/main/resources/application-mysql.yml
Normal file
52
ndplan/src/main/resources/application-mysql.yml
Normal file
@@ -0,0 +1,52 @@
|
||||
server:
|
||||
port: 8080
|
||||
context-path: /kssw
|
||||
tomcat:
|
||||
uri-encoding: utf-8
|
||||
|
||||
spring:
|
||||
profiles:
|
||||
## 具体加载的什么环境的配置文件
|
||||
active: test
|
||||
mvc:
|
||||
view:
|
||||
prefix: /
|
||||
suffix: .jsp
|
||||
http:
|
||||
multipart:
|
||||
maxFileSize: 104800Mb
|
||||
maxRequestSize: 20000Mb
|
||||
jpa:
|
||||
generate-ddl: false
|
||||
database: mysql
|
||||
show-sql: true
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
naming:
|
||||
properties:
|
||||
hibernate:
|
||||
hbm2ddl:
|
||||
auto: update
|
||||
current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
|
||||
###########日志
|
||||
logging:
|
||||
level:
|
||||
root: INFO
|
||||
org.hibernate: INFO
|
||||
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
|
||||
org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
|
||||
com.tky.sanwei: INFO
|
||||
|
||||
system-app:
|
||||
appid: 8aa67879c0
|
||||
appsecret: 4d02fb08a7a8aa67879c04c5683f3161
|
||||
#appid={appid}&appsecret={appsecret}
|
||||
tokenurl: http://10.1.0.23:30000/baseservice/rest/tokenservice/gettoken?
|
||||
#sessionid={sessionid}&token={token}
|
||||
loginurl: http://10.1.0.23:30000/baseservice/rest/authInfoService/getLoginUser?
|
||||
#{id}
|
||||
userinfobyidurl: http://10.1.0.101/servicesapi/users/getUserById/
|
||||
#########
|
||||
upload:
|
||||
path: D:\Data\
|
||||
sdModifyPath: D:\SanDianQianGai\
|
||||
25
ndplan/src/main/resources/application-oracle152.yml
Normal file
25
ndplan/src/main/resources/application-oracle152.yml
Normal file
@@ -0,0 +1,25 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:oracle:thin:@152.136.214.62:1521:xe
|
||||
username: kssw
|
||||
password: kssw
|
||||
driver-class-name: oracle.jdbc.driver.OracleDriver
|
||||
|
||||
basicPlatform:
|
||||
loginUrl: http://10.30.1.9:9880/baseservicetest/rest/secret/login
|
||||
getSSOUserInfoByToken: http://10.30.1.9:9300/servicesapitest/users/getSSOUserInfoByToken/
|
||||
getDepartpartmentsByUserId: http://10.30.1.9:9300/servicesapitest/users/getJSDeptsByUserId/{userid}
|
||||
getProjectinfoByUserId: http://10.30.1.9:9300/servicesapitest/users/getProjectinfoByUserId/{id}
|
||||
getAllArea: http://10.30.1.9:9300/servicesapitest/categoryItems/getCategoryItems
|
||||
getUserByLoginAccountUrl: http://10.30.1.9:9300/servicesapitest/users/getUserByAccount/
|
||||
getUserByIdUrl: http://10.30.1.9:9300/servicesapitest/users/getUserById/
|
||||
getProjectAreaByUserId: http://10.30.1.9:9300/servicesapitest/users/getProjectAreaByUserId/{userid}
|
||||
getBdInfo: http://10.30.1.9:9300/servicesapitest/projectSection/getProjectSectionById/{id}
|
||||
getProjectSectionByUserId: http://10.30.1.9:9300/servicesapitest/users/getProjectSectionByUserId/{userid}
|
||||
getProjectInfosByCategoryItemId: http://10.30.1.9:9300/servicesapitest/categoryItems/getProjectInfoItemId/{categoryItemId}
|
||||
getProjectSectionByProjectInfoId: http://10.30.1.9:9300/servicesapitest/projectInfo/getProjectSectionByInfoId/
|
||||
getSGByJL: http://10.30.1.9:9300/servicesapitest/projectSection/getProjectSectionList/
|
||||
getBuildByProjectSectionId: http://10.30.1.9:9300/servicesapitest/projectSection/getBuildList/
|
||||
getProjectSiteListById: http://10.30.1.9:9300/servicesapitest/build/getProjectSiteListById/
|
||||
getBbsBySiteId: http://10.1.0.157:8080/gcstfj/bbsinterface/getDataOnebyOne?
|
||||
|
||||
27
ndplan/src/main/resources/application-pro.yml
Normal file
27
ndplan/src/main/resources/application-pro.yml
Normal file
@@ -0,0 +1,27 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:sqlserver://172.25.26.74:1433;DatabaseName=BIMWEB_Test2
|
||||
username: sa
|
||||
password: 123
|
||||
#使用druid数据源
|
||||
type: com.alibaba.druid.pool.DruidDataSource
|
||||
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
|
||||
|
||||
basicPlatform:
|
||||
loginUrl: http://10.1.0.23:30000/baseservice/rest/secret/login
|
||||
getUserByLoginAccountUrl: http://10.1.0.111:9300/servicesapi/users/getUserByAccount/
|
||||
getUserByIdUrl: http://10.1.0.111:9300/servicesapi/users/getUserById/
|
||||
getDepartpartmentsByUserId: http://10.1.0.101/servicesapi/users/getJSDeptsByUserId/{userid}
|
||||
getProjectAreaByUserId: http://10.1.0.101/servicesapi/users/getProjectAreaByUserId/{userid}
|
||||
getBdInfo: http://10.1.0.101/servicesapi/projectSection/getProjectSectionById/{id}
|
||||
getProjectSectionByUserId: http://10.1.0.101/servicesapi/users/getProjectSectionByUserId/{userid}
|
||||
getProjectinfoByUserId: http://10.1.0.101/servicesapi/users/getProjectinfoByUserId/{id}
|
||||
getAllArea: http://10.1.0.101/servicesapi/categoryItems/getCategoryItems
|
||||
getProjectInfosByCategoryItemId: http://10.1.0.101/servicesapi/categoryItems/getProjectInfoItemId/{categoryItemId}
|
||||
getProjectSectionByProjectInfoId: http://10.1.0.101/servicesapi/projectInfo/getProjectSectionByInfoId/
|
||||
getSGByJL: http://10.1.0.101/servicesapi/projectSection/getProjectSectionList/
|
||||
getBuildByProjectSectionId: http://10.1.0.101/servicesapi/projectSection/getBuildList/
|
||||
getProjectSiteListById: http://10.1.0.101/servicesapi/build/getProjectSiteListById/
|
||||
##appid=1503468978582046&siteid=35169&parentid=1011590
|
||||
getBbsBySiteId: http://10.1.0.157:8080/gcstfj/bbsinterface/getDataOnebyOne?
|
||||
getSSOUserInfoByToken: http://10.1.0.101/servicesapi/users/getSSOUserInfoByToken/
|
||||
26
ndplan/src/main/resources/application-test.yml
Normal file
26
ndplan/src/main/resources/application-test.yml
Normal file
@@ -0,0 +1,26 @@
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://152.136.214.62:3306/dzspxt?useUnicode=true&characterEncoding=utf-8&useSSL=false
|
||||
username: root
|
||||
password: Mysql@Password!q2w3e
|
||||
driver-class-name: com.mysql.jdbc.Driver
|
||||
|
||||
|
||||
basic-platform:
|
||||
loginUrl: http://10.30.1.9:9880/baseservicetest/rest/secret/login
|
||||
getSSOUserInfoByToken: http://10.30.1.9:9300/servicesapitest/users/getSSOUserInfoByToken/
|
||||
getDepartpartmentsByUserId: http://10.30.1.9:9300/servicesapitest/users/getJSDeptsByUserId/{userid}
|
||||
getProjectinfoByUserId: http://10.30.1.9:9300/servicesapitest/users/getProjectinfoByUserId/{id}
|
||||
getAllArea: http://10.30.1.9:9300/servicesapitest/categoryItems/getCategoryItems
|
||||
getUserByLoginAccountUrl: http://10.30.1.9:9300/servicesapitest/users/getUserByAccount/
|
||||
getUserByIdUrl: http://10.30.1.9:9300/servicesapitest/users/getUserById/
|
||||
getProjectAreaByUserId: http://10.30.1.9:9300/servicesapitest/users/getProjectAreaByUserId/{userid}
|
||||
getBdInfo: http://10.30.1.9:9300/servicesapitest/projectSection/getProjectSectionById/{id}
|
||||
getProjectSectionByUserId: http://10.30.1.9:9300/servicesapitest/users/getProjectSectionByUserId/{userid}
|
||||
getProjectInfosByCategoryItemId: http://10.30.1.9:9300/servicesapitest/categoryItems/getProjectInfoItemId/{categoryItemId}
|
||||
getProjectSectionByProjectInfoId: http://10.30.1.9:9300/servicesapitest/projectInfo/getProjectSectionByInfoId/
|
||||
getSGByJL: http://10.30.1.9:9300/servicesapitest/projectSection/getProjectSectionList/
|
||||
getBuildByProjectSectionId: http://10.30.1.9:9300/servicesapitest/projectSection/getBuildList/
|
||||
getProjectSiteListById: http://10.30.1.9:9300/servicesapitest/build/getProjectSiteListById/
|
||||
getBbsBySiteId: http://10.1.0.157:8080/gcstfj/bbsinterface/getDataOnebyOne?
|
||||
25
ndplan/src/main/resources/application.yml
Normal file
25
ndplan/src/main/resources/application.yml
Normal file
@@ -0,0 +1,25 @@
|
||||
server:
|
||||
port: 8080
|
||||
servlet:
|
||||
context-path: /ndplan
|
||||
tomcat:
|
||||
uri-encoding: utf-8
|
||||
spring:
|
||||
profiles:
|
||||
active: test
|
||||
main:
|
||||
lazy-initialization: true
|
||||
mvc:
|
||||
view:
|
||||
prefix: /
|
||||
suffix: .jsp
|
||||
jpa:
|
||||
generate-ddl: false
|
||||
database: mysql
|
||||
show-sql: true
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
properties:
|
||||
hibernate:
|
||||
hbm2ddl:
|
||||
auto: update
|
||||
BIN
ndplan/src/main/resources/fdfsclient-jar-with-dependencies.jar
Normal file
BIN
ndplan/src/main/resources/fdfsclient-jar-with-dependencies.jar
Normal file
Binary file not shown.
9
ndplan/src/main/resources/file_service.properties
Normal file
9
ndplan/src/main/resources/file_service.properties
Normal file
@@ -0,0 +1,9 @@
|
||||
|
||||
#test env
|
||||
#serverName=http://10.60.1.160:8080/fdfsServer
|
||||
#token=5a614beb-41ae-4e2f-a5a6-a62e3dd4b93e
|
||||
|
||||
|
||||
# product env
|
||||
serverName=http://10.1.0.231:8080/fdfsServer
|
||||
token=480c3991-3b66-47c7-b40d-4c86f64719e4
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user