提交 1e059a78 authored 作者: wyl's avatar wyl

pushCode

上级 1b066f8c
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version> <version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/> <!-- lookup parent from repository -->
</parent> </parent>
<groupId>com.zjty</groupId> <groupId>com.zjty</groupId>
...@@ -78,7 +78,7 @@ ...@@ -78,7 +78,7 @@
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId> <artifactId>spring-websocket</artifactId>
<version>4.3.17.RELEASE</version> <!-- <version>4.3.17.RELEASE</version>-->
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
...@@ -95,6 +95,22 @@ ...@@ -95,6 +95,22 @@
<artifactId>jpa-spec</artifactId> <artifactId>jpa-spec</artifactId>
<version>3.2.1</version> <version>3.2.1</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-invoker</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.25</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -3,8 +3,11 @@ package com.zjty.adaptationmaster; ...@@ -3,8 +3,11 @@ package com.zjty.adaptationmaster;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@SpringBootApplication @SpringBootApplication
@EnableScheduling
public class AdaptationMasterApplication { public class AdaptationMasterApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
package com.zjty.adaptationmaster.adaptor.controller;
import com.zjty.adaptationmaster.base.response.ServerResponse;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
@Controller
@RequestMapping("/checkcenter")
public class CheckCenterController {
//页面请求
@GetMapping("/socket/{cid}")
public ModelAndView socket(@PathVariable String cid) {
ModelAndView mav=new ModelAndView("/socket");
mav.addObject("cid", cid);
return mav;
}
//推送数据接口
@ResponseBody
@RequestMapping("/socket/push/{cid}")
public ServerResponse pushToWeb(@PathVariable String cid, String message) {
// try {
// WebSocketServer.sendInfo(cid,message);
// } catch (IOException e) {
// e.printStackTrace();
// return ServerResponse.error(cid+"#"+e.getMessage());
// }
return ServerResponse.success(cid);
}
}
package com.zjty.adaptationmaster.adaptor.controller;
import com.zjty.adaptationmaster.base.response.ServerResponse;
import com.zjty.adaptationmaster.utils.MavenCompiler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
@RestController
@RequestMapping("/compile")
public class CompileController {
@GetMapping("/getUUID")
public ServerResponse getUUID(){
return ServerResponse.success(UUID.randomUUID().toString());
}
@GetMapping("/compile")
public ServerResponse compile(String UUID){
// MavenCompiler mavenCompiler = new MavenCompiler("C:\\home\\project\\rsc\\hrmbclient\\pom.xml","D:\\apache-maven-3.5.4",UUID);
// mavenCompiler.compiler();
return ServerResponse.success();
}
}
package com.zjty.adaptationmaster.adaptor.controller;
import com.zjty.adaptationmaster.adaptor.service.DeployService;
import com.zjty.adaptationmaster.base.response.ServerResponse;
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;
@Controller
@RequestMapping("/deploy")
public class DeployController {
@Autowired
private DeployService deployService;
@GetMapping("/compileProject")
public ServerResponse compile(int projectId,String uuid){
return deployService.compile(projectId,uuid);
}
@GetMapping("/deployProject")
public ServerResponse deploy(int projectId,String uuid){
return deployService.deploy(projectId,uuid);
}
}
package com.zjty.adaptationmaster.adaptor.controller;
import com.zjty.adaptationmaster.adaptor.service.InspectService;
import com.zjty.adaptationmaster.base.response.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class InspectController {
@Autowired
private InspectService inspectService;
public ServerResponse inspect(int projectId){
return inspectService.inspect(projectId);
}
}
...@@ -40,4 +40,9 @@ public class ProjectController { ...@@ -40,4 +40,9 @@ public class ProjectController {
return projectService.findProject(page,project); return projectService.findProject(page,project);
} }
@PostMapping("/getProjectState")
public ServerResponse getProjectState(){
return projectService.deployList();
}
} }
package com.zjty.adaptationmaster.adaptor.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.adaptor.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@ServerEndpoint("/webServer/{projectId}")
@Component
public class WebSocketServer {
private Logger logger = LoggerFactory.getLogger(getClass());
private static Map<String,WebSocketServer> map = new HashMap<>();
private Session session;
private String uuid;
@OnOpen
public void onOpen(Session session,@PathParam("projectId")String uuid){
this.session = session;
this.uuid = uuid;
//session.getOpenSessions().
map.put(uuid,this);
try {
sendMessage("连接成功");
} catch (IOException e) {
logger.error("websocket IO异常");
}
logger.info("连接成功"+session.getId());
}
@OnClose
public void onClose(Session session){
map.remove(this.uuid);
logger.info("连接关闭"+session.getId());
}
@OnMessage
public void onMessage(Session session,String message){
// try {
//map.get(uuid).sendMessage(message);
logger.info(uuid+"sendMsg"+message);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
@OnError
public void onError(Session session,Throwable error){
logger.info(error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static void sendInfo(String sessionId,String msg,String action,String state,String projectName){
try {
map.get(sessionId).sendMessage(LocalDateTime.now()+"\t"+projectName+"\t"+action+"\t"+state+"\t"+msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.zjty.adaptationmaster.adaptor.entity; package com.zjty.adaptationmaster.adaptor.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
...@@ -24,33 +22,24 @@ public class Project { ...@@ -24,33 +22,24 @@ public class Project {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; private Integer id;
@Column(unique = true)
private String projectName;//项目名称 private String projectName;//项目名称
private String language;//语言
private String framework;//架构
private String isSeparate;//前后端是否分离
private String databaseType;//数据库类型
private String codeUrl;//当前源码源码路径 private String codeUrl;//当前源码源码路径
private Integer status = 1;//状态(0:删除 1:未删除) private Integer status = 1;//状态(0:删除 1:未删除)
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date startTime = new Date();//开始时间 private Date startTime = new Date();//开始时间
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date updateTime;//更新时间 private Date updateTime;//更新时间
@OneToMany(mappedBy = "project", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @OneToMany(mappedBy = "project", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Rule> rules;//自定义的规则 private List<Rule> rules;//自定义的规则
@ManyToMany @ManyToMany
@JoinTable(name = "project_ruleSet", @JoinTable(name = "project_ruleSet",
joinColumns = @JoinColumn(name = "p_id",referencedColumnName = "id"), joinColumns = @JoinColumn(name = "p_id",referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "r_id", referencedColumnName = "id")) inverseJoinColumns = @JoinColumn(name = "r_id", referencedColumnName = "id"))
private List<RuleSet> ruleSets;//规则集 private List<RuleSet> ruleSets;//规则集
private boolean compileSuccess = false;
@OneToOne
private Report report;
private boolean deploySuccess = false;
} }
...@@ -4,23 +4,35 @@ import lombok.AllArgsConstructor; ...@@ -4,23 +4,35 @@ import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List;
@Entity
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class Report { public class Report {
public String type;//语言类型
public String structure;//项目架构 private Language language;//语言
public String sqlType;//数据库类型 private String framework;//架构
private Separate isSeparate;//前后端是否分离
private DatabaseType databaseType;//数据库类型
private String compileFilePath;//项目编译文件,如果是maven项目,用maven编译,那么就是pom.xml
public DependenceManagement dependenceManagement;//版本管理方式 public DependenceManagement dependenceManagement;//版本管理方式
public Path depMagFilepath;//版本管理文件地址 public List<String> jarPath;//依赖文件的地址列表,用于编译,如果不是用版本管理工具
@Override private String packagePath;
public String toString(){
return ""+type+structure+sqlType;
}
public static enum DependenceManagement{ public enum DependenceManagement{
MAVEN,GRADLE,ANT MAVEN,GRADLE,ANT
} }
public enum Separate{
WHOLE,SEPARATE
}
public enum DatabaseType{
MYSQL,ORACLE,SQLSERVER,POSTGRE
}
public enum Language{
JAVA,PYTHON,CPP
}
} }
...@@ -41,15 +41,15 @@ public class Rule { ...@@ -41,15 +41,15 @@ public class Rule {
private String target;//文本匹配目标 private String target;//文本匹配目标
private String replacing;//更改方式 全文替换/正则替换 private String replacing;//更改方式 全文替换/正则替换
public static enum MatchType{ public enum MatchType{
PATH,NAME,SUFFIX PATH,NAME,SUFFIX
} }
public static enum TextMatch{ public enum TextMatch{
AREA AREA
} }
public static enum DealWay{ public enum DealWay{
REPLACE,INSERTAFTER,INSERTBEFORE REPLACE,INSERTAFTER,INSERTBEFORE
} }
} }
...@@ -11,4 +11,5 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; ...@@ -11,4 +11,5 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @Date : 2019-12-07 10:55 * @Date : 2019-12-07 10:55
*/ */
public interface ProjectDao extends JpaRepository<Project, Integer>,JpaSpecificationExecutor { public interface ProjectDao extends JpaRepository<Project, Integer>,JpaSpecificationExecutor {
Project findByProjectName(String projectName);
} }
package com.zjty.adaptationmaster.adaptor.service;
import com.zjty.adaptationmaster.base.response.ServerResponse;
public interface DeployService {
ServerResponse compile(int projectId, String uuid);
ServerResponse deploy(int projectId, String uuid);
}
...@@ -4,6 +4,7 @@ import com.zjty.adaptationmaster.adaptor.entity.Rule; ...@@ -4,6 +4,7 @@ import com.zjty.adaptationmaster.adaptor.entity.Rule;
import com.zjty.adaptationmaster.base.response.ServerResponse; import com.zjty.adaptationmaster.base.response.ServerResponse;
import com.zjty.adaptationmaster.adaptor.service.AdaptationService; import com.zjty.adaptationmaster.adaptor.service.AdaptationService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
...@@ -16,6 +17,7 @@ public class AdaptationServiceImpl implements AdaptationService { ...@@ -16,6 +17,7 @@ public class AdaptationServiceImpl implements AdaptationService {
@Autowired @Autowired
private Adaptor adaptor; private Adaptor adaptor;
@Override @Override
public ServerResponse adapt(HttpServletResponse response) throws IOException { public ServerResponse adapt(HttpServletResponse response) throws IOException {
......
...@@ -10,6 +10,7 @@ import org.springframework.stereotype.Component; ...@@ -10,6 +10,7 @@ import org.springframework.stereotype.Component;
import java.io.*; import java.io.*;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.*; import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import java.util.*; import java.util.*;
...@@ -23,6 +24,7 @@ public class Adaptor { ...@@ -23,6 +24,7 @@ public class Adaptor {
//private AdaptationDetailLogEntityDao adaptationDetailLogEntityDao; //private AdaptationDetailLogEntityDao adaptationDetailLogEntityDao;
@Autowired @Autowired
private OriginalFileDao originalFileDao; private OriginalFileDao originalFileDao;
//@Value("${base.path}") //@Value("${base.path}")
private String basePath = Const.CONSOLE; private String basePath = Const.CONSOLE;
//线程池数量,合适的线程数量能让程序更快 //线程池数量,合适的线程数量能让程序更快
...@@ -98,7 +100,7 @@ public class Adaptor { ...@@ -98,7 +100,7 @@ public class Adaptor {
WriterBySort bySort = new WriterBySort(); WriterBySort bySort = new WriterBySort();
File newFile = file.toFile(); File newFile = file.toFile();
newFile.createNewFile(); newFile.createNewFile();
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(newFile), "utf-8"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(newFile), StandardCharsets.UTF_8);
bySort.setWriter(writer); bySort.setWriter(writer);
for (String s : Files.readAllLines(originalPath, Charset.forName("utf-8"))) { for (String s : Files.readAllLines(originalPath, Charset.forName("utf-8"))) {
if (linesRepository.put(s)) { if (linesRepository.put(s)) {
...@@ -191,10 +193,7 @@ public class Adaptor { ...@@ -191,10 +193,7 @@ public class Adaptor {
if(readedFiles==null)readedFiles = new ArrayList<>(); if(readedFiles==null)readedFiles = new ArrayList<>();
readedFiles.add(new StringBuilder(readedFile)); readedFiles.add(new StringBuilder(readedFile));
count+=readedFile.length(); count+=readedFile.length();
if(count>LIMIT){ return count > LIMIT;
return true;
}
return false;
} }
} }
...@@ -213,10 +212,7 @@ public class Adaptor { ...@@ -213,10 +212,7 @@ public class Adaptor {
if(readedFiles==null)readedFiles = new ArrayList<>(); if(readedFiles==null)readedFiles = new ArrayList<>();
readedFiles.add(readedFile); readedFiles.add(readedFile);
count+=readedFile.getAttributes().size(); count+=readedFile.getAttributes().size();
if(count>LIMIT){ return count > LIMIT;
return true;
}
return false;
} }
} }
......
package com.zjty.adaptationmaster.adaptor.service.Impl;
import com.zjty.adaptationmaster.adaptor.entity.Project;
import com.zjty.adaptationmaster.adaptor.repository.ProjectDao;
import com.zjty.adaptationmaster.adaptor.service.DeployService;
import com.zjty.adaptationmaster.base.enums.Const;
import com.zjty.adaptationmaster.base.response.ServerResponse;
import com.zjty.adaptationmaster.utils.ApusicDeployer;
import com.zjty.adaptationmaster.utils.MavenCompiler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DeployServiceImpl implements DeployService {
@Autowired
private ProjectDao projectDao;
@Override
public ServerResponse compile(int projectId, String uuid) {
// Project project = new Project();
// project.setCompileFilePath("C:\\home\\project\\rsc\\hrmbclient\\pom.xml");
// project.setDependenceManagement(Report.DependenceManagement.MAVEN);
Project project = projectDao.getOne(projectId);
if(project.getReport()==null)return ServerResponse.error("请进行项目体检或完善项目信息");
switch (project.getReport().getDependenceManagement()) {
case MAVEN:
new MavenCompiler(project, Const.MAVENHOME, uuid).compiler();
}
return ServerResponse.success(project);
}
@Override
public ServerResponse deploy(int projectId, String uuid) {
// Project project = new Project();
// project.setPackagePath("/home/user/Desktop/hrmanager-0.0.1-SNAPSHOT.war");
Project project = projectDao.getOne(projectId);
new ApusicDeployer(Const.CTLPATH,Const.MAVENHOME).deploy(project,uuid);
return ServerResponse.success(project);
}
}
package com.zjty.adaptationmaster.adaptor.service.Impl;
import com.zjty.adaptationmaster.adaptor.entity.Project;
import com.zjty.adaptationmaster.adaptor.repository.ProjectDao;
import com.zjty.adaptationmaster.adaptor.service.InspectService;
import com.zjty.adaptationmaster.base.response.ServerResponse;
import com.zjty.adaptationmaster.utils.Inspector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
@Service
public class InspectServiceImpl implements InspectService {
@Autowired
private ProjectDao projectDao;
@Transactional
@Override
public ServerResponse inspect(int projectId) {
Project project = projectDao.getOne(projectId);
return ServerResponse.success(new Inspector(project,new HashMap<>(),new HashMap<>(),new ArrayList<>()).inspect());
}
}
package com.zjty.adaptationmaster.adaptor.service.Impl;
import com.zjty.adaptationmaster.utils.StringCompareUtil;
import com.zjty.adaptationmaster.adaptor.entity.Report;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 项目体检,根据既定特征值,
* 扫描、统计、分析项目特征,
* 生成报告
*
*/
public class Inspectors {
private String path;
private Map<String, Counter> matchMap;//后缀计数器
//特定后缀文件的地址集合
private List<Path> propertiesConfigPaths = new ArrayList<>();
private List<Path> ymlConfigPaths = new ArrayList<>();
private List<Path> xmlConfigPaths = new ArrayList<>();
//版本管理配置文件地址
private Path pomPath;
private boolean havePom = false;
private boolean haveIvy = false;
public List<String> matchStrings;
private Report report = new Report();
public void setPath(String path) {
this.path = path;
}
public void setMatchMap(Map<String, Counter> matchMap) {
this.matchMap = matchMap;
}
public static void main(String[] args) {
Inspectors inspectors = new Inspectors();
inspectors.setPath("C:\\Users\\wyl\\Desktop\\testReplace");
Map<String,Counter> map = new HashMap<>();
map.put("java",new Counter());
map.put("jsp",new Counter());
map.put("html",new Counter());
inspectors.setMatchMap(map);
inspectors.inspect();
//打印分析数据
for(Map.Entry<String,Counter> entry:map.entrySet()) {
System.out.println("项目中"+entry.getKey()+"类型文件共有" + entry.getValue().getI()+"个");
}
//打印体检报告
System.out.println(inspectors.analysis());
}
/**
* FileVisitResult.CONTINUE 继续遍历
* FileVisitResult.TERMINATE 中止访问
* FileVisitResult.SKIP_SIBLINGS 不访问同级的文件或目录
* FileVisitResult.SKIP_SUBTREE 不访问子目录
*/
public void inspect(){
try {
String glob = "glob:**/*.txt";
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
Files.walkFileTree(Paths.get(path), new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
//判断后缀
for (Map.Entry<String, Counter> s : matchMap.entrySet()) {
if (dir.endsWith(s.getKey())) {
s.getValue().plus();
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
boolean matches = pathMatcher.matches(file);
for(String s:matchStrings){
}
if (file.endsWith("properties")) {
propertiesConfigPaths.add(file);
}
if(file.endsWith("yml")){
ymlConfigPaths.add(file);
}
if(file.endsWith("xml")){
xmlConfigPaths.add(file);
if(file.endsWith("pom.xml")){
havePom = true;
pomPath = file;
}else if(file.endsWith("ivy.xml")){
haveIvy = true;
pomPath = file;
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public Report analysis(){
if(matchMap.get("java").getI()>0){
report.setType("java");
}
if(matchMap.get("jsp").getI()>0){
report.setStructure("whole");
}
if(matchMap.get("html").getI()>0){
report.setStructure("separation");
}
for(Path path:propertiesConfigPaths){
try {
for(String s:Files.readAllLines(path)){
int index = StringCompareUtil.compare(s, "spring.datasource.driver-class-name");
if(index >- 1){
if(!s.startsWith("#")){
/**
* MySQL数据库:
*
*     1)驱动包:https://mvnrepository.com/artifact/mysql/mysql-connector-java(下载路径)
*
*     2)驱动类名:com.mysql.jdbc.Driver
*
*     3)JDBC的URL:jdbc:mysql://IP地址:端口号/数据库名字
*
*      注:端口号缺省为:3306
*
* SQL server数据库:
*
*     1)驱动包:https://mvnrepository.com/artifact/com.microsoft.sqlserver/sqljdbc4(下载路径)
*
*     2)驱动类名:com.microsoft.jdbc.sqlserver.SQLServerDriver
*
*     3)JDBC的URL:jdbc:microsoft:sqlserver://IP地址:端口号;DatabaseName=数据库名
*
*     4)sqljdbc和sqljdbc4区别:https://blog.csdn.net/cainiao_M/article/details/53404222
*
*     注:端口号缺省为:1433
*
* Oracle数据库:
*
*     1)驱动包:https://mvnrepository.com/artifact/com.oracle/ojdbc6(下载路径)
*
*     2)驱动类名:oracle.jdbc.driver.OracleDriver
*
*     3)JDBC的URL:jdbc:oracle:thin:@IP地址:端口号:数据库名
*
*     4)ojdbc6和ojdbc14的区别:ojdbc14.jar(适合java-1.4和1.5),ojdbc6(适合java-1.6)
*
*     注:端口号缺省为:1521
*/
if(StringCompareUtil.compare(s, "mysql")>-1){
report.setSqlType("mysql");
}else if(StringCompareUtil.compare(s, "sqlserver")>-1){
report.setSqlType("SQLServer");
}else if(StringCompareUtil.compare(s, "oracle")>-1){
report.setSqlType("oracle");
}else if(StringCompareUtil.compare(s, "postgre")>-1){
report.setSqlType("postgre");
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
if(havePom){
report.setDependenceManagement(Report.DependenceManagement.MAVEN);
report.setDepMagFilepath(pomPath);
}
return null;
}
private static class Counter {
private int i = 0;
public void plus(){
i++;
}
public int getI() {
return i;
}
public void reset(){
i = 0;
}
}
}
...@@ -7,7 +7,9 @@ import com.zjty.adaptationmaster.adaptor.entity.Rule; ...@@ -7,7 +7,9 @@ import com.zjty.adaptationmaster.adaptor.entity.Rule;
import com.zjty.adaptationmaster.adaptor.entity.RuleSet; import com.zjty.adaptationmaster.adaptor.entity.RuleSet;
import com.zjty.adaptationmaster.adaptor.repository.ProjectDao; import com.zjty.adaptationmaster.adaptor.repository.ProjectDao;
import com.zjty.adaptationmaster.adaptor.service.ProjectService; import com.zjty.adaptationmaster.adaptor.service.ProjectService;
import com.zjty.adaptationmaster.base.enums.Const;
import com.zjty.adaptationmaster.base.response.ServerResponse; import com.zjty.adaptationmaster.base.response.ServerResponse;
import com.zjty.adaptationmaster.utils.ApusicDeployer;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
...@@ -79,4 +81,9 @@ public class ProjectServiceImpl implements ProjectService { ...@@ -79,4 +81,9 @@ public class ProjectServiceImpl implements ProjectService {
} }
return ServerResponse.success(new ListResponse<>(projectDao.count(spec),projects)); return ServerResponse.success(new ListResponse<>(projectDao.count(spec),projects));
} }
@Override
public ServerResponse deployList() {
return ServerResponse.success(new ApusicDeployer(Const.CTLPATH,Const.MAVENHOME).list());
}
} }
package com.zjty.adaptationmaster.adaptor.service;
import com.zjty.adaptationmaster.base.response.ServerResponse;
public interface InspectService {
ServerResponse inspect(int projectId);
}
...@@ -16,4 +16,6 @@ public interface ProjectService { ...@@ -16,4 +16,6 @@ public interface ProjectService {
ServerResponse deleteProject(Integer id);//删除项目 ServerResponse deleteProject(Integer id);//删除项目
ServerResponse findProject(Integer page , Project project);//查询项目 ServerResponse findProject(Integer page , Project project);//查询项目
ServerResponse deployList();
} }
package com.zjty.adaptationmaster.base.configuration;
public class ValueConfig {
}
...@@ -2,24 +2,12 @@ package com.zjty.adaptationmaster.base.configuration; ...@@ -2,24 +2,12 @@ package com.zjty.adaptationmaster.base.configuration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 开启websocket支持
*/
@Configuration @Configuration
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { public class WebSocketConfig {
@Override @Bean
public void configureMessageBroker(MessageBrokerRegistry registry) { public ServerEndpointExporter serverEndpointExporter() {
registry.enableSimpleBroker("/topic","/user"); return new ServerEndpointExporter();
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/webServer").withSockJS();
//registry.addEndpoint("/queueServer").withSockJS();
} }
} }
package com.zjty.adaptationmaster.base.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DeployStatus {
private boolean compile;
private boolean deploy;
private boolean running;
}
package com.zjty.adaptationmaster.base.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class ProjectStatueFromMiddleware {
private String name;
private String description;
private String state;
}
...@@ -33,4 +33,8 @@ public class Const { ...@@ -33,4 +33,8 @@ public class Const {
String SERVER_RESPONSE_DATA_EXAMPLE = String SERVER_RESPONSE_DATA_EXAMPLE =
"[{'name' : '设备1号', 'id' : 'K001002'},{'name' : '设备2号', 'id' : 'K003004'}]"; "[{'name' : '设备1号', 'id' : 'K001002'},{'name' : '设备2号', 'id' : 'K003004'}]";
} }
public static final String MAVENHOME = "D:\\apache-maven-3.5.4";
public static final String CTLPATH = "/home/user/Desktop/AAS-V9.0/bin/appctl";
public static final String CTLPWD = "Qwert123!@#";
} }
package com.zjty.adaptationmaster.utils;
import com.zjty.adaptationmaster.adaptor.controller.WebSocketServer;
import com.zjty.adaptationmaster.adaptor.entity.Project;
import com.zjty.adaptationmaster.base.entity.ProjectStatueFromMiddleware;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
@AllArgsConstructor
@NoArgsConstructor
public class ApusicDeployer {
private String ctlPath;
private String ctlPwd;
public void deploy(Project project,String webSocketName){
String command = ctlPath+" -p '"+ctlPwd+"' install "+project.getProjectName()+" "+project.getReport().getPackagePath();
try {
Process exec = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
WebSocketServer.sendInfo(line, webSocketName,"部署","running",project.getProjectName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public List<ProjectStatueFromMiddleware> list(){
List<ProjectStatueFromMiddleware> result = new ArrayList<>();
String command = ctlPath+" -p '"+ctlPwd+"' list";
try {
Process exec = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
boolean titleEnd = false;
String line = null;
while ((line = reader.readLine()) != null) {
if(line.startsWith("---------------"))titleEnd = true;
if(titleEnd){
String[] split = line.split("\\s{2,}");
ProjectStatueFromMiddleware projectStatue = new ProjectStatueFromMiddleware(split[0],split[1],split[2]);
result.add(projectStatue);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
package com.zjty.adaptationmaster.utils;
import ch.ethz.ssh2.Connection;
public class Connector {
private String ip;
private String userName;
private String pwd;
public void connect(){
Connection connection = new Connection(ip);
// connection.connect();
// connection.authenticateWithPassword(userName,pwd);
}
}
package com.zjty.adaptationmaster.utils;
import com.zjty.adaptationmaster.adaptor.entity.Project;
import com.zjty.adaptationmaster.adaptor.entity.Report;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 项目体检,根据既定特征值,
* 扫描、统计、分析项目特征,
* 生成报告
*
*/
public class Inspector {
public static void main(String[] args) {
Project project = new Project();
project.setCodeUrl("");
Map<String,Report.Language> suffixLanguageMapping = new HashMap<>();
Map<String, Report.Separate> suffixSeparateMapping = new HashMap<>();
List<String> configFileSuffixList = new ArrayList<>();
Inspector inspector = new Inspector(project,suffixLanguageMapping,suffixSeparateMapping,configFileSuffixList);
}
private Project project;
private Report report;
private Map<String, Counter> languageMatchMap;
private Map<String, Counter> separateMatchMap;
private Map<String, Report.Language> suffixLanguageMapping;
private Map<String, Report.Separate> suffixSeparateMapping;
private Map<String,List<Path>> configFileTypePathsMapping;
public Inspector(Project project,Map<String,Report.Language> suffixLanguageMapping,Map<String, Report.Separate> suffixSeparateMapping,List<String> configFileSuffixList){
this.project = project;
this.suffixLanguageMapping = suffixLanguageMapping;
this.suffixSeparateMapping = suffixSeparateMapping;
this.languageMatchMap = new HashMap<>();
for(String s:suffixLanguageMapping.keySet()){
languageMatchMap.put(s,new Counter());
}
this.separateMatchMap = new HashMap<>();
for(String s:suffixSeparateMapping.keySet()){
separateMatchMap.put(s,new Counter());
}
this.configFileTypePathsMapping = new HashMap<>();
for(String s:configFileSuffixList){
configFileTypePathsMapping.put(s,new ArrayList<>());
}
this.report = new Report();
}
private List<Path> propertiesConfigPaths = new ArrayList<>();
private List<Path> ymlConfigPaths = new ArrayList<>();
private List<Path> xmlConfigPaths = new ArrayList<>();
/**
* FileVisitResult.CONTINUE 继续遍历
* FileVisitResult.TERMINATE 中止访问
* FileVisitResult.SKIP_SIBLINGS 不访问同级的文件或目录
* FileVisitResult.SKIP_SUBTREE 不访问子目录
*/
public Report inspect(){
try {
FileSystem aDefault = FileSystems.getDefault();
Map<String,PathMatcher> languageSuffixMatcherMapping = new HashMap<>();
for(String s:suffixLanguageMapping.keySet()){
languageSuffixMatcherMapping.put(s,aDefault.getPathMatcher("glob:**/*."+s));
}
Map<String,PathMatcher> separateSuffixMatcherMapping = new HashMap<>();
for(String s:suffixLanguageMapping.keySet()){
separateSuffixMatcherMapping.put(s,aDefault.getPathMatcher("glob:**/*."+s));
}
Map<PathMatcher,String> configFileMatcherSuffixMapping = new HashMap<>();
for(String s:configFileTypePathsMapping.keySet()){
configFileMatcherSuffixMapping.put(aDefault.getPathMatcher("glob:**/*."+s),s);
}
Files.walkFileTree(Paths.get(project.getCodeUrl()), new FileVisitor<Path>() {
/**
* 统计某个后缀出现的次数
* @param dir
* @param attrs
* @return
* @throws IOException
*/
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
for(Map.Entry<String,PathMatcher> entry:languageSuffixMatcherMapping.entrySet()){
if(entry.getValue().matches(dir)){
languageMatchMap.get(entry.getKey()).plus();
}
}
for(Map.Entry<String,PathMatcher> entry:separateSuffixMatcherMapping.entrySet()){
if(entry.getValue().matches(dir)){
separateMatchMap.get(entry.getKey()).plus();
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
for(Map.Entry<PathMatcher,String> entry:configFileMatcherSuffixMapping.entrySet()){
if(entry.getKey().matches(file)){
configFileTypePathsMapping.get(entry.getValue()).add(file);
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
return analysis();
}
public Report analysis(){
for(Map.Entry<String,Counter> entry:languageMatchMap.entrySet()){
if(entry.getValue().getNumber()>0){
report.setLanguage(suffixLanguageMapping.get(entry.getKey()));
}
}
for(Map.Entry<String,Counter> entry:separateMatchMap.entrySet()){
if(entry.getValue().getNumber()>0){
report.setIsSeparate(suffixSeparateMapping.get(entry.getKey()));
}
}
for(Map.Entry<String,List<Path>> entry:configFileTypePathsMapping.entrySet()){
}
// for(Path path:propertiesConfigPaths){
// try {
// for(String s:Files.readAllLines(path)){
// int index = StringCompareUtil.compare(s, "spring.datasource.driver-class-name");
// if(index > -1){
// if(!s.startsWith("#")){
// /**
// * MySQL数据库:
// *     1)驱动包:https://mvnrepository.com/artifact/mysql/mysql-connector-java(下载路径)
// *     2)驱动类名:com.mysql.jdbc.Driver
// *     3)JDBC的URL:jdbc:mysql://IP地址:端口号/数据库名字
// *      注:端口号缺省为:3306
// *
// * SQL server数据库:
// *     1)驱动包:https://mvnrepository.com/artifact/com.microsoft.sqlserver/sqljdbc4(下载路径)
// *     2)驱动类名:com.microsoft.jdbc.sqlserver.SQLServerDriver
// *     3)JDBC的URL:jdbc:microsoft:sqlserver://IP地址:端口号;DatabaseName=数据库名
// *     4)sqljdbc和sqljdbc4区别:https://blog.csdn.net/cainiao_M/article/details/53404222
// *     注:端口号缺省为:1433
// *
// * Oracle数据库:
// *     1)驱动包:https://mvnrepository.com/artifact/com.oracle/ojdbc6(下载路径)
// *     2)驱动类名:oracle.jdbc.driver.OracleDriver
// *     3)JDBC的URL:jdbc:oracle:thin:@IP地址:端口号:数据库名
// *     4)ojdbc6和ojdbc14的区别:ojdbc14.jar(适合java-1.4和1.5),ojdbc6(适合java-1.6)
// *     注:端口号缺省为:1521
// */
// if(StringCompareUtil.compare(s, "mysql")>-1){
// report.setDatabaseType(Report.DatabaseType.MYSQL);
// }else if(StringCompareUtil.compare(s, "sqlserver")>-1){
// report.setDatabaseType(Report.DatabaseType.SQLSERVER);
// }else if(StringCompareUtil.compare(s, "oracle")>-1){
// report.setDatabaseType(Report.DatabaseType.ORACLE);
// }else if(StringCompareUtil.compare(s, "postgre")>-1){
// report.setDatabaseType(Report.DatabaseType.POSTGRE);
// }
// }
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
return null;
}
public class Counter {
private int i = 0;
public void plus(){
i++;
}
public int getNumber() {
return i;
}
public void reset(){
i = 0;
}
}
}
package com.zjty.adaptationmaster.utils;
import com.zjty.adaptationmaster.adaptor.controller.WebSocketServer;
import com.zjty.adaptationmaster.adaptor.entity.Project;
import com.zjty.adaptationmaster.base.enums.Const;
import org.apache.maven.shared.invoker.*;
import org.apache.maven.shared.utils.cli.CommandLineException;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
public class MavenCompiler {
private Project project;
private String mavenHome;
private String webSocketId;
public MavenCompiler(Project project,String mavenHome,String webSocketId){
this.project = project;
this.mavenHome = mavenHome;
this.webSocketId = webSocketId;
}
public void compiler(){
InvocationRequest request = new DefaultInvocationRequest();
request.setPomFile(new File(project.getReport().getCompileFilePath()));
request.setGoals(Collections.singletonList("compile"));
Invoker invoker = new DefaultInvoker();
invoker.setMavenHome(new File(mavenHome));
invoker.setOutputHandler(new InvocationOutputHandler() {
@Override
public void consumeLine(String s) throws IOException {
WebSocketServer.sendInfo(webSocketId,s,"编译","running",project.getProjectName());
//System.out.println(s);
}
});
try {
InvocationResult execute = invoker.execute(request);
CommandLineException executionException = execute.getExecutionException();
if(executionException==null){
if(execute.getExitCode()==0){
project.setCompileSuccess(true);
}
}else {
WebSocketServer.sendInfo(webSocketId,"项目编译出错","编译","error",project.getProjectName());
WebSocketServer.sendInfo(webSocketId,executionException.getMessage(),"编译","error",project.getProjectName());
}
} catch (MavenInvocationException e) {
e.printStackTrace();
}
}
// public static void main(String[] args) {
// Project project = new Project();
// project.getReport().setCompileFilePath("C:\\home\\project\\rsc\\hrmbclient\\pom.xml");
// MavenCompiler mavenCompiler = new MavenCompiler(project, Const.MAVENHOME,"aa");
// mavenCompiler.compiler();
// }
public static void main(String[] args) {
InvocationRequest request = new DefaultInvocationRequest();
request.setPomFile(new File("D:\\SingleHRManger1.0(scannerAndFriger)"));
request.setGoals(Collections.singletonList("compile"));
Invoker invoker = new DefaultInvoker();
//invoker.setMavenHome(new File(mavenHome));
invoker.setOutputHandler(new InvocationOutputHandler() {
@Override
public void consumeLine(String s) throws IOException {
System.out.println(s);
//WebSocketServer.sendInfo(webSocketId,s,"编译","running",project.getProjectName());
//System.out.println(s);
}
});
}
}
package com.zjty.adaptationmaster.utils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class MyXmlReader {
private Document document;
public MyXmlReader(Path path){
try {
document = new SAXReader().read(Files.newInputStream(path));
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Document getDocument() {
return document;
}
}
package com.zjty.adaptationmaster.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
public class PropertiesReader {
public static Properties readProperties(Path path){
InputStream inputStream = null;
Properties properties = new Properties();
try {
inputStream = Files.newInputStream(path);
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
}
...@@ -13,10 +13,8 @@ import java.nio.file.Path; ...@@ -13,10 +13,8 @@ import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import java.util.List; import java.util.List;
public class ReadedFileTask implements Runnable {
@Autowired public class ReadedFileTask implements Runnable {
private SimpMessagingTemplate template;
private List<ReadedFile> readedFiles; private List<ReadedFile> readedFiles;
//private Writer responseWriter; //private Writer responseWriter;
...@@ -36,6 +34,7 @@ public class ReadedFileTask implements Runnable { ...@@ -36,6 +34,7 @@ public class ReadedFileTask implements Runnable {
this.index = index; this.index = index;
} }
@Override @Override
public void run() { public void run() {
for(ReadedFile readedFile:readedFiles){ for(ReadedFile readedFile:readedFiles){
...@@ -62,7 +61,7 @@ public class ReadedFileTask implements Runnable { ...@@ -62,7 +61,7 @@ public class ReadedFileTask implements Runnable {
} }
//container.add(readedFile.getPath().getFileName()+"文本替换:"+entity.getTextMatching()+"|"+entity.getReplacing()); //container.add(readedFile.getPath().getFileName()+"文本替换:"+entity.getTextMatching()+"|"+entity.getReplacing());
template.convertAndSend("===="+readedFile.getPath().getFileName()+"////"+entity.getTextMatching()+"||||"+entity.getReplacing(),"1L"); //template.convertAndSend("===="+readedFile.getPath().getFileName()+"////"+entity.getTextMatching()+"||||"+entity.getReplacing(),"1L");
//responseWriter.write("===="+readedFile.getPath().getFileName()+"////"+entity.getTextMatching()+"||||"+entity.getReplacing()); //responseWriter.write("===="+readedFile.getPath().getFileName()+"////"+entity.getTextMatching()+"||||"+entity.getReplacing());
} }
......
...@@ -48,8 +48,8 @@ public class StringCompareUtil { ...@@ -48,8 +48,8 @@ public class StringCompareUtil {
*/ */
private static int getNext(String pattern,String str,int[] N) { private static int getNext(String pattern,String str,int[] N) {
int n = pattern.length(); int n = pattern.length();
char v1[] = str.toCharArray(); char[] v1 = str.toCharArray();
char v2[] = pattern.toCharArray(); char[] v2 = pattern.toCharArray();
int x = 0; int x = 0;
while (n-- != 0) { while (n-- != 0) {
if (v1[x] != v2[x]){ if (v1[x] != v2[x]){
......
package com.zjty.adaptationmaster.utils;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Map;
public class YamlReader {
private String path;
private Map<String,Map> map;
public YamlReader(String path){
this.path = path;
Yaml yaml = new Yaml();
try {
map = yaml.loadAs(new FileInputStream(path),Map.class);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String getSpringDatasourceUrl(){
return (String) ((Map)((map.get("spring")).get("datasource"))).get("url");
}
public static void main(String[] args) {
String s = "# mybatis\n" +
"mybatis:\n" +
" type-aliases-package: info.ideatower.component.inscriber.entity\n" +
" mapper-locations: classpath:mapping/*.xml\n" +
" config-locations: classpath:mybatis-config.xml\n" +
"\n" +
"# 应用组件通信等配置\n" +
"component:\n" +
" misso:\n" +
" log:\n" +
" addr: http://localhost:8009\n" +
" error:\n" +
" enable: on\n" +
"\n" +
"Related:\n" +
" Projects:\n" +
" - Rx\n" +
" - Kwalify\n" +
" - yaml_vim\n" +
" - yatools.net\n" +
" - JSON\n" +
" - Pygments";
String s1 = "logging:\n" +
" level:\n" +
" root: debug\n" +
" com.cax: debug\n" +
" file: logs/debug.log\n" +
"spring:\n" +
" datasource:\n" +
" driver-class-name: com.mysql.cj.jdbc.Driver\n" +
" url: jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC\n" +
" username: root\n" +
" password:\n" +
" jpa:\n" +
" hibernate:\n" +
" ddl-auto: create\n" +
" show-sql: true\n" +
" open-in-view: false\n";
Yaml yaml = new Yaml();
Map<String,Map> map = yaml.loadAs(s1, Map.class);
System.out.println(((Map)(map.get("spring")).get("datasource")).get("url"));
//System.out.println(ymmm.getSpring().getDataSource().getDriverClassName());
// System.out.println(map);
// for (Map.Entry<String,Map> entry:map.entrySet()){
// System.out.println(entry);
//
// System.out.println(entry.getValue());
//// System.out.println(entry.getKey()+"\t"+entry.getValue());
// }
//只能解析map和properties
// YamlMapFactoryBean yamlMapFactoryBean = new YamlMapFactoryBean();
// yamlMapFactoryBean.setResources(new ClassPathResource("test.yml"));
// Map<String, Object> object = yamlMapFactoryBean.getObject();
// ymmm ymmm = ((ymmm)object);
// System.out.println(ymmm.getSpring().getDataSource().getDriverClassName());
//ymmm ymmm = JSON.parseObject(s1, ymmm.class);
//System.out.println(ymmm.getSpring().getDataSource().getDriverClassName());
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DataSource{
private String driverClassName;
private String url;
private String username;
private String password;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class spring{
private DataSource dataSource;
}
@Data
public class ymmm{
private spring spring;
public ymmm(){
}
public ymmm(spring spring){
this.spring = spring;
}
}
}
logging:
level:
root: debug
com.cax: debug
file: logs/debug.log
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password:
jpa:
hibernate:
ddl-auto: create
show-sql: true
open-in-view: false
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论