提交 e5b7c86f authored 作者: wyl's avatar wyl

adaptationEngineDone

上级 43095f76
......@@ -35,6 +35,50 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.data</groupId>-->
<!-- <artifactId>spring-data-jpa</artifactId>-->
<!-- <version>2.2.1.RELEASE</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
......
......@@ -2,6 +2,7 @@ package com.zjty.adaptationmaster;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
public class AdaptationMasterApplication {
......
package com.zjty.adaptationmaster.adaptor.enginer;
import com.zjty.adaptationmaster.adaptor.entity.AdaptationDetailsLogEntity;
import com.zjty.adaptationmaster.adaptor.entity.OriginalFile;
import com.zjty.adaptationmaster.adaptor.entity.Rule;
import com.zjty.adaptationmaster.managerment.dao.AdaptationDetailLogEntityDao;
import com.zjty.adaptationmaster.managerment.dao.OriginalFileDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Component
public class Adaptor {
//@Autowired
//private AdaptationDetailLogEntityDao adaptationDetailLogEntityDao;
@Autowired
private OriginalFileDao originalFileDao;
@Value("${base.path}")
private String basePath;
//线程池数量,合适的线程数量能让程序更快
private static final int poolSize = 20;
//为避免内存溢出,对于超大文件,切分成部分分别读入处理,最后拼接写出
private static final long LIMIT = 200*1024*1024;
//将适配进度写出,用于页面实时展示
PrintWriter responseWriter;
List<Rule> ruleList;
String projectPath;
//private List<Rule> adaptorEntities = new ArrayList<>();
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
public void setRuleList(List<Rule> ruleList) {
this.ruleList = ruleList;
}
public void setWriter(PrintWriter writer) {
this.responseWriter = writer;
}
public void doAdapt(){
//String regular = preprocesAdaptation();
//List<String> strings1 = preprocessRegular();
Map<String, Rule> strings1 = preprocessRegular();
if(strings1.size()<1){
System.out.println("检测到匹配规则为空");
return;
}
ThreadPoolExecutor pool = new ThreadPoolExecutor(poolSize,poolSize,10, TimeUnit.SECONDS,new ArrayBlockingQueue<>(poolSize*2));
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
List<OriginalFile> originalFiles = new ArrayList<>();
//记录实际具体适配内容
//List<AdaptationDetailsLogEntity> detailsLogEntities = new ArrayList<>();
ReadedFileRepository repository = new ReadedFileRepository();
try {
Files.walkFileTree(Paths.get(projectPath),new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// String pathString = file.toString();
// pathString.indexOf(System.getProperty("file.separator"),basePath.length());
boolean match = false;
List<Rule> thisFileMatched = null;
//不符合规则的路径过滤掉
for(String regular:strings1.keySet()) {
if (FileSystems.getDefault().getPathMatcher("glob:"+regular).matches(file)) {
if(thisFileMatched==null)
thisFileMatched = new ArrayList<>();
thisFileMatched.add(strings1.get(regular));
match = true;
}
}
String storePath ="originalFile/"+ UUID.randomUUID().toString()+"/"+file.getFileName();
//原先文件的新地址
Path originalPath = Paths.get(basePath +storePath);
File parentFile = originalPath.toFile().getParentFile();
if(!parentFile.exists()||!parentFile.isDirectory())parentFile.mkdirs();
if(match) {
OriginalFile originalFile = new OriginalFile(file.toString(),originalPath.toString(),new Date());
originalFiles.add(originalFile);
Files.move(file, originalPath);
//splitedFile.setDeal(true);
System.out.println("过滤得到符合规则的文件" + file);
if (attrs.size() > LIMIT) {
System.out.println("找到大文件" + file);
ReadedLinesRepository linesRepository = new ReadedLinesRepository();
int i = 0;
WriterBySort bySort = new WriterBySort();
File newFile = file.toFile();
newFile.createNewFile();
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(newFile), "utf-8");
bySort.setWriter(writer);
for (String s : Files.readAllLines(originalPath, Charset.forName("utf-8"))) {
if (linesRepository.put(s)) {
List<ReadedFile> readedFiles = new ArrayList<>();
readedFiles.add(new ReadedFile(linesRepository.getReadedFiles(), attrs, file,thisFileMatched));
ReadedFileTask apacheTask = new ReadedFileTask(readedFiles,responseWriter);
apacheTask.setBySort(bySort);
apacheTask.setIndex(i);
pool.submit(apacheTask);
i++;
}
}
List<ReadedFile> readedFiles = new ArrayList<>();
readedFiles.add(new ReadedFile(linesRepository.getReadedFiles(), attrs, file,thisFileMatched));
ReadedFileTask apacheTask = new ReadedFileTask(readedFiles,responseWriter);
apacheTask.setBySort(bySort);
apacheTask.setIndex(i);
pool.submit(apacheTask);
i++;
bySort.setSize(i);
}else {
String s = new String(Files.readAllBytes(originalPath));
ReadedFile readedFile = new ReadedFile(s, attrs, file,thisFileMatched);
if (repository.put(readedFile)) {
ReadedFileTask apacheTask = new ReadedFileTask(repository.getReadedFiles(), responseWriter);
pool.submit(apacheTask);
}
}
}/*else {
Files.copy(file, Paths.get(newPath));
}*/
return FileVisitResult.CONTINUE;
}
});
ReadedFileTask apacheTask = new ReadedFileTask(repository.getReadedFiles(), responseWriter);
pool.submit(apacheTask);
pool.shutdown();
try {
pool.awaitTermination(1,TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
}
originalFileDao.saveAll(originalFiles);
//adaptationDetailLogEntityDao.saveAll(detailsLogEntities);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 预处理适配规则,将规则实体类处理成glob表达式
* @return
*/
private Map<String,Rule> preprocessRegular() {
//List<String> result = new ArrayList<>();
Map<String,Rule> result = new HashMap<>();
for (Rule adaptorEntity : ruleList) {
switch (adaptorEntity.getPathMatchType()) {
case SUFFIX:
result.put("**/**" + adaptorEntity.getPath(),adaptorEntity);
break;
case PATH:
result.put("" + adaptorEntity.getPath(),adaptorEntity);
break;
case NAME:
result.put("**/" + adaptorEntity.getPath(),adaptorEntity);
break;
}
}
return result;
}
/**
* 对于大文件,按行读取,积攒到一定大小去处理
* 这里put进来每行
* 大小不够时返回false
* 大小够时返回true
*/
private class ReadedLinesRepository{
private static final long LIMIT = 200*1024*1024;//字节*k*m
private List<StringBuilder> readedFiles;
private long count;
public String getReadedFiles() {
return readedFiles.toString();
}
public boolean put(String readedFile){
if(readedFiles==null)readedFiles = new ArrayList<>();
readedFiles.add(new StringBuilder(readedFile));
count+=readedFile.length();
if(count>LIMIT){
return true;
}
return false;
}
}
/**
* 读取到的大量小文件,积累到一定的大小,才交给一个线程去处理
*/
private class ReadedFileRepository{
private List<ReadedFile> readedFiles;
private long count;
public List<ReadedFile> getReadedFiles() {
return readedFiles;
}
public boolean put(ReadedFile readedFile){
if(readedFiles==null)readedFiles = new ArrayList<>();
readedFiles.add(readedFile);
count+=readedFile.getAttributes().size();
if(count>LIMIT){
return true;
}
return false;
}
}
/**
* 过大的文件,切割成几块,每块编号,分给每个线程处理,处理结束后,按编号顺序写出
* 这里按编号控制写出顺序
*/
public class WriterBySort{
private int currentIndex = -1;
private Map<Integer,String> map = new TreeMap<>();
private Writer contentWriter;
private int size;
public void setWriter(Writer writer) {
this.contentWriter = writer;
}
public void setSize(int size) {
this.size = size;
if(currentIndex==size){
try {
contentWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void insert(Integer key, String value){
map.put(key,value);
while (map.get(currentIndex+1)!=null){
try {
contentWriter.write(map.remove(currentIndex+1));
} catch (IOException e) {
e.printStackTrace();
}
currentIndex++;
if(currentIndex == size){
try {
contentWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
package com.zjty.adaptationmaster.adaptor.enginer;
import com.zjty.adaptation.adaptor.enginer.util.StringCompareUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class ApacheTask implements Runnable {
private List<File> file1;
private List<AdaptorEntity> adaptorEntities;
public void setFile(List<File> file) {
this.file1 = file;
}
/**
* 规则示例1
* 将/src/com/zjty/hrmanager/util/BeginYearClear下的
* import org.slf4j.Logger;改为import org.apache.log4j.Logger
*
*
* 规则示例2
* 将pom.xml文件中的mysql依赖改为postgresql依赖
*
* 规则示例3
* 将数据库实体类所映射的表明 table1 改为 table2
*
* 规则示例4
* 将前端代码中请求地址192.168.1.81:8011/***改为192.168.1.81:6888/hrm/***
*
* 规则示例5
*
*/
//对于 处理规则 的预处理
public void preAdaptation(){
for(AdaptorEntity adaptorEntity:adaptorEntities){
switch (adaptorEntity.getMatchType()){
case ALL:
}
}
}
@Override
public void run() {
try {
for (File file:file1) {
//List<String> stringList = FileUtils.readLines(file, "utf-8");
// String s = FileUtils.readFileToString(file, "utf-8");
// if(KMP.kmpMatch(s,"一二三四五")==-1){
//
// }
LineIterator lineIterator = FileUtils.lineIterator(file, "gbk");
while (lineIterator.hasNext()) {
int index = /*KMP.kmpMatch*/StringCompareUtil.compare(lineIterator.next(), "2019-11-27 13:55:36,648 INFO [DefaultSoapUICore] Settings saved to [C:\\Users\\wyl\\soapui-setting中华s.xml]");
if(index>-1){
System.out.println("存在");
}
//System.out.println(lineIterator.next());
//if(lineIterator.next().contains("tyConfig extends WebSecurityConfigurerAdapte")){
// if (lineIterator.next().indexOf("一二三四五")!=-1) {
//
// System.out.println("存在");
// }
// if(lineIterator.next().contains("\\u4e00\\u4e8c\\u4e09\\u56db\\u4e94")){
// System.out.println("存在2");
// }
//
// if(lineIterator.next().contains("liuqibajiushi")){
// System.out.println("存在1");
// }
}
//for(String s:stringList){
// if(s.contains(" LOGINUSER = \"loginuser\"; //ca")){
// System.out.println("存在");
// }
//}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
......@@ -137,9 +137,9 @@ public class Engine {
}
List<Runnable> rejectedTask = new ArrayList<>();
private void execute(List<File> files){
ApacheTask stringFactory = new ApacheTask();
stringFactory.setFile(files);
pool.submit(stringFactory);
// ApacheTask stringFactory = new ApacheTask();
// stringFactory.setFile(files);
// pool.submit(stringFactory);
}
/**
......
......@@ -19,10 +19,10 @@ public class Engine1 {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String s = new String(Files.readAllBytes(file));
ReadedFile readedFile = new ReadedFile(s,attrs);
ReadedFile readedFile = new ReadedFile(s,attrs,file,new ArrayList<>());
if(repository.put(readedFile)){
ApacheTask apacheTask = new ApacheTask();
apacheTask.setFile(repository.getReadedFiles());
// ApacheTask apacheTask = new ApacheTask();
// apacheTask.setFile(repository.getReadedFiles());
}
return FileVisitResult.CONTINUE;
}
......
package com.zjty.adaptationmaster.adaptor.enginer;
import com.zjty.adaptationmaster.adaptor.entity.Rule;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
@Data
@NoArgsConstructor
......@@ -12,4 +15,6 @@ import java.nio.file.attribute.BasicFileAttributes;
public class ReadedFile {
private String content;
private BasicFileAttributes attributes;
private Path path;
private List<Rule> thisMatchedRule;
}
package com.zjty.adaptationmaster.adaptor.enginer;
import com.zjty.adaptationmaster.adaptor.entity.Rule;
import java.io.*;
import java.util.List;
public class ReadedFileTask implements Runnable {
private List<ReadedFile> readedFiles;
private Writer responseWriter;
public ReadedFileTask(List<ReadedFile> readedFiles,Writer responseWriter){
this.readedFiles = readedFiles;
this.responseWriter = responseWriter;
}
private Adaptor.WriterBySort bySort;
private int index;
public void setBySort(Adaptor.WriterBySort bySort) {
this.bySort = bySort;
}
public void setIndex(int index) {
this.index = index;
}
@Override
public void run() {
for(ReadedFile readedFile:readedFiles){
String content = readedFile.getContent();
System.out.println("规则数量"+readedFile.getThisMatchedRule().size());
for(Rule entity:readedFile.getThisMatchedRule()){
System.out.println("文本匹配方式"+entity.getTextMatching());
switch (entity.getTextMatching()){
case AREA:
String[] split = entity.getTarget().split("\\|\\|");
String begin = split[0];
String matching = split[1];
String end = split[2];
System.out.println(begin+"||"+matching+"||"+end);
int i = content.indexOf(matching);
if(i>-1){
int beginIndex = content.lastIndexOf(begin, i);
int endIndex = content.indexOf(end, i + 1);
if(beginIndex>-1&&endIndex>-1){
content = content.substring(0,beginIndex)+entity.getReplacing()+content.substring(endIndex+end.length());
}
}
}
//container.add(readedFile.getPath().getFileName()+"文本替换:"+entity.getTextMatching()+"|"+entity.getReplacing());
try {
responseWriter.write("===="+readedFile.getPath().getFileName()+"////"+entity.getTextMatching()+"||||"+entity.getReplacing());
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if(bySort!=null){
System.out.println("toBySort");
bySort.insert(index,content);
}else {
System.out.println("writerFile");
File file = readedFile.getPath().toFile();
file.createNewFile();
OutputStreamWriter contentWriter = new OutputStreamWriter(new FileOutputStream(file));
contentWriter.write(content);
contentWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.zjty.adaptationmaster.adaptor.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AdaptationDetailsLogEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String projectId;
private Date time;
private String path;
// private String before;
// private String after;
@ElementCollection
private List<String> details = new ArrayList<>();
private String userId;
}
package com.zjty.adaptationmaster.adaptor.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class OriginalFile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String originalPath;
private String storePath;
private Date date;
public OriginalFile(String originalPath, String storePath, Date date) {
this.originalPath = originalPath;
this.storePath = storePath;
this.date = date;
}
}
package com.zjty.adaptationmaster.adaptor.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Rule {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int ruleSetId;
private int projectId;
private MatchType pathMatchType;//文件匹配方式 路径/文件名/后缀
private String path;//文件路径匹配
private TextMatch textMatching;//文本匹配方式 全文匹配/正则匹配
/**
* AREA
* beginString||matching||endString
*/
private String target;//文本匹配目标
private String replacing;//更改方式 全文替换/正则替换
public static enum MatchType{
PATH,NAME,SUFFIX
}
public static enum TextMatch{
AREA
}
public static enum DealWay{
REPLACE,INSERTAFTER,INSERTBEFORE
}
}
package com.zjty.adaptationmaster.adaptor.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RuleSet {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String des;
}
package com.zjty.adaptationmaster.adaptor.enginer.examination;
package com.zjty.adaptationmaster.adaptor.examination;
import com.zjty.adaptation.adaptor.enginer.Counter;
import com.zjty.adaptation.adaptor.enginer.util.StringCompareUtil;
import com.zjty.adaptationmaster.adaptor.enginer.Counter;
import com.zjty.adaptationmaster.adaptor.enginer.util.StringCompareUtil;
import java.io.IOException;
import java.nio.file.*;
......
package com.zjty.adaptationmaster.adaptor.enginer.examination;
package com.zjty.adaptationmaster.adaptor.examination;
import lombok.AllArgsConstructor;
import lombok.Data;
......
package com.zjty.adaptationmaster.managerment.controller;
import com.zjty.adaptationmaster.managerment.entity.response.ServerResponse;
import com.zjty.adaptationmaster.managerment.service.AdaptationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/adapt")
public class AdaptationController {
@Autowired
private AdaptationService adaptationService;
@GetMapping("/adapt")
public ServerResponse adapt(HttpServletResponse response) throws IOException {
System.out.println("请求");
return adaptationService.adapt(response);
}
}
package com.zjty.adaptationmaster.managerment.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/connect")
public class SocketController implements WebSocketHandler {
int i = 0;
// @GetMapping("/get")
// public void getConnect(HttpServletResponse response){
// while (i<10){
// try {
// response.getWriter().write("第"+i+++"句话。。。");
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
// Thread.currentThread().sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
}
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
}
@Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
package com.zjty.adaptationmaster.managerment.dao;
import com.zjty.adaptationmaster.adaptor.entity.AdaptationDetailsLogEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AdaptationDetailLogEntityDao extends JpaRepository<AdaptationDetailsLogEntity,Integer> {
}
package com.zjty.adaptationmaster.managerment.dao;
import com.zjty.adaptationmaster.adaptor.entity.OriginalFile;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OriginalFileDao extends JpaRepository<OriginalFile,Integer> {
}
package com.zjty.adaptationmaster.managerment.entity.response;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* <p>Description : 异常结果枚举类,用于统一异常状态码与相关描述信息
* @Date : 2017/12/13 0:51
* @author : M@tr!x [xhyrzldf@foxmail.com]
*/
@AllArgsConstructor
@Getter
public enum ResponseCode {
/**
* 服务器成功返回用户请求的数据
*/
OK(200, "[GET]:服务器成功返回用户请求的数据,返回资源对象"),
/**
* 用户新建或修改数据成功
*/
CREATED(201, "[POST/PUT/PATCH]:用户新建或修改数据成功,返回新生成或修改的资源对象"),
/**
* 表示一个请求已经进入后台排队(异步任务)
*/
ACCEPTED(202, "[*]:表示一个请求已经进入后台排队(异步任务)"),
/**
* 用户上传文件成功
*/
UPLOADED(203, "[POST]文件上传成功"),
/**
* 用户删除数据成功
*/
NO_CONTENT(204, " [DELETE]:用户删除数据成功"),
/**
* 用户发出的请求有错误,服务器没有进行新建或修改数据的操作
*/
INVALID_REQUEST(400, "[POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作"),
/**
* 表示用户没有权限(令牌、用户名、密码错误)
*/
UNAUTHORIZED(401, " [*]:表示用户没有权限(令牌、用户名、密码错误)"),
/**
* 表示用户登录超时
*/
LOGINOUTTIME(402, " [*]:表示用户登录超时"),
/**
* 表示用户得到授权(与401错误相对),但是访问是被禁止的
*/
FORBIDDEN(403, " [*] 表示用户得到授权(与401错误相对),但是访问是被禁止的"),
/**
* 用户发出的请求针对的是不存在的记录,服务器没有进行操作,该操作是幂等的
*/
NOT_FOUND(404, " [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操作"),
/**
* 非法参数,请求中附带的参数不符合要求规范
*/
ILLEGAL_PARAMETER(405, "[*]:非法参数,请求中附带的参数不符合要求规范"),
/**
* 用户请求的格式不可得(比如用户请求JSON格式,但是只有XML格式)
*/
NOT_ACCEPTABLE(406, " [GET]:用户请求的格式不可得(比如用户请求JSON格式,但是只有XML格式)"),
/**
* 用户的参数不得为空
*/
NOT_NULL_PARAMETER(408, "传递的参数不能为空"),
/**
* 用户请求的资源被永久删除,且不会再得到的
*/
GONE(413, "[GET]:用户请求的资源被永久删除,且不会再得到的"),
/**
* [PUT,PATCH,POST,DELETE]:操作没有成功,并没有数据发生变化
*/
NO_CHANGED(414, "[PUT,PATCH,POST,DELETE]:操作没有成功,并没有数据发生变化"),
/**
* 创建一个对象时,发生一个验证错误
*/
UNPROCESSABLE_ENTITY(422, "[POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误"),
/**
* 服务器发生错误
*/
INTERNAL_SERVER_ERROR(500, "服务器发生错误");
/**
* 结果代码编号
*/
private Integer code;
/**
* 结果信息
*/
private String msg;
}
package com.zjty.adaptationmaster.managerment.entity.response;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import static com.zjty.adaptationmaster.managerment.entity.response.ResponseCode.*;
/**
* Description : 结果类,用于统一返回格式 对外提供关于响应结果的很多便利的静态方法
*
* @author : M@tr!x [xhyrzldf@foxmail.com]
* @Date : 2017/12/13 0:05
*/
@SuppressWarnings({"WeakerAccess", "unused"})
@Getter
public class ServerResponse<T> {
/**
* 错误码
*/
@JSONField(ordinal = 1)
private Integer code;
/**
* 提示信息
*/
@JSONField(ordinal = 2)
private String msg;
/**
* 具体的内容
*/
@JSONField(ordinal = 3)
private T data;
/* 以下为返回成功响应结果的各类重载静态方法 */
public static <T> ServerResponse<T> success() {
return new ServerResponse<>(OK.getCode(), OK.getMsg());
}
public static <T> ServerResponse<T> success(T data) {
return new ServerResponse<>(OK.getCode(), OK.getMsg(), data);
}
public static <T> ServerResponse<T> success(String msg, T data) {
return new ServerResponse<>(OK.getCode(), msg, data);
}
public static <T> ServerResponse<T> saveSuccess(T data) {
return new ServerResponse<>(CREATED.getCode(), CREATED.getMsg(), data);
}
public static <T> ServerResponse<T> deleteSuccess() {
return new ServerResponse<>(NO_CONTENT.getCode(), NO_CONTENT.getMsg());
}
public static <T> ServerResponse<T> deleteSuccessWithCount(Number effectCount) {
return new ServerResponse<>(NO_CONTENT.getCode(), "删除成功,操作删除的数据条数为: " + effectCount);
}
public static <T> ServerResponse<T> deleteSuccessWithId(Number id) {
return new ServerResponse<>(NO_CONTENT.getCode(), "删除成功,操作删除的数据id为: " + id);
}
public static <T> ServerResponse<T> uploadSuccess(T data) {
return new ServerResponse<>(UPLOADED.getCode(), UPLOADED.getMsg(), data);
}
public static <T> ServerResponse<T> messageSuccess(String msg) {
return new ServerResponse<>(OK.getCode(), msg);
}
/* 以下为返回失败响应结果的各类重载静态方法 */
public static <T> ServerResponse<T> error() {
return new ServerResponse<>(INTERNAL_SERVER_ERROR.getCode(), INTERNAL_SERVER_ERROR.getMsg());
}
public static <T> ServerResponse<T> error(String errorMessage) {
return new ServerResponse<>(INTERNAL_SERVER_ERROR.getCode(), errorMessage);
}
public static <T> ServerResponse<T> error(ResponseCode responseCode) {
return new ServerResponse<>(responseCode.getCode(), responseCode.getMsg());
}
public static <T> ServerResponse<T> error(ResponseCode responseCode, String errorMessage) {
return new ServerResponse<>(responseCode.getCode(), errorMessage);
}
public static <T> ServerResponse<T> error(ResponseCode responseCode, String errorMessage,T data) {
return new ServerResponse<>(responseCode.getCode(), errorMessage,data);
}
/* 以下为提供给CONTROL层向文件服务器操作文件获得相应结果的相关方法 */
// /**
// * <b>向文件服务器上传文件并且取得{@code {@link ServerResponse}}类型的响应结果</b>
// * <p>
// * <p>封装了control层的关于文件上传的代码
// * <p>
// * <p>例如file是a.txt,dirName=template, 在文件服务器上存放的位置就是{@code root(根目录)/template/a.txt }
// *
// * @param file {@link MultipartFile} 接受到的文件俺对象
// * @param dirName 在文件服务器上的文件夹名
// * @return {@link ServerResponse} (包含了成功与导致失败的结果)
// */
// public static ServerResponse uploadAndGet(
// @RequestParam("file") Optional<MultipartFile> file, String dirName) {
// // 空指针判断
// if (!file.isPresent()) return error(NOT_NULL_PARAMETER);
// // 上传文件并且获得相应结果
// MultipartFile uploadFile = file.get();
// FileServerResponse fsp =
// HttpClientUtil.uploadFileToServer(uploadFile, dirName, uploadFile.getOriginalFilename());
// // 根据返回结果的状态码确定相应的返回信息(200返回成功,否则error)
// return (fsp.getCode() == 200) ? uploadSuccess(fsp.getData()) : error(NO_CHANGED, fsp.getMsg());
// }
// /**
// * <b>向文件服务器删除文件并且取得{@code {@link ServerResponse}}类型的响应结果</b>
// * <p>
// * <p>封装了control层的关于文件上传的代码
// * <p>
// * <p>例如提供的参数如下
// * <li>fileName = reset-hv_20180115144834_wV9A9iVD.png
// * <li>dirName = templates
// * <li>那么实际删除的文件路径为: {@code root(根目录)/templates/reset-hv_20180115144834_wV9A9iVD.png}
// *
// * @param fileName 要删除的文件名<b>注意是文件服务器上的文件名,例如<b>reset-hv_20180115144834_wV9A9iVD.png</b> 格式为{@code
// * 原始文件名_timestamp_uuid8位}
// * @param dirName 要删除的文件所处的文件目录
// * @return {@link ServerResponse} (包含了成功与导致失败的结果)
// */
// public static ServerResponse deleteAndGet(
// @RequestParam(value = "fileName") Optional<String> fileName, String dirName) {
// // 空指针判断
// if (!fileName.isPresent()) return error(NOT_NULL_PARAMETER);
// // 发送删除文件的请求,附带文件所在的目录和在服务器中的文件名
// FileServerResponse fsp = HttpClientUtil.daleteFileToServer(dirName, fileName.get());
// // 根据返回结果的状态码确定相应的返回信息(200返回成功,否则error)
// return (fsp.getCode() == 200) ? deleteSuccess() : error(NO_CHANGED, fsp.getMsg());
// }
/* 将构造器私有,防止外部进行实例化 仅提供给内部静态方法调用 * */
private ServerResponse() {
}
private ServerResponse(Integer code) {
this.code = code;
}
private ServerResponse(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
private ServerResponse(String msg, T data) {
this.msg = msg;
this.data = data;
}
private ServerResponse(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
}
package com.zjty.adaptationmaster.managerment.service;
import com.zjty.adaptationmaster.managerment.entity.response.ServerResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public interface AdaptationService {
ServerResponse adapt(HttpServletResponse response) throws IOException;
}
package com.zjty.adaptationmaster.managerment.service.impl;
import com.zjty.adaptationmaster.adaptor.enginer.Adaptor;
import com.zjty.adaptationmaster.adaptor.entity.Rule;
import com.zjty.adaptationmaster.managerment.entity.response.ServerResponse;
import com.zjty.adaptationmaster.managerment.service.AdaptationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class AdaptationServiceImpl implements AdaptationService {
@Autowired
private Adaptor adaptor;
@Override
public ServerResponse adapt(HttpServletResponse response) throws IOException {
Rule rule = new Rule();
rule.setPathMatchType(Rule.MatchType.NAME);
rule.setPath("pom.xml");
rule.setTextMatching(Rule.TextMatch.AREA);
rule.setTarget("<groupId>||mysql||</groupId>");
rule.setReplacing("<groupId>org.postgresql</groupId>");
List<Rule> objects = new ArrayList<>();
objects.add(rule);
//Adaptor adaptor = new Adaptor(adaptationDetailLogEntityDao, originalFileDao);
adaptor.setWriter(response.getWriter());
adaptor.setRuleList(objects);
adaptor.setProjectPath("C:\\home\\project\\rsc\\hrmbclient");
adaptor.doAdapt();
return ServerResponse.success();
}
}
server.port=8015
spring.datasource.url=jdbc:mysql://localhost:3306/adapt?useSSL=false&serverTimezone=Asia/Shanghai&autoReconnect=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
base.path=C:\\home\\master\\
\ No newline at end of file
package com.zjty.adaptationmaster;
import org.junit.Test;
import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
public class Test1 {
@Test
public void test(){
PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:**/pom.xml");
System.out.println(pathMatcher.matches(Paths.get("/static/aaa/pom.xml")));
}
@Test
public void test1(){
String rsc = "aaa||bbb||cccc";
String[] split = rsc.split("\\|\\|");
System.out.println(split);
for (String s:split){
System.out.println(s);
}
System.out.println(split[0]+"||"+split[1]+"||"+split[2]);
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论