Pārlūkot izejas kodu

第一次提交项目

wuweihao 5 gadi atpakaļ
vecāks
revīzija
c5453776fe

+ 0 - 0
s.txt


+ 14 - 0
src/main/java/com/fd/GisCesiumApplication.java

@@ -0,0 +1,14 @@
+package com.fd;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
+
+@SpringBootApplication
+public class GisCesiumApplication extends SpringBootServletInitializer {
+
+    public static void main(String[] args) {
+        SpringApplication.run(GisCesiumApplication.class, args);
+    }
+
+}

+ 41 - 0
src/main/java/com/fd/config/MyInterceptor.java

@@ -0,0 +1,41 @@
+package com.fd.config;
+
+import lombok.extern.log4j.Log4j2;
+import org.springframework.web.servlet.HandlerInterceptor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * Created by Owen on 2019/10/25 0025 16:49
+ *
+ *  拦截验证
+ */
+@Log4j2
+public class MyInterceptor implements HandlerInterceptor {
+
+    //重写preHandle方法
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+        log.info("run preHandle");
+
+        log.info("request url: {}", request.getRequestURL());
+
+
+        String originHeader = request.getHeader("origin");
+//        response.setHeader("Access-Control-Allow-Origin", originHeader);
+        String requestHeaders = request.getHeader("Access-Control-Request-Headers");
+        if (requestHeaders==null) {
+            requestHeaders = "";
+        }
+        response.setHeader("Access-Control-Allow-Credentials", "true");
+        response.setHeader("Access-Control-Allow-Methods", "HEAD,PUT,DELETE,POST,GET");
+        response.setHeader("Access-Control-Allow-Headers", "Accept, Origin, XRequestedWith, Content-Type, LastModified," + requestHeaders);
+        response.setHeader("Access-Control-Allow-Origin", "*");
+
+
+        return true;
+    }
+
+
+}

+ 44 - 0
src/main/java/com/fd/config/Swagger2.java

@@ -0,0 +1,44 @@
+package com.fd.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import springfox.documentation.builders.ApiInfoBuilder;
+import springfox.documentation.builders.PathSelectors;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.service.ApiInfo;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+/**
+ * Created by owen on 2018/4/1
+ *
+ * 集成Swagger有3步:
+ * 1.pom.xml添加依赖
+ * 2.添加Swagger2.class
+ * 3.Application.class 加上注解@EnableSwagger2 表示开启Swagger
+ * 4.http://localhost:8080/swagger-ui.html#/
+ *
+ * 2.9.2 不需要字启动类配置注解
+ */
+@Configuration
+@EnableSwagger2
+public class Swagger2 {
+    @Bean
+    public Docket createRestApi() {
+        return new Docket(DocumentationType.SWAGGER_2)
+                .apiInfo(apiInfo())
+                .select()
+                .apis(RequestHandlerSelectors.basePackage("com.fd.controller"))
+                .paths(PathSelectors.any())
+                .build();
+    }
+
+    private ApiInfo apiInfo() {
+        return new ApiInfoBuilder()
+                .title("xx项目 RESTful APIs")
+                .description("xx项目后台api接口文档")
+                .version("1.0")
+                .build();
+    }
+}

+ 46 - 0
src/main/java/com/fd/config/WebMvcConfg.java

@@ -0,0 +1,46 @@
+package com.fd.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * Created by Owen on 2019/10/25 0025 16:29
+ */
+@Configuration
+public class WebMvcConfg implements WebMvcConfigurer {
+
+
+    @Bean
+    public MyInterceptor myInterceptor(){
+        return new MyInterceptor();
+    }
+
+    /**
+   * 重写addInterceptors方法
+   * addPathPatterns:需要拦截的访问路径
+   * excludePathPatterns:不需要拦截的路径,
+   * String数组类型可以写多个用","分割
+   */
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        registry.addInterceptor(myInterceptor())
+//                .addPathPatterns("/**")
+                .addPathPatterns("/api/vts/**")
+                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html");
+    }
+
+    /**
+     * 配置全局跨域
+     */
+    @Override
+    public void addCorsMappings(CorsRegistry registry) {
+        registry.addMapping("/**")
+                .allowedOrigins("*")
+                .allowCredentials(true)
+                .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
+                .maxAge(3600);
+    }
+}

+ 32 - 0
src/main/java/com/fd/constant/MsgCode.java

@@ -0,0 +1,32 @@
+package com.fd.constant;
+
+/**
+ * Created by Owen on 2019/10/25 0025 15:10
+ */
+public class MsgCode {
+
+    public static final String SUCCESS = "success";
+
+    public static final String E50001 = "文件为空";
+
+    public static final String E50002 = "Id不存在";
+
+    public static final String E50003 = "文件删除失败";
+
+    public static final String E50004 = "文件不存在";
+
+    public static final String E50005 = "命令执行失败";
+
+
+
+
+
+
+
+
+
+
+
+
+
+}

+ 18 - 0
src/main/java/com/fd/constant/TypeCode.java

@@ -0,0 +1,18 @@
+package com.fd.constant;
+
+/**
+ * Created by Owen on 2019/11/7 0007 11:10
+ *
+ * 文件类型
+ */
+public class TypeCode {
+
+    public static final String FILE_TYPE_RASTER_TIF = "tif"; // 栅格数据
+
+    public static final String FILE_TYPE_VECTOR_SHP = "shp"; // 矢量数据
+
+    public static final String FILE_TYPE_MODEL_OSGB = "osgb"; // 模型数据
+
+
+
+}

+ 50 - 0
src/main/java/com/fd/controller/FdModelController.java

@@ -0,0 +1,50 @@
+package com.fd.controller;
+
+import com.fd.constant.TypeCode;
+import com.fd.dto.PageDto;
+import com.fd.server.FileServer;
+import com.fd.util.R;
+import io.swagger.annotations.ApiOperation;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * Created by Owen on 2019/11/12 0012 9:40
+ *
+ * 3D模型数据
+ */
+@Log4j2
+@RequestMapping("api/fdModel")
+@RestController
+public class FdModelController {
+
+    @Autowired
+    private FileServer fileServer;
+
+
+    @ApiOperation("上传3D模型数据")
+    @PostMapping(value = "upload", consumes = { "multipart/form-data" })
+    private R upload(@RequestParam("file") MultipartFile file){
+        log.info("run upload");
+        return fileServer.uploadBigFile(file, TypeCode.FILE_TYPE_MODEL_OSGB);
+    }
+
+    @ApiOperation("获取3D模型数据列表")
+    @PostMapping(value = "list")
+    private R list(@RequestBody PageDto param){
+        log.info("run list");
+        return fileServer.findByType(TypeCode.FILE_TYPE_MODEL_OSGB, param);
+    }
+
+    /**
+     * 删除文件
+     */
+    @ApiOperation("删除文件")
+    @GetMapping("delete/{fileId}/")
+    private R deleteFile(@PathVariable("fileId") Long fileId) {
+        log.info("run deleteFile: {}", fileId);
+        return fileServer.deleteById(fileId);
+    }
+}

+ 39 - 0
src/main/java/com/fd/controller/GeoController.java

@@ -0,0 +1,39 @@
+package com.fd.controller;
+
+import com.fd.server.FileServer;
+import com.fd.util.R;
+import io.swagger.annotations.ApiOperation;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+
+/**
+ * Created by Owen on 2019/11/13 0013 10:59
+ */
+@Log4j2
+@RequestMapping("api/geo")
+@RestController
+public class GeoController {
+
+    @Autowired
+    private FileServer fileServer;
+
+
+    @ApiOperation("layer:图层名称, zxy:坐标")
+    @GetMapping("/{layer}/{z}/{x}/{y}/")
+    private R getGeoData(HttpServletResponse response,
+                         @PathVariable("layer") String layer,
+                         @PathVariable("z") String z,
+                         @PathVariable("x") String x,
+                         @PathVariable("y") String y) {
+        String filePath = layer + File.separator + z + File.separator + x + File.separator + y + ".pbf";
+        return fileServer.getGeoData(response, filePath);
+
+    }
+}

+ 51 - 0
src/main/java/com/fd/controller/RasterController.java

@@ -0,0 +1,51 @@
+package com.fd.controller;
+
+import com.fd.constant.TypeCode;
+import com.fd.dto.PageDto;
+import com.fd.server.FileServer;
+import com.fd.util.R;
+import io.swagger.annotations.ApiOperation;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * Created by Owen on 2019/11/12 0012 9:40
+ *
+ * 栅格数据
+ */
+@Log4j2
+@RequestMapping("api/raster")
+@RestController
+public class RasterController {
+
+    @Autowired
+    private FileServer fileServer;
+
+
+    @ApiOperation("上传栅格数据")
+    @PostMapping(value = "upload", consumes = { "multipart/form-data" })
+    private R upload(@RequestParam("file") MultipartFile file){
+        log.info("run upload");
+        return fileServer.uploadBigFile(file, TypeCode.FILE_TYPE_RASTER_TIF);
+    }
+
+    @ApiOperation("获取栅格数据列表")
+    @PostMapping(value = "list")
+    private R list(@RequestBody PageDto param){
+        log.info("run list");
+        return fileServer.findByType(TypeCode.FILE_TYPE_RASTER_TIF, param);
+    }
+
+
+    /**
+     * 删除文件
+     */
+    @ApiOperation("删除文件")
+    @GetMapping("delete/{fileId}/")
+    private R deleteFile(@PathVariable("fileId") Long fileId) {
+        log.info("run deleteFile: {}", fileId);
+        return fileServer.deleteById(fileId);
+    }
+}

+ 20 - 0
src/main/java/com/fd/controller/TestController.java

@@ -0,0 +1,20 @@
+package com.fd.controller;
+
+import com.fd.util.R;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Created by Owen on 2019/11/11 0011 15:03
+ */
+@RequestMapping("api")
+@RestController
+public class TestController {
+
+    @GetMapping("test")
+    private R test() {
+
+        return new R(200, "hahhahaah");
+    }
+}

+ 16 - 0
src/main/java/com/fd/controller/TranslationController.java

@@ -0,0 +1,16 @@
+package com.fd.controller;
+
+import lombok.extern.log4j.Log4j2;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * Created by Owen on 2019/11/12 0012 9:40
+ *
+ * 坐标转换
+ */
+@Log4j2
+@RequestMapping
+@RestController
+public class TranslationController {
+}

+ 50 - 0
src/main/java/com/fd/controller/VectorController.java

@@ -0,0 +1,50 @@
+package com.fd.controller;
+
+import com.fd.constant.TypeCode;
+import com.fd.dto.PageDto;
+import com.fd.server.FileServer;
+import com.fd.util.R;
+import io.swagger.annotations.ApiOperation;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * Created by Owen on 2019/11/12 0012 9:40
+ *
+ * 矢量数据
+ */
+@Log4j2
+@RequestMapping("api/vector")
+@RestController
+public class VectorController {
+
+    @Autowired
+    private FileServer fileServer;
+
+
+    @ApiOperation("上传矢量数据")
+    @PostMapping(value = "upload/{directoryName}/", consumes = { "multipart/form-data" })
+    private R upload(@RequestParam("file") MultipartFile file, @PathVariable("directoryName") String directoryName){
+        log.info("run upload");
+        return fileServer.uploadFile(file, directoryName, TypeCode.FILE_TYPE_VECTOR_SHP);
+    }
+
+    @ApiOperation("获取矢量数据列表")
+    @PostMapping(value = "list")
+    private R list(@RequestBody PageDto param){
+        log.info("run list");
+        return fileServer.findByType(TypeCode.FILE_TYPE_VECTOR_SHP, param);
+    }
+
+    /**
+     * 删除文件
+     */
+    @ApiOperation("删除文件")
+    @GetMapping("delete/{fileId}/")
+    private R deleteFile(@PathVariable("fileId") Long fileId) {
+        log.info("run deleteFile: {}", fileId);
+        return fileServer.deleteById(fileId);
+    }
+}

+ 17 - 0
src/main/java/com/fd/dto/PageDto.java

@@ -0,0 +1,17 @@
+package com.fd.dto;
+
+import lombok.Data;
+
+/**
+ * Created by Owen on 2019/10/28 0028 12:24
+ */
+@Data
+public class PageDto {
+
+    private Integer pageNum;
+
+    private Integer pageSize;
+
+
+
+}

+ 31 - 0
src/main/java/com/fd/entity/BaseEntity.java

@@ -0,0 +1,31 @@
+package com.fd.entity;
+
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import lombok.Data;
+
+import javax.persistence.*;
+import java.io.Serializable;
+import java.util.Date;
+
+@Data
+@MappedSuperclass  // 表示是父类,不会映射到数据库
+public class BaseEntity implements Serializable {
+
+    private static final long serialVersionUID = -3208275178665615559L;
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Long id;
+
+
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    @Column
+    private Date createTime;
+
+
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    @Column
+    private Date updateTime;
+
+
+}

+ 44 - 0
src/main/java/com/fd/entity/FileEntity.java

@@ -0,0 +1,44 @@
+package com.fd.entity;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import lombok.Data;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Table;
+import java.io.Serializable;
+
+
+/**
+ * Created by Owen on 2019/10/28 0028 11:15
+ */
+@Data
+@Entity
+@Table(name = "t_file")
+public class FileEntity extends BaseEntity implements Serializable {
+    private static final long serialVersionUID = 3663614649370191338L;
+
+
+
+    @Column
+    private String fileName; // 文件名称
+
+    @Column
+    private String fileUrl; // 文件路径
+
+//    @JsonIgnore
+//    @Column
+//    private String description; // 描述
+//
+//    @JsonIgnore
+//    @Column
+//    private String version; // 版本
+
+
+    @Column
+    private String type; // 文件类型
+
+
+    @Column
+    private Integer status; // 状态,是否可用 1:完成, 0:未完成
+}

+ 22 - 0
src/main/java/com/fd/repository/FileRepository.java

@@ -0,0 +1,22 @@
+package com.fd.repository;
+
+import com.fd.entity.FileEntity;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Query;
+
+/**
+ * Created by Owen on 2019/10/28 0028 11:36
+ *
+ * JpaSpecificationExecutor 条件分页查询
+ */
+public interface FileRepository extends JpaRepository<FileEntity, Long>, JpaSpecificationExecutor<FileEntity> {
+
+    // 条件分页查询
+    Page<FileEntity> findByType(String type, Pageable pageable);
+
+    @Query(value = "select r from FileEntity r where r.type=?1 or r.type =?2")
+    Page<FileEntity> findByType(String type, String type1, Pageable pageable);
+}

+ 25 - 0
src/main/java/com/fd/server/FileServer.java

@@ -0,0 +1,25 @@
+package com.fd.server;
+
+import com.fd.dto.PageDto;
+import com.fd.util.R;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * Created by Owen on 2019/11/12 0012 10:04
+ */
+public interface FileServer {
+
+    // 大文件上传
+    R uploadBigFile(MultipartFile file, String type);
+
+    // 小文件上传
+    R uploadFile(MultipartFile file, String directoryName, String type);
+
+    R findByType(String param, PageDto pageDto);
+
+    R deleteById(Long fileId);
+
+    R getGeoData(HttpServletResponse response, String filePath);
+}

+ 11 - 0
src/main/java/com/fd/server/IBaseServer.java

@@ -0,0 +1,11 @@
+package com.fd.server;
+
+import java.io.Serializable;
+
+/**
+ * Created by Owen on 2019/11/12 0012 14:15
+ */
+public interface IBaseServer<T, ID extends Serializable> {
+
+//    public abstract
+}

+ 175 - 0
src/main/java/com/fd/server/impl/FileServerImpl.java

@@ -0,0 +1,175 @@
+package com.fd.server.impl;
+
+import com.fd.constant.MsgCode;
+import com.fd.dto.PageDto;
+import com.fd.entity.FileEntity;
+import com.fd.repository.FileRepository;
+import com.fd.server.FileServer;
+import com.fd.util.FileUtils;
+import com.fd.util.R;
+import lombok.extern.log4j.Log4j2;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Sort;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.servlet.http.HttpServletResponse;
+import javax.transaction.Transactional;
+import java.io.File;
+import java.io.IOException;
+import java.util.Base64;
+import java.util.Date;
+import java.util.Optional;
+
+/**
+ * Created by Owen on 2019/11/12 0012 10:05
+ */
+@Log4j2
+@Service
+@Transactional
+public class FileServerImpl implements FileServer {
+
+    @Value("${input.file.path}")
+    private String INPUT_FILE_PATH;
+
+    @Value("${output.file.path}")
+    private String OUTPUT_FILE_PATH;
+
+    @Autowired
+    private FileRepository fileRepository;
+
+    @Override
+    public R uploadBigFile(MultipartFile file, String type) {
+        if (file.isEmpty() || file.getSize() <= 0) {
+            log.info("文件为空");
+            return new R(50001, MsgCode.E50001);
+        }
+
+        // 文件名全名
+        String fullFileName = file.getOriginalFilename();
+
+        // 创建目录路径
+        FileUtils.createDir(INPUT_FILE_PATH);
+
+        // 拼接唯一文件名
+        long timeMillis = System.currentTimeMillis();
+        String fileName = timeMillis + "_" + fullFileName;
+
+        // 文件保存路径
+        String filePath = INPUT_FILE_PATH + fileName;
+
+        // 写文件到本地
+        try {
+            FileUtils.bigFileWrite(file.getInputStream(), filePath);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        log.info("filePath: {}", filePath);
+
+        // 保存信息到db
+        FileEntity entity = new FileEntity();
+        entity.setFileName(fileName);
+        entity.setFileUrl(filePath);
+        entity.setCreateTime(new Date());
+        entity.setUpdateTime(new Date());
+        entity.setType(type);
+        fileRepository.save(entity);
+
+        return new R(200, entity);
+    }
+
+    @Override
+    public R uploadFile(MultipartFile file, String directoryName, String type) {
+        if (file.isEmpty() || file.getSize() <= 0) {
+            log.info("文件为空");
+            return new R(50001, MsgCode.E50001);
+        }
+
+        // 文件名全名
+        String fullFileName = file.getOriginalFilename();
+
+        // 创建目录路径
+        FileUtils.createDir(INPUT_FILE_PATH + directoryName);
+
+        // 拼接唯一文件名
+//        String fileName = FileUtils.dateStr() + fullFileName;
+
+        // 文件保存路径
+        String filePath = INPUT_FILE_PATH + directoryName + File.separator + fullFileName;
+        log.info("filePath: {}", filePath);
+
+        // 写文件到本地
+        try {
+            byte[] bytes = file.getBytes();
+            String content = Base64.getEncoder().encodeToString(bytes);
+            FileUtils.base64ToFileWriter(content, filePath);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+
+        // 保存信息到db
+        FileEntity entity = new FileEntity();
+        entity.setFileName(fullFileName);
+        entity.setFileUrl(filePath);
+        entity.setCreateTime(new Date());
+        entity.setUpdateTime(new Date());
+        entity.setType(type);
+        fileRepository.save(entity);
+
+        return new R(200, entity);
+    }
+
+
+    @Override
+    public R findByType(String type, PageDto pageDto) {
+        Page<FileEntity> page = fileRepository.findByType(type, PageRequest.of(pageDto.getPageNum(), pageDto.getPageSize(), Sort.by("createTime").descending()));
+        return new R(200, page);
+    }
+
+    @Override
+    public R deleteById(Long fileId) {
+        // 删除服务器文件
+        Optional<FileEntity> e = fileRepository.findById(fileId);
+        if (!e.isPresent()) {
+            return new R(50002, MsgCode.E50002);
+        }
+        FileEntity fileEntity = e.get();
+        String fileName = fileEntity.getFileName();
+        // 文件
+        if (fileName.contains(".")) {
+            File file = new File(fileEntity.getFileUrl());
+            file.delete();
+        } else { // 目录
+            FileUtils.delAllFile(fileEntity.getFileUrl());
+        }
+
+        // 删除数据库记录
+        fileRepository.deleteById(fileId);
+
+        return new R(200, MsgCode.SUCCESS);
+    }
+
+    @Override
+    public R getGeoData(HttpServletResponse response, String filePath) {
+        // 判断文件是否存在
+        filePath = OUTPUT_FILE_PATH + filePath;
+        log.info("filePath: {}", filePath);
+        File file = new File(filePath);
+        if (!file.exists()) {
+            log.info("文件不存在: {}", filePath);
+            return new R(50004, MsgCode.E50004);
+
+        }
+
+        try {
+            FileUtils.fileDownload(response, filePath);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        // 文件下载,不能有返回值
+        return null;
+    }
+}

+ 261 - 0
src/main/java/com/fd/util/FileUtils.java

@@ -0,0 +1,261 @@
+package com.fd.util;
+
+import lombok.extern.log4j.Log4j2;
+import org.springframework.util.ResourceUtils;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.text.SimpleDateFormat;
+import java.util.Base64;
+import java.util.Date;
+
+/**
+ * Created by Owen on 2019/10/25 0025 14:20
+ */
+@Log4j2
+public class FileUtils {
+
+
+    /**
+     * web 文件下载
+     * @param response
+     * @param path 源文件路径
+     * @param path 源文件名
+     * @return
+     * @throws Exception
+     */
+    public static void fileDownload(HttpServletResponse response, String path) throws Exception {
+        String fileName = path.substring(path.lastIndexOf(File.separator)+1);
+        // 当文件名不是英文名的时候,最好使用url解码器去编码一下,
+        fileName= URLEncoder.encode(fileName,"UTF-8");
+
+        // 获取response的输出流,用来输出文件
+//        ServletOutputStream out = response.getOutputStream();
+        OutputStream out = response.getOutputStream();
+
+        // 将响应的类型
+        response.setContentType("APPLICATION/OCTET-STREAM");
+        response.setHeader("Content-Disposition","attachment; filename="+fileName);
+
+        // 以输入流的形式读取文件
+//        log.info("zipPath: " + path);
+        FileInputStream in = new FileInputStream(path);
+
+        //可以自己 指定缓冲区的大小
+        byte[] buffer = new byte[1024];
+        int len = 0;
+        while ((len = in.read(buffer)) != -1) {
+            out.write(buffer, 0, len);
+            out.flush();
+        }
+        //关闭输入输出流
+        out.close();
+        in.close();
+    }
+
+    /**
+     * 获取类路径
+     */
+    public static String getResource(){
+        String path = "";
+        try {
+            path = ResourceUtils.getURL("classpath:").getPath();
+            path = URLDecoder.decode(path,"utf-8");
+            log.info("classpath path :"+path);
+        } catch (Exception e) {
+            log.error(" classpath Error" + e.getMessage(), e);
+        }
+        return path;
+    }
+
+
+    /**
+     * 创建文件夹
+     * destDirName:文件夹名称
+     */
+    public static void createDir(String destDirName) {
+        File dir = new File(destDirName);
+        // 创建目录
+        if (!dir.exists()) {
+            dir.mkdirs();
+        }
+    }
+
+    /**
+     * 大文件读写
+     *
+     * 1.先将文件中的内容读入到缓冲输入流中
+     * 2.将输入流中的数据通过缓冲输出流写入到目标文件中
+     * 3.关闭输入流和输出流
+     *
+     * in: 输入流
+     * path: 保持位置
+     */
+
+    public static void bigFileWrite(InputStream in, String path) throws IOException {
+        long start = System.currentTimeMillis();
+        // 输入缓冲流
+        BufferedInputStream inputBuff = new BufferedInputStream(in);
+
+        // 输出缓冲流
+        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(path));
+        int len = 0;
+        byte[] buffer = new byte[1024];
+        while ((len = inputBuff.read(buffer)) != -1) {
+            stream.write(buffer, 0, len);
+        }
+        stream.flush();
+        stream.close();
+        inputBuff.close();
+
+        long end = System.currentTimeMillis();
+
+        System.out.println("total: "+ (end-start)/1000);
+    }
+
+
+    /**
+     *
+     * @param content base64内容
+     * @param path 输出文件路径,需要后缀名
+     * @return
+     */
+    public static  boolean base64ToFileWriter(String content, String path) {
+        if (content == null) {
+            return false;
+        }
+        try {
+            byte[] b = Base64.getDecoder().decode(content);
+            // processing data
+            for (int i = 0; i < b.length; ++i) {
+                if (b[i] < 0) {
+                    b[i] += 256;
+                }
+            }
+            OutputStream out = new FileOutputStream(path);
+            out.write(b);
+            out.flush();
+            out.close();
+            return true;
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+
+    /**
+     * 读取文件方法
+     * @param Path 文件路径
+     * @return 返回内容
+     */
+    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;
+    }
+
+
+    /**
+     * 生成文件
+     * @param content 内容
+     * @param path 生成路径
+     * @throws IOException
+     */
+    public static void fileWriter(String content, String path) throws IOException {
+        FileWriter writer = new FileWriter(path);
+        writer.write(content);
+        writer.flush();
+        writer.close();
+    }
+
+    // 获取时间戳
+    public static String dateStr() {
+        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
+        String format = df.format(new Date());
+        long timeMillis = System.currentTimeMillis();
+        return format + "_" + timeMillis + "_";
+    }
+
+    /**
+     * 删除指定文件夹下所有文件
+     * @param path 文件夹完整绝对路径
+     * @return
+     */
+    public static boolean delAllFile(String path) {
+        boolean flag = false;
+        File file = new File(path);
+        if (!file.exists()) {
+            return flag;
+        }
+        if (!file.isDirectory()) {
+            return flag;
+        }
+        String[] tempList = file.list();
+        File temp = null;
+        for (int i = 0; i < tempList.length; i++) {
+            if (path.endsWith(File.separator)) {
+                temp = new File(path + tempList[i]);
+            } else {
+                temp = new File(path + File.separator + tempList[i]);
+            }
+            if (temp.isFile()) {
+                temp.delete();
+            }
+            if (temp.isDirectory()) {
+//                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
+//                delFolder(path + "/" + tempList[i]);//再删除空文件夹
+                delAllFile(path + tempList[i]);//先删除文件夹里面的文件
+                delFolder(path + tempList[i]);//再删除空文件夹
+                flag = true;
+            }
+        }
+        return flag;
+    }
+
+
+    /**
+     * 删除文件夹
+     * @param folderPath 文件夹完整绝对路径
+     */
+    public static void delFolder(String folderPath) {
+        try {
+            delAllFile(folderPath); //删除完里面所有内容
+            String filePath = folderPath;
+            filePath = filePath.toString();
+            File myFilePath = new File(filePath);
+            myFilePath.delete(); //删除空文件夹
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    public static void main(String[] args) {
+        String a = "aaaa"+ File.separator + "1111.bb";
+        String b = "aaaa\\1111.bb";
+        System.out.println(a.substring(a.lastIndexOf(File.separator)+1));
+        System.out.println(b.substring(b.lastIndexOf(File.separator)+1));
+    }
+}

+ 145 - 0
src/main/java/com/fd/util/R.java

@@ -0,0 +1,145 @@
+package com.fd.util;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
+
+import java.io.Serializable;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+public class R implements Serializable {
+
+	private static final long serialVersionUID = 2719931935414658118L;
+
+	private final Integer status;
+
+	private final String message;
+
+//	@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
+	@JsonInclude(value = Include.NON_NULL)
+	private final Object data;
+
+	@JsonInclude(value = Include.NON_EMPTY)
+	private final String[] exceptions;
+
+	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+	private final Date timestamp;
+
+	public R(Integer status, String message) {
+
+		super();
+		this.status = status;
+		this.message = message;
+		this.data = null;
+		this.timestamp = addTime();
+		this.exceptions = null;
+
+	}
+
+
+
+	
+	public R(Integer status, Object data) {
+
+		super();
+
+		this.status = status;
+		this.message = null;
+
+		this.data = data;
+		this.timestamp = addTime();
+		this.exceptions = null;
+
+	}
+	
+
+
+	public R(Integer status, String message, String key, Object value) {
+
+		super();
+
+		this.status = status;
+
+		this.message = message;
+
+		Map<String, Object> map = new HashMap<String, Object>();
+
+		if (key == null || ("").equals(key)) {
+			map.put("key", value);
+		} else {
+			map.put(key, value);
+		}
+
+		this.data = map;
+
+		this.timestamp = addTime();
+		this.exceptions = null;
+
+	}
+
+	public R(Integer status, Throwable ex) {
+
+		super();
+
+		this.status = status;
+		this.message = ex.getMessage();
+		this.data = null;
+		StackTraceElement[] stackTeanceElement = ex.getStackTrace();
+		this.exceptions = new String[stackTeanceElement.length];
+		for (int i = 0; i < stackTeanceElement.length; i++) {
+			this.exceptions[i] = stackTeanceElement[i].toString();
+		}
+		this.timestamp = addTime();
+	}
+
+	public R(Integer status, String message, Throwable ex) {
+
+		super();
+
+		this.status = status;
+
+		this.message = message;
+
+		this.data = null;
+
+		StackTraceElement[] stackTeanceElement = ex.getStackTrace();
+		this.exceptions = new String[stackTeanceElement.length];
+		for (int i = 0; i < stackTeanceElement.length; i++) {
+			this.exceptions[i] = stackTeanceElement[i].toString();
+		}
+
+		this.timestamp = addTime();
+
+	}
+
+	public Integer getStatus() {
+		return status;
+	}
+
+	public String getMessage() {
+		return message;
+	}
+
+	public Object getData() {
+		return data;
+	}
+
+	public String[] getExceptions() {
+		return exceptions;
+	}
+
+	public Date getTimestamp() {
+		return timestamp;
+	}
+
+	public Date addTime(){
+		Calendar nowTime= Calendar.getInstance();
+        nowTime.add(Calendar.MINUTE,15);
+        Date time = nowTime.getTime();
+        return time;
+	}
+}