提交 5e5c736f authored 作者: zhangshuang's avatar zhangshuang

合并分支 'zs' 到 'master'

Zs 查看合并请求 ty_wyl/adaptation-master1!34
package com.zjty.adaptationmaster.adaptor.controller; package com.zjty.adaptationmaster.adaptor.controller;
import com.zjty.adaptationmaster.adaptor.entity.db.DBDeleteResponse;
import com.zjty.adaptationmaster.adaptor.entity.db.DBManage; import com.zjty.adaptationmaster.adaptor.entity.db.DBManage;
import com.zjty.adaptationmaster.adaptor.service.DBManageService; import com.zjty.adaptationmaster.adaptor.service.DBManageService;
import com.zjty.adaptationmaster.base.response.ServerResponse; import com.zjty.adaptationmaster.base.response.ServerResponse;
...@@ -27,4 +28,9 @@ public class DBManageController { ...@@ -27,4 +28,9 @@ public class DBManageController {
public ServerResponse findDatabaseManagement(){ public ServerResponse findDatabaseManagement(){
return databaseService.findDatabase(); return databaseService.findDatabase();
} }
@PutMapping("/deleteDB")
public ServerResponse deleteDB(@RequestBody DBDeleteResponse dbDeleteResponse){
return databaseService.deleteDB(dbDeleteResponse);
}
} }
package com.zjty.adaptationmaster.adaptor.controller; package com.zjty.adaptationmaster.adaptor.controller;
import com.zjty.adaptationmaster.adaptor.entity.db.DBDeleteResponse;
import com.zjty.adaptationmaster.adaptor.entity.db.DBRecordPage; import com.zjty.adaptationmaster.adaptor.entity.db.DBRecordPage;
import com.zjty.adaptationmaster.adaptor.service.DBRecordService; import com.zjty.adaptationmaster.adaptor.service.DBRecordService;
import com.zjty.adaptationmaster.base.response.ServerResponse; import com.zjty.adaptationmaster.base.response.ServerResponse;
...@@ -21,8 +20,5 @@ public class DBRecordController { ...@@ -21,8 +20,5 @@ public class DBRecordController {
return dbRecordService.pageFind(dbRecordPage); return dbRecordService.pageFind(dbRecordPage);
} }
@PutMapping("deleteDB")
public ServerResponse deleteDB(@RequestBody DBDeleteResponse dbDeleteResponse){
return dbRecordService.deleteDB(dbDeleteResponse);
}
} }
...@@ -4,17 +4,15 @@ import com.zjty.adaptationmaster.adaptor.entity.Project; ...@@ -4,17 +4,15 @@ import com.zjty.adaptationmaster.adaptor.entity.Project;
import com.zjty.adaptationmaster.adaptor.service.InspectService; import com.zjty.adaptationmaster.adaptor.service.InspectService;
import com.zjty.adaptationmaster.base.response.ServerResponse; import com.zjty.adaptationmaster.base.response.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/inspect") @RequestMapping("/inspect")
public class InspectController { public class InspectController {
@Autowired @Autowired
private InspectService inspectService; private InspectService inspectService;
@GetMapping("/inspect") @PutMapping("/inspect")
public ServerResponse inspect(Project projectId){ public ServerResponse inspect(@RequestBody Project projectId){
return inspectService.inspect(projectId); return inspectService.inspect(projectId);
} }
} }
package com.zjty.adaptationmaster.adaptor.controller;
import com.alibaba.fastjson.JSONObject;
import com.zjty.adaptationmaster.base.response.ServerResponse;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@RequestMapping("/send")
public class Test {
@PutMapping("/test/{uuid}")
public ServerResponse test(@PathVariable String uuid){
JSONObject jo = new JSONObject();
jo.put("message", "这是后台返回的消息!");
try {
WebSocketServer.sendIn(uuid,JSONObject.toJSONString(jo));
} catch (Exception e) {
e.printStackTrace();
}
return ServerResponse.success();
}
}
...@@ -27,7 +27,9 @@ public class WebSocketServer { ...@@ -27,7 +27,9 @@ public class WebSocketServer {
public void onOpen(Session session,@PathParam("uuid")String uuid){ public void onOpen(Session session,@PathParam("uuid")String uuid){
this.session = session; this.session = session;
this.uuid = uuid; this.uuid = uuid;
System.out.println(this.uuid + "\t" + this.session);
//session.getOpenSessions(). //session.getOpenSessions().
logger.info("uuid:"+uuid);
map.put(uuid,this); map.put(uuid,this);
try { try {
sendMessage("连接成功"); sendMessage("连接成功");
...@@ -73,6 +75,8 @@ public class WebSocketServer { ...@@ -73,6 +75,8 @@ public class WebSocketServer {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static void sendIn(String sessionId,String message) throws IOException {
map.get(sessionId).sendMessage(message);
}
} }
...@@ -28,6 +28,8 @@ public class MiddlewareManagement { ...@@ -28,6 +28,8 @@ public class MiddlewareManagement {
private String ip;//中间件ip private String ip;//中间件ip
private String type;//类型
private String port;//端口号 private String port;//端口号
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
......
package com.zjty.adaptationmaster.adaptor.entity; package com.zjty.adaptationmaster.adaptor.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
...@@ -18,6 +19,7 @@ import java.util.List; ...@@ -18,6 +19,7 @@ import java.util.List;
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
@Entity @Entity
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class Project { public class Project {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
...@@ -26,6 +28,10 @@ public class Project { ...@@ -26,6 +28,10 @@ public class Project {
@Column(unique = true) @Column(unique = true)
private String projectName;//项目名称 private String projectName;//项目名称
private String sourceDB;//原数据库
private String createTypeDB;//目标数据库
private String createMiddleware;//目标中间件
private String codeUrl;//当前源码源码路径 private String codeUrl;//当前源码源码路径
private Integer status = 1;//状态(0:删除 1:未删除) private Integer status = 1;//状态(0:删除 1:未删除)
......
package com.zjty.adaptationmaster.adaptor.entity;
import org.springframework.context.ApplicationContext;
public class SystemVariable {
public static ApplicationContext context;
}
...@@ -7,10 +7,13 @@ import org.springframework.data.jpa.repository.Modifying; ...@@ -7,10 +7,13 @@ import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import java.util.List;
public interface DBRecordDao extends JpaRepository<DBRecord,Integer>, JpaSpecificationExecutor { public interface DBRecordDao extends JpaRepository<DBRecord,Integer>, JpaSpecificationExecutor {
@Query("update DBRecord d set d.status =:status where d.dbName =:dbName")
@Modifying @Modifying
@Query("update DBRecord d set d.status =:status where d.dbName =:dbName")
void delete(@Param(value = "dbName") String dbName, @Param(value = "status") Integer status); void delete(@Param(value = "dbName") String dbName, @Param(value = "status") Integer status);
List<DBRecord> findDBRecordsByStatus(Integer status);
} }
package com.zjty.adaptationmaster.adaptor.service; package com.zjty.adaptationmaster.adaptor.service;
import com.zjty.adaptationmaster.adaptor.entity.db.DBDeleteResponse;
import com.zjty.adaptationmaster.adaptor.entity.db.DBManage; import com.zjty.adaptationmaster.adaptor.entity.db.DBManage;
import com.zjty.adaptationmaster.base.response.ServerResponse; import com.zjty.adaptationmaster.base.response.ServerResponse;
...@@ -11,4 +12,6 @@ public interface DBManageService { ...@@ -11,4 +12,6 @@ public interface DBManageService {
ServerResponse deleteDatabase(Integer id); ServerResponse deleteDatabase(Integer id);
ServerResponse findDatabase(); ServerResponse findDatabase();
ServerResponse deleteDB(DBDeleteResponse dbDeleteResponse);
} }
...@@ -9,5 +9,4 @@ public interface DBRecordService { ...@@ -9,5 +9,4 @@ public interface DBRecordService {
ServerResponse pageFind(DBRecordPage dbRecordPage); ServerResponse pageFind(DBRecordPage dbRecordPage);
ServerResponse deleteDB(DBDeleteResponse dbDeleteResponse);
} }
...@@ -64,7 +64,7 @@ public class AdaptationServiceImpl implements AdaptationService { ...@@ -64,7 +64,7 @@ public class AdaptationServiceImpl implements AdaptationService {
FileUtil fileUtil = new FileUtil(); FileUtil fileUtil = new FileUtil();
project.setCodeUrl(Const.UPLOAD_LOCATION+File.separator+project.getProjectName()); project.setCodeUrl(Const.UPLOAD_LOCATION+File.separator+project.getProjectName());
try { try {
fileUtil.unzip(path,project.getCodeUrl()); fileUtil.unZip(new File(path),project.getCodeUrl());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
......
package com.zjty.adaptationmaster.adaptor.service.Impl; package com.zjty.adaptationmaster.adaptor.service.Impl;
import com.zjty.adaptationmaster.adaptor.entity.db.DBDeleteResponse;
import com.zjty.adaptationmaster.adaptor.entity.db.DBManage; import com.zjty.adaptationmaster.adaptor.entity.db.DBManage;
import com.zjty.adaptationmaster.adaptor.entity.db.DBRecord;
import com.zjty.adaptationmaster.adaptor.repository.DBManageDao; import com.zjty.adaptationmaster.adaptor.repository.DBManageDao;
import com.zjty.adaptationmaster.adaptor.repository.DBRecordDao;
import com.zjty.adaptationmaster.adaptor.service.DBManageService; import com.zjty.adaptationmaster.adaptor.service.DBManageService;
import com.zjty.adaptationmaster.base.response.ServerResponse; import com.zjty.adaptationmaster.base.response.ServerResponse;
import com.zjty.adaptationmaster.utils.Regular;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@Service @Service
public class DBManageServiceImpl implements DBManageService { public class DBManageServiceImpl implements DBManageService {
@Autowired @Autowired
private DBManageDao databaseDao; private DBManageDao databaseDao;
@Autowired
private DBRecordDao dbRecordDao;
@Value("${highgo.driver}")
private String highgoDriver;
@Value("${highgo.connectionType}")
private String highgoConnnectionType;
@Value("${highgo.dbName}")
private String highgoDBName;
/** /**
* 新增数据库配置文件 * 新增数据库配置文件
...@@ -49,4 +67,40 @@ public class DBManageServiceImpl implements DBManageService { ...@@ -49,4 +67,40 @@ public class DBManageServiceImpl implements DBManageService {
return ServerResponse.success(databaseDao.findDatabaseManagementByStatus(1)); return ServerResponse.success(databaseDao.findDatabaseManagementByStatus(1));
} }
/**
* 数据库删除
* @param dbDeleteResponse
* @return
*/
@Override
@Transactional
public ServerResponse deleteDB(DBDeleteResponse dbDeleteResponse) {
DBManage dbManage = databaseDao.findDBManageByIdAndStatus(dbDeleteResponse.getId(),1);
if(dbDeleteResponse.getDbType().equals("highgo")){
dbManage.setDatabaseName(highgoDBName);
dbManage.setDriver(highgoDriver);
dbManage.setConnectionType(highgoConnnectionType);
}
Connection connection = Regular.databaseConnection(dbManage);
if (connection != null) {
PreparedStatement preparedStatement = null;
try {
String findDB = "DROP DATABASE IF EXISTS " + dbDeleteResponse.getDbName()+ ";";
preparedStatement = connection.prepareStatement(findDB);
preparedStatement.execute();
dbRecordDao.delete(dbDeleteResponse.getDbName(),0);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return ServerResponse.success();
}
} }
...@@ -111,7 +111,6 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -111,7 +111,6 @@ public class DBMigrateServiceImpl implements DBMigrateService {
File file = new File(path); File file = new File(path);
FileReader fileReader = null; FileReader fileReader = null;
BufferedReader bufferedReader = null; BufferedReader bufferedReader = null;
List<String> tableList = new ArrayList<>();
List<String> insertList = new ArrayList<>(); List<String> insertList = new ArrayList<>();
List<String> elseList = new ArrayList<>(); List<String> elseList = new ArrayList<>();
PreparedStatement preparedStatement1 = null; PreparedStatement preparedStatement1 = null;
...@@ -120,7 +119,7 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -120,7 +119,7 @@ public class DBMigrateServiceImpl implements DBMigrateService {
bufferedReader = new BufferedReader(fileReader); bufferedReader = new BufferedReader(fileReader);
String s; String s;
String sql = ""; String sql = "";
ThreadPoolExecutor pool = new ThreadPoolExecutor(poolSize,poolSize,10, TimeUnit.SECONDS,new ArrayBlockingQueue<>(poolSize*2)); ThreadPoolExecutor pool = new ThreadPoolExecutor(poolSize,poolSize,10, TimeUnit.SECONDS,new ArrayBlockingQueue<>(poolSize * 2));
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
while ((s = bufferedReader.readLine()) != null){ while ((s = bufferedReader.readLine()) != null){
if(Regular.lowerAndUpper(s,"INSERT") && Regular.lowerAndUpper(s,"INTO")){ if(Regular.lowerAndUpper(s,"INSERT") && Regular.lowerAndUpper(s,"INTO")){
...@@ -144,15 +143,21 @@ public class DBMigrateServiceImpl implements DBMigrateService { ...@@ -144,15 +143,21 @@ public class DBMigrateServiceImpl implements DBMigrateService {
SQLExecuteTask sqlExecuteTask = new SQLExecuteTask(connection1); SQLExecuteTask sqlExecuteTask = new SQLExecuteTask(connection1);
sqlExecuteTask.setSql(insert); sqlExecuteTask.setSql(insert);
pool.submit(sqlExecuteTask); pool.submit(sqlExecuteTask);
System.out.println("核心线程数" + pool.getPoolSize() + "\t" + "存活线程数:" + pool.getActiveCount() + "\t" + "等待数量:" + pool.getQueue().size() +"\t" + "任务数量:" + pool.getTaskCount());
} }
if(pool.getCorePoolSize() == 0){ //数据库连接池关闭
pool.shutdown();
try {
pool.awaitTermination(1,TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
}
//关闭后执行新建索引和外键的sql语句
for(String elseChar:elseList){ for(String elseChar:elseList){
SQLExecuteTask sqlExecuteTask = new SQLExecuteTask(connection1); SQLExecuteTask sqlExecuteTask = new SQLExecuteTask(connection1);
sqlExecuteTask.setSql(elseChar); sqlExecuteTask.setSql(elseChar);
pool.submit(sqlExecuteTask); pool.submit(sqlExecuteTask);
} }
}
System.out.println("");
System.out.println("sql执行时间为:" + (System.currentTimeMillis() - b)); System.out.println("sql执行时间为:" + (System.currentTimeMillis() - b));
log.info(databaseResponse.getSqlPath() + "执行完成"); log.info(databaseResponse.getSqlPath() + "执行完成");
} catch (Exception e) { } catch (Exception e) {
......
...@@ -35,10 +35,10 @@ public class DBRecordServiceImpl implements DBRecordService { ...@@ -35,10 +35,10 @@ public class DBRecordServiceImpl implements DBRecordService {
public ServerResponse pageFind(DBRecordPage dbRecordPage) { public ServerResponse pageFind(DBRecordPage dbRecordPage) {
Specification<DBRecord> specifications = Specifications.<DBRecord>and() Specification<DBRecord> specifications = Specifications.<DBRecord>and()
.eq(dbRecordPage.getCreateType() != null,"createType",dbRecordPage.getCreateType()) .eq(dbRecordPage.getCreateType() != null,"createType",dbRecordPage.getCreateType())
.eq(dbRecordPage.getUserName() != null,"userName",dbRecordPage.getUserName()) //.eq(dbRecordPage.getUserName() != null,"userName",dbRecordPage.getUserName())
.eq("status",1) .eq("status",1)
.build(); .build();
Integer page = dbRecordPage.getPage(); /*Integer page = dbRecordPage.getPage();
Integer size = dbRecordPage.getSize(); Integer size = dbRecordPage.getSize();
if(page == null || page <= 0){ if(page == null || page <= 0){
page = 1; page = 1;
...@@ -50,38 +50,7 @@ public class DBRecordServiceImpl implements DBRecordService { ...@@ -50,38 +50,7 @@ public class DBRecordServiceImpl implements DBRecordService {
long count = dbRecordDao.count(specifications); long count = dbRecordDao.count(specifications);
if(count < 0){ if(count < 0){
return ServerResponse.error(); return ServerResponse.error();
} }*/
return ServerResponse.success(new DBRecordReturn(count,dbRecordDao.findAll(specifications,pageable).getContent())); return ServerResponse.success(dbRecordDao.findAll(specifications));
}
/**
* 数据库删除
* @param dbDeleteResponse
* @return
*/
@Override
@Transactional
public ServerResponse deleteDB(DBDeleteResponse dbDeleteResponse) {
DBManage dbManage = dbManageDao.findDBManageByIdAndStatus(dbDeleteResponse.getId(),1);
Connection connection = Regular.databaseConnection(dbManage);
if (connection != null) {
PreparedStatement preparedStatement = null;
try {
String findDB = "DROP DATABASE IF EXISTS " + dbDeleteResponse.getDbName()+ ";";
preparedStatement = connection.prepareStatement(findDB);
preparedStatement.execute();
dbRecordDao.delete(dbDeleteResponse.getDbName(),0);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return ServerResponse.success();
} }
} }
...@@ -32,7 +32,7 @@ public class FileUploadServiceImpl implements FileUploadService { ...@@ -32,7 +32,7 @@ public class FileUploadServiceImpl implements FileUploadService {
BufferedOutputStream bos = null; BufferedOutputStream bos = null;
FileReturn fileReturn = new FileReturn(); FileReturn fileReturn = new FileReturn();
String sourceName = multipartFile.getOriginalFilename(); String sourceName = multipartFile.getOriginalFilename();
String suffix = sourceName.substring(sourceName.lastIndexOf(".")+1); String suffix = sourceName.substring(sourceName.lastIndexOf("."));
String fileName = UUID.randomUUID().toString() + suffix; String fileName = UUID.randomUUID().toString() + suffix;
//不存在该目录,创建目录 //不存在该目录,创建目录
File file = new File("/sqlFile/uploads"); File file = new File("/sqlFile/uploads");
......
package com.zjty.adaptationmaster.base.response; package com.zjty.adaptationmaster.base.response;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zjty.adaptationmaster.utils.HttpClientUtil; import com.zjty.adaptationmaster.utils.HttpClientUtil;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
......
package com.zjty.adaptationmaster.utils; package com.zjty.adaptationmaster.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
public class FileUtil { public class FileUtil {
private static final int BUFFEREDSIZE = 1024;
/**
* 解压zip格式的压缩文件到当前文件夹
*
* @param zipFileName
* @throws Exception
*/
@SuppressWarnings("unchecked")
public synchronized void unzipFile(String zipFileName) throws Exception {
try {
File f = new File(zipFileName);
ZipFile zipFile = new ZipFile(zipFileName);
if ((!f.exists()) && (f.length() <= 0)) {
throw new Exception("要解压的文件不存在!");
}
String strPath, gbkPath, strtemp;
File tempFile = new File(f.getParent());
strPath = tempFile.getAbsolutePath();
java.util.Enumeration e = zipFile.getEntries();
while (e.hasMoreElements()) {
org.apache.tools.zip.ZipEntry zipEnt = (ZipEntry) e.nextElement();
gbkPath = zipEnt.getName();
if (zipEnt.isDirectory()) {
strtemp = strPath + "/" + gbkPath;
File dir = new File(strtemp);
dir.mkdirs();
continue;
} else {
//读写文件
InputStream is = zipFile.getInputStream(zipEnt);
BufferedInputStream bis = new BufferedInputStream(is);
gbkPath = zipEnt.getName();
strtemp = strPath + "/" + gbkPath;
//建目录
String strsubdir = gbkPath;
for (int i = 0; i < strsubdir.length(); i++) {
if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {
String temp = strPath + "/" + strsubdir.substring(0, i);
File subdir = new File(temp);
if (!subdir.exists())
subdir.mkdir();
}
}
FileOutputStream fos = new FileOutputStream(strtemp);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int c;
while ((c = bis.read()) != -1) {
bos.write((byte) c);
}
bos.close();
fos.close();
}
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
static int BUFFER_SIZE = 1024;
/** /**
* 解压zip格式的压缩文件到指定位置 * zip解压
* * @param srcFile zip源文件
* @param zipFileName 压缩文件 * @param destDirPath 解压后的目标文件夹
* @param extPlace 解压目录 * @throws RuntimeException 解压失败会抛出运行时异常
* @throws Exception
*/ */
@SuppressWarnings("unchecked") public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
public synchronized void unzip(String zipFileName, String extPlace) throws Exception { long start = System.currentTimeMillis();
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
}
// 开始解压
ZipFile zipFile = null;
try { try {
(new File(extPlace)).mkdirs(); zipFile = new ZipFile(srcFile);
File f = new File(zipFileName); Enumeration<?> entries = zipFile.entries();
ZipFile zipFile = new ZipFile(zipFileName); while (entries.hasMoreElements()) {
if ((!f.exists()) && (f.length() <= 0)) { ZipEntry entry = (ZipEntry) entries.nextElement();
throw new Exception("要解压的文件不存在!"); System.out.println("解压" + entry.getName());
} // 如果是文件夹,就创建个文件夹
String strPath, gbkPath, strtemp; if (entry.isDirectory()) {
File tempFile = new File(extPlace); String dirPath = destDirPath + "/" + entry.getName();
strPath = tempFile.getAbsolutePath(); File dir = new File(dirPath);
java.util.Enumeration e = zipFile.getEntries();
while (e.hasMoreElements()) {
org.apache.tools.zip.ZipEntry zipEnt = (ZipEntry) e.nextElement();
gbkPath = zipEnt.getName();
if (zipEnt.isDirectory()) {
strtemp = strPath + File.separator + gbkPath;
File dir = new File(strtemp);
dir.mkdirs(); dir.mkdirs();
continue;
} else { } else {
//读写文件 // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
InputStream is = zipFile.getInputStream(zipEnt); File targetFile = new File(destDirPath + "/" + entry.getName());
BufferedInputStream bis = new BufferedInputStream(is); // 保证这个文件的父文件夹必须要存在
gbkPath = zipEnt.getName(); if(!targetFile.getParentFile().exists()){
strtemp = strPath + File.separator + gbkPath; targetFile.getParentFile().mkdirs();
}
//建目录 targetFile.createNewFile();
String strsubdir = gbkPath; // 将压缩文件内容写入到这个文件中
for (int i = 0; i < strsubdir.length(); i++) { InputStream is = zipFile.getInputStream(entry);
if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) { FileOutputStream fos = new FileOutputStream(targetFile);
String temp = strPath + File.separator + strsubdir.substring(0, i); int len;
File subdir = new File(temp); byte[] buf = new byte[BUFFER_SIZE];
if (!subdir.exists()) while ((len = is.read(buf)) != -1) {
subdir.mkdir(); fos.write(buf, 0, len);
} }
} // 关流顺序,先打开的后关闭
FileOutputStream fos = new FileOutputStream(strtemp);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int c;
while ((c = bis.read()) != -1) {
bos.write((byte) c);
}
bos.close();
fos.close(); fos.close();
is.close();
} }
} }
long end = System.currentTimeMillis();
System.out.println("解压完成,耗时:" + (end - start) +" ms");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); throw new RuntimeException("unzip error from ZipUtils", e);
throw e;
}
}
/**
* 解压zip格式的压缩文件到指定位置
*
* @param zipFileName 压缩文件
* @param extPlace 解压目录
* @throws Exception
*/
@SuppressWarnings("unchecked")
public synchronized void unzip(String zipFileName, String extPlace, boolean whether) throws Exception {
try {
(new File(extPlace)).mkdirs();
File f = new File(zipFileName);
ZipFile zipFile = new ZipFile(zipFileName);
if ((!f.exists()) && (f.length() <= 0)) {
throw new Exception("要解压的文件不存在!");
}
String strPath, gbkPath, strtemp;
File tempFile = new File(extPlace);
strPath = tempFile.getAbsolutePath();
java.util.Enumeration e = zipFile.getEntries();
while (e.hasMoreElements()) {
org.apache.tools.zip.ZipEntry zipEnt = (ZipEntry) e.nextElement();
gbkPath = zipEnt.getName();
if (zipEnt.isDirectory()) {
strtemp = strPath + File.separator + gbkPath;
File dir = new File(strtemp);
dir.mkdirs();
continue;
} else {
//读写文件
InputStream is = zipFile.getInputStream(zipEnt);
BufferedInputStream bis = new BufferedInputStream(is);
gbkPath = zipEnt.getName();
strtemp = strPath + File.separator + gbkPath;
//建目录
String strsubdir = gbkPath;
for (int i = 0; i < strsubdir.length(); i++) {
if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {
String temp = strPath + File.separator + strsubdir.substring(0, i);
File subdir = new File(temp);
if (!subdir.exists())
subdir.mkdir();
}
}
FileOutputStream fos = new FileOutputStream(strtemp);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int c;
while ((c = bis.read()) != -1) {
bos.write((byte) c);
}
bos.close();
fos.close();
}
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
/**
* 压缩zip格式的压缩文件
*
* @param inputFilename 压缩的文件或文件夹及详细路径
* @param zipFilename 输出文件名称及详细路径
* @throws IOException
*/
public synchronized void zip(String inputFilename, String zipFilename) throws IOException {
zip(new File(inputFilename), zipFilename);
}
/**
* 压缩zip格式的压缩文件
*
* @param inputFile 需压缩文件
* @param zipFilename 输出文件及详细路径
* @throws IOException
*/
public synchronized void zip(File inputFile, String zipFilename) throws IOException {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename));
try {
zip(inputFile, out, "");
} catch (IOException e) {
throw e;
} finally { } finally {
if(zipFile != null){
out.close();
}
}
/**
* 压缩zip格式的压缩文件
*
* @param inputFile 需压缩文件
* @param out 输出压缩文件
* @param base 结束标识
* @throws IOException
*/
@SuppressWarnings("unused")
private synchronized void zip(File inputFile, ZipOutputStream out, String base) throws IOException {
if (inputFile.isDirectory()) {
File[] inputFiles = inputFile.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < inputFiles.length; i++) {
zip(inputFiles[i], out, base + inputFiles[i].getName());
}
} else {
if (base.length() > 0) {
out.putNextEntry(new ZipEntry(base));
} else {
out.putNextEntry(new ZipEntry(inputFile.getName()));
}
FileInputStream in = new FileInputStream(inputFile);
try { try {
int c; zipFile.close();
byte[] by = new byte[BUFFEREDSIZE];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
} catch (IOException e) { } catch (IOException e) {
throw e; e.printStackTrace();
} finally {
in.close();
} }
} }
} }
/**
* 解压tar格式的压缩文件到指定目录下
*
* @param tarFileName 压缩文件
* @param extPlace 解压目录
* @throws Exception
*/
public synchronized void untar(String tarFileName, String extPlace) throws Exception {
} }
/** public static void main(String[] args) {
* 压缩tar格式的压缩文件
*
* @param inputFilename 压缩文件
* @param tarFilename 输出路径
* @throws IOException
*/
public synchronized void tar(String inputFilename, String tarFilename) throws IOException {
tar(new File(inputFilename), tarFilename);
}
/** String filePath = "C:\\Users\\wyl\\Desktop\\alllib.zip";
* 压缩tar格式的压缩文件 String path = "C:\\Users\\wyl\\Desktop\\unZip";
*
* @param inputFile 压缩文件
* @param tarFilename 输出路径
* @throws IOException
*/
public synchronized void tar(File inputFile, String tarFilename) throws IOException {
TarOutputStream out = new TarOutputStream(new FileOutputStream(tarFilename));
try { try {
tar(inputFile, out, ""); unZip(new File(filePath),path);
} catch (IOException e) { } catch (Exception e) {
throw e; e.printStackTrace();
} finally {
out.close();
}
}
/**
* 压缩tar格式的压缩文件
*
* @param inputFile 压缩文件
* @param out 输出文件
* @param base 结束标识
* @throws IOException
*/
@SuppressWarnings("unused")
private synchronized void tar(File inputFile, TarOutputStream out, String base) throws IOException {
if (inputFile.isDirectory()) {
File[] inputFiles = inputFile.listFiles();
out.putNextEntry(new TarEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < inputFiles.length; i++) {
tar(inputFiles[i], out, base + inputFiles[i].getName());
}
} else {
if (base.length() > 0) {
out.putNextEntry(new TarEntry(base));
} else {
out.putNextEntry(new TarEntry(inputFile.getName()));
}
FileInputStream in = new FileInputStream(inputFile);
try {
int c;
byte[] by = new byte[BUFFEREDSIZE];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
} catch (IOException e) {
throw e;
} finally {
in.close();
}
} }
} }
/* <!-- ant -->
maven 坐标
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.7</version>
</dependency>
*/
} }
package com.zjty.adaptationmaster.utils;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class FileZip {
public static void unZipFiles(File zipFile, String descDir)throws IOException
{
File pathFile = new File(descDir);
if(!pathFile.exists())
{
pathFile.mkdirs();
}
//解决zip文件中有中文目录或者中文文件
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
for(Enumeration entries = zip.entries(); entries.hasMoreElements();)
{
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");;
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if(!file.exists())
{
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory())
{
continue;
}
//输出文件路径信息
System.out.println(outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while((len=in.read(buf1))>0)
{
out.write(buf1,0,len);
}
in.close();
out.close();
}
zip.close(); //**原博忘记关了,所以我在做完这些操作后想要删除文件时,一直已占用,必须关掉服务器才可以**
System.out.println("******************解压完毕********************");
}
}
...@@ -98,6 +98,10 @@ public class Regular { ...@@ -98,6 +98,10 @@ public class Regular {
s = StringType(s,"double","real"); s = StringType(s,"double","real");
//插入值时boolean类型转换 //插入值时boolean类型转换
s = replaceLowerAndUpper(s,"BIT(1)","boolean"); s = replaceLowerAndUpper(s,"BIT(1)","boolean");
//替换longtext
s = replaceLowerAndUpper(s,"longtext","text");
//替换mediumtext
s = replaceLowerAndUpper(s,"mediumtext","text");
//从第一个创建表的可执行命令开始 //从第一个创建表的可执行命令开始
if(lowerAndUpper(s,"DROP") && lowerAndUpper(s,"TABLE") && executeOne){ if(lowerAndUpper(s,"DROP") && lowerAndUpper(s,"TABLE") && executeOne){
isFirstDrop = true; isFirstDrop = true;
...@@ -231,8 +235,8 @@ public class Regular { ...@@ -231,8 +235,8 @@ public class Regular {
* 大小写都替换 * 大小写都替换
*/ */
public static String replaceLowerAndUpper(String s,String upper,String replacement){ public static String replaceLowerAndUpper(String s,String upper,String replacement){
s = s.replaceAll(upper,replacement); s = s.replace(upper,replacement);
s = s.replaceAll(upper.toLowerCase(),replacement); s = s.replace(upper.toLowerCase(),replacement);
return s; return s;
} }
...@@ -285,6 +289,6 @@ public class Regular { ...@@ -285,6 +289,6 @@ public class Regular {
public static void main(String[] args) { public static void main(String[] args) {
mySqlRegular("C:\\Users\\admin\\Desktop\\database\\new_debug.sql","new_debug"); mySqlRegular("D:\\sqlFile\\uploads\\63c6e098-73fd-4999-b289-b3d120a07e87.sql","test11111");
} }
} }
package com.zjty.adaptationmaster; package com.zjty.adaptationmaster;
import com.zjty.adaptationmaster.adaptor.entity.db.DBManage;
import com.zjty.adaptationmaster.utils.Regular;
import org.postgresql.copy.CopyManager;
import org.postgresql.core.BaseConnection;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
public class Test4 { public class Test4 {
public static void main(String[] args) { public static void main(String[] args) {
String s = "123)456)789)0"; String s = "\"record_alarm\" bit(1) DEFAULT NULL,";
String[] array = s.split("\\)"); System.out.println(s.replaceAll("bit(1)","boolean"));
for(String si:array){
System.out.println(si);
}
} }
} }
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论