自动打包工具

dev
youhong.ai 2023-07-04 12:30:53 +08:00
parent 7143747a25
commit ef336b906d
16 changed files with 734 additions and 5 deletions

171
FileSelectionApp.java Normal file
View File

@ -0,0 +1,171 @@
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
public class FileSelectionApp extends JFrame {
private JTree fileTree;
private JCheckBox[] checkBoxes;
private JLabel statusLabel;
public FileSelectionApp() {
setTitle("文件选择");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 400);
setLocationRelativeTo(null);
// 创建选择按钮
JButton selectButton = new JButton("打包选中的文件或文件夹");
selectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectItems();
}
});
// 创建文件树
fileTree = new JTree(getFileTreeModel());
fileTree.setRootVisible(false);
fileTree.setShowsRootHandles(true);
fileTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
updateStatusLabel();
}
});
JScrollPane treeScrollPane = new JScrollPane(fileTree);
// 创建结果标签
statusLabel = new JLabel();
updateStatusLabel();
// 创建面板并添加组件
JPanel panel = new JPanel(new BorderLayout());
panel.add(selectButton, BorderLayout.NORTH);
panel.add(treeScrollPane, BorderLayout.CENTER);
panel.add(statusLabel, BorderLayout.SOUTH);
// 将面板添加到窗口
add(panel);
}
private DefaultMutableTreeNode getFileTreeModel() {
File targetDir = new File("target/classes/");
DefaultMutableTreeNode root = new DefaultMutableTreeNode(targetDir.getName());
buildFileTree(root, targetDir);
return root;
}
private void buildFileTree(DefaultMutableTreeNode parent, File directory) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(file.getName());
parent.add(node);
if (file.isDirectory()) {
buildFileTree(node, file);
}
}
}
}
private void selectItems() {
List<File> selectedFiles = new ArrayList<>();
DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) fileTree.getModel().getRoot();
Enumeration<?> enumeration = rootNode.breadthFirstEnumeration();
while (enumeration.hasMoreElements()) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumeration.nextElement();
if (node.isLeaf() && checkBoxes[node.getLevel()].isSelected()) {
TreePath path = new TreePath(node.getPath());
selectedFiles.add(new File(path.toString().substring(1).replace(", ", "/")));
}
}
if (!selectedFiles.isEmpty()) {
createZipFile(selectedFiles);
} else {
statusLabel.setText("请勾选要打包的文件或文件夹");
}
}
private void createZipFile(List<File> files) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File zipFile = fileChooser.getSelectedFile();
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile))) {
for (File file : files) {
addFileToZip(file, file.getName(), zipOutputStream);
}
statusLabel.setText("已将文件打包为:" + zipFile.getAbsolutePath());
} catch (IOException e) {
statusLabel.setText("打包文件时出现错误:" + e.getMessage());
}
}
}
private void addFileToZip(File file, String entryName, ZipOutputStream zipOutputStream) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
addFileToZip(child, entryName + "/" + child.getName(), zipOutputStream);
}
}
} else {
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(file);
zipOutputStream.putNextEntry(new ZipEntry(entryName));
int length;
while ((length = fis.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.closeEntry();
fis.close();
}
}
private void updateStatusLabel() {
TreePath[] paths = fileTree.getSelectionPaths();
if (paths != null) {
int selectedCount = paths.length;
statusLabel.setText("已选中 " + selectedCount + " 个文件/文件夹");
} else {
statusLabel.setText("");
}
}
public static void main(String[] args) {
// 设置外观和风格
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FileSelectionApp().setVisible(true);
}
});
}
}

BIN
checked.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
icons/file.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
icons/folder.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

103
package.py Normal file
View File

@ -0,0 +1,103 @@
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
from zipfile import ZipFile
selected_items = []
def toggle_selection(event):
item = tree.item(tree.focus())
file_path = item['text']
if item['tags'] == ('file',):
if file_path in selected_items:
selected_items.remove(file_path)
else:
selected_items.append(file_path)
update_selection_label()
def select_items():
if selected_items:
zip_file = 'selected_items.zip'
with ZipFile(zip_file, 'w') as zf:
for item in selected_items:
arcname = os.path.relpath(item, target_path)
if os.path.isfile(item):
zf.write(item, arcname)
elif os.path.isdir(item):
for root, dirs, files in os.walk(item):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, target_path)
zf.write(file_path, arcname)
result_label.config(text=f'文件已打包为 {zip_file}')
selected_items.clear()
update_selection_label()
def update_selection_label():
selection_label.config(text=f'已选中 {len(selected_items)} 个文件/文件夹')
def build_tree(parent, directory):
for item in os.listdir(directory):
item_path = os.path.join(directory, item)
if os.path.isdir(item_path):
item_node = tree.insert(parent, 'end', text=item, open=False, tags=('folder',))
build_tree(item_node, item_path)
else:
tree.insert(parent, 'end', text=item, tags=('file',))
def toggle_checkbox(event):
item_id = tree.identify_row(event.y)
if item_id:
is_checked = tree.tag_has('checked', item_id)
if is_checked:
tree.tag_remove('checked', item_id)
else:
tree.tag_add('checked', item_id)
# 创建主窗口
root = tk.Tk()
root.title("文件选择")
root.geometry("600x400")
# 计算窗口居中的位置
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
window_width = 600
window_height = 400
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
root.geometry(f"{window_width}x{window_height}+{x}+{y}")
# 选择目标文件夹
target_path = os.path.join(os.getcwd(), 'target/classes/')
# 创建选择按钮
select_button = tk.Button(root, text='打包选中的文件或文件夹', command=select_items)
select_button.pack(pady=10)
# 创建目录树
tree = ttk.Treeview(root, selectmode='none')
tree.pack(fill='both', expand=True)
# 创建滚动条
scrollbar = ttk.Scrollbar(root, orient='vertical', command=tree.yview)
scrollbar.pack(side='right', fill='y')
tree.configure(yscrollcommand=scrollbar.set)
# 添加当前目录下的文件和文件夹到目录树
build_tree('', target_path)
# 创建结果标签
result_label = tk.Label(root, text='')
result_label.pack()
# 创建已选中文件数标签
selection_label = tk.Label(root, text='')
selection_label.pack()
# 绑定鼠标点击事件
tree.bind('<Button-1>', toggle_checkbox)
# 启动主循环
root.mainloop()

View File

@ -130,7 +130,12 @@
<artifactId>easypoi-annotation</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.controlsfx/controlsfx -->
<dependency>
<groupId>org.controlsfx</groupId>
<artifactId>controlsfx</artifactId>
<version>8.40.14</version>
</dependency>
</dependencies>

View File

@ -29,9 +29,9 @@ import java.util.Objects;
@WeaIocReplaceComponent("CompressDocPictureService")
public class CompressDocPictureImpl {
private final CompressDocPictureMapper mapper = Util.getMapper(CompressDocPictureMapper.class);
private CompressDocPictureMapper mapper = null;
private final Logger log = Util.getLogger();
private Logger log = null;
/**
*
@ -42,6 +42,12 @@ public class CompressDocPictureImpl {
*/
@WeaReplaceAfter(value = "/api/doc/save/save", order = 1)
public String after(WeaAfterReplaceParam weaAfterReplaceParam) {
if (Objects.isNull(mapper)) {
mapper = Util.getMapper(CompressDocPictureMapper.class);
}
if (Objects.isNull(log)) {
log = Util.getLogger();
}
String data = weaAfterReplaceParam.getData();
try {
Map<String, Object> paramMap = weaAfterReplaceParam.getParamMap();

View File

@ -0,0 +1,63 @@
import aiyh.utils.tool.cn.hutool.core.util.StrUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.function.Function;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileCompressor {
public static void compressFiles(List<String> filePaths, String outputZipPath, Function<String, String> replacePath) throws IOException {
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(outputZipPath))) {
for (String filePath : filePaths) {
File file = new File(filePath);
if (file.exists()) {
if (file.isDirectory()) {
addDirectoryToZip(file, file.getPath(), zipOutputStream, replacePath);
} else {
addFileToZip(file, file.getParent(), zipOutputStream, replacePath);
}
} else {
throw new IOException("File not found: " + filePath);
}
}
}
}
private static void addDirectoryToZip(File directory, String parentPath, ZipOutputStream zipOutputStream, Function<String, String> replacePath) throws IOException {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
addDirectoryToZip(file, parentPath + File.separator + file.getName(), zipOutputStream, replacePath);
} else {
addFileToZip(file, parentPath, zipOutputStream, replacePath);
}
}
}
}
private static void addFileToZip(File file, String parentPath, ZipOutputStream zipOutputStream, Function<String, String> replacePath) throws IOException {
try (FileInputStream fileInputStream = new FileInputStream(file)) {
String entryPath = parentPath + File.separator + file.getName();
String finalPath = replacePath.apply(entryPath);
if (StrUtil.isBlank(finalPath)) {
finalPath = "/";
}
ZipEntry zipEntry = new ZipEntry(finalPath);
zipOutputStream.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) >= 0) {
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.closeEntry();
}
}
}

View File

@ -0,0 +1,61 @@
import javafx.scene.control.CheckBox;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Getter
@Setter
@ToString
public class FileInfo {
private String filePath;
private String fileName;
private String fileType;
private boolean isSelected;
private List<FileInfo> children;
private CheckBox checkBox;
// Constructors
public FileInfo(String filePath, String fileName, String fileType, boolean isSelected) {
this.filePath = filePath;
this.fileName = fileName;
this.fileType = fileType;
this.isSelected = isSelected;
}
public FileInfo() {
}
// Methods
public void addChild(FileInfo child) {
if (Objects.isNull(children)) {
this.children = new ArrayList<>();
}
boolean added = children.add(child);
if (added) {
child.setCheckBox(new CheckBox());
child.getCheckBox().setSelected(this.isSelected());
} else {
// 处理添加失败的情况
System.out.println("Failed to add child");
}
}
public boolean hasChildren() {
return children != null && !children.isEmpty();
}
@Override
public String toString() {
return fileName;
}
public boolean isDirectory() {
return this.fileType.equals(FileTreeBuilder.DIRECTORY_TYPE);
}
}

View File

@ -0,0 +1,110 @@
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class FileTreeBuilder {
public static final String DIRECTORY_TYPE = "文件夹";
public static final String FILE_TYPE = "文件";
public static FileInfo buildFileTree(String directoryPath) {
File root = new File(directoryPath);
if (!root.exists() || !root.isDirectory()) {
System.out.println("Invalid directory path: " + directoryPath);
return null;
}
List<String> blacklistPrefixes = Arrays.asList(
"target" + File.separator + "generated-sources",
"target" + File.separator + "generated-test-sources",
"target" + File.separator + "test-classes",
"target" + File.separator + "classes" + File.separator + "aiyh",
"target" + File.separator + "classes" + File.separator + "ebu7common",
"target" + File.separator + "classes" + File.separator + "ln",
"target" + File.separator + "classes" + File.separator + "cus_getlog"
);
return buildFileTreeRecursively(root, blacklistPrefixes);
}
public static FileInfo buildFileTree(String directoryPath, List<String> blacklistPrefixes) {
File root = new File(directoryPath);
if (!root.exists() || !root.isDirectory()) {
System.out.println("Invalid directory path: " + directoryPath);
return null;
}
return buildFileTreeRecursively(root, blacklistPrefixes);
}
private static FileInfo buildFileTreeRecursively(File directory, List<String> blacklistPrefixes) {
String filePath = directory.getAbsolutePath();
String fileName = directory.getName();
String fileType = DIRECTORY_TYPE;
boolean isSelected = false;
FileInfo fileInfo = new FileInfo();
fileInfo.setFilePath(filePath);
fileInfo.setFileName(fileName);
fileInfo.setFileType(fileType);
fileInfo.setSelected(isSelected);
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
if (!isBlacklisted(file.getAbsolutePath(), blacklistPrefixes)) {
FileInfo child = buildFileTreeRecursively(file, blacklistPrefixes);
fileInfo.addChild(child);
}
} else {
if (isBlacklisted(file.getPath(), blacklistPrefixes)) {
continue;
}
String childFilePath = file.getAbsolutePath();
String childFileName = file.getName();
String childFileType = FILE_TYPE;
boolean childIsSelected = false;
FileInfo childFileInfo = new FileInfo();
childFileInfo.setFilePath(childFilePath);
childFileInfo.setFileName(childFileName);
childFileInfo.setFileType(childFileType);
childFileInfo.setSelected(childIsSelected);
fileInfo.addChild(childFileInfo);
}
}
}
return fileInfo;
}
private static boolean isBlacklisted(String filePath, List<String> blacklistPrefixes) {
if (filePath.endsWith(".DS_Store") || filePath.endsWith(".DSStore")) {
return true;
}
for (String prefix : blacklistPrefixes) {
String path = FileTreeBuilder.class.getResource("").getPath();
String prefixPath = path.substring(0, path.indexOf(File.separator + "target" + File.separator)) + File.separator;
if (filePath.startsWith(prefixPath + prefix)) {
return true;
}
}
return false;
}
public static void printFileTree(FileInfo fileInfo, int level) {
if (fileInfo != null) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(fileInfo.getFileName());
List<FileInfo> children = fileInfo.getChildren();
for (FileInfo child : children) {
printFileTree(child, level + 1);
}
}
}
public static void main(String[] args) {
String directoryPath = "target/";
FileInfo fileTree = buildFileTree(directoryPath);
printFileTree(fileTree, 0);
}
}

View File

@ -0,0 +1,182 @@
import aiyh.utils.Util;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TreeViewExample extends Application {
private boolean isEcology = false;
private final List<String> filePaths = new ArrayList<>();
private TreeView<FileInfo> treeView;
private TreeItem<FileInfo> rootItem;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("EBU7部开发一部自动打包工具");
FileInfo fileInfo = FileTreeBuilder.buildFileTree("target/");
rootItem = createTreeItem(fileInfo);
treeView = new TreeView<>(rootItem);
treeView.setShowRoot(false);
treeView.setCellFactory(treeViewParam -> new CheckBoxTreeCell());
BorderPane root = new BorderPane();
root.setCenter(treeView);
HBox buttonBox = new HBox();
buttonBox.setSpacing(10);
buttonBox.setPadding(new Insets(10));
buttonBox.setAlignment(Pos.CENTER_RIGHT);
Button button = new Button("生成升级包");
button.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialFileName("sh_ebu_dev_1_ecology.zip");
File outputFile = fileChooser.showSaveDialog(primaryStage);
if (outputFile != null) {
try {
FileCompressor.compressFiles(filePaths, outputFile.getAbsolutePath(), path -> {
String rootPath = Util.class.getResource("/").getPath();
rootPath = rootPath.split(File.separator + "target" + File.separator)[0] + File.separator + "target" + File.separator + "classes" + File.separator;
String replace = "/ecology/" + (isEcology ? "WEB-INF/classes/" : "classbean/");
if (path.endsWith(".jar")) {
replace = "/ecology/WEB-INF/lib/";
path = rootPath + path.substring(path.lastIndexOf(File.separator) + 1);
} else if (path.contains("WEB-INF")) {
replace = "/ecology/";
}
replace = path.replace(rootPath, replace);
return replace;
});
clearSelections();
updateTreeView();
showSuccessAlert("升级包制作成功!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
VBox checkBoxBox = new VBox();
checkBoxBox.setPadding(new Insets(10));
checkBoxBox.setAlignment(Pos.CENTER_RIGHT);
CheckBox checkBox = new CheckBox("是否是信创环境");
checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
this.isEcology = newValue;
});
checkBoxBox.getChildren().add(checkBox);
buttonBox.getChildren().addAll(button, checkBoxBox);
root.setBottom(buttonBox);
Scene scene = new Scene(root, 600, 400);
scene.getStylesheets().add("style.css"); // 加载自定义的 CSS 文件
primaryStage.setScene(scene);
primaryStage.show();
}
private TreeItem<FileInfo> createTreeItem(FileInfo fileInfo) {
TreeItem<FileInfo> treeItem = new TreeItem<>(fileInfo);
List<FileInfo> children = fileInfo.getChildren();
if (children != null) {
for (FileInfo child : children) {
TreeItem<FileInfo> childItem = createTreeItem(child);
treeItem.getChildren().add(childItem);
}
}
return treeItem;
}
private void clearSelections() {
for (String filePath : filePaths) {
TreeItem<FileInfo> item = findTreeItem(filePath, rootItem);
if (item != null) {
FileInfo fileInfo = item.getValue();
fileInfo.setSelected(false);
}
}
filePaths.clear();
}
private void updateTreeView() {
treeView.setRoot(null); // 清除原有根节点
treeView.setRoot(rootItem); // 重新设置根节点
}
private TreeItem<FileInfo> findTreeItem(String filePath, TreeItem<FileInfo> root) {
if (root.getValue().getFilePath().equals(filePath)) {
return root;
} else {
for (TreeItem<FileInfo> child : root.getChildren()) {
TreeItem<FileInfo> foundItem = findTreeItem(filePath, child);
if (foundItem != null) {
return foundItem;
}
}
return null;
}
}
private class CheckBoxTreeCell extends TreeCell<FileInfo> {
private final CheckBox checkBox;
public CheckBoxTreeCell() {
checkBox = new CheckBox();
checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
FileInfo fileInfo = getItem();
fileInfo.setSelected(newValue);
String filePath = fileInfo.getFilePath();
if (newValue) {
if (!filePaths.contains(filePath)) {
filePaths.add(filePath);
}
} else {
filePaths.remove(filePath);
}
System.out.println(fileInfo.getFilePath());
});
}
@Override
protected void updateItem(FileInfo item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
} else {
checkBox.setSelected(item.isSelected());
checkBox.setText(item.getFileName());
setGraphic(checkBox);
}
}
}
private void showSuccessAlert(String message) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("提示");
alert.setHeaderText(null);
alert.setContentText(message);
alert.showAndWait();
}
public static void main(String[] args) {
launch(args);
}
}

View File

@ -30,7 +30,7 @@ public class BaseTest {
protected final Logger log = Util.getLogger();
private static Properties propertiesStatic;
public static Properties propertiesStatic;
@BeforeClass
public static void beforeStatic() {
@ -130,7 +130,7 @@ public class BaseTest {
@Test
public void with() {
Logger logger = Util.getLogger();
logger.info("aafasdf");
String sql = "select COMPANYNAME,LICENSE,EXPIREDATE,CVERSION from license ";

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,28 @@
.tree-view {
-fx-padding: 10px;
}
.tree-cell {
-fx-padding: 5px;
}
.tree-cell .tree-disclosure-node {
-fx-graphic: url("icons/folder.png");
}
.tree-cell .tree-disclosure-node.expanded {
-fx-graphic: url("icons/folder.png");
}
.tree-cell .tree-leaf {
-fx-graphic: url("icons/file.png");
}
.button-box {
-fx-spacing: 10px;
-fx-padding: 10px;
}
.checkbox-label {
-fx-padding: 0 0 0 5px;
}

BIN
unchecked.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB