diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..9a6f660c --- /dev/null +++ b/pom.xml @@ -0,0 +1,119 @@ + + 4.0.0 + + com.wb + dbtool + 0.0.1-SNAPSHOT + jar + + + org.springframework.boot + spring-boot-starter-parent + 2.0.3.RELEASE + + + + + maven + http://repository.jboss.org/nexus/content/groups/public/ + + true + + + true + + default + + + + + UTF-8 + UTF-8 + 1.8 + true + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-freemarker + + + + org.springframework.boot + spring-boot-devtools + provided + true + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-security + + + + org.apache.poi + poi-ooxml + 3.14 + + + org.apache.poi + poi-ooxml-schemas + 3.14 + + + com.oracle.driver + odbc + 1.0.0 + system + ${basedir}/attach/ojdbc8.jar + + + + + + dbtool + + ${basedir}/src/main/java + + + ${basedir}/src/main/resources + + + ${basedir}/src/main/java + + **/mpr/*.xml + + + + ${basedir}/src/main/resources + + *.bat + + ${project.basedir}/target + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-resources-plugin + + + + diff --git a/src/main/java/xyz/wbsite/dbtool/Application.java b/src/main/java/xyz/wbsite/dbtool/Application.java new file mode 100644 index 00000000..0e3c5100 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/Application.java @@ -0,0 +1,30 @@ +package xyz.wbsite.dbtool; + +import xyz.wbsite.dbtool.javafx.JavaFxApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +@SpringBootApplication +@EnableAutoConfiguration +public class Application extends SpringBootServletInitializer { + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.execute(new Runnable() { + @Override + public void run() { + JavaFxApplication.main(args); + } + }); +// SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/JavaFxApplication.java b/src/main/java/xyz/wbsite/dbtool/javafx/JavaFxApplication.java new file mode 100644 index 00000000..deff452d --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/JavaFxApplication.java @@ -0,0 +1,1372 @@ +package xyz.wbsite.dbtool.javafx; + +import javafx.application.Application; +import javafx.beans.property.SimpleBooleanProperty; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.event.ActionEvent; +import javafx.event.Event; +import javafx.event.EventHandler; +import javafx.fxml.FXMLLoader; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.control.cell.ChoiceBoxTableCell; +import javafx.scene.control.cell.PropertyValueFactory; +import javafx.scene.control.cell.TextFieldTableCell; +import javafx.scene.control.cell.TextFieldTreeCell; +import javafx.scene.input.*; +import javafx.scene.layout.BorderPane; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.Pane; +import javafx.scene.paint.Color; +import javafx.stage.Stage; +import javafx.stage.WindowEvent; +import javafx.util.Callback; +import javafx.util.converter.DefaultStringConverter; +import javafx.util.converter.IntegerStringConverter; +import xyz.wbsite.dbtool.javafx.ctrl.DbDetailController; +import xyz.wbsite.dbtool.javafx.ctrl.MainController; +import xyz.wbsite.dbtool.javafx.ctrl.ProjectDetailController; +import xyz.wbsite.dbtool.javafx.ctrl.TableDetailController; +import xyz.wbsite.dbtool.javafx.customview.DBCheckBoxTableCell; +import xyz.wbsite.dbtool.javafx.enumeration.FieldType; +import xyz.wbsite.dbtool.javafx.manger.ManagerFactory; +import xyz.wbsite.dbtool.javafx.manger.ProjectManager; +import xyz.wbsite.dbtool.javafx.po.Field; +import xyz.wbsite.dbtool.javafx.po.Module; +import xyz.wbsite.dbtool.javafx.po.Project; +import xyz.wbsite.dbtool.javafx.po.Table; +import xyz.wbsite.dbtool.javafx.tool.Tool; + +import java.net.URL; +import java.util.Iterator; +import java.util.List; + +public class JavaFxApplication extends Application { + + private ProjectManager dBmanger = ManagerFactory.getdBManager(); + private TreeView mdtree = null; + private Pane detail = null; + private TableView feilds = null; + private Button add = null; + private Button sub = null; + private CheckBox addSysFields = null; + private FXMLLoader mainloader; + private FXMLLoader projectdetailloader; + private FXMLLoader mddetailloader; + private FXMLLoader tabledetailloader; + private MainController mainController; + private ProjectDetailController projectDetailController; + private DbDetailController mdDetailController; + private TableDetailController tableDetailController; + private Project currentProject; + private Module currentMD; + private Table currentTable; + private ContextMenu project_menu; + private ContextMenu md_right_menu; + private ContextMenu table_right_menu; + private XEventHandler xEventHandler = new XEventHandler(); + private boolean dragMD = false; + + @Override + public void start(Stage primaryStage) throws Exception { + + BorderPane root = mainloader.getRoot(); + + primaryStage.setTitle("DBtool"); + primaryStage.setScene(new Scene(root, 700, 500)); + primaryStage.show(); + + primaryStage.setOnCloseRequest(new EventHandler() { + @Override + public void handle(WindowEvent event) { + primaryStage.close(); + System.exit(0); + } + }); + + } + + @Override + public void init() throws Exception { + URL main = JavaFxApplication.class.getClassLoader().getResource("fxml/main.fxml"); + if (main == null) { + main = getClass().getResource("../../../fxml/main.fxml"); + } + mainloader = new FXMLLoader(main); + mainloader.load(); + mainController = mainloader.getController(); + mainController.setMain(this); + mdtree = mainController.getDbtree(); + detail = mainController.getDetail(); + feilds = mainController.getFeilds(); + feilds.setEditable(true); + feilds.setSortPolicy(new Callback() { + @Override + public Boolean call(TableView param) { + //禁止点击列头排序 + return false; + } + }); + add = mainController.getAdd(); + add.setOnMouseClicked(new EventHandler() { + @Override + public void handle(MouseEvent event) { + addField(); + } + }); + sub = mainController.getSub(); + sub.setOnMouseClicked(new EventHandler() { + @Override + public void handle(MouseEvent event) { + subField(); + } + }); + + addSysFields = mainController.getAddSysFields(); + addSysFields.setOnMouseClicked(new EventHandler() { + @Override + public void handle(MouseEvent event) { + checkSysFields(); + } + }); + + ContextMenu con = new ContextMenu(new MenuItem("新增"), new MenuItem("删除"), new MenuItem("向上调整"), new MenuItem("向下调整")); + con.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + MenuItem target = (MenuItem) event.getTarget(); + int index = feilds.getSelectionModel().getSelectedIndex(); + List fields = currentTable.getFields(); + + if ("新增".equals(target.getText())) { + addField(); + } + + if (index != -1) { + switch (target.getText()) { + case "删除": + subField(); + break; + case "向上调整": + if (index > 0) { + fields.add(index - 1, fields.get(index)); + fields.add(index + 1, fields.get(index)); + fields.remove(index); + fields.remove(index + 1); + } + break; + case "向下调整": + if (index < fields.size() - 1) { + fields.add(index, fields.get(index + 1)); + fields.add(index + 2, fields.get(index + 1)); + fields.remove(index + 1); + fields.remove(index + 2); + } + break; + } + loadingTable(); + feilds.getSelectionModel().clearSelection(); + } + } + }); + feilds.setContextMenu(con); + + project_menu = new ContextMenu(new MenuItem("新增模块")); + md_right_menu = new ContextMenu(new MenuItem("新增对象"), new MenuItem("删除模块"), new MenuItem("向上调整"), new MenuItem("向下调整")); + table_right_menu = new ContextMenu(new MenuItem("删除对象")); + project_menu.setOnAction(xEventHandler); + md_right_menu.setOnAction(xEventHandler); + table_right_menu.setOnAction(xEventHandler); + + URL projectdetail = JavaFxApplication.class.getClassLoader().getResource("fxml/projectdetail.fxml"); + if (projectdetail == null) { + projectdetail = getClass().getResource("../../../fxml/projectdetail.fxml"); + } + projectdetailloader = new FXMLLoader(projectdetail); + projectdetailloader.load(); + projectDetailController = projectdetailloader.getController(); + + URL mddetail = JavaFxApplication.class.getClassLoader().getResource("fxml/moduledetail.fxml"); + if (mddetail == null) { + mddetail = getClass().getResource("../../../fxml/moduledetail.fxml"); + } + mddetailloader = new FXMLLoader(mddetail); + mddetailloader.load(); + mdDetailController = mddetailloader.getController(); + + + URL tabledetail = JavaFxApplication.class.getClassLoader().getResource("fxml/tabledetail.fxml"); + if (tabledetail == null) { + tabledetail = getClass().getResource("../../../fxml/tabledetail.fxml"); + } + tabledetailloader = new FXMLLoader(tabledetail); + tabledetailloader.load(); + tableDetailController = tabledetailloader.getController(); + + mdtree.setShowRoot(true); + mdtree.setEditable(true); + mdtree.setDisable(false); + mdtree.setCellFactory(new Callback() { + @Override + public TreeCell call(TreeView param) { + TextFieldTreeCell textFieldTreeCell = new TextFieldTreeCell(new DefaultStringConverter()); + textFieldTreeCell.setEditable(false); + // creating cell from deafult factory + TreeCell treeCell = textFieldTreeCell.forTreeView().call(param); + // setting handlers + textFieldTreeCell.setOnDragDetected(new EventHandler() { + @Override + public void handle(MouseEvent event) { + TextFieldTreeCell source = (TextFieldTreeCell) event.getSource(); + String text = source.getText(); + Module dbByDBName = dBmanger.findDBByDBName(text); + if (dbByDBName != null) { + dragMD = true; + } else { + dragMD = false; + } + if (dragMD) { + System.out.println("拖拽模块:" + text); + } else { + System.out.println("拖拽对象:" + text); + } + Dragboard md = source.startDragAndDrop(TransferMode.ANY); + ClipboardContent content = new ClipboardContent(); + content.putString((String) source.getText()); + md.setContent(content); + event.consume(); + } + }); + textFieldTreeCell.setOnDragOver(new EventHandler() { + @Override + public void handle(DragEvent event) { + Dragboard md = event.getDragboard(); + TextFieldTreeCell source = (TextFieldTreeCell) event.getSource(); + + Module dbByDBName = dBmanger.findDBByDBName(source.getText()); + + if (dragMD && dbByDBName != null) { + double y = event.getY(); + double height = textFieldTreeCell.getHeight(); + + if (source.getText().equals(md.getString())) { + event.acceptTransferModes(TransferMode.MOVE); + } else if (y >= height / 4 && y < height * 3 / 4) { + event.acceptTransferModes(TransferMode.MOVE); + } + } + + if (!dragMD && dbByDBName == null) { + double y = event.getY(); + double height = textFieldTreeCell.getHeight(); + + if (y >= height / 4 && y < height * 3 / 4) { + event.acceptTransferModes(TransferMode.MOVE); + } else { + event.acceptTransferModes(TransferMode.COPY); + } + } + event.consume(); + } + }); + textFieldTreeCell.setOnDragDropped(new EventHandler() { + @Override + public void handle(DragEvent event) { + Dragboard md = event.getDragboard(); + String m1 = md.getString(); + + TreeCell source = (TreeCell) event.getSource(); + String m2 = ((TreeCell) event.getGestureTarget()).getItem(); + + if (dragMD) { + List mds = dBmanger.getMds(); + + int i1 = 0, i2 = 0; + for (int i = 0; i < mds.size(); i++) { + if (mds.get(i).getModuleName().equals(m1)) { + i1 = i; + } + if (mds.get(i).getModuleName().equals(m2)) { + i2 = i; + } + } + + if (event.getTransferMode().equals(TransferMode.COPY)) {//插入 + + } else if (event.getTransferMode().equals(TransferMode.MOVE)) {//交换 + Tool.exchange(mds, i1, i2); + Tool.exchange(currentProject.getChildren(), i1, i2); + } + } else { + if (currentMD != null) { + int i1 = 0, i2 = 0; + Table t1 = null, t2 = null; + for (int i = 0; i < currentMD.getTables().size(); i++) { + if (currentMD.getTables().get(i).getTableName().equals(m1)) { + i1 = i; + t1 = currentMD.getTables().get(i); + } + if (currentMD.getTables().get(i).getTableName().equals(m2)) { + i2 = i; + t2 = currentMD.getTables().get(i); + } + } + if (t1 == null || t2 == null) { + return; + } + + if (event.getTransferMode().equals(TransferMode.COPY)) {//插入 + double y = event.getY(); + double height = textFieldTreeCell.getHeight(); + if (y < height / 2) { + currentMD.getTables().add(i2, t1); + currentMD.getChildren().add(i2, t1); + } else { + currentMD.getTables().add(i2 + 1, t1); + currentMD.getChildren().add(i2 + 1, t1); + } + if (i1 < i2) { + currentMD.getTables().remove(i1); + currentMD.getChildren().remove(i1); + } else { + currentMD.getTables().remove(i1 + 1); + currentMD.getChildren().remove(i1 + 1); + } + + } else if (event.getTransferMode().equals(TransferMode.MOVE)) {//交换 + Tool.exchange(currentMD.getTables(), i1, i2); + Tool.exchange(currentMD.getChildren(), i1, i2); + } + } + } + event.setDropCompleted(true); + event.consume(); + mdtree.getSelectionModel().clearSelection(); + int focusedIndex = mdtree.getFocusModel().getFocusedIndex(); + System.out.println(focusedIndex); + } + }); + return textFieldTreeCell; + } + }); + mdtree.setOnEditCommit(new YEventHandler()); + mdtree.setOnMouseClicked(new EventHandler() { + @Override + public void handle(MouseEvent event) { + TreeItem targetItem = (TreeItem) mdtree.getSelectionModel().getSelectedItem(); + + if (targetItem == null) + return; + + int level = getLevel(targetItem); + + switch (level) { + case 0: {//查看模块 + mdtree.setContextMenu(project_menu); + loadingProject(); + } + break; + case 1: {//查看模块 + + mdtree.setContextMenu(md_right_menu); + currentMD = dBmanger.findDBByDBName((String) targetItem.getValue()); + currentTable = null; + loadingModule(); + } + break; + case 2: {//查看对象 + mdtree.setContextMenu(table_right_menu); + TreeItem parent = targetItem.getParent(); + currentMD = dBmanger.findDBByDBName((String) parent.getValue()); + if (currentMD != null) { + currentTable = dBmanger.findTableByTableName(currentMD, (String) targetItem.getValue()); + } + loadingTable(); + break; + } + default: + break; + } + } + }); + + + {//初始化模块面板 + mdDetailController.getModuleComment().textProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, String oldValue, String newValue) { + if (currentMD != null) { + currentMD.setModuleComment(newValue); + } + } + }); + + mdDetailController.getModulePrefix().textProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, String oldValue, String newValue) { + if (currentMD != null) { + currentMD.setModulePrefix(newValue); + } + } + }); + + mdDetailController.getModuleName().textProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, String oldValue, String newValue) { + if (currentMD != null) { + currentMD.setModuleName(newValue); + } + } + }); + } + + {// 初始化项目面板 + projectDetailController.getProjectName().textProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, String oldValue, String newValue) { + currentProject.setProjectName(newValue); + } + }); + projectDetailController.getProjectBasePackage().textProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, String oldValue, String newValue) { + currentProject.setProjectBasePackage(newValue); + } + }); + projectDetailController.getProjectAuthor().textProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, String oldValue, String newValue) { + currentProject.setProjectAuthor(newValue); + } + }); + } + + {//初始化表面板 + tableDetailController.getTablename().textProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, String oldValue, String newValue) { + if (currentTable != null) { + currentTable.setTableName(newValue); +// invalidateLeft(); + } + } + }); + tableDetailController.getTablecomment().textProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, String oldValue, String newValue) { + if (currentTable != null) { + currentTable.setTableComment(newValue); + } + } + }); + tableDetailController.getCreate().selectedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + currentTable.setCreate(newValue); + } + }); + tableDetailController.getDelete().selectedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + currentTable.setDelete(newValue); + } + }); + tableDetailController.getUpdate().selectedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + currentTable.setUpdate(newValue); + } + }); + tableDetailController.getFind().selectedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + currentTable.setFind(newValue); + } + }); + tableDetailController.getGet().selectedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + currentTable.setGet(newValue); + } + }); + tableDetailController.getSearch().selectedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + currentTable.setSearch(newValue); + } + }); + tableDetailController.getGetAll().selectedProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + currentTable.setGetAll(newValue); + } + }); + } + ManagerFactory.getReflashManager(this).start(); + + loadingProjectTree(); + checkSysFields(); + super.init(); + } + + private void checkSysFields() { + if (currentMD != null) { + boolean selected = addSysFields.isSelected(); + removeSysFields(currentMD); + if (selected) { + bitchInsertSysFields(currentMD); + } + if (currentTable != null) { + loadingTable(); + } + } + } + + private void removeSysFields() { + for (Module md : dBmanger.getMds()) { + for (Table table : md.getTables()) { + Iterator iterator = table.getFields().iterator(); + while (iterator.hasNext()) { + Field next = iterator.next(); + if (next.getIsSystem()) { + iterator.remove(); + } + } + } + } + } + + private void removeSysFields(Module md) { + md.setHasSysFields(false); + for (Table table : md.getTables()) { + Iterator iterator = table.getFields().iterator(); + while (iterator.hasNext()) { + Field next = iterator.next(); + if (next.getIsSystem()) { + iterator.remove(); + } + } + } + } + + private void insertSysFields(Table table) { + Field id = new Field("ID"); + id.setIsSystem(true); + id.setIsMust(true); + id.setIsPrimaryKey(true); + id.setFieldType(FieldType.Long); + id.setFieldLength(19); + id.setFieldComment("主键"); + + Field row_version = new Field("ROW_VERSION"); + row_version.setIsSystem(true); + row_version.setIsMust(true); + row_version.setFieldType(FieldType.Long); + row_version.setFieldLength(19); + row_version.setFieldComment("行版本"); + + Field is_deleted = new Field("IS_DELETED"); + is_deleted.setIsSystem(true); + is_deleted.setIsMust(true); + is_deleted.setDefaultValue("0"); + is_deleted.setFieldType(FieldType.Boolean); + is_deleted.setFieldLength(1); + is_deleted.setFieldComment("是否已删除"); + + Field created_by = new Field("CREATE_BY"); + created_by.setIsSystem(true); + created_by.setIsMust(true); + created_by.setFieldType(FieldType.Long); + created_by.setFieldLength(19); + created_by.setFieldComment("创建用户"); + + Field creation_time = new Field("CREATE_TIME"); + creation_time.setIsSystem(true); + creation_time.setIsMust(true); + creation_time.setDefaultValue("NULL"); + creation_time.setFieldType(FieldType.Date); + creation_time.setFieldComment("创建时间"); + + Field last_updated_by = new Field("LAST_UPDATE_BY"); + last_updated_by.setIsSystem(true); + creation_time.setDefaultValue("NULL"); + last_updated_by.setFieldType(FieldType.Long); + last_updated_by.setFieldLength(19); + last_updated_by.setFieldComment("最后更新用户"); + + Field last_update_time = new Field("LAST_UPDATE_TIME"); + last_update_time.setIsSystem(true); + last_update_time.setFieldType(FieldType.Date); + last_update_time.setFieldComment("最后更新时间"); + + table.putFirstField(id); + table.putField(row_version); + table.putField(is_deleted); + table.putField(created_by); + table.putField(creation_time); + table.putField(last_updated_by); + table.putField(last_update_time); + } + + private void bitchInsertSysFields() { + for (Module md : dBmanger.getMds()) { + md.getTables().forEach(this::insertSysFields); + } + } + + private void bitchInsertSysFields(Module md) { + md.setHasSysFields(true); + md.getTables().forEach(this::insertSysFields); + } + + private void addField() { + if (currentTable != null && feilds != null) { + List fields = currentTable.getFields(); + String fieldName = dBmanger.getNewFieldName(fields); + System.out.println("新增字段-" + fieldName + "成功!"); + feilds.getSelectionModel().select(fields.size() - 1); + loadingTable(); + } + } + + private void subField() { + if (currentTable != null) { + int selectedIndex = feilds.getSelectionModel().getSelectedIndex(); + if (selectedIndex > -1 && !currentTable.getFields().get(selectedIndex).getIsSystem()) { + currentTable.getFields().remove(selectedIndex); + feilds.getSelectionModel().clearSelection(); + loadingTable(); + } + + } + } + + public void loadingProjectTree() { + currentProject = dBmanger.getProject(); + currentProject.setValue(currentProject.getProjectName()); + currentProject.setExpanded(true); + + mdtree.setRoot(currentProject); + + for (int i = 0; i < currentProject.getModules().size(); i++) { + Module module = currentProject.getModules().get(i); + module.setExpanded(true); + + for (Table table : module.getTables()) { + table.setExpanded(true); + module.getChildren().add(table); + } + } + + } + + private int getLevel(TreeItem treeItem) { + TreeItem root = mdtree.getRoot(); + int level = 0; + if (treeItem == root) { + level = 0; + } else if (treeItem.getParent() == root) { + level = 1; + } else if (treeItem.getParent().getParent() == root) { + level = 2; + } + return level; + } + + private void loadingModule() { + if (currentMD != null) { + addSysFields.setSelected(currentMD.isHasSysFields()); + } + + if (currentMD == null) { + return; + } + + GridPane gridPane = mddetailloader.getRoot(); + mdDetailController.getModuleComment().setText(currentMD.getModuleComment()); + mdDetailController.getModulePrefix().setText(currentMD.getModulePrefix()); + mdDetailController.getModuleName().setText(currentMD.getModuleName()); + + if (gridPane != null) { + detail.getChildren().clear(); + detail.getChildren().add(gridPane); + } + if (feilds != null && feilds.getItems() != null) { + feilds.getItems().clear(); + } + } + + private void loadingProject() { + GridPane gridPane = projectdetailloader.getRoot(); + projectDetailController.getProjectName().setText(currentProject.getProjectName()); + projectDetailController.getProjectBasePackage().setText(currentProject.getProjectBasePackage()); + projectDetailController.getProjectAuthor().setText(currentProject.getProjectAuthor()); + + if (gridPane != null) { + detail.getChildren().clear(); + detail.getChildren().add(gridPane); + } + if (feilds != null && feilds.getItems() != null) { + feilds.getItems().clear(); + } + } + + /** + * 加载对象信息 + */ + private void loadingTable() { + if (currentMD != null) { + addSysFields.setSelected(currentMD.isHasSysFields()); + } else if (currentTable != null && currentTable.getdBhandle() != null) { + addSysFields.setSelected(currentTable.getdBhandle().isHasSysFields()); + } + GridPane gridPane = tabledetailloader.getRoot(); + if (currentTable != null) { + tableDetailController.getTablename().setText(currentTable.getTableName()); + tableDetailController.getTablecomment().setText(currentTable.getTableComment()); + tableDetailController.getCreate().setSelected(currentTable.getCreate()); + tableDetailController.getDelete().setSelected(currentTable.getDelete()); + tableDetailController.getUpdate().setSelected(currentTable.getUpdate()); + tableDetailController.getFind().setSelected(currentTable.getFind()); + tableDetailController.getGet().setSelected(currentTable.getGet()); + tableDetailController.getSearch().setSelected(currentTable.getSearch()); + tableDetailController.getGetAll().setSelected(currentTable.getGetAll()); + + } + + + if (gridPane != null) { + detail.getChildren().clear(); + detail.getChildren().add(gridPane); + } + ObservableList columns = feilds.getColumns(); + columns.get(0).setCellValueFactory(new PropertyValueFactory("fieldName")); + columns.get(0).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + + param.setOnEditCommit(new EventHandler() { + @Override + public void handle(TableColumn.CellEditEvent event) { + int row = event.getTablePosition().getRow(); + Field field = currentTable.getFields().get(row); + + String newValue = (String) event.getNewValue(); + field.setFieldName(newValue); + if (newValue.endsWith("_ID")) { + field.setFieldType(FieldType.Long); + loadingTable(); + } + } + }); + + TextFieldTableCell textFieldTableCell = new TextFieldTableCell(new DefaultStringConverter()) { + + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + if (currentTable != null) { + int index = this.getTableRow().getIndex(); + if (index >= 0 && index <= currentTable.getFields().size() - 1) { + Field field = currentTable.getFields().get(index); + if (field.getIsSystem()) { + ignoreField(this); + this.setDisable(true); + } else { + recoveryField(this); + this.setDisable(false); + } + } + } + } + }; + + textFieldTableCell.setOnDragDetected(new EventHandler() { + @Override + public void handle(MouseEvent event) { + TableCell source = (TableCell) event.getSource(); + Dragboard md = source.startDragAndDrop(TransferMode.ANY); + ClipboardContent content = new ClipboardContent(); + content.putString((String) source.getItem()); + md.setContent(content); +// System.out.println("Dragging: " + db.getString()); + event.consume(); + } + }); + textFieldTableCell.setOnDragOver(new EventHandler() { + @Override + public void handle(DragEvent event) { + Dragboard md = event.getDragboard(); + + if (md.hasString()) { + double y = event.getY(); + double height = textFieldTableCell.getHeight(); + + if (y >= height / 4 && y < height * 3 / 4) { + event.acceptTransferModes(TransferMode.MOVE); + } else { + event.acceptTransferModes(TransferMode.COPY); + } + } + +// System.out.println("DragOver: " + db.getString()); + event.consume(); + } + }); + textFieldTableCell.setOnDragDropped(new EventHandler() { + @Override + public void handle(DragEvent event) { + Dragboard md = event.getDragboard(); + String f1 = md.getString(); + + TableCell source = (TableCell) event.getSource(); + String f2 = ((TableCell) event.getGestureTarget()).getText(); + + if (currentTable != null) { + int i1 = 0, i2 = 0; + Field t1 = null, t2 = null; + for (int i = 0; i < currentTable.getFields().size(); i++) { + if (currentTable.getFields().get(i).getFieldName().equals(f1)) { + i1 = i; + t1 = currentTable.getFields().get(i); + } + if (currentTable.getFields().get(i).getFieldName().equals(f2)) { + i2 = i; + t2 = currentTable.getFields().get(i); + } + } + + if (event.getTransferMode().equals(TransferMode.COPY)) {//插入 + double y = event.getY(); + double height = textFieldTableCell.getHeight(); + + if (y < height / 2) { + currentTable.getFields().add(i2, t1); + } else { + currentTable.getFields().add(i2 + 1, t1); + } + if (i1 < i2) { + currentTable.getFields().remove(i1); + } else { + currentTable.getFields().remove(i1 + 1); + } + + } else if (event.getTransferMode().equals(TransferMode.MOVE)) {//交换 + currentTable.getFields().add(i1, t2); + currentTable.getFields().remove(i1 + 1); + currentTable.getFields().add(i2, t1); + currentTable.getFields().remove(i2 + 1); + } + loadingTable(); + } + event.setDropCompleted(true); + event.consume(); + } + }); + return textFieldTableCell; + } + }); + columns.get(1).setCellValueFactory(new PropertyValueFactory("fieldType")); + columns.get(1).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + ObservableList objects = FXCollections.observableArrayList(); + + Class clz = FieldType.class; + for (Object obj : clz.getEnumConstants()) { + if (obj instanceof FieldType) { + objects.add((FieldType) obj); + } + } + ChoiceBoxTableCell choiceBoxTableCell = new ChoiceBoxTableCell(objects) { + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + if (currentTable != null) { + int index = this.getTableRow().getIndex(); + if (index >= 0 && index <= currentTable.getFields().size() - 1) { + Field field = currentTable.getFields().get(index); + FieldType fieldType = field.getFieldType(); + if (fieldType.isFix() && fieldType.getDefaultLength() != field.getFieldLength()) { + field.setFieldLength(fieldType.getDefaultLength()); + feilds.refresh(); + } + if (field.getIsSystem()) { + ignoreField(this); + this.setDisable(true); + } else { + recoveryField(this); + this.setDisable(false); + } + } + } + } + }; + + param.setOnEditCommit(new EventHandler() { + @Override + public void handle(TableColumn.CellEditEvent event) { + int row = event.getTablePosition().getRow(); + Field field = currentTable.getFields().get(row); + field.setFieldType((FieldType) event.getNewValue()); + } + }); + return choiceBoxTableCell; + } + }); + columns.get(2).setCellValueFactory(new PropertyValueFactory("fieldLength")); + columns.get(2).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + param.setOnEditCommit(new EventHandler() { + @Override + public void handle(TableColumn.CellEditEvent event) { + int row = event.getTablePosition().getRow(); + Field field = currentTable.getFields().get(row); + if ("String_var".equals(field.getFieldType().toString()) || "String_super".equals(field.getFieldType().toString())) { + try { + field.setFieldLength((Integer) event.getNewValue()); + } catch (Exception e) { + e.printStackTrace(); + } + } + feilds.refresh(); + } + }); + TextFieldTableCell textFieldTableCell = new TextFieldTableCell(new IntegerStringConverter()) { + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + if (currentTable != null) { + int index = this.getTableRow().getIndex(); + if (index >= 0 && index <= currentTable.getFields().size() - 1) { + Field field = currentTable.getFields().get(index); + if (field.getIsSystem()) { + ignoreField(this); + this.setDisable(true); + } else { + recoveryField(this); + this.setDisable(false); + } + } + } + } + }; + return textFieldTableCell; + } + }); + columns.get(3).setCellValueFactory(new PropertyValueFactory("defaultValue")); + columns.get(3).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + param.setOnEditCommit(new EventHandler() { + @Override + public void handle(TableColumn.CellEditEvent event) { + int row = event.getTablePosition().getRow(); + Field field = currentTable.getFields().get(row); + field.setDefaultValue((String) event.getNewValue()); + } + }); + return new TextFieldTableCell(new DefaultStringConverter()) { + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + if (currentTable != null) { + int index = this.getTableRow().getIndex(); + if (index >= 0 && index <= currentTable.getFields().size() - 1) { + Field field = currentTable.getFields().get(index); + if (field.getIsSystem()) { + ignoreField(this); + this.setDisable(true); + } else { + recoveryField(this); + this.setDisable(false); + } + } + } + } + }; + } + }); + columns.get(4).setCellValueFactory(new PropertyValueFactory("isPrimaryKey")); + columns.get(4).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + DBCheckBoxTableCell checkBoxTableCell = new DBCheckBoxTableCell(); + + DBCheckBoxTableCell.sCallback sCallback = checkBoxTableCell.new sCallback() { + @Override + public ObservableValue call(Integer param) { + super.call(param); + List fields = currentTable.getFields(); + + if (fields.get(param).getIsSystem()) { + checkBoxTableCell.setInvalid(true); + } else { + checkBoxTableCell.setInvalid(false); + } + if (fields.get(param).getIsPrimaryKey()) { + return new SimpleBooleanProperty(true); + } else { + return new SimpleBooleanProperty(false); + } + } + }; + checkBoxTableCell.setSelectedStateCallback(sCallback); + checkBoxTableCell.setOnChangeListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + int param1 = checkBoxTableCell.getParam(); + Field field = currentTable.getFields().get(param1); + field.setIsPrimaryKey(newValue); + } + }); + return checkBoxTableCell; + } + }); + columns.get(5).setCellValueFactory(new PropertyValueFactory("isMust")); + columns.get(5).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + final DBCheckBoxTableCell checkBoxTableCell = new DBCheckBoxTableCell(); + DBCheckBoxTableCell.sCallback sCallback = checkBoxTableCell.new sCallback() { + @Override + public ObservableValue call(Integer param) { + super.call(param); + List fields = currentTable.getFields(); + if (fields.get(param).getIsSystem()) { + checkBoxTableCell.setInvalid(true); + } else { + checkBoxTableCell.setInvalid(false); + } + if (fields.get(param).getIsMust()) { + return new SimpleBooleanProperty(true); + } else { + return new SimpleBooleanProperty(false); + } + } + }; + checkBoxTableCell.setSelectedStateCallback(sCallback); + checkBoxTableCell.setOnChangeListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + int param1 = checkBoxTableCell.getParam(); + Field field = currentTable.getFields().get(param1); + field.setIsMust(newValue); + } + }); + return checkBoxTableCell; + } + }); + columns.get(6).setCellValueFactory(new PropertyValueFactory("isQuery")); + columns.get(6).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + final DBCheckBoxTableCell checkBoxTableCell = new DBCheckBoxTableCell(); + DBCheckBoxTableCell.sCallback sCallback = checkBoxTableCell.new sCallback() { + @Override + public ObservableValue call(Integer param) { + super.call(param); + List fields = currentTable.getFields(); + if (fields.get(param).getIsSystem()) { + checkBoxTableCell.setInvalid(true); + } else { + checkBoxTableCell.setInvalid(false); + } + if (fields.get(param).getIsQuery()) { + return new SimpleBooleanProperty(true); + } else { + return new SimpleBooleanProperty(false); + } + } + }; + checkBoxTableCell.setSelectedStateCallback(sCallback); + checkBoxTableCell.setOnChangeListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + int param1 = checkBoxTableCell.getParam(); + Field field = currentTable.getFields().get(param1); + field.setIsQuery(newValue); + } + }); + return checkBoxTableCell; + } + }); + columns.get(7).setCellValueFactory(new PropertyValueFactory("isSearch")); + columns.get(7).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + final DBCheckBoxTableCell checkBoxTableCell = new DBCheckBoxTableCell(); + DBCheckBoxTableCell.sCallback sCallback = checkBoxTableCell.new sCallback() { + @Override + public ObservableValue call(Integer param) { + super.call(param); + List fields = currentTable.getFields(); + if (fields.get(param).getIsSystem()) { + checkBoxTableCell.setInvalid(true); + } else { + checkBoxTableCell.setInvalid(false); + } + if (fields.get(param).getIsSearch()) { + return new SimpleBooleanProperty(true); + } else { + return new SimpleBooleanProperty(false); + } + } + }; + checkBoxTableCell.setSelectedStateCallback(sCallback); + checkBoxTableCell.setOnChangeListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + int param1 = checkBoxTableCell.getParam(); + Field field = currentTable.getFields().get(param1); + field.setIsSearch(newValue); + } + }); + return checkBoxTableCell; + } + }); + columns.get(8).setCellValueFactory(new PropertyValueFactory("fieldComment")); + columns.get(8).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + + param.setOnEditCommit(new EventHandler() { + @Override + public void handle(TableColumn.CellEditEvent event) { + int row = event.getTablePosition().getRow(); + Field field = currentTable.getFields().get(row); + field.setFieldComment((String) event.getNewValue()); + } + }); + return new TextFieldTableCell(new DefaultStringConverter()) { + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + if (currentTable != null) { + int index = this.getTableRow().getIndex(); + if (index >= 0 && index <= currentTable.getFields().size() - 1) { + Field field = currentTable.getFields().get(index); + if (field.getIsSystem()) { + ignoreField(this); + this.setDisable(true); + } else { + recoveryField(this); + this.setDisable(false); + } + } + } + } + }; + } + }); + + ObservableList data = null; + if (currentTable != null) { + List fields = currentTable.getFields(); + data = FXCollections.observableArrayList(); + data.addAll(fields); + } + + feilds.setItems(data); + } + + void ignoreField(TableCell tableCell) { + tableCell.setTextFill(Color.gray(0.8)); + } + + void recoveryField(TableCell tableCell) { + tableCell.setTextFill(Color.BLACK); + } + + + /** + * 双击目录树编辑处理器 + */ + private class YEventHandler implements EventHandler { + + @Override + public void handle(TreeView.EditEvent event) { + TreeItem treeItem = event.getTreeItem(); + int level = getLevel(treeItem); + System.out.println("原值:" + event.getOldValue()); + System.out.println("现值:" + event.getNewValue()); + + switch (level) { + case 0: {//编辑项目名称 + dBmanger.getProject().setProjectName((String) event.getNewValue()); + loadingProject(); + } + break; + case 1: {//编辑模块 + Module md = dBmanger.findDBByDBName((String) event.getOldValue()); + md.setModuleName((String) event.getNewValue()); + loadingModule(); + } + break; + case 2: {//编辑对象 + TreeItem parent = treeItem.getParent(); + Module md = dBmanger.findDBByDBName((String) parent.getValue()); + Table table = dBmanger.findTableByTableName(md, (String) event.getOldValue()); + if (table != null) { + table.setTableName((String) event.getNewValue()); + loadingTable(); + } + break; + } + default: + break; + } + } + } + + /** + * 目录树右击菜单处理器 + */ + private class XEventHandler implements EventHandler { + + @Override + public void handle(Event event) { + MenuItem target = (MenuItem) event.getTarget(); + + String text = target.getText(); + Project project =(Project) mdtree.getRoot(); + + TreeItem targetItem = (TreeItem) mdtree.getFocusModel().getFocusedItem(); + int index = -1; + index = mdtree.getFocusModel().getFocusedIndex(); + if (targetItem == null) { + targetItem = (TreeItem) mdtree.getSelectionModel().getSelectedItem(); + } + if (index == -1) { + index = mdtree.getSelectionModel().getSelectedIndex(); + } + if (text != null && targetItem != null) { + switch (text) { + + case "向上调整": + if (index > 0) { + Tool.exchange(dBmanger.getProject().getModules(), index - 1, index); + Tool.exchange(dBmanger.getProject().getChildren(), index - 1, index); + } + break; + case "向下调整": + List mds = dBmanger.getMds(); + if (index < mds.size() - 1) { + Tool.exchange(dBmanger.getProject().getModules(), index, index + 1); + Tool.exchange(dBmanger.getProject().getChildren(), index, index + 1); + } + break; + case "新增模块": + dBmanger.getNewModuleName(); + break; + case "删除模块": + if (targetItem != null && targetItem.getParent() == project) { + currentProject.getChildren().remove(targetItem); + boolean b = dBmanger.removeDBByDBName((String) targetItem.getValue()); + if (b) { + System.out.println("删除模块" + targetItem.getValue() + "成功!"); + } + } + break; + case "新增对象": + int level = getLevel(targetItem); + + switch (level) { + case 1: {//对模块右击 + System.out.println("模块:" + targetItem.getValue()); + Module md = dBmanger.findDBByDBName((String) targetItem.getValue()); + if (md != null) { + Table newTableName = dBmanger.getNewTableName(md); + if (addSysFields.isSelected()) { + insertSysFields(newTableName); + } + targetItem.getChildren().add(newTableName); + } + } + break; + case 2: {//对对象右击 + TreeItem parent = targetItem.getParent(); + System.out.println("对象:" + parent.getValue()); + Module md = dBmanger.findDBByDBName((String) parent.getValue()); + Table newTableName = dBmanger.getNewTableName(md); + if (addSysFields.isSelected()) { + insertSysFields(newTableName); + } + parent.getChildren().add(new TreeItem<>(newTableName.getTableName())); + break; + } + default: + break; + } + break; + case "删除对象": + level = 0; + if (targetItem != null && targetItem.getParent() == project) { + level = 0; + } else if (targetItem != null && targetItem.getParent().getParent() == project) { + level = 1; + } + switch (level) { + case 0: {//对模块右击 + System.out.println("模块:" + targetItem.getValue()); + Module md = dBmanger.findDBByDBName((String) targetItem.getValue()); + Table newTableName = dBmanger.getNewTableName(md); + if (addSysFields.isSelected()) { + insertSysFields(newTableName); + } + targetItem.getChildren().add(new TreeItem<>(newTableName.getTableName())); + } + break; + case 1: {//对对象右击 + TreeItem parent = targetItem.getParent(); + System.out.println("对象:" + parent.getValue()); + Module md = dBmanger.findDBByDBName((String) parent.getValue()); + + for (Table table : md.getTables()) { + if (table.getTableName().equals(targetItem.getValue())) { + md.getTables().remove(table); + md.getChildren().remove(targetItem); + System.out.println("移除'" + targetItem.getValue() + "'对象成功!"); + break; + } + } + break; + } + default: + break; + } + default: + } + } else if (text != null && targetItem == null) { + switch (text) { + case "新增模块": + dBmanger.getNewModuleName(); + break; + default: + break; + } + } + } + } + + private void updateDbTree(List mds) { + TreeItem root = mdtree.getRoot(); + for (Module md : mds) { + TreeItem treeItem = new TreeItem<>(md.getModuleName()); + treeItem.setExpanded(true); + for (Table table : md.getTables()) { + TreeItem tree = new TreeItem<>(table.getTableName()); + treeItem.getChildren().add(tree); + } + root.getChildren().add(treeItem); + } + } + + public static void main(String[] args) { + launch(args); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/ConnectInfoController.java b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/ConnectInfoController.java new file mode 100644 index 00000000..a87d0e55 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/ConnectInfoController.java @@ -0,0 +1,91 @@ +package xyz.wbsite.dbtool.javafx.ctrl; + +import javafx.fxml.FXML; +import javafx.scene.control.Button; +import javafx.scene.control.ChoiceBox; +import javafx.scene.control.TextField; + +public class ConnectInfoController { + + @FXML + private ChoiceBox databaseType; + @FXML + private TextField driver; + @FXML + private TextField url; + @FXML + private TextField userName; + @FXML + private TextField password; + + @FXML + private Button test; + @FXML + private Button load; + @FXML + private Button cancel; + + public ChoiceBox getDatabaseType() { + return databaseType; + } + + public void setDatabaseType(ChoiceBox databaseType) { + this.databaseType = databaseType; + } + + public TextField getUrl() { + return url; + } + + public void setUrl(TextField url) { + this.url = url; + } + + public TextField getUserName() { + return userName; + } + + public TextField getDriver() { + return driver; + } + + public void setDriver(TextField driver) { + this.driver = driver; + } + + public void setUserName(TextField userName) { + this.userName = userName; + } + + public TextField getPassword() { + return password; + } + + public void setPassword(TextField password) { + this.password = password; + } + + public Button getTest() { + return test; + } + + public void setTest(Button test) { + this.test = test; + } + + public Button getLoad() { + return load; + } + + public void setLoad(Button load) { + this.load = load; + } + + public Button getCancel() { + return cancel; + } + + public void setCancel(Button cancel) { + this.cancel = cancel; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/DbDetailController.java b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/DbDetailController.java new file mode 100644 index 00000000..5e76b5c8 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/DbDetailController.java @@ -0,0 +1,38 @@ +package xyz.wbsite.dbtool.javafx.ctrl; + +import javafx.fxml.FXML; +import javafx.scene.control.TextField; + +public class DbDetailController { + + @FXML + private TextField moduleComment; + @FXML + private TextField modulePrefix; + @FXML + private TextField moduleName; + + public TextField getModuleName() { + return moduleName; + } + + public void setModuleName(TextField moduleName) { + this.moduleName = moduleName; + } + + public TextField getModuleComment() { + return moduleComment; + } + + public void setModuleComment(TextField moduleComment) { + this.moduleComment = moduleComment; + } + + public TextField getModulePrefix() { + return modulePrefix; + } + + public void setModulePrefix(TextField modulePrefix) { + this.modulePrefix = modulePrefix; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/GenerateOptionController.java b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/GenerateOptionController.java new file mode 100644 index 00000000..c4f0eec5 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/GenerateOptionController.java @@ -0,0 +1,79 @@ +package xyz.wbsite.dbtool.javafx.ctrl; + +import xyz.wbsite.dbtool.javafx.listener.GenerateOptionListener; +import javafx.fxml.FXML; +import javafx.scene.control.Button; +import javafx.scene.control.CheckBox; +import javafx.scene.control.RadioButton; +import javafx.scene.control.ToggleGroup; + +public class GenerateOptionController { + + private GenerateOptionListener listener; + + @FXML + private CheckBox springmvc; + @FXML + private CheckBox mybatis; + @FXML + private ToggleGroup type; + @FXML + private ToggleGroup db; + @FXML + private Button ok; + @FXML + private Button cancel; + + public String getDataBase() { + RadioButton value = (RadioButton) db.selectedToggleProperty().getValue(); + String name = value.textProperty().getValue(); + return name.toUpperCase(); + } + + public GenerateOptionListener getListener() { + return listener; + } + + public void setListener(GenerateOptionListener listener) { + this.listener = listener; + } + + public CheckBox getSpringmvc() { + return springmvc; + } + + public void setSpringmvc(CheckBox springmvc) { + this.springmvc = springmvc; + } + + public CheckBox getMybatis() { + return mybatis; + } + + public void setMybatis(CheckBox mybatis) { + this.mybatis = mybatis; + } + + public String getType() { + RadioButton value = (RadioButton) type.selectedToggleProperty().getValue(); + String name = value.textProperty().getValue(); + System.out.println(name); + return name; + } + + public Button getOk() { + return ok; + } + + public void setOk(Button ok) { + this.ok = ok; + } + + public Button getCancel() { + return cancel; + } + + public void setCancel(Button cancel) { + this.cancel = cancel; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/MainController.java b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/MainController.java new file mode 100644 index 00000000..613b2f6b --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/MainController.java @@ -0,0 +1,193 @@ +package xyz.wbsite.dbtool.javafx.ctrl; + +import javafx.event.ActionEvent; +import javafx.fxml.FXML; +import javafx.scene.control.Button; +import javafx.scene.control.CheckBox; +import javafx.scene.control.TableView; +import javafx.scene.control.TreeView; +import javafx.scene.layout.Pane; +import javafx.stage.DirectoryChooser; +import javafx.stage.Stage; +import xyz.wbsite.dbtool.javafx.JavaFxApplication; +import xyz.wbsite.dbtool.javafx.enumeration.DataBase; +import xyz.wbsite.dbtool.javafx.listener.GenerateOptionListener; +import xyz.wbsite.dbtool.javafx.manger.ManagerFactory; +import xyz.wbsite.dbtool.javafx.manger.ProjectManager; +import xyz.wbsite.dbtool.javafx.po.Project; +import xyz.wbsite.dbtool.javafx.tool.Dialog; + +import java.io.File; + +public class MainController { + private ProjectManager dBmanger = ManagerFactory.getdBManager(); + + @FXML + private TreeView dbtree; + @FXML + private Pane detail; + @FXML + private TableView feilds; + @FXML + private Button add; + @FXML + private Button sub; + @FXML + private CheckBox addSysFields; + + private JavaFxApplication main; + + public ProjectManager getdBmanger() { + return dBmanger; + } + + public void setdBmanger(ProjectManager dBmanger) { + this.dBmanger = dBmanger; + } + + public JavaFxApplication getMain() { + return main; + } + + public void setMain(JavaFxApplication main) { + this.main = main; + } + + public Button getAdd() { + return add; + } + + public void setAdd(Button add) { + this.add = add; + } + + public Button getSub() { + return sub; + } + + public CheckBox getAddSysFields() { + return addSysFields; + } + + public void setAddSysFields(CheckBox addSysFields) { + this.addSysFields = addSysFields; + } + + public void setSub(Button sub) { + this.sub = sub; + } + + public TableView getFeilds() { + return feilds; + } + + public void setFeilds(TableView feilds) { + this.feilds = feilds; + } + + public TreeView getDbtree() { + return dbtree; + } + + public void setDbtree(TreeView dbtree) { + this.dbtree = dbtree; + } + + public Pane getDetail() { + return detail; + } + + public void setDetail(Pane detail) { + this.detail = detail; + } + + @FXML + public void showFileChooser(ActionEvent actionEvent) { + DirectoryChooser directoryChooser = new DirectoryChooser(); + Stage stage = new Stage(); + File file = directoryChooser.showDialog(stage); + + if (file != null && file.exists()) { + dBmanger.setPath(file.getAbsolutePath()); + dBmanger.invalidate(); + main.loadingProjectTree(); + + System.out.println(file.getAbsolutePath()); + } + } + + public boolean doSave(ActionEvent actionEvent) { + if (dBmanger.getPath() == null || "".equals(dBmanger.getPath())) { + DirectoryChooser directoryChooser = new DirectoryChooser(); + Stage stage = new Stage(); + File file = directoryChooser.showDialog(stage); + + if (file == null) { + + return false; + } + dBmanger.setPath(file.getAbsolutePath()); + System.out.println(file.getAbsolutePath()); + } + dBmanger.save(); + System.out.println("自动保存成功"); + return true; + } + + @FXML + public void save(ActionEvent actionEvent) { + doSave(actionEvent); + } + + @FXML + public void saveAs(ActionEvent actionEvent) { + DirectoryChooser directoryChooser = new DirectoryChooser(); + Stage stage = new Stage(); + File file = directoryChooser.showDialog(stage); + + if (file != null) { + dBmanger.setPath(file.getAbsolutePath()); + dBmanger.save(); + } + } + + @FXML + public void clear(ActionEvent actionEvent) { + Project project = dBmanger.getProject(); + project = new Project(); + } + + @FXML + public void showConnectInfo(ActionEvent actionEvent) { + Dialog.showDBConnectInput(); + } + + @FXML + public void generate(ActionEvent actionEvent) { + if (!this.doSave(null)) { + return; + } + if (dBmanger.doCheck()) { + DirectoryChooser directoryChooser = new DirectoryChooser(); + directoryChooser.setInitialDirectory(new File(dBmanger.getPath())); + Stage stage = new Stage(); + File file = directoryChooser.showDialog(stage); + + if (file != null) { + //展示生成方式 + Dialog.showGenerateOption(new GenerateOptionListener() { + @Override + public void onGenerate(String option, DataBase dataBase) { + System.out.println("生成目录:" + file.getAbsolutePath()); + dBmanger.generate(file.getAbsolutePath(), option, dataBase); + } + }); + } + } + } + + @FXML + public void generateApi(ActionEvent actionEvent) { + Dialog.showApi(); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/ProjectDetailController.java b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/ProjectDetailController.java new file mode 100644 index 00000000..6a0c1700 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/ProjectDetailController.java @@ -0,0 +1,39 @@ +package xyz.wbsite.dbtool.javafx.ctrl; + +import javafx.fxml.FXML; +import javafx.scene.control.TextField; + +public class ProjectDetailController { + + @FXML + private TextField projectName; + @FXML + private TextField projectBasePackage; + @FXML + private TextField projectAuthor; + + + public TextField getProjectName() { + return projectName; + } + + public void setProjectName(TextField projectName) { + this.projectName = projectName; + } + + public TextField getProjectBasePackage() { + return projectBasePackage; + } + + public void setProjectBasePackage(TextField projectBasePackage) { + this.projectBasePackage = projectBasePackage; + } + + public TextField getProjectAuthor() { + return projectAuthor; + } + + public void setProjectAuthor(TextField projectAuthor) { + this.projectAuthor = projectAuthor; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/SdkInfoController.java b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/SdkInfoController.java new file mode 100644 index 00000000..7b7a535c --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/SdkInfoController.java @@ -0,0 +1,548 @@ +package xyz.wbsite.dbtool.javafx.ctrl; + +import xyz.wbsite.dbtool.javafx.customview.DBCheckBoxTableCell; +import xyz.wbsite.dbtool.javafx.po.Api; +import xyz.wbsite.dbtool.javafx.tool.Dialog; +import xyz.wbsite.dbtool.javafx.tool.Tool; +import javafx.beans.property.SimpleBooleanProperty; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.fxml.FXML; +import javafx.scene.control.*; +import javafx.scene.control.cell.PropertyValueFactory; +import javafx.scene.control.cell.TextFieldTableCell; +import javafx.util.Callback; +import javafx.util.converter.DefaultStringConverter; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class SdkInfoController { + + @FXML + private TextField modulePath; + @FXML + private TextField sdkPath; + @FXML + private Button selectModulePath; + @FXML + private Button selectSdkPath; + @FXML + private Button start; + @FXML + private Button cancel; + @FXML + private CheckBox All; + @FXML + private CheckBox api; + @FXML + private CheckBox create; + @FXML + private CheckBox delete; + @FXML + private CheckBox update; + @FXML + private CheckBox find; + @FXML + private CheckBox search; + @FXML + private CheckBox get; + @FXML + private CheckBox getAll; + @FXML + private TableView apis; + @FXML + private List data = new ArrayList<>(); + + public Button getSelectModulePath() { + return selectModulePath; + } + + public void setSelectModulePath(Button selectModulePath) { + this.selectModulePath = selectModulePath; + } + + public Button getSelectSdkPath() { + return selectSdkPath; + } + + public void setSelectSdkPath(Button selectSdkPath) { + this.selectSdkPath = selectSdkPath; + } + + public List getData() { + return data; + } + + public CheckBox getSearch() { + return search; + } + + public CheckBox getAll() { + return All; + } + + public void setAll(CheckBox all) { + All = all; + } + + public void setSearch(CheckBox search) { + this.search = search; + } + + public CheckBox getCreate() { + return create; + } + + public CheckBox getApi() { + return api; + } + + public void setApi(CheckBox api) { + this.api = api; + } + + public void setCreate(CheckBox create) { + this.create = create; + } + + public CheckBox getDelete() { + return delete; + } + + public void setDelete(CheckBox delete) { + this.delete = delete; + } + + public CheckBox getUpdate() { + return update; + } + + public void setUpdate(CheckBox update) { + this.update = update; + } + + public CheckBox getFind() { + return find; + } + + public void setFind(CheckBox find) { + this.find = find; + } + + public CheckBox getGet() { + return get; + } + + public void setGet(CheckBox get) { + this.get = get; + } + + public void setData(List data) { + this.data = data; + } + + public TextField getModulePath() { + return modulePath; + } + + public void setModulePath(TextField modulePath) { + this.modulePath = modulePath; + } + + public TextField getSdkPath() { + return sdkPath; + } + + public void setSdkPath(TextField sdkPath) { + this.sdkPath = sdkPath; + } + + public Button getStart() { + return start; + } + + public void setStart(Button start) { + this.start = start; + } + + public Button getCancel() { + return cancel; + } + + public void setCancel(Button cancel) { + this.cancel = cancel; + } + + public TableView getApis() { + return apis; + } + + public CheckBox getGetAll() { + return getAll; + } + + public void setGetAll(CheckBox getAll) { + this.getAll = getAll; + } + + public void setApis(TableView apis) { + this.apis = apis; + } + + public void load() { + File moduleFile = new File(modulePath.getText()); + String module = moduleFile.getName(); + + if (moduleFile.exists()) { + data.clear(); + File reqs = new File(moduleFile.getAbsolutePath() + File.separator + "req"); + + if (!reqs.exists()) { + return; + } + + Dialog.showProgress("扫描API..."); + for (File req : reqs.listFiles()) { + Api api = new Api(); + api.setReq(req); + api.setTargetRequest(req.getName().replace(".java", "")); + + //查找依赖ent + List entities = findEntities(req); + for (String entity : entities) { + api.getDepEnt().add(entity); + } + //查找依赖enums + List enums = findEnums(req); + for (String anEnum : enums) { + api.getDepEnum().add(anEnum); + } + //查找依赖req + List reqss = findReq(req); + for (String string : reqss) { + api.getDepReq().add(string); + } + + //找response + File rsp = new File(moduleFile.getAbsolutePath() + File.separator + "rsp" + File.separator + req.getName().replace("Request", "Response")); + if (rsp.exists()) { + api.setRsp(rsp); + api.setTargetResponse(rsp.getName().replace(".java", "")); + + //查找依赖ent + List entities_ = findEntities(rsp); + for (String entity : entities_) { + api.getDepEnt().add(entity); + } + //查找依赖enums + List enums_ = findEnums(rsp); + for (String anEnum : enums_) { + api.getDepEnum().add(anEnum); + } + //查找依赖req + List reqss_ = findReq(rsp); + for (String string : reqss_) { + api.getDepReq().add(string); + } + } + + api.setMethod("api." + module + "." + Tool.camelToPoint(req.getName().replaceAll("Request\\.java", ""))); + + + if (api.getTargetRequest().startsWith("Api")){ + api.setCheck(true); + }else { + api.setCheck(false); + } + + if (api.getRsp() == null || !api.getRsp().exists()) { + api.setError("响应不存在"); + api.setCheck(false); + } + for (String s : api.getDepReq()) { + File en = new File(moduleFile.getAbsolutePath() + File.separator + "req" + File.separator + s + ".java"); + if (!en.exists()) { + api.setError("依赖的" + s + "(Request)不存在、"); + api.setCheck(false); + } + } + for (String s : api.getDepEnt()) { + File en = new File(moduleFile.getAbsolutePath() + File.separator + "ent" + File.separator + s + ".java"); + if (!en.exists()) { + api.setError("依赖的" + s + "(Entity)不存在、"); + api.setCheck(false); + } + } + for (String s : api.getDepEnum()) { + File en = new File(moduleFile.getAbsolutePath() + File.separator + "enums" + File.separator + s + ".java"); + if (!en.exists()) { + api.setError("依赖的" + s + "(Enum)不存在、"); + api.setCheck(false); + } + } + + data.add(api); + initData(); + } + Dialog.stopPopup(); + } + } + + public List findEntities(File file) { + ArrayList strings = new ArrayList<>(); + InputStreamReader read = null;//考虑到编码格式 + try { + read = new InputStreamReader(new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String line = null; + while ((line = bufferedReader.readLine()) != null) { + //指定字符串判断处 + if (line.contains(".ent.")) { + Pattern compile = Pattern.compile(".*\\.ent\\.(.*);"); + + Matcher matcher = compile.matcher(line); + + if (matcher.find()) { + String group = matcher.group(1); + strings.add(group); +// System.out.println(group); + } + } + } + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return strings; + } + + public List findEnums(File file) { + ArrayList strings = new ArrayList<>(); + InputStreamReader read = null;//考虑到编码格式 + try { + read = new InputStreamReader(new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String line = null; + while ((line = bufferedReader.readLine()) != null) { + //指定字符串判断处 + if (line.contains(".enums.")) { + Pattern compile = Pattern.compile(".*\\.enums\\.(.*);"); + + Matcher matcher = compile.matcher(line); + + if (matcher.find()) { + String group = matcher.group(1); + strings.add(group); +// System.out.println(group); + } + } + } + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return strings; + } + + public List findReq(File file) { + ArrayList strings = new ArrayList<>(); + InputStreamReader read = null;//考虑到编码格式 + try { + read = new InputStreamReader(new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String line = null; + Pattern compile1 = Pattern.compile(".*private\\s([a-zA-Z_]*Request)\\s[a-zA-Z_]*Request;.*"); + Pattern compile2 = Pattern.compile(".*private\\sList<([a-zA-Z_]*Request)>\\s[a-zA-Z_]*Requests;.*"); + Pattern compile3 = Pattern.compile(".*private\\sList<([a-zA-Z_]*Request)>\\s[a-zA-Z_]*RequestList;.*"); + + + while ((line = bufferedReader.readLine()) != null) { + //携带一个Request + if (line.matches(".*private\\s([a-zA-Z_]*Request)\\s[a-zA-Z_]*Request;.*")) { + Matcher matcher = compile1.matcher(line); + + if (matcher.find()) { + String group = matcher.group(1); + + strings.add(group); + System.out.println(group); + } + } + //携带一个List<*Request> *Requests; + if (line.matches(".*private\\sList<([a-zA-Z_]*Request)>\\s[a-zA-Z_]*Requests;.*")) { + Matcher matcher = compile2.matcher(line); + + if (matcher.find()) { + String group = matcher.group(1); + + strings.add(group); + System.out.println(group); + } + } + //携带一个List<*Request> *RequestList; + if (line.matches(".*private\\sList<([a-zA-Z_]*Request)>\\s[a-zA-Z_]*RequestList;.*")) { + Matcher matcher = compile3.matcher(line); + + if (matcher.find()) { + String group = matcher.group(1); + + strings.add(group); + System.out.println(group); + } + } + } + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return strings; + } + + + public void initData() { + apis.setEditable(true); + apis.setSortPolicy(new Callback() { + @Override + public Boolean call(TableView param) { + //禁止点击列头排序 + return false; + } + }); + ObservableList columns = apis.getColumns(); + columns.get(0).setCellValueFactory(new PropertyValueFactory("check")); + columns.get(0).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + final DBCheckBoxTableCell checkBoxTableCell = new DBCheckBoxTableCell(); + DBCheckBoxTableCell.sCallback sCallback = checkBoxTableCell.new sCallback() { + @Override + public ObservableValue call(Integer param) { + super.call(param); +// if (data.get(param).isCheck()) { +// checkBoxTableCell.setInvalid(true); +// } else { +// checkBoxTableCell.setInvalid(false); +// } + if (data.get(param).isCheck()) { + return new SimpleBooleanProperty(true); + } else { + return new SimpleBooleanProperty(false); + } + } + }; + checkBoxTableCell.setSelectedStateCallback(sCallback); + checkBoxTableCell.setOnChangeListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) { + int param1 = checkBoxTableCell.getParam(); + Api api = data.get(param1); + api.setCheck(newValue); + } + }); + return checkBoxTableCell; + } + }); + columns.get(1).setCellValueFactory(new PropertyValueFactory("error")); + columns.get(1).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { +// param.setOnEditCommit(new EventHandler() { +// @Override +// public void handle(TableColumn.CellEditEvent event) { +// int row = event.getTablePosition().getRow(); +// Api api = data.get(row); +// api.setReqName((String) event.getNewValue()); +// } +// }); + + TextFieldTableCell textFieldTableCell = new TextFieldTableCell(new DefaultStringConverter()) { + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + } + }; + + textFieldTableCell.setEditable(false); + return textFieldTableCell; + } + }); + + columns.get(2).setCellValueFactory(new PropertyValueFactory("targetRequest")); + columns.get(2).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { +// param.setOnEditCommit(new EventHandler() { +// @Override +// public void handle(TableColumn.CellEditEvent event) { +// int row = event.getTablePosition().getRow(); +// Api api = data.get(row); +// api.setTargetRequest((String) event.getNewValue()); +// } +// }); + TextFieldTableCell textFieldTableCell = new TextFieldTableCell(new DefaultStringConverter()) { + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + } + }; + textFieldTableCell.setEditable(false); + return textFieldTableCell; + } + }); + columns.get(3).setCellValueFactory(new PropertyValueFactory("targetResponse")); + columns.get(3).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { +// param.setOnEditCommit(new EventHandler() { +// @Override +// public void handle(TableColumn.CellEditEvent event) { +// int row = event.getTablePosition().getRow(); +// Api api = data.get(row); +// api.setTargetResponse((String) event.getNewValue()); +// } +// }); + TextFieldTableCell textFieldTableCell = new TextFieldTableCell(new DefaultStringConverter()) { + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + } + }; + textFieldTableCell.setEditable(false); + return textFieldTableCell; + } + }); + + columns.get(4).setCellValueFactory(new PropertyValueFactory("method")); + columns.get(4).setCellFactory(new Callback() { + @Override + public TableCell call(TableColumn param) { + TextFieldTableCell textFieldTableCell = new TextFieldTableCell(new DefaultStringConverter()) { + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + } + }; + textFieldTableCell.setEditable(false); + return textFieldTableCell; + } + }); + ObservableList ObservableList = FXCollections.observableArrayList(); + ObservableList.addAll(data); + apis.setItems(ObservableList); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/TableDetailController.java b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/TableDetailController.java new file mode 100644 index 00000000..1a65f197 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/ctrl/TableDetailController.java @@ -0,0 +1,100 @@ +package xyz.wbsite.dbtool.javafx.ctrl; + +import javafx.fxml.FXML; +import javafx.scene.control.CheckBox; +import javafx.scene.control.TextField; + +public class TableDetailController { + + @FXML + private TextField tablename; + @FXML + private TextField tablecomment; + + @FXML + private CheckBox create; + @FXML + private CheckBox delete; + @FXML + private CheckBox update; + @FXML + private CheckBox find; + @FXML + private CheckBox get; + @FXML + private CheckBox search; + @FXML + private CheckBox getAll; + + public CheckBox getCreate() { + return create; + } + + public void setCreate(CheckBox create) { + this.create = create; + } + + public CheckBox getDelete() { + return delete; + } + + public void setDelete(CheckBox delete) { + this.delete = delete; + } + + public CheckBox getUpdate() { + return update; + } + + public void setUpdate(CheckBox update) { + this.update = update; + } + + public CheckBox getFind() { + return find; + } + + public void setFind(CheckBox find) { + this.find = find; + } + + public CheckBox getGet() { + return get; + } + + public void setGet(CheckBox get) { + this.get = get; + } + + public CheckBox getSearch() { + return search; + } + + public void setSearch(CheckBox search) { + this.search = search; + } + + public CheckBox getGetAll() { + return getAll; + } + + public void setGetAll(CheckBox getAll) { + this.getAll = getAll; + } + + public TextField getTablename() { + return tablename; + } + + public void setTablename(TextField tablename) { + this.tablename = tablename; + } + + public TextField getTablecomment() { + return tablecomment; + } + + public void setTablecomment(TextField tablecomment) { + this.tablecomment = tablecomment; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/customview/DBCheckBoxTableCell.java b/src/main/java/xyz/wbsite/dbtool/javafx/customview/DBCheckBoxTableCell.java new file mode 100644 index 00000000..8aa6889b --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/customview/DBCheckBoxTableCell.java @@ -0,0 +1,75 @@ +package xyz.wbsite.dbtool.javafx.customview; + +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.scene.control.CheckBox; +import javafx.scene.control.cell.CheckBoxTableCell; +import javafx.util.Callback; +import javafx.util.StringConverter; + +import java.lang.reflect.Field; + +public class DBCheckBoxTableCell extends CheckBoxTableCell { + + private CheckBox checkBox = null; + private int param = 0; + + public DBCheckBoxTableCell() { + init(); + } + + public DBCheckBoxTableCell(Callback getSelectedProperty) { + super(getSelectedProperty); + init(); + } + + public void setInvalid(boolean value) { + super.setDisable(value); + } + + public DBCheckBoxTableCell(Callback getSelectedProperty, StringConverter converter) { + super(getSelectedProperty, converter); + init(); + } + + public class sCallback implements Callback> { + + @Override + public ObservableValue call(Integer param) { + DBCheckBoxTableCell.this.param = param; + return null; + } + } + + public int getParam() { + return param; + } + + public void setParam(int param) { + this.param = param; + } + + public void setOnChangeListener(ChangeListener changeListener) { + checkBox.selectedProperty().addListener(changeListener); + } + + private void init() { + Class superclass = this.getClass().getSuperclass(); + + try { + Field field = superclass.getDeclaredField("checkBox"); + field.setAccessible(true); + checkBox = (CheckBox) field.get(this); + checkBox.setFocusTraversable(false); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + + @Override + public void updateItem(Object item, boolean empty) { + super.updateItem(item, empty); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/enumeration/DataBase.java b/src/main/java/xyz/wbsite/dbtool/javafx/enumeration/DataBase.java new file mode 100644 index 00000000..23b168d1 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/enumeration/DataBase.java @@ -0,0 +1,7 @@ +package xyz.wbsite.dbtool.javafx.enumeration; + + +public enum DataBase { + ORACLE, + MYSQL +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/enumeration/FieldType.java b/src/main/java/xyz/wbsite/dbtool/javafx/enumeration/FieldType.java new file mode 100644 index 00000000..a0b9cee1 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/enumeration/FieldType.java @@ -0,0 +1,240 @@ +package xyz.wbsite.dbtool.javafx.enumeration; + +public enum FieldType { + Boolean(0), + Byte(0), + Bytes(0), + Short(0), + Integer(0), + Long(0), + Float(0), + Double(0), + Character(0), + String_1(1), + String_10(10), + String_var(20, false), + String_var50(50), + String_var100(100), + String_var255(255), + String_var500(500), + String_var2500(2500), + String_var4000(4000), + String_super(0), + Date(0), + BigDecimal(0); + + private int defaultLength; + private boolean fix = true; + + public boolean isFix() { + return fix; + } + + public int getDefaultLength() { + return defaultLength; + } + + public void setDefaultLength(int defaultLength) { + this.defaultLength = defaultLength; + } + + FieldType(int defaultLength) { + this.defaultLength = defaultLength; + } + + FieldType(int defaultLength, boolean fix) { + this.defaultLength = defaultLength; + this.fix = fix; + } + + public static FieldType parse(String str) { + if (str == null) { + return null; + } + FieldType fieldType = null; + try { + fieldType = FieldType.valueOf(str); + } catch (IllegalArgumentException e) { + tryGetsimilar(str, 0); + } + if (fieldType == null) { + return FieldType.String_var50; + } + return fieldType; + } + + public static FieldType parse(String str, int length) { + if (str == null) { + return null; + } + FieldType fieldType = null; + try { + fieldType = FieldType.valueOf(str); + } catch (IllegalArgumentException e) { + fieldType = tryGetsimilar(str, length); + } + if (fieldType == null) { + return FieldType.String_var50; + } + return fieldType; + } + + public static FieldType tryGetsimilar(String str, int length) { + if (str.contains("CHAR")) { + return FieldType.String_var50; + } else if (str.contains("NUMBER")) { + + } else if (str.contains("DATE")) { + return FieldType.Date; + } else if (str.contains("BLOB")) { + return FieldType.Bytes; + } + return null; + } + + @Override + public String toString() { + if (Boolean.name().equals(this.name())) { + return "boolean"; + } else if (Byte.name().equals(this.name())) { + return "byte"; + } else if (Short.name().equals(this.name())) { + return "short"; + } else if (Integer.name().equals(this.name())) { + return "int"; + } else if (Long.name().equals(this.name())) { + return "long"; + } else if (Float.name().equals(this.name())) { + return "float"; + } else if (Double.name().equals(this.name())) { + return "double"; + } else if (Character.name().equals(this.name())) { + return "char"; + } else if (Date.name().equals(this.name())) { + return "Date"; + } else if (Bytes.name().equals(this.name())) { + return "byte[]"; + } else if (BigDecimal.name().equals(this.name())) { + return "BigDecimal"; + } else if (String_1.name().equals(this.name())) { + return "String_1"; + } else if (String_10.name().equals(this.name())) { + return "String_10"; + } else if (String_var.name().equals(this.name())) { + return "String_var"; + } else if (String_var50.name().equals(this.name())) { + return "String_var50"; + } else if (String_var100.name().equals(this.name())) { + return "String_var100"; + } else if (String_var255.name().equals(this.name())) { + return "String_var255"; + } else if (String_var500.name().equals(this.name())) { + return "String_var500"; + } else if (String_var2500.name().equals(this.name())) { + return "String_var2500"; + } else if (String_var4000.name().equals(this.name())) { + return "String_var4000"; + } else if (String_super.name().equals(this.name())) { + return "String_super"; + } else { + return ""; + } + } + + public String javaType() { + if (Boolean.name().equals(this.name())) { + return "Boolean"; + } else if (Byte.name().equals(this.name())) { + return "Byte"; + } else if (Short.name().equals(this.name())) { + return "Short"; + } else if (Integer.name().equals(this.name())) { + return "Integer"; + } else if (Long.name().equals(this.name())) { + return "Long"; + } else if (Float.name().equals(this.name())) { + return "Float"; + } else if (Double.name().equals(this.name())) { + return "Double"; + } else if (Character.name().equals(this.name())) { + return "Character"; + } else if (Date.name().equals(this.name())) { + return "Date"; + } else if (Bytes.name().equals(this.name())) { + return "Byte[]"; + } else if (BigDecimal.name().equals(this.name())) { + return "BigDecimal"; + } else if (String_1.name().equals(this.name())) { + return "String"; + } else if (String_10.name().equals(this.name())) { + return "String"; + } else if (String_var.name().equals(this.name())) { + return "String"; + } else if (String_var50.name().equals(this.name())) { + return "String"; + } else if (String_var100.name().equals(this.name())) { + return "String"; + } else if (String_var255.name().equals(this.name())) { + return "String"; + } else if (String_var500.name().equals(this.name())) { + return "String"; + } else if (String_var2500.name().equals(this.name())) { + return "String"; + } else if (String_var4000.name().equals(this.name())) { + return "String"; + } else if (String_super.name().equals(this.name())) { + return "String"; + } else { + return ""; + } + } + + public String jdbcType() { + if (Boolean.name().equals(this.name())) { + return "BIT"; + } else if (Byte.name().equals(this.name())) { + return "TINYINT"; + } else if (Short.name().equals(this.name())) { + return "SMALLINT"; + } else if (Integer.name().equals(this.name())) { + return "INTEGER"; + } else if (Long.name().equals(this.name())) { + return "BIGINT"; + } else if (Float.name().equals(this.name())) { + return "FLOAT"; + } else if (Double.name().equals(this.name())) { + return "DOUBLE"; + } else if (Character.name().equals(this.name())) { + return "CHAR"; + } else if (Date.name().equals(this.name())) { + return "TIMESTAMP"; + } else if (Bytes.name().equals(this.name())) { + return "BINARY"; + } else if (BigDecimal.name().equals(this.name())) { + return "DECIMAL"; + } else if (String_1.name().equals(this.name())) { + return "CHAR"; + } else if (String_10.name().equals(this.name())) { + return "CHAR"; + } else if (String_var.name().equals(this.name())) { + return "VARCHAR"; + } else if (String_var50.name().equals(this.name())) { + return "VARCHAR"; + } else if (String_var100.name().equals(this.name())) { + return "VARCHAR"; + } else if (String_var255.name().equals(this.name())) { + return "VARCHAR"; + } else if (String_var500.name().equals(this.name())) { + return "VARCHAR"; + } else if (String_var2500.name().equals(this.name())) { + return "VARCHAR"; + } else if (String_var4000.name().equals(this.name())) { + return "VARCHAR"; + } else if (String_super.name().equals(this.name())) { + return "VARCHAR"; + } else { + return ""; + } + + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/listener/GenerateOptionListener.java b/src/main/java/xyz/wbsite/dbtool/javafx/listener/GenerateOptionListener.java new file mode 100644 index 00000000..d3de38a9 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/listener/GenerateOptionListener.java @@ -0,0 +1,7 @@ +package xyz.wbsite.dbtool.javafx.listener; + +import xyz.wbsite.dbtool.javafx.enumeration.DataBase; + +public interface GenerateOptionListener { + void onGenerate(String option,DataBase dataBase); +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/manger/FreeMarkerManager.java b/src/main/java/xyz/wbsite/dbtool/javafx/manger/FreeMarkerManager.java new file mode 100644 index 00000000..57bba0e3 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/manger/FreeMarkerManager.java @@ -0,0 +1,61 @@ +package xyz.wbsite.dbtool.javafx.manger; + +import freemarker.cache.*; +import freemarker.template.*; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.lang.Nullable; +import org.springframework.ui.freemarker.SpringTemplateLoader; +import org.springframework.util.ClassUtils; +import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; +import org.springframework.web.util.UriTemplate; + +import java.io.*; +import java.net.URL; +import java.util.Properties; + +public class FreeMarkerManager { + private FreeMarkerConfigurer freeMarkerConfigurer; + + public FreeMarkerManager() { + freeMarkerConfigurer = new FreeMarkerConfigurer(); + // 初始化一些配置 + Configuration cfg = new Configuration(Configuration.VERSION_2_3_28); + cfg.setDefaultEncoding("UTF-8"); + cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); + cfg.setNumberFormat("0.##"); + + MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(new TemplateLoader[]{ + new ClassTemplateLoader(ClassUtils.getDefaultClassLoader(), "/modules"), + }); + + cfg.setTemplateLoader(multiTemplateLoader); + freeMarkerConfigurer.setConfiguration(cfg); + } + + public void outputTemp(File outfile, String template, Object model) { + try { + if (!outfile.exists()) { + outfile.createNewFile(); + } + + //获取连接 + Configuration configuration = freeMarkerConfigurer.getConfiguration(); + //设置编码 + configuration.setDefaultEncoding("UTF-8"); + //获取ftl,由于已经在配置文件中配置了路径所以在这里直接写模板名称就可以 + Template temp = configuration.getTemplate(template); + //输出文件路径 + Writer wr = new OutputStreamWriter(new FileOutputStream(outfile),"UTF-8"); + //写入 + temp.process(model, wr); + //关闭流 + wr.close(); + } catch (IOException e) { + e.printStackTrace(); + } catch (TemplateException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/manger/ManagerFactory.java b/src/main/java/xyz/wbsite/dbtool/javafx/manger/ManagerFactory.java new file mode 100644 index 00000000..60c36c66 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/manger/ManagerFactory.java @@ -0,0 +1,36 @@ +package xyz.wbsite.dbtool.javafx.manger; + +import xyz.wbsite.dbtool.javafx.JavaFxApplication; + +public class ManagerFactory { + private static XmlManager xmlManager = null; + private static ReflashManager reflashManager =null; + private static ProjectManager dBManager; + private static FreeMarkerManager freeMarkerManager; + + static { + xmlManager = new XmlManager(); + dBManager = new ProjectManager(); + freeMarkerManager = new FreeMarkerManager(); + } + + public static ProjectManager getdBManager() { + return dBManager; + } + + public static FreeMarkerManager getFreeMarkerManager() { + return freeMarkerManager; + } + + + public static XmlManager getXmlManager() { + return xmlManager; + } + + public static ReflashManager getReflashManager(JavaFxApplication main) { + if (reflashManager == null){ + reflashManager = new ReflashManager(main); + } + return reflashManager; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/manger/ProjectManager.java b/src/main/java/xyz/wbsite/dbtool/javafx/manger/ProjectManager.java new file mode 100644 index 00000000..dc4e0a8a --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/manger/ProjectManager.java @@ -0,0 +1,476 @@ +package xyz.wbsite.dbtool.javafx.manger; + +import org.springframework.boot.system.ApplicationHome; +import xyz.wbsite.dbtool.javafx.enumeration.DataBase; +import xyz.wbsite.dbtool.javafx.enumeration.FieldType; +import xyz.wbsite.dbtool.javafx.manger.callable.SDKCallable; +import xyz.wbsite.dbtool.javafx.manger.callable.SpringBootCallable; +import xyz.wbsite.dbtool.javafx.po.*; +import xyz.wbsite.dbtool.javafx.tool.Dialog; + +import java.io.File; +import java.sql.*; +import java.util.List; +import java.util.Map; +import java.util.concurrent.*; + +public class ProjectManager { + + public static boolean isUpdate = false; + private XmlManager xmlService; + public static AbstractDBmapper dBmapper; + public static String path; + private Project project = new Project(); + + public ProjectManager() { + xmlService = ManagerFactory.getXmlManager(); + try { + ApplicationHome home = new ApplicationHome(getClass()); + File jarFile = home.getSource(); + this.path = jarFile.getParent() + File.separator + "project"; + } catch (Exception e) { + e.printStackTrace(); + this.path = System.getProperty("user.home") + File.separator + "project"; + } + invalidate(); + } + + public Module findDBByDBName(String name) { + for (Module md : project.getModules()) { + if (md.getModuleName().equals(name)) { + return md; + } + } + return null; + } + + public boolean removeDBByDBName(String name) { + for (Module md : project.getModules()) { + if (md.getModuleName().equals(name)) { + project.getModules().remove(md); + return true; + } + } + return false; + } + + public Table findTableByTableName(Module md, String name) { + for (Table t : md.getTables()) { + if (t.getTableName().equals(name)) { + return t; + } + } + return null; + } + + public Table getNewTableName(Module md) { + String base = "NEW_TABLE"; + String name = base; + int k = 0; + do { + int i; + for (i = 0; i < md.getTables().size(); i++) { + if (name.equals(md.getTables().get(i).getTableName())) { + break; + } + } + if (i < md.getTables().size()) { + k++; + name = base + "_" + k; + } else { + Table table = new Table(name); + table.setTableComment("注释"); + table.setCreate(true); + table.setDelete(true); + table.setUpdate(true); + table.setFind(true); + table.setGet(true); + table.setSearch(false); + table.setGetAll(false); + + md.putTable(table); + return table; + } + } while (true); + } + + public String getNewModuleName() { + String base = "example"; + String name = base; + int k = 0; + do { + int i; + for (i = 0; i < project.getModules().size(); i++) { + if (name.equals(project.getModules().get(i).getModuleName())) { + break; + } + } + if (i < project.getModules().size()) { + k++; + name = base + k; + } else { + Module md = new Module(name); + md.setModuleName(name); + md.setModuleComment("注释"); + project.putModule(md); + return name; + } + } while (true); + } + + public String getNewFieldName(List fields) { + String base = "NEW_FIELD"; + String name = base; + int k = 0; + do { + int i; + for (i = 0; i < fields.size(); i++) { + if (name.equals(fields.get(i).getFieldName())) { + break; + } + } + if (i < fields.size()) { + k++; + name = base + "_" + k; + } else { + Field field = new Field(name); + field.setDefaultValue("NULL"); + field.setIsQuery(false); + field.setIsMust(false); + field.setIsPrimaryKey(false); + field.setFieldType(FieldType.String_var50); + field.setFieldLength(FieldType.String_var50.getDefaultLength()); + int j = 0; + for (; j < fields.size(); j++) { + if (fields.get(j).getFieldName().equals("ROW_VERSION")) { + break; + } + } + fields.add(j, field); + return name; + } + } while (true); + } + + public List getMds() { + return project.getModules(); + } + + public Project getProject() { + return project; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + if (path != null && !path.equals(this.path)) { + this.path = path; + invalidate(); + } + } + + public boolean doCheck() { + if (project.getProjectName() == null || "".equals(project.getProjectName())) { + Dialog.showConfirmDialog("没有填写项目名!"); + return false; + } else if (project.getProjectBasePackage() == null || "".equals(project.getProjectBasePackage())) { + Dialog.showConfirmDialog("没有填写基本域名!"); + return false; + } else if (project.getProjectAuthor() == null || "".equals(project.getProjectAuthor())) { + Dialog.showConfirmDialog("没有填写作者!"); + return false; + } + for (Module md : project.getModules()) { + if (md.getModuleName() == null || "".equals(md.getModuleName())) { + Dialog.showConfirmDialog("项目" + project.getProjectName() + "没有填写模块名!"); + return false; + } else if (md.getModuleComment() == null || "".equals(md.getModuleComment())) { + Dialog.showConfirmDialog("项目" + project.getProjectName() + "没有模块注释!"); + return false; + } + } + return true; + } + + /** + * 保存配置文件 + */ + public void save() { + if (path != null) { + File file = new File(path); + if (!file.exists()) { + file.mkdirs(); + } + xmlService.save(path, project); + } + } + + private void clear(File f) { + if (f.isDirectory()) { + File[] files = f.listFiles(); + for (File file : files) { + if (file.isDirectory()) { + clear(file); + boolean delete = file.delete(); + + System.out.println("删除" + file.getName() + (delete ? "成功" : "失败")); + } else { + boolean delete = file.delete(); + + System.out.println("删除" + file.getName() + (delete ? "成功" : "失败")); + } + } + } + } + + private static ExecutorService service = Executors.newFixedThreadPool(1); + + public void tryGetDBmapper(DataBase dataBase) { + if (dataBase.name().equals(DataBase.MYSQL.name())) { + dBmapper = new MySqlDBmapper(dataBase); + } else if (dataBase.name().equals(DataBase.ORACLE.name())) { + dBmapper = new OracleDBmapper(dataBase); + } + } + + /** + * 生成模板 入口 + * + * @param path + */ + public void generate(final String path, final String option, final DataBase dataBase) { + tryGetDBmapper(dataBase); + + File root = new File(path); + if (!root.exists()) { + Dialog.showTimedDialog(1000, "目录不存在!"); + } + Dialog.showProgress("生成中..."); + new Thread() { + @Override + public void run() { + Callable callback = null; + switch (option) { + case "SpringBoot": + callback = new SpringBootCallable(path, dataBase, project, option); + break; + case "SpringMVC_Mybatis": +// callback = new SpringMVCMybatisCallable(path, dataBase, project, option); + break; + default: + + } + + Future submit = service.submit(callback); + try { + submit.get(); + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + Dialog.stopPopup(); + Dialog.showSuccess("生成完成."); + } + }.start(); + } + + + public void generateSDK(File module, File sdk, List apis) { + if (module.exists()) { + boolean mkdirs = sdk.mkdirs(); + File reqList = new File(module.getAbsolutePath() + File.separator + "req"); + File rspList = new File(module.getAbsolutePath() + File.separator + "rsp"); + File entList = new File(module.getAbsolutePath() + File.separator + "ent"); + File enumsList = new File(module.getAbsolutePath() + File.separator + "enums"); + SDKCallable sdkCallable = new SDKCallable(sdk, reqList, rspList, entList, enumsList, apis); + Future submit = service.submit(sdkCallable); + try { + Boolean b = (Boolean) submit.get(); + if (!b) { + Dialog.showError("请确认目录结构是否存在或正确!"); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (ExecutionException e) { + e.printStackTrace(); + } + + Dialog.showSuccess("Api生成完成."); + } + } + + public void invalidate() { + project = xmlService.inflate(path); + } + + public static boolean testConnect(Map properties) { + + String url = properties.get("url"); + String username = properties.get("username"); + String password = properties.get("password"); + String driverClassName = properties.get("driverClassName"); + + try { + //加载MySql的驱动类 + Class.forName(driverClassName); + + Connection cn = DriverManager.getConnection(url, username, password); + cn.close(); + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public static boolean loadMD(Map properties) { + + String type = properties.get("type"); + String url = properties.get("url"); + String username = properties.get("username"); + String password = properties.get("password"); + String driverClassName = properties.get("driverClassName"); + Connection cn = null; + + if ("Orcale".equals(type)) { + try { + dBmapper = new OracleDBmapper(DataBase.ORACLE); + + //加载驱动类 + Class.forName(driverClassName); + cn = DriverManager.getConnection(url, username, password); + + Module md = new Module(username); + //查询所有表 + Statement statement = cn.createStatement(); + ResultSet rs = statement.executeQuery("select t.table_name,c.comments from user_tables t LEFT JOIN user_tab_comments c ON t.table_name = c.table_name ORDER BY T .table_name"); + + while (rs.next()) { + Table table = new Table(rs.getString("table_name"), rs.getString("comments")); + md.putTable(table); + } + + for (Table table : md.getTables()) { + String sql = "SELECT T.*,CASE WHEN C.POSITION='1' THEN '1' ELSE '0' END PrimaryKey FROM(select A.COLUMN_ID,A.COLUMN_NAME,A.DATA_TYPE,A.DATA_LENGTH,A .DATA_PRECISION,A .DATA_SCALE,A.NULLABLE,A.DATA_DEFAULT,B.comments from user_tab_columns A ,user_col_comments B where A.Table_Name='" + table.getTableName() + "' AND B.Table_Name='" + table.getTableName() + "' AND A.COLUMN_NAME=B.COLUMN_NAME) T LEFT JOIN user_cons_columns C ON T.COLUMN_NAME = C.COLUMN_NAME AND POSITION = '1' AND C.Table_Name='" + table.getTableName() + "' ORDER BY T .COLUMN_ID"; + ResultSet set = statement.executeQuery(sql); + + while (set.next()) { + Field field = new Field(); + + field.setFieldName(set.getString("COLUMN_NAME")); + + String data_type = set.getString("DATA_TYPE"); + int data_length = set.getInt("DATA_LENGTH"); + int data_precision = set.getInt("DATA_PRECISION"); + int data_scale = set.getInt("DATA_SCALE"); + field.setFieldType(dBmapper.getType(data_type, data_length, data_precision, data_scale)); + field.setFieldLength(set.getInt("DATA_LENGTH")); + String nullable = set.getString("NULLABLE"); + field.setDefaultValue(set.getString("DATA_DEFAULT")); + field.setFieldComment(set.getString("COMMENTS")); + if ("N".equals(nullable)) { + field.setIsMust(true); + } else { + field.setIsMust(false); + } + String primarykey = set.getString("PRIMARYKEY"); + if ("1".equals(primarykey)) { + field.setIsPrimaryKey(true); + } else { + field.setIsPrimaryKey(false); + } + field.setIsQuery(false); + + table.putField(field); + } + } + + ManagerFactory.getdBManager().project.putModule(md); + isUpdate = true; + return true; + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + cn.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } else if ("Mysql".equals(type)) { + try { + dBmapper = new MySqlDBmapper(DataBase.MYSQL); + + //加载驱动类 + Class.forName(driverClassName); + cn = DriverManager.getConnection(url, username, password); + + String[] split = url.split("/"); + String dbName = split[split.length - 1]; + + Module md = new Module(dbName); + //查询所有表 + Statement statement = cn.createStatement(); + ResultSet rs = statement.executeQuery("SELECT TABLE_NAME,TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '" + dbName + "'"); + + while (rs.next()) { + Table table = new Table(rs.getString("TABLE_NAME"), rs.getString("TABLE_COMMENT")); + md.putTable(table); + } + + for (Table table : md.getTables()) { + String sql = "select COLUMN_NAME,COLUMN_COMMENT,COLUMN_KEY,COLUMN_DEFAULT,IS_NULLABLE,DATA_TYPE, COLUMN_TYPE,CHARACTER_MAXIMUM_LENGTH from information_schema.COLUMNS where table_name = '" + table.getTableName() + "' and table_schema = '" + dbName + "' ORDER BY ORDINAL_POSITION ASC"; + ResultSet set = statement.executeQuery(sql); + + while (set.next()) { + Field field = new Field(); + + field.setFieldName(set.getString("COLUMN_NAME")); + + if ("NO".equals(set.getString("IS_NULLABLE"))) { + field.setIsMust(true); + } else { + field.setIsMust(false); + } + + if ("PRI".equals(set.getString("COLUMN_KEY"))) { + field.setIsPrimaryKey(true); + } else { + field.setIsPrimaryKey(false); + } + + String data_type = set.getString("DATA_TYPE"); + int data_length = set.getInt("CHARACTER_MAXIMUM_LENGTH"); + field.setFieldType(dBmapper.getType(data_type, data_length, 0, 0)); + field.setFieldLength(0); + if ("varchar".equals(data_type) || "char".equals(data_type)) { + int length = Integer.parseInt(set.getString("CHARACTER_MAXIMUM_LENGTH")); + field.setFieldLength(length); + } + + field.setDefaultValue(set.getString("COLUMN_DEFAULT")); + field.setFieldComment(set.getString("COLUMN_COMMENT")); + + field.setIsQuery(false); + + table.putField(field); + } + } + + ManagerFactory.getdBManager().project.putModule(md); + isUpdate = true; + return true; + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } + + return false; + } + return false; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/manger/ReflashManager.java b/src/main/java/xyz/wbsite/dbtool/javafx/manger/ReflashManager.java new file mode 100644 index 00000000..bbac4d1f --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/manger/ReflashManager.java @@ -0,0 +1,26 @@ +package xyz.wbsite.dbtool.javafx.manger; + +import xyz.wbsite.dbtool.javafx.JavaFxApplication; + +public class ReflashManager extends Thread{ + private JavaFxApplication main; + + public ReflashManager(JavaFxApplication main) { + this.main = main; + } + + @Override + public void run() { + while (true){ + try { + Thread.sleep(200); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (ProjectManager.isUpdate){ + main.loadingProjectTree(); + ProjectManager.isUpdate = false; + } + } + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/manger/XmlManager.java b/src/main/java/xyz/wbsite/dbtool/javafx/manger/XmlManager.java new file mode 100644 index 00000000..a0ed316d --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/manger/XmlManager.java @@ -0,0 +1,295 @@ +package xyz.wbsite.dbtool.javafx.manger; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import xyz.wbsite.dbtool.javafx.enumeration.FieldType; +import xyz.wbsite.dbtool.javafx.po.Field; +import xyz.wbsite.dbtool.javafx.po.Module; +import xyz.wbsite.dbtool.javafx.po.Project; +import xyz.wbsite.dbtool.javafx.po.Table; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.*; + +public class XmlManager { + + public Project inflate(String path) { + Project project = new Project(); + + if (path == null || "".equals(path)) { + return project; + } + File file = new File(path); + if (!file.exists()) { + System.err.println("目录不存在!"); + } else { + File dbFile = new File(path); + + if (!dbFile.exists()) { + dbFile.mkdir(); + } else { + File[] files = dbFile.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(".xml") || name.endsWith(".XML"); + } + }); + + //开始解析 + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + for (File xml : files) { + FileInputStream inputStream = null; + try { + inputStream = new FileInputStream(xml); + Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); + + Element dbElement = document.getDocumentElement(); + + if ("project".endsWith(dbElement.getNodeName())) { + System.out.println("发现项目:" + xml.getName()); + + NodeList projectName = dbElement.getElementsByTagName("projectName"); + if (projectName.getLength() == 1) { + project.setProjectName(projectName.item(0).getTextContent()); + } + + NodeList projectBasePackage = dbElement.getElementsByTagName("projectBasePackage"); + if (projectBasePackage.getLength() == 1) { + project.setProjectBasePackage(projectBasePackage.item(0).getTextContent()); + } + + NodeList projectAuthor = dbElement.getElementsByTagName("projectAuthor"); + if (projectAuthor.getLength() == 1) { + project.setProjectAuthor(projectAuthor.item(0).getTextContent()); + } + + NodeList modules = dbElement.getElementsByTagName("module"); + if (modules.getLength() > 0) { + + for (int i = 0; i < modules.getLength(); i++) { + Module module = new Module(); + Element moduleElement = (Element) modules.item(i); + + NodeList moduleName = moduleElement.getElementsByTagName("moduleName"); + if (moduleName.getLength() == 1) { + module.setModuleName(moduleName.item(0).getTextContent()); + } + + NodeList moduleComment = moduleElement.getElementsByTagName("moduleComment"); + if (moduleComment.getLength() == 1) { + module.setModuleComment(moduleComment.item(0).getTextContent()); + } + + NodeList modulePrefix = moduleElement.getElementsByTagName("modulePrefix"); + if (modulePrefix.getLength() == 1) { + module.setModulePrefix(modulePrefix.item(0).getTextContent()); + } + + NodeList hasSysFields = moduleElement.getElementsByTagName("hasSysFields"); + if (hasSysFields.getLength() == 1) { + module.setHasSysFields(Boolean.parseBoolean(hasSysFields.item(0).getTextContent())); + } + + NodeList tables = moduleElement.getElementsByTagName("table"); + if (tables.getLength() > 0) { + for (int j = 0; j < tables.getLength(); j++) { + Element tableElement = (Element) tables.item(j); + Table table = new Table(); + table.setdBhandle(module); + table.setTableName(tableElement.getAttribute("tableName")); + table.setTableComment(tableElement.getAttribute("tableComment")); + table.setCreate(Boolean.parseBoolean(tableElement.getAttribute("create"))); + table.setDelete(Boolean.parseBoolean(tableElement.getAttribute("delete"))); + table.setUpdate(Boolean.parseBoolean(tableElement.getAttribute("update"))); + table.setFind(Boolean.parseBoolean(tableElement.getAttribute("find"))); + table.setGet(Boolean.parseBoolean(tableElement.getAttribute("get"))); + table.setSearch(Boolean.parseBoolean(tableElement.getAttribute("search"))); + table.setGetAll(Boolean.parseBoolean(tableElement.getAttribute("getAll"))); + + NodeList fields = tableElement.getElementsByTagName("field"); + + if (fields.getLength() > 0) { + for (int k = 0; k < fields.getLength(); k++) { + Element fieldElement = (Element) fields.item(k); + Field field = new Field(); + field.setFieldName(fieldElement.getAttribute("fieldName")); + field.setFieldType(FieldType.parse(fieldElement.getAttribute("fieldType"))); + field.setFieldLength(Integer.parseInt(fieldElement.getAttribute("fieldLength"))); + field.setFieldComment(fieldElement.getAttribute("fieldComment")); + field.setDefaultValue(fieldElement.getAttribute("defaultValue")); + field.setIsSystem(Boolean.parseBoolean(fieldElement.getAttribute("IsSystem"))); + field.setIsMust(Boolean.parseBoolean(fieldElement.getAttribute("isMust"))); + field.setIsPrimaryKey(Boolean.parseBoolean(fieldElement.getAttribute("isPrimaryKey"))); + field.setIsQuery(Boolean.parseBoolean(fieldElement.getAttribute("isQuery"))); + field.setIsSearch(Boolean.parseBoolean(fieldElement.getAttribute("isSearch"))); + table.putField(field); + } + } + module.putTable(table); + } + } + project.putModule(module); + } + } + System.out.println("数据初始化成功..."); + return project; + } + } catch (Exception e) { + System.out.println("文件:'" + xml.getName() + "'解析失败!请检查语法是否正确!"); + e.printStackTrace(); + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } + } + return project; + } + + public boolean saveAs(String path, Project project) { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder; + //生成DOM模型 + try { + builder = dbFactory.newDocumentBuilder(); + Document doc = builder.newDocument(); + + Element rootProject = doc.createElement("project"); + doc.appendChild(rootProject); + + Element projectName = doc.createElement("projectName"); + projectName.setTextContent(project.getProjectName()); + Element projectBasePackage = doc.createElement("projectBasePackage"); + projectBasePackage.setTextContent(project.getProjectBasePackage()); + Element projectAuthor = doc.createElement("projectAuthor"); + projectAuthor.setTextContent(project.getProjectAuthor()); + rootProject.appendChild(projectName); + rootProject.appendChild(projectBasePackage); + rootProject.appendChild(projectAuthor); + + Element modules = doc.createElement("modules"); + rootProject.appendChild(modules); + + //region Description + for (Module md : project.getModules()) { + Element module = doc.createElement("module"); + + Element moduleName = doc.createElement("moduleName"); + Element moduleComment = doc.createElement("moduleComment"); + Element modulePrefix = doc.createElement("modulePrefix"); + Element hasSysFields = doc.createElement("hasSysFields"); + moduleName.setTextContent(md.getModuleName()); + moduleComment.setTextContent(md.getModuleComment()); + modulePrefix.setTextContent(md.getModulePrefix()); + hasSysFields.setTextContent(String.valueOf(md.isHasSysFields())); + module.appendChild(moduleComment); + module.appendChild(modulePrefix); + module.appendChild(moduleName); + module.appendChild(hasSysFields); + + Element tables = doc.createElement("tables"); + module.appendChild(tables); + for (Table t : md.getTables()) { + Element table = doc.createElement("table"); + table.setAttribute("tableName", t.getTableName()); + table.setAttribute("tableComment", t.getTableComment()); + table.setAttribute("create", t.getCreate().toString()); + table.setAttribute("delete", t.getDelete().toString()); + table.setAttribute("update", t.getUpdate().toString()); + table.setAttribute("find", t.getFind().toString()); + table.setAttribute("get", t.getGet().toString()); + table.setAttribute("search", t.getSearch().toString()); + table.setAttribute("getAll", t.getGetAll().toString()); + + Element fields = doc.createElement("fields"); + + table.appendChild(fields); + + for (Field f : t.getFields()) { + Element field = doc.createElement("field"); + field.setAttribute("fieldName", f.getFieldName()); + if (f.getFieldType() != null) { + field.setAttribute("fieldType", f.getFieldType().name()); + } + if (f.getFieldLength() != null) { + field.setAttribute("fieldLength", f.getFieldLength().toString()); + } + field.setAttribute("fieldComment", f.getFieldComment()); + field.setAttribute("defaultValue", f.getDefaultValue()); + if (f.getIsMust() != null) { + field.setAttribute("isMust", f.getIsMust().toString()); + } + field.setAttribute("isQuery", f.getIsQuery().toString()); + field.setAttribute("isSearch", f.getIsSearch().toString()); + if (f.getIsPrimaryKey() != null) { + field.setAttribute("isPrimaryKey", f.getIsPrimaryKey().toString()); + } + if (f.getIsSystem() != null) { + field.setAttribute("IsSystem", f.getIsSystem().toString()); + } + fields.appendChild(field); + } + tables.appendChild(table); + } + modules.appendChild(module); + } + //endregion + + //输出文件 + FileOutputStream stream = null; + try { + Transformer t = TransformerFactory.newInstance().newTransformer(); + + //设置换行和缩进 + t.setOutputProperty(OutputKeys.INDENT, "yes"); + t.setOutputProperty(OutputKeys.METHOD, "xml"); + + File dbFile = new File(path); + if (!dbFile.exists()) { + dbFile.mkdirs(); + } + File file = new File(dbFile.getAbsolutePath() + File.separator + project.getProjectName() + ".xml"); + if (!file.exists()) { + file.createNewFile(); + } + stream = new FileOutputStream(file); + t.transform(new DOMSource(doc), new StreamResult(stream)); + } catch (Exception e) { + e.printStackTrace(); + return false; + } finally { + if (stream != null) { + try { + stream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } catch (ParserConfigurationException e) { + e.printStackTrace(); + e.printStackTrace(); + return false; + } + return true; + } + + public boolean save(String path, Project project) { + File projectFile = new File(path); + saveAs(projectFile.getAbsolutePath(), project); + return true; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/manger/callable/SDKCallable.java b/src/main/java/xyz/wbsite/dbtool/javafx/manger/callable/SDKCallable.java new file mode 100644 index 00000000..d881eab6 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/manger/callable/SDKCallable.java @@ -0,0 +1,748 @@ +package xyz.wbsite.dbtool.javafx.manger.callable; + +import xyz.wbsite.dbtool.javafx.manger.ProjectManager; +import xyz.wbsite.dbtool.javafx.manger.FreeMarkerManager; +import xyz.wbsite.dbtool.javafx.manger.ManagerFactory; +import xyz.wbsite.dbtool.javafx.po.AbstractDBmapper; +import xyz.wbsite.dbtool.javafx.po.Api; +import xyz.wbsite.dbtool.javafx.tool.JavaClassReader; +import xyz.wbsite.dbtool.javafx.tool.JavaEnumReader; +import xyz.wbsite.dbtool.javafx.tool.Tool; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.Callable; + +import static xyz.wbsite.dbtool.javafx.tool.Tool.clear; + +public class SDKCallable implements Callable { + + private File sdk; + private File req; + private File rsp; + private File ent; + private File enums; + private List apis; + private Tool tool = new Tool(); + + private FreeMarkerManager freeMarkerManager; + + public SDKCallable(File sdk, File req, File rsp, File ent, File enums, List apis) { + this.sdk = sdk; + this.req = req; + this.rsp = rsp; + this.ent = ent; + this.enums = enums; + this.apis = apis; + this.freeMarkerManager = ManagerFactory.getFreeMarkerManager(); + } + + private AbstractDBmapper dBmapper; + + public Boolean call() throws Exception { + if (!sdk.exists()) { + sdk.mkdir(); + } else { + clear(sdk); + } + + dBmapper = ProjectManager.dBmapper; + + { + System.out.println("生成模块:Pom"); + HashMap ctx = new HashMap(); + ctx.put("sdk", sdk.getName().toLowerCase()); + File file = new File(sdk.getAbsolutePath() + File.separator + "pom.xml"); + freeMarkerManager.outputTemp(file, "Java_api/pom.ftl", ctx); + } + + File frameWork = null; + String domain = null; + String module = null; + Set managerList = new HashSet<>(); + List methodList = new ArrayList<>(); + + for (Api api : apis) { + if (api.isCheck()) { + + try { + //region 生成request + JavaClassReader javaClassReader = new JavaClassReader(api.getReq()); + + Method method = new Method(); + method.setStringMethod(api.getMethod()); + method.setRequest(javaClassReader.getClassName()); + method.setTarget(Tool.getRequestTarget(javaClassReader.getClassName())); + method.setMethod(Tool.getRequestAction(javaClassReader.getClassName())); + method.setManager(Tool.getRequestTarget(javaClassReader.getClassName()) + "Manager"); + methodList.add(method); + StringBuffer stringBuffer = new StringBuffer(""); + stringBuffer.append(sdk.getPath() + File.separator); + stringBuffer.append("src" + File.separator); + stringBuffer.append("main" + File.separator); + stringBuffer.append("java" + File.separator); + + String[] split = javaClassReader.getDomainName().split("\\."); + + managerList.add(method.getManager()); + + for (String s1 : split) { + stringBuffer.append(s1 + File.separator); + } + if (frameWork == null) { + frameWork = new File(stringBuffer.toString()); + frameWork.mkdirs(); + } + if (domain == null) { + domain = javaClassReader.getDomainName(); + } + if (module == null) { + module = javaClassReader.getModuleName(); + } + + stringBuffer.append(javaClassReader.getModuleName()); + + File request = new File(stringBuffer.toString() + File.separator + "request"); + request.mkdirs(); + + { + HashMap ctx = new HashMap(); + ctx.put("package", "package " + javaClassReader.getDomainName() + "." + javaClassReader.getModuleName() + "." + "request;"); + ctx.put("domain", javaClassReader.getDomainName()); + ctx.put("module", javaClassReader.getModuleName()); + ctx.put("importList", javaClassReader.getImportList()); + ctx.put("annotation", javaClassReader.getAnnotationList()); + ctx.put("className", javaClassReader.getClassName().replaceAll("Request", "")); + ctx.put("body", javaClassReader.getBody()); + ctx.put("tool", tool); + ctx.put("hasList", javaClassReader.isHasList()); + ctx.put("findOrSearchflag", javaClassReader.getFindOrSearchflag()); + File file = new File(request.getAbsolutePath() + File.separator + api.getReq().getName()); + + freeMarkerManager.outputTemp(file, "Java_api/module/request/request.ftl", ctx); + System.out.println("生成文件" + file.getName() + "成功"); + } + //endregion + } catch (IOException e) { + e.printStackTrace(); + } + + + try { + //region 生成response + JavaClassReader javaClassReader = new JavaClassReader(api.getRsp()); + + StringBuffer stringBuffer = new StringBuffer(""); + stringBuffer.append(sdk.getPath() + File.separator); + stringBuffer.append("src" + File.separator); + stringBuffer.append("main" + File.separator); + stringBuffer.append("java" + File.separator); + + String[] split = javaClassReader.getDomainName().split("\\."); + + + for (String s1 : split) { + stringBuffer.append(s1 + File.separator); + } + + stringBuffer.append(javaClassReader.getModuleName()); + + File response = new File(stringBuffer.toString() + File.separator + "response"); + response.mkdirs(); + + { + HashMap ctx = new HashMap(); + ctx.put("package", "package " + javaClassReader.getDomainName() + "." + javaClassReader.getModuleName() + "." + "request;"); + ctx.put("domain", javaClassReader.getDomainName()); + ctx.put("module", javaClassReader.getModuleName()); + ctx.put("importList", javaClassReader.getImportList()); + ctx.put("annotation", javaClassReader.getAnnotationList()); + ctx.put("className", javaClassReader.getClassName().replaceAll("Response", "")); + ctx.put("body", javaClassReader.getBody()); + ctx.put("tool", tool); + ctx.put("hasList", javaClassReader.isHasList()); + ctx.put("Tclass", javaClassReader.getTclass()); + File file = new File(response.getAbsolutePath() + File.separator + api.getRsp().getName().replaceAll("Request", "Response")); + + freeMarkerManager.outputTemp(file, "Java_api/module/response/response.ftl", ctx); + System.out.println("生成文件" + api.getRsp().getName() + "成功"); + } + //endregion + } catch (IOException e) { + e.printStackTrace(); + } + + for (String s : api.getDepReq()) { + try { + File f = new File(req.getAbsolutePath() + File.separator + s + ".java"); + if (!f.exists()) { + System.err.println("文件" + f.getAbsolutePath() + "不存在"); + continue; + } + JavaClassReader javaClassReader = new JavaClassReader(f); + + Method method = new Method(); + method.setStringMethod(api.getMethod()); + method.setRequest(javaClassReader.getClassName()); + method.setTarget(Tool.getRequestTarget(javaClassReader.getClassName())); + method.setMethod(Tool.getRequestAction(javaClassReader.getClassName())); + method.setManager(Tool.getRequestTarget(javaClassReader.getClassName()) + "Manager"); + + StringBuffer stringBuffer = new StringBuffer(""); + stringBuffer.append(sdk.getPath() + File.separator); + stringBuffer.append("src" + File.separator); + stringBuffer.append("main" + File.separator); + stringBuffer.append("java" + File.separator); + + String[] split = javaClassReader.getDomainName().split("\\."); + + for (String s1 : split) { + stringBuffer.append(s1 + File.separator); + } + if (frameWork == null) { + frameWork = new File(stringBuffer.toString()); + frameWork.mkdirs(); + } + if (domain == null) { + domain = javaClassReader.getDomainName(); + } + if (module == null) { + module = javaClassReader.getModuleName(); + } + + stringBuffer.append(javaClassReader.getModuleName()); + + File request = new File(stringBuffer.toString() + File.separator + "request"); + request.mkdirs(); + + { + HashMap ctx = new HashMap(); + ctx.put("package", "package " + javaClassReader.getDomainName() + "." + javaClassReader.getModuleName() + "." + "request;"); + ctx.put("domain", javaClassReader.getDomainName()); + ctx.put("module", javaClassReader.getModuleName()); + ctx.put("importList", javaClassReader.getImportList()); + ctx.put("annotation", javaClassReader.getAnnotationList()); + ctx.put("className", javaClassReader.getClassName().replaceAll("Request", "")); + ctx.put("body", javaClassReader.getBody()); + ctx.put("tool", tool); + ctx.put("hasList", javaClassReader.isHasList()); + ctx.put("findOrSearchflag", javaClassReader.getFindOrSearchflag()); + File file = new File(request.getAbsolutePath() + File.separator + f.getName()); + + freeMarkerManager.outputTemp(file, "Java_api/module/request/request.ftl", ctx); + System.out.println("生成文件" + file.getName() + "成功"); + } + //endregion + } catch (IOException e) { + e.printStackTrace(); + } + + try { + File f = new File(rsp.getAbsolutePath() + File.separator + s.replaceAll("Request", "Response.java")); + if (!f.exists()){ + System.err.println("文件" + f.getAbsolutePath() + "不存在"); + } + JavaClassReader javaClassReader = new JavaClassReader(f); + + StringBuffer stringBuffer = new StringBuffer(""); + stringBuffer.append(sdk.getPath() + File.separator); + stringBuffer.append("src" + File.separator); + stringBuffer.append("main" + File.separator); + stringBuffer.append("java" + File.separator); + + String[] split = javaClassReader.getDomainName().split("\\."); + + + for (String s1 : split) { + stringBuffer.append(s1 + File.separator); + } + + stringBuffer.append(javaClassReader.getModuleName()); + + File response = new File(stringBuffer.toString() + File.separator + "response"); + response.mkdirs(); + + { + HashMap ctx = new HashMap(); + ctx.put("package", "package " + javaClassReader.getDomainName() + "." + javaClassReader.getModuleName() + "." + "request;"); + ctx.put("domain", javaClassReader.getDomainName()); + ctx.put("module", javaClassReader.getModuleName()); + ctx.put("importList", javaClassReader.getImportList()); + ctx.put("annotation", javaClassReader.getAnnotationList()); + ctx.put("className", javaClassReader.getClassName().replaceAll("Response", "")); + ctx.put("body", javaClassReader.getBody()); + ctx.put("tool", tool); + ctx.put("hasList", javaClassReader.isHasList()); + ctx.put("Tclass", javaClassReader.getTclass()); + File file = new File(response.getAbsolutePath() + File.separator + f.getName()); + + freeMarkerManager.outputTemp(file, "Java_api/module/response/response.ftl", ctx); + System.out.println("生成文件" + api.getRsp().getName() + "成功"); + } + //endregion + } catch (IOException e) { + e.printStackTrace(); + } + } + + for (String s : api.getDepEnt()) { + + try { + File f = new File(ent.getAbsolutePath() + File.separator + s + ".java"); + if (!f.exists()) { + System.out.println("文件" + f.getAbsolutePath() + "不存在"); + continue; + } + JavaClassReader javaClassReader = new JavaClassReader(f); + + StringBuffer stringBuffer = new StringBuffer(""); + stringBuffer.append(sdk.getPath() + File.separator); + stringBuffer.append("src" + File.separator); + stringBuffer.append("main" + File.separator); + stringBuffer.append("java" + File.separator); + + String[] split = javaClassReader.getDomainName().split("\\."); + + + for (String s1 : split) { + stringBuffer.append(s1 + File.separator); + } + + stringBuffer.append(javaClassReader.getModuleName()); + + File entity = new File(stringBuffer.toString() + File.separator + "entity"); + entity.mkdirs(); + + { + HashMap ctx = new HashMap(); + ctx.put("package", "package " + javaClassReader.getDomainName() + "." + javaClassReader.getModuleName() + "." + "request;"); + ctx.put("domain", javaClassReader.getDomainName()); + ctx.put("module", javaClassReader.getModuleName()); + ctx.put("importList", javaClassReader.getImportList()); + ctx.put("annotation", javaClassReader.getAnnotationList()); + ctx.put("className", javaClassReader.getClassName().replaceAll("Entity", "")); + ctx.put("body", javaClassReader.getBody()); + ctx.put("tool", tool); + File file = new File(entity.getAbsolutePath() + File.separator + f.getName()); + freeMarkerManager.outputTemp(file, "Java_api/module/entity/entity.ftl", ctx); + System.out.println("生成文件" + file.getName() + "成功"); + } + //endregion + } catch (IOException e) { + e.printStackTrace(); + } + } + + for (String s : api.getDepEnum()) { + try { + File f = new File(enums.getAbsolutePath() + File.separator + s + ".java"); + if (!f.exists()) { + System.err.println("文件" + f.getAbsolutePath() + "不存在"); + continue; + } + JavaEnumReader javaEnumReader = new JavaEnumReader(f); + + StringBuffer stringBuffer = new StringBuffer(""); + stringBuffer.append(sdk.getPath() + File.separator); + stringBuffer.append("src" + File.separator); + stringBuffer.append("main" + File.separator); + stringBuffer.append("java" + File.separator); + + String[] split = javaEnumReader.getDomainName().split("\\."); + + + for (String s1 : split) { + stringBuffer.append(s1 + File.separator); + } + + stringBuffer.append(javaEnumReader.getModuleName()); + + File enums_ = new File(stringBuffer.toString() + File.separator + "enums"); + enums_.mkdirs(); + + { + HashMap ctx = new HashMap(); + ctx.put("package", "package " + javaEnumReader.getDomainName() + "." + javaEnumReader.getModuleName() + "." + "enums;"); + ctx.put("domain", javaEnumReader.getDomainName()); + ctx.put("module", javaEnumReader.getModuleName()); + ctx.put("annotation", javaEnumReader.getAnnotationList()); + ctx.put("className", javaEnumReader.getClassName()); + ctx.put("body", javaEnumReader.getBody()); + ctx.put("tool", tool); + + File file = new File(enums_.getAbsolutePath() + File.separator + f.getName()); + freeMarkerManager.outputTemp(file, "Java_api/module/enums/type.ftl", ctx); + System.out.println("生成文件" + file.getName() + "成功"); + } + //endregion + + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + +// if (req.exists() && rsp.exists() && ent.exists()) { +// File[] files = req.listFiles(); +// System.out.println("生成模块:Request,Response,Entity"); +// for (File f : files) { +// try { +// //region 生成request +// JavaClassReader javaClassReader = new JavaClassReader(f); +// +// Method method = new Method(); +// method.setStringMethod("api." + javaClassReader.getModuleName() + "." + Tool.camelToPoint(javaClassReader.getClassName().replaceAll("Request", ""))); +// method.setRequest(javaClassReader.getClassName()); +// method.setTarget(Tool.getRequestTarget(javaClassReader.getClassName())); +// method.setMethod(Tool.getRequestAction(javaClassReader.getClassName())); +// method.setManager(Tool.getRequestTarget(javaClassReader.getClassName()) + "Manager"); +// methodList.add(method); +// StringBuffer stringBuffer = new StringBuffer(""); +// stringBuffer.append(sdk.getPath() + File.separator); +// stringBuffer.append("src" + File.separator); +// stringBuffer.append("main" + File.separator); +// stringBuffer.append("java" + File.separator); +// +// String[] split = javaClassReader.getDomainName().split("\\."); +// +// +// for (String s1 : split) { +// stringBuffer.append(s1 + File.separator); +// } +// if (frameWork == null) { +// frameWork = new File(stringBuffer.toString()); +// frameWork.mkdirs(); +// } +// if (domain == null) { +// domain = javaClassReader.getDomainName(); +// } +// if (module == null) { +// module = javaClassReader.getModuleName(); +// } +// +// stringBuffer.append(javaClassReader.getModuleName()); +// +// File request = new File(stringBuffer.toString() + File.separator + "request"); +// request.mkdirs(); +// +// { +// HashMap ctx = new HashMap(); +// ctx.put("package", "package " + javaClassReader.getDomainName() + "." + javaClassReader.getModuleName() + "." + "request;"); +// ctx.put("domain", javaClassReader.getDomainName()); +// ctx.put("module", javaClassReader.getModuleName()); +// ctx.put("importList", javaClassReader.getImportList()); +// ctx.put("annotation", javaClassReader.getAnnotationList()); +// ctx.put("className", javaClassReader.getClassName().replaceAll("Request", "")); +// ctx.put("body", javaClassReader.getBody()); +// ctx.put("tool", tool); +// ctx.put("hasList", javaClassReader.isHasList()); +// ctx.put("findOrSearchflag", javaClassReader.getFindOrSearchflag()); +// File file = new File(request.getAbsolutePath() + File.separator + f.getName()); +// +// freeMarkerManager.outputTemp(file, "Java_api/module/request/request.ftl", ctx); +// System.out.println("生成文件" + file.getName() + "成功"); +// } +// //endregion +// } catch (IOException e) { +// e.printStackTrace(); +// } +// +// try { +// //region 生成response +// File r = new File(f.getParent().replaceAll("req", "rsp") + File.separator + f.getName().replaceAll("Request", "Response")); +// JavaClassReader javaClassReader = new JavaClassReader(r); +// +// StringBuffer stringBuffer = new StringBuffer(""); +// stringBuffer.append(sdk.getPath() + File.separator); +// stringBuffer.append("src" + File.separator); +// stringBuffer.append("main" + File.separator); +// stringBuffer.append("java" + File.separator); +// +// String[] split = javaClassReader.getDomainName().split("\\."); +// +// +// for (String s1 : split) { +// stringBuffer.append(s1 + File.separator); +// } +// +// stringBuffer.append(javaClassReader.getModuleName()); +// +// File response = new File(stringBuffer.toString() + File.separator + "response"); +// response.mkdirs(); +// +// { +// HashMap ctx = new HashMap(); +// ctx.put("package", "package " + javaClassReader.getDomainName() + "." + javaClassReader.getModuleName() + "." + "request;"); +// ctx.put("domain", javaClassReader.getDomainName()); +// ctx.put("module", javaClassReader.getModuleName()); +// ctx.put("importList", javaClassReader.getImportList()); +// ctx.put("annotation", javaClassReader.getAnnotationList()); +// ctx.put("className", javaClassReader.getClassName().replaceAll("Response", "")); +// ctx.put("body", javaClassReader.getBody()); +// ctx.put("tool", tool); +// ctx.put("hasList", javaClassReader.isHasList()); +// ctx.put("Tclass", javaClassReader.getTclass()); +// File file = new File(response.getAbsolutePath() + File.separator + f.getName().replaceAll("Request", "Response")); +// +// freeMarkerManager.outputTemp(file, "Java_api/module/response/response.ftl", ctx); +// System.out.println("生成文件" + r.getName() + "成功"); +// } +// //endregion +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// +// for (File f : ent.listFiles()) { +// try { +// //region 生成entity +// JavaClassReader javaClassReader = new JavaClassReader(f); +// managerList.add(javaClassReader.getClassName() + "Manager"); +// +// StringBuffer stringBuffer = new StringBuffer(""); +// stringBuffer.append(sdk.getPath() + File.separator); +// stringBuffer.append("src" + File.separator); +// stringBuffer.append("main" + File.separator); +// stringBuffer.append("java" + File.separator); +// +// String[] split = javaClassReader.getDomainName().split("\\."); +// +// +// for (String s1 : split) { +// stringBuffer.append(s1 + File.separator); +// } +// +// stringBuffer.append(javaClassReader.getModuleName()); +// +// File entity = new File(stringBuffer.toString() + File.separator + "entity"); +// entity.mkdirs(); +// +// { +// HashMap ctx = new HashMap(); +// ctx.put("package", "package " + javaClassReader.getDomainName() + "." + javaClassReader.getModuleName() + "." + "request;"); +// ctx.put("domain", javaClassReader.getDomainName()); +// ctx.put("module", javaClassReader.getModuleName()); +// ctx.put("importList", javaClassReader.getImportList()); +// ctx.put("annotation", javaClassReader.getAnnotationList()); +// ctx.put("className", javaClassReader.getClassName().replaceAll("Entity", "")); +// ctx.put("body", javaClassReader.getBody()); +// ctx.put("tool", tool); +// File file = new File(entity.getAbsolutePath() + File.separator + f.getName()); +// freeMarkerManager.outputTemp(file, "Java_api/module/entity/entity.ftl", ctx); +// System.out.println("生成文件" + file.getName() + "成功"); +// } +// //endregion +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// } else { +// return false; +// } +// +// if (enums.exists()) { +// System.out.println("生成模块:Enums"); +// for (File f : enums.listFiles()) { +// try { +// //region 生成enums +// JavaEnumReader javaEnumReader = new JavaEnumReader(f); +// +// StringBuffer stringBuffer = new StringBuffer(""); +// stringBuffer.append(sdk.getPath() + File.separator); +// stringBuffer.append("src" + File.separator); +// stringBuffer.append("main" + File.separator); +// stringBuffer.append("java" + File.separator); +// +// String[] split = javaEnumReader.getDomainName().split("\\."); +// +// +// for (String s1 : split) { +// stringBuffer.append(s1 + File.separator); +// } +// +// stringBuffer.append(javaEnumReader.getModuleName()); +// +// File enums_ = new File(stringBuffer.toString() + File.separator + "enums"); +// enums_.mkdirs(); +// +// { +// HashMap ctx = new HashMap(); +// ctx.put("package", "package " + javaEnumReader.getDomainName() + "." + javaEnumReader.getModuleName() + "." + "enums;"); +// ctx.put("domain", javaEnumReader.getDomainName()); +// ctx.put("module", javaEnumReader.getModuleName()); +// ctx.put("annotation", javaEnumReader.getAnnotationList()); +// ctx.put("className", javaEnumReader.getClassName()); +// ctx.put("body", javaEnumReader.getBody()); +// ctx.put("tool", tool); +// +// File file = new File(enums_.getAbsolutePath() + File.separator + f.getName()); +// freeMarkerManager.outputTemp(file, "Java_api/module/enums/type.ftl", ctx); +// System.out.println("生成文件" + file.getName() + "成功"); +// } +// //endregion +// +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// } + + { + System.out.println("生成模块:ApiController"); + HashMap ctx = new HashMap(); + ctx.put("tool", tool); + ctx.put("domain", domain); + ctx.put("module", module); + ctx.put("managerList", managerList); + ctx.put("methodList", methodList); + File file = new File(frameWork.getAbsolutePath() + File.separator + module + File.separator + "ApiController.java"); + freeMarkerManager.outputTemp(file, "Java_api/module/controller/ApiController.ftl", ctx); + } + + System.out.println("生成基础类"); + HashMap ctx = new HashMap(); + ctx.put("domain", domain); + ctx.put("module", module); + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "ApiEntity.java"); + freeMarkerManager.outputTemp(file, "/Java_api/ApiEntity.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "AESUtil.java"); + freeMarkerManager.outputTemp(file, "/Java_api/AESUtil.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "ApiClient.java"); + freeMarkerManager.outputTemp(file, "/Java_api/ApiClient.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "ApiRequest.java"); + freeMarkerManager.outputTemp(file, "/Java_api/ApiRequest.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "ApiFindRequest.java"); + freeMarkerManager.outputTemp(file, "/Java_api/ApiFindRequest.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "ApiSearchRequest.java"); + freeMarkerManager.outputTemp(file, "/Java_api/ApiSearchRequest.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "ApiResponse.java"); + freeMarkerManager.outputTemp(file, "/Java_api/ApiResponse.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "ApiFindResponse.java"); + freeMarkerManager.outputTemp(file, "/Java_api/ApiFindResponse.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "Base64Util.java"); + freeMarkerManager.outputTemp(file, "/Java_api/Base64Util.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "DownloadUtil.java"); + freeMarkerManager.outputTemp(file, "/Java_api/DownloadUtil.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "Error.java"); + freeMarkerManager.outputTemp(file, "/Java_api/Error.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "ErrorType.java"); + freeMarkerManager.outputTemp(file, "/Java_api/ErrorType.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "FileUploadRequest.java"); + freeMarkerManager.outputTemp(file, "/Java_api/FileUploadRequest.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "FileUploadResponse.java"); + freeMarkerManager.outputTemp(file, "/Java_api/FileUploadResponse.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "MapperUtil.java"); + freeMarkerManager.outputTemp(file, "/Java_api/MapperUtil.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "MD5Util.java"); + freeMarkerManager.outputTemp(file, "/Java_api/MD5Util.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "RSAUtil.java"); + freeMarkerManager.outputTemp(file, "/Java_api/RSAUtil.ftl", ctx); + } + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "ProgressRequestBody.java"); + freeMarkerManager.outputTemp(file, "/Java_api/ProgressRequestBody.ftl", ctx); + } + + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "SortType.java"); + freeMarkerManager.outputTemp(file, "/Java_api/SortType.ftl", ctx); + } + + { + File file = new File(frameWork.getAbsolutePath() + File.separator + "StringUtils.java"); + freeMarkerManager.outputTemp(file, "/Java_api/StringUtils.ftl", ctx); + } + //4.0.1 去掉验证 减少体积 +// { +// File file = new File(frameWork.getAbsolutePath() + File.separator + "ValidationUtil.java"); +// freeMarkerManager.outputTemp(file, "/Java_api/ValidationUtil.ftl", ctx); +// } + System.out.println("finish"); + return true; + } + + + public class Method { + private String request; + private String stringMethod; + private String manager; + private String method; + private String target; + + public String getRequest() { + return request; + } + + public void setRequest(String request) { + this.request = request; + } + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public String getStringMethod() { + return stringMethod; + } + + public void setStringMethod(String stringMethod) { + this.stringMethod = stringMethod; + } + + public String getManager() { + return manager; + } + + public void setManager(String manager) { + this.manager = manager; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/manger/callable/SpringBootCallable.java b/src/main/java/xyz/wbsite/dbtool/javafx/manger/callable/SpringBootCallable.java new file mode 100644 index 00000000..1685a1f8 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/manger/callable/SpringBootCallable.java @@ -0,0 +1,705 @@ +package xyz.wbsite.dbtool.javafx.manger.callable; + +import xyz.wbsite.dbtool.javafx.enumeration.DataBase; +import xyz.wbsite.dbtool.javafx.manger.FreeMarkerManager; +import xyz.wbsite.dbtool.javafx.manger.ManagerFactory; +import xyz.wbsite.dbtool.javafx.manger.ProjectManager; +import xyz.wbsite.dbtool.javafx.manger.XmlManager; +import xyz.wbsite.dbtool.javafx.po.AbstractDBmapper; +import xyz.wbsite.dbtool.javafx.po.Module; +import xyz.wbsite.dbtool.javafx.po.Project; +import xyz.wbsite.dbtool.javafx.po.Table; +import xyz.wbsite.dbtool.javafx.tool.Tool; + +import java.io.File; +import java.util.Date; +import java.util.HashMap; +import java.util.concurrent.Callable; + +import static xyz.wbsite.dbtool.javafx.tool.Tool.clear; + +public class SpringBootCallable implements Callable { + + private String root; + private DataBase dataBase; + private Project project; + private String option; + + private FreeMarkerManager freeMarkerManager; + + public SpringBootCallable(String root, DataBase dataBase, Project project, String option) { + this.root = root; + this.dataBase = dataBase; + this.project = project; + this.option = option; + this.freeMarkerManager = ManagerFactory.getFreeMarkerManager(); + } + + private AbstractDBmapper dBmapper; + + public Boolean call() throws Exception { + dBmapper = ProjectManager.dBmapper; + + // 创建项目文件夹 + File projectDir = new File(root + File.separator + project.getProjectName()); + if (!projectDir.exists()) { + projectDir.mkdir(); + } else { + clear(projectDir); + } + + // 生成POM + generatePom(projectDir, project, dataBase, option); + + // 生成Maven-java及域名目录 + String basePackage = project.getProjectBasePackage(); + String[] split = basePackage.split("\\."); + StringBuffer stringBuffer = new StringBuffer(projectDir.getAbsolutePath() + File.separator + "src" + File.separator + "main"); + stringBuffer.append(File.separator).append("java"); + for (String s : split) { + stringBuffer.append(File.separator).append(s); + } + File src = new File(stringBuffer.toString()); + if (!src.exists()) { + src.mkdirs(); + } + + // 生成资源目录 + stringBuffer = new StringBuffer(projectDir.getAbsolutePath() + File.separator + "src" + File.separator + "main"); + stringBuffer.append(File.separator).append("resources"); + File resources = new File(stringBuffer.toString()); + if (!resources.exists()) { + resources.mkdirs(); + } + + // 生成单元测试java目录 + stringBuffer = new StringBuffer(projectDir.getAbsolutePath()); + stringBuffer.append(File.separator).append("src").append(File.separator).append("test").append(File.separator).append("java"); + for (String s : split) { + stringBuffer.append(File.separator).append(s); + } + File testSrc = new File(stringBuffer.toString()); + if (!testSrc.exists()) { + testSrc.mkdirs(); + } + + // 生成单元测试resources目录 + stringBuffer = new StringBuffer(projectDir.getAbsolutePath()); + stringBuffer.append(File.separator).append("src").append(File.separator).append("test").append(File.separator).append("resources"); + File testResources = new File(stringBuffer.toString()); + if (!testResources.exists()) { + testResources.mkdirs(); + } + + {//生成java文件 + //生成Controller + System.out.println("生成模块:action"); + generateController(new File(src.getAbsolutePath(), "action"), project, dataBase, option); + + //module + { + for (Module module : project.getModules()) { + module.setProjectAuthor(project.getProjectAuthor()); + module.setProjectBasePackage(project.getProjectBasePackage()); + module.setProjectName(project.getProjectName()); + + File modulePath = new File(src.getAbsolutePath(), module.getModuleName()); + modulePath.mkdirs(); + + System.out.println("生成模块:Entity"); + generateEntity(new File(modulePath.getAbsolutePath(), "ent"), module, dataBase, option); + System.out.println("生成模块:Enums"); + generateEnums(new File(modulePath.getAbsolutePath(), "enums"), module, dataBase, option); + System.out.println("生成模块:Mapper"); + generateMapper(new File(modulePath.getAbsolutePath(), "mpr"), module, dataBase, option); + System.out.println("生成模块:Manager"); + generateManager(new File(modulePath.getAbsolutePath(), "mgr"), module, dataBase, option); + System.out.println("生成模块:Requset"); + generateRequset(new File(modulePath.getAbsolutePath(), "req"), module, dataBase, option); + System.out.println("生成模块:Response"); + generateResponse(new File(modulePath.getAbsolutePath(), "rsp"), module, dataBase, option); + } + } + + //framework + System.out.println("生成模块:framework"); + generateFramework(new File(src.getAbsolutePath(), "framework"), project, dataBase, option); + + System.out.println("生成模块:Application"); + generateApplication(new File(src.getAbsolutePath()), project, dataBase, option); + } + + {//生成resources文件 + System.out.println("生成模块:Resources"); + generateResources(resources, project, dataBase, option); + for (Module module : project.getModules()) { + generateResourcesSQL(resources, module, dataBase, option); + } + System.out.println("生成模块:Static"); + generateStatic(resources, project, dataBase, option); + System.out.println("生成模块:Templates"); + generateTemplates(resources, project, dataBase, option); + } + + {//生成test + System.out.println("生成模块:Test"); + generateTest(testSrc, project, dataBase, option); + generateTestResources(testResources, project, dataBase, option); + } + System.out.println("finish"); + return true; + } + + + /** + * 生成POM.xml + * + * @param root + * @param project + */ + public void generatePom(File root, Project project, DataBase dataBase, String option) { + HashMap ctx = new HashMap(); + ctx.put("projectName", project.getProjectName()); + ctx.put("basePackage", project.getProjectBasePackage()); + ctx.put("dataBase", dataBase.toString()); + + File file = new File(root.getAbsolutePath(), "pom.xml"); + + freeMarkerManager.outputTemp(file, option + "/pom.ftl", ctx); + } + + + /** + * 生成Controller类 + * + * @param root + * @param project + */ + public void generateController(File root, Project project, DataBase dataBase, String option) { + if (!root.exists()) { + root.mkdirs(); + } else { + clear(root); + } + HashMap ctx = new HashMap(); + ctx.put("basePackage", project.getProjectBasePackage()); + ctx.put("author", project.getProjectAuthor()); + ctx.put("date", new Date()); + ctx.put("modules", project.getModules()); + + File control = new File(root.getAbsolutePath(), "control"); + control.mkdirs(); + freeMarkerManager.outputTemp(new File(control.getAbsolutePath(), "Footer.java"), option + "/java/action/control/Footer.java", ctx); + freeMarkerManager.outputTemp(new File(control.getAbsolutePath(), "Header.java"), option + "/java/action/control/Header.java", ctx); + + File screen = new File(root.getAbsolutePath(), "screen"); + screen.mkdirs(); + freeMarkerManager.outputTemp(new File(screen.getAbsolutePath(), "Index.java"), option + "/java/action/screen/Index.java", ctx); + + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "GlobalController.java"), option + "/java/action/GlobalController.ftl", ctx); + + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "AjaxController.java"), option + "/java/action/AjaxController.ftl", ctx); + } + + /** + * 生成entity + * + * @param root + * @param md + */ + public void generateEntity(File root, Module md, DataBase dataBase, String option) { + if (!root.exists()) { + root.mkdirs(); + } else { + clear(root); + } + + for (Table table : md.getTables()) { + HashMap ctx = new HashMap(); + ctx.put("tool", Tool.class); + ctx.put("basePackage", md.getProjectBasePackage()); + ctx.put("moduleName", md.getModuleName()); + ctx.put("table", table); + ctx.put("author", md.getProjectAuthor()); + ctx.put("date", new Date()); + + File file = new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + ".java"); + + freeMarkerManager.outputTemp(file, option + "/java/ent/entity.ftl", ctx); + } + } + + /** + * 生成Enums + * + * @param root + * @param md + */ + public void generateEnums(File root, Module md, DataBase dataBase, String option) { + if (!root.exists()) { + root.mkdirs(); + } else { + clear(root); + } + + HashMap ctx = new HashMap(); + ctx.put("tool", Tool.class); + ctx.put("basePackage", md.getProjectBasePackage()); + ctx.put("moduleName", md.getModuleName()); + ctx.put("author", md.getProjectAuthor()); + ctx.put("date", new Date()); + + File file = new File(root.getAbsolutePath(), "Type.java"); + + freeMarkerManager.outputTemp(file, option + "/java/enums/Type.ftl", ctx); + } + + /** + * 生成Mapper + * + * @param root + * @param md + */ + public void generateMapper(File root, Module md, DataBase dataBase, String option) { + if (!root.exists()) { + root.mkdirs(); + } else { + clear(root); + } + HashMap ctx = new HashMap(); + + ctx.put("tool", Tool.class); + ctx.put("module", md); + ctx.put("dataBase", dataBase.toString()); + ctx.put("basePackage", md.getProjectBasePackage()); + ctx.put("moduleName", md.getModuleName()); + ctx.put("author", md.getProjectAuthor()); + ctx.put("date", new Date()); + + for (Table table : md.getTables()) { + ctx.put("table", table); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Mapper" + ".java"), option + "/java/mpr/mapperJava.ftl", ctx); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Mapper" + ".xml"), option + "/java/mpr/mapper.ftl", ctx); + } + } + + public void generateManager(File root, Module md, DataBase dataBase, String option) { + if (!root.exists()) { + root.mkdirs(); + } else { + clear(root); + } + HashMap ctx = new HashMap(); + + ctx.put("tool", Tool.class); + ctx.put("basePackage", md.getProjectBasePackage()); + ctx.put("moduleName", md.getModuleName()); + ctx.put("author", md.getProjectAuthor()); + ctx.put("date", new Date()); + + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "ApiManager" + ".java"), option + "/java/mgr/ApiManager.java", ctx); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "ApiManagerImpl" + ".java"), option + "/java/mgr/ApiManagerImpl.java", ctx); + + for (Table table : md.getTables()) { + ctx.put("table", table); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Manager" + ".java"), option + "/java/mgr/manager.ftl", ctx); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "ManagerImpl" + ".java"), option + "/java/mgr/managerImpl.ftl", ctx); + } + + } + + /** + * 生成Requset + * + * @param root + * @param md + */ + public void generateRequset(File root, Module md, DataBase dataBase, String option) { + if (!root.exists()) { + root.mkdirs(); + } else { + clear(root); + } + + HashMap ctx = new HashMap(); + ctx.put("tool", Tool.class); + ctx.put("basePackage", md.getProjectBasePackage()); + ctx.put("moduleName", md.getModuleName()); + ctx.put("author", md.getProjectAuthor()); + ctx.put("date", new Date()); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "ApiExampleRequest" + ".java"), option + "/java/req/ApiExampleRequest.java", ctx); + + for (Table table : md.getTables()) { + ctx.put("table", table); + + if (table.getCreate() != null && table.getCreate()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "CreateRequest" + ".java"), option + "/java/req/createRequestClass.ftl", ctx); + } + + if (table.getDelete() != null && table.getDelete()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "DeleteRequest" + ".java"), option + "/java/req/deleteRequestClass.ftl", ctx); + } + + if (table.getUpdate() != null && table.getUpdate()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "UpdateRequest" + ".java"), option + "/java/req/updateRequestClass.ftl", ctx); + } + + if (table.getFind() != null && table.getFind()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "FindRequest" + ".java"), option + "/java/req/findRequestClass.ftl", ctx); + } + + if (table.getGet() != null && table.getGet()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "GetRequest" + ".java"), option + "/java/req/getRequestClass.ftl", ctx); + } + + if (table.getSearch() != null && table.getSearch()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "SearchRequest" + ".java"), option + "/java/req/searchRequestClass.ftl", ctx); + } + if (table.getGetAll() != null && table.getGetAll()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "GetAllRequest" + ".java"), option + "/java/req/getAllRequestClass.ftl", ctx); + } + } + } + + /** + * 生成一般文件 + * + * @param root + * @param md + */ + public void generateResponse(File root, Module md, DataBase dataBase, String option) { + if (!root.exists()) { + root.mkdirs(); + } else { + clear(root); + } + + HashMap ctx = new HashMap(); + ctx.put("tool", Tool.class); + ctx.put("basePackage", md.getProjectBasePackage()); + ctx.put("moduleName", md.getModuleName()); + ctx.put("author", md.getProjectAuthor()); + ctx.put("date", new Date()); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "ApiExampleResponse" + ".java"), option + "/java/rsp/ApiExampleResponse.java", ctx); + + for (Table table : md.getTables()) { + ctx.put("table", table); + + if (table.getCreate() != null && table.getCreate()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "CreateResponse" + ".java"), option + "/java/rsp/createResponseClass.ftl", ctx); + } + + if (table.getDelete() != null && table.getDelete()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "DeleteResponse" + ".java"), option + "/java/rsp/deleteResponseClass.ftl", ctx); + } + + if (table.getUpdate() != null && table.getUpdate()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "UpdateResponse" + ".java"), option + "/java/rsp/updateResponseClass.ftl", ctx); + } + + if (table.getFind() != null && table.getFind()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "FindResponse" + ".java"), option + "/java/rsp/findResponseClass.ftl", ctx); + } + + if (table.getGet() != null && table.getGet()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "GetResponse" + ".java"), option + "/java/rsp/getResponseClass.ftl", ctx); + } + + if (table.getSearch() != null && table.getSearch()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "SearchResponse" + ".java"), option + "/java/rsp/searchResponseClass.ftl", ctx); + } + if (table.getGetAll() != null && table.getGetAll()) { + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "GetAllResponse" + ".java"), option + "/java/rsp/getAllResponseClass.ftl", ctx); + } + } + } + + /** + * 生成framework类 + * + * @param root + * @param project + */ + public void generateFramework(File root, Project project, DataBase dataBase, String option) { + if (!root.exists()) { + root.mkdirs(); + } else { + clear(root); + } + HashMap ctx = new HashMap(); + ctx.put("basePackage", project.getProjectBasePackage()); + ctx.put("moduleName", project.getProjectName()); + ctx.put("timestamp", new Date().getTime()); + + File base = new File(root.getAbsolutePath(), "base"); + base.mkdirs(); + File config = new File(root.getAbsolutePath(), "config"); + config.mkdirs(); + File freemarker = new File(root.getAbsolutePath(), "freemarker"); + freemarker.mkdirs(); + File springmvc = new File(root.getAbsolutePath(), "springmvc"); + springmvc.mkdirs(); + File utils = new File(root.getAbsolutePath(), "utils"); + utils.mkdirs(); + + //base + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "BaseEntity.java"), option + "/java/framework/base/BaseEntity.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "BaseFindRequest.java"), option + "/java/framework/base/BaseFindRequest.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "BaseFindResponse.java"), option + "/java/framework/base/BaseFindResponse.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "BaseGetAllRequest.java"), option + "/java/framework/base/BaseGetAllRequest.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "BaseRequest.java"), option + "/java/framework/base/BaseRequest.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "BaseResponse.java"), option + "/java/framework/base/BaseResponse.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "BaseSearchRequest.java"), option + "/java/framework/base/BaseSearchRequest.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "BaseUpdateRequest.java"), option + "/java/framework/base/BaseUpdateRequest.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "Control.java"), option + "/java/framework/base/Control.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "Error.java"), option + "/java/framework/base/Error.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "ErrorType.java"), option + "/java/framework/base/ErrorType.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "FileUploadResponse.java"), option + "/java/framework/base/FileUploadResponse.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "Screen.java"), option + "/java/framework/base/Screen.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "SortType.java"), option + "/java/framework/base/SortType.java", ctx); + freeMarkerManager.outputTemp(new File(base.getAbsolutePath(), "Token.java"), option + "/java/framework/base/Token.java", ctx); + + //config + freeMarkerManager.outputTemp(new File(config.getAbsolutePath(), "BeanDefinitionRegistryConfig.java"), option + "/java/framework/config/BeanDefinitionRegistryConfig.java", ctx); + freeMarkerManager.outputTemp(new File(config.getAbsolutePath(), "SecurityConfig.java"), option + "/java/framework/config/SecurityConfig.java", ctx); + freeMarkerManager.outputTemp(new File(config.getAbsolutePath(), "TaskConfig.java"), option + "/java/framework/config/TaskConfig.java", ctx); + freeMarkerManager.outputTemp(new File(config.getAbsolutePath(), "ThreadPoolConfig.java"), option + "/java/framework/config/ThreadPoolConfig.java", ctx); + freeMarkerManager.outputTemp(new File(config.getAbsolutePath(), "WebMvcConfig.java"), option + "/java/framework/config/WebMvcConfig.java", ctx); + + //freemarker + freeMarkerManager.outputTemp(new File(freemarker.getAbsolutePath(), "ViewNameTranslator.java"), option + "/java/framework/freemarker/ViewNameTranslator.java", ctx); + freeMarkerManager.outputTemp(new File(freemarker.getAbsolutePath(), "Layout.java"), option + "/java/framework/freemarker/Layout.java", ctx); + freeMarkerManager.outputTemp(new File(freemarker.getAbsolutePath(), "Uri.java"), option + "/java/framework/freemarker/Uri.java", ctx); + + //springmvc + freeMarkerManager.outputTemp(new File(springmvc.getAbsolutePath(), "GlobalHandlerInterceptor.java"), option + "/java/framework/springmvc/GlobalHandlerInterceptor.java", ctx); + + //uitls + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "Base64Util.java"), option + "/java/framework/utils/Base64Util.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "AESUtil.java"), option + "/java/framework/utils/AESUtil.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "CookieUtil.java"), option + "/java/framework/utils/CookieUtil.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "LogUtil.java"), option + "/java/framework/utils/LogUtil.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "MapperUtil.java"), option + "/java/framework/utils/MapperUtil.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "MD5Util.java"), option + "/java/framework/utils/MD5Util.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "ProcessUtil.java"), option + "/java/framework/utils/ProcessUtil.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "RSAUtil.java"), option + "/java/framework/utils/RSAUtil.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "ValidationUtil.java"), option + "/java/framework/utils/ValidationUtil.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "WebUtils.java"), option + "/java/framework/utils/WebUtils.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "LocalData.java"), option + "/java/framework/utils/LocalData.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "IDgenerator.java"), option + "/java/framework/utils/IDgenerator.java", ctx); + freeMarkerManager.outputTemp(new File(utils.getAbsolutePath(), "Message.java"), option + "/java/framework/utils/Message.java", ctx); + } + + /** + * 生成base类 + * + * @param root + * @param project + */ + public void generateApplication(File root, Project project, DataBase dataBase, String option) { + + HashMap ctx = new HashMap(); + ctx.put("basePackage", project.getProjectBasePackage()); + ctx.put("moduleName", project.getProjectName()); + ctx.put("timestamp", new Date().getTime()); + + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "Application.java"), option + "/java/Application.ftl", ctx); + } + + /** + * 生成properties + * + * @param root + * @param project + */ + public void generateResources(File root, Project project, DataBase dataBase, String option) { + HashMap ctx = new HashMap(); + + ctx.put("basePackage", project.getProjectBasePackage()); + ctx.put("tool", Tool.class); + ctx.put("dataBase", dataBase.toString()); + ctx.put("author", project.getProjectAuthor()); + ctx.put("dBmapper", dBmapper); + ctx.put("date", new Date()); + ctx.put("projectName", project.getProjectName()); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "start-dev.bat"), option + "/resources/start-dev.bat", ctx); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "start-prod.bat"), option + "/resources/start-prod.bat", ctx); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "application-dev.properties"), option + "/resources/application-dev.ftl", ctx); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "application-prod.properties"), option + "/resources/application-prod.ftl", ctx); + Tool.outputResource(option + "/resources/banner.txt", new File(root.getAbsolutePath(), "banner.txt")); + Tool.outputResource(option + "/resources/logback-config.xml", new File(root.getAbsolutePath(), "logback-config.xml")); + + File lib = new File(root.getAbsolutePath(), "lib"); + lib.mkdirs(); + Tool.outputResource(option + "/resources/lib/ojdbc7-12.1.0.2.jar", new File(lib.getAbsolutePath(), "ojdbc7-12.1.0.2.jar")); + + File dbtool = new File(root.getAbsolutePath(), "dbtool"); + dbtool.mkdirs(); + { + XmlManager xmlManager = ManagerFactory.getXmlManager(); + xmlManager.saveAs(dbtool.getAbsolutePath(), project); + } + } + + /** + * 生成properties + * + * @param root + * @param md + */ + public void generateResourcesSQL(File root, Module md, DataBase dataBase, String option) { + HashMap ctx = new HashMap(); + + ctx.put("basePackage", md.getProjectBasePackage()); + ctx.put("moduleName", md.getModuleName()); + ctx.put("tool", Tool.class); + ctx.put("dataBase", dataBase.toString()); + ctx.put("module", md); + ctx.put("author", md.getProjectAuthor()); + ctx.put("dBmapper", dBmapper); + ctx.put("date", new Date()); + + File tableDir = new File(root.getAbsolutePath(), md.getModuleName() + "_table"); + tableDir.mkdirs(); + + for (Table table : md.getTables()) { + ctx.put("table", table); + freeMarkerManager.outputTemp(new File(tableDir.getAbsolutePath(), table.getTableName() + ".sql"), option + "/resources/table.ftl", ctx); + } + freeMarkerManager.outputTemp(new File(tableDir.getAbsolutePath(), "ALL_TABLE.sql"), option + "/resources/tableAll.ftl", ctx); + } + + public void generateTestResources(File root, Project project, DataBase dataBase, String option) { + HashMap ctx = new HashMap(); + + ctx.put("basePackage", project.getProjectBasePackage()); + ctx.put("moduleName", project.getProjectName()); + ctx.put("tool", Tool.class); + ctx.put("dataBase", dataBase.toString()); + ctx.put("author", project.getProjectAuthor()); + ctx.put("dBmapper", dBmapper); + ctx.put("date", new Date()); + freeMarkerManager.outputTemp(new File(root.getAbsolutePath(), "application.properties"), option + "/test/application.properties", ctx); + Tool.outputResource(option + "/test/logback-config.xml", new File(root.getAbsolutePath(), "logback-config.xml")); + } + + /** + * 生成static + * + * @param root + * @param project + */ + public void generateStatic(File root, Project project, DataBase dataBase, String option) { + + HashMap ctx = new HashMap(); + ctx.put("basePackage", project.getProjectBasePackage()); + ctx.put("tool", Tool.class); + ctx.put("author", project.getProjectAuthor()); + ctx.put("date", new Date()); + ctx.put("modules", project.getModules()); + + File static_ = new File(root.getAbsolutePath(), "static"); + boolean mkdirs = static_.mkdirs(); + File css = new File(static_.getAbsolutePath(), "css"); + boolean mkdirs1 = css.mkdirs(); + File js = new File(static_.getAbsolutePath(), "js"); + boolean mkdirs2 = js.mkdirs(); + File img = new File(static_.getAbsolutePath(), "img"); + boolean mkdirs3 = img.mkdirs(); + + File dist = new File(static_.getAbsolutePath(), "dist"); + boolean mkdirs4 = dist.mkdirs(); + + {//css文件 + freeMarkerManager.outputTemp(new File(css.getAbsolutePath(), "base.css"), option + "/resources/static/css/base.css", ctx); + } + + {//js文件 + freeMarkerManager.outputTemp(new File(js.getAbsolutePath(), "ajax.js"), option + "/resources/static/js/ajax.ftl", ctx); + } + {//img + Tool.outputResource(option + "/resources/static/img/favicon.ico", new File(img.getAbsolutePath(), "favicon.ico")); + Tool.outputResource(option + "/resources/static/img/logo.png", new File(img.getAbsolutePath(), "logo.png")); + } + + {//dist文件 + + Tool.outputResource(option + "/resources/static/dist/lib.min.css", new File(dist.getAbsolutePath(), "lib.min.css")); + Tool.outputResource(option + "/resources/static/dist/lib.min.js", new File(dist.getAbsolutePath(), "lib.min.js")); + + + File fonts = new File(dist.getAbsolutePath(), "fonts"); + fonts.mkdirs(); + + Tool.outputResource(option + "/resources/static/dist/fonts/element-icons.woff", new File(fonts.getAbsolutePath(), "element-icons.woff")); + Tool.outputResource(option + "/resources/static/dist/fonts/w-e-icon.woff", new File(fonts.getAbsolutePath(), "w-e-icon.woff")); + + } + } + + /** + * 生成static + * + * @param root + * @param project + */ + public void generateTemplates(File root, Project project, DataBase dataBase, String option) { + {//生成 + File templates = new File(root.getAbsolutePath(), "templates"); + templates.mkdirs(); + + File control = new File(templates.getAbsolutePath(), "control"); + control.mkdirs(); + File layout = new File(templates.getAbsolutePath(), "layout"); + layout.mkdirs(); + File screen = new File(templates.getAbsolutePath(), "screen"); + screen.mkdirs(); + Tool.outputResource(option + "/resources/templates/control/nav.ftl", new File(control.getAbsolutePath(), "nav.ftl")); + Tool.outputResource(option + "/resources/templates/control/header.ftl", new File(control.getAbsolutePath(), "header.ftl")); + Tool.outputResource(option + "/resources/templates/control/footer.ftl", new File(control.getAbsolutePath(), "footer.ftl")); + Tool.outputResource(option + "/resources/templates/control/macro.ftl", new File(control.getAbsolutePath(), "macro.ftl")); + Tool.outputResource(option + "/resources/templates/layout/default.ftl", new File(layout.getAbsolutePath(), "default.ftl")); + Tool.outputResource(option + "/resources/templates/layout/wap.ftl", new File(layout.getAbsolutePath(), "wap.ftl")); + Tool.outputResource(option + "/resources/templates/screen/demo.ftl", new File(screen.getAbsolutePath(), "demo.ftl")); + Tool.outputResource(option + "/resources/templates/screen/index.ftl", new File(screen.getAbsolutePath(), "index.ftl")); + Tool.outputResource(option + "/resources/templates/403.ftl", new File(templates.getAbsolutePath(), "403.ftl")); + Tool.outputResource(option + "/resources/templates/404.ftl", new File(templates.getAbsolutePath(), "404.ftl")); + Tool.outputResource(option + "/resources/templates/500.ftl", new File(templates.getAbsolutePath(), "500.ftl")); + } + } + + public void generateTest(File root, Project project, DataBase dataBase, String option) { + + File config = new File(root.getAbsolutePath(), "config"); + config.mkdirs(); + + { + HashMap ctx = new HashMap(); + ctx.put("tool", Tool.class); + ctx.put("basePackage", project.getProjectBasePackage()); + ctx.put("moduleName", project.getProjectName()); + ctx.put("author", project.getProjectAuthor()); + ctx.put("date", new Date()); + freeMarkerManager.outputTemp(new File(config.getAbsolutePath(), "TestConfig" + ".java"), option + "/test/TestConfig.ftl", ctx); + } + + for (Module md : project.getModules()) { + File module = new File(root.getAbsolutePath(), md.getModuleName()); + module.mkdirs(); + + for (Table table : md.getTables()) { + HashMap ctx = new HashMap(); + + ctx.put("tool", Tool.class); + ctx.put("basePackage", md.getProjectBasePackage()); + ctx.put("moduleName", md.getModuleName()); + ctx.put("table", table); + ctx.put("author", md.getProjectAuthor()); + ctx.put("date", new Date()); + + freeMarkerManager.outputTemp(new File(module.getAbsolutePath(), Tool.lineToClassName(table.getTableName()) + "Test" + ".java"), option + "/test/test.ftl", ctx); + } + } + + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/manger/callable/SpringMVCMybatisCallable.java b/src/main/java/xyz/wbsite/dbtool/javafx/manger/callable/SpringMVCMybatisCallable.java new file mode 100644 index 00000000..4d05f0df --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/manger/callable/SpringMVCMybatisCallable.java @@ -0,0 +1,666 @@ +//package xyz.wbsite.dbtool.javafx.manger.callable; +// +//import xyz.wbsite.dbtool.javafx.enumeration.DataBase; +//import xyz.wbsite.dbtool.javafx.manger.ProjectManager; +//import xyz.wbsite.dbtool.javafx.manger.FreeMarkerManager; +//import xyz.wbsite.dbtool.javafx.manger.ManagerFactory; +//import xyz.wbsite.dbtool.javafx.manger.XmlManager; +//import xyz.wbsite.dbtool.javafx.po.AbstractDBmapper; +//import xyz.wbsite.dbtool.javafx.po.Module; +//import xyz.wbsite.dbtool.javafx.po.Table; +//import xyz.wbsite.dbtool.javafx.tool.Tool; +// +//import java.io.*; +//import java.util.ArrayList; +//import java.util.Date; +//import java.util.HashMap; +//import java.util.concurrent.Callable; +// +//import static xyz.wbsite.dbtool.javafx.tool.Tool.clear; +// +//public class SpringMVCMybatisCallable implements Callable { +// +// private String root; +// private DataBase dataBase; +// private Module md; +// private String option; +// private Tool tool = new Tool(); +// +// private FreeMarkerManager freeMarkerManager; +// +// public SpringMVCMybatisCallable(String root, DataBase dataBase, Module md, String option) { +// this.root = root; +// this.dataBase = dataBase; +// this.md = md; +// this.option = option; +// this.freeMarkerManager = ManagerFactory.getFreeMarkerManager(); +// } +// +// private AbstractDBmapper dBmapper; +// +// public Boolean call() throws Exception { +// +// File module = new File(root + File.separator + md.getModuleName()); +// if (!module.exists()) { +// module.mkdir(); +// } else { +// clear(module); +// } +// +// dBmapper = ProjectManager.dBmapper; +// +// String basePackage = md.getBasePackage(); +// +// String[] split = basePackage.split("\\."); +// +// System.out.println("生成模块:Pom"); +// generatePom(module, md, dataBase, option); +// StringBuffer stringBuffer = new StringBuffer(module.getAbsolutePath() + File.separator + "src" + File.separator + "main"); +// stringBuffer.append(File.separator).append("java"); +// for (String s : split) { +// stringBuffer.append(File.separator).append(s); +// } +// stringBuffer.append(File.separator).append(md.getModuleName()); +// +// File src = new File(stringBuffer.toString()); +// if (!src.exists()) { +// src.mkdirs(); +// } +// +// stringBuffer = new StringBuffer(module.getAbsolutePath() + File.separator + "src" + File.separator + "main"); +// stringBuffer.append(File.separator).append("resources"); +// File resources = new File(stringBuffer.toString()); +// if (!resources.exists()) { +// resources.mkdirs(); +// } +// +// stringBuffer = new StringBuffer(module.getAbsolutePath() + File.separator + "src" + File.separator + "main"); +// stringBuffer.append(File.separator).append("webapp"); +// File webapp = new File(stringBuffer.toString()); +// if (!webapp.exists()) { +// webapp.mkdirs(); +// } +// +// stringBuffer = new StringBuffer(module.getAbsolutePath()); +// stringBuffer.append(File.separator).append("src").append(File.separator).append("test").append(File.separator).append("java"); +// for (String s : split) { +// stringBuffer.append(File.separator).append(s); +// } +// +// File testSrc = new File(stringBuffer.toString()); +// if (!testSrc.exists()) { +// testSrc.mkdirs(); +// } +// +// stringBuffer = new StringBuffer(module.getAbsolutePath()); +// stringBuffer.append(File.separator).append("src").append(File.separator).append("test").append(File.separator).append("resources"); +// File testResources = new File(stringBuffer.toString()); +// if (!testResources.exists()) { +// testResources.mkdirs(); +// } +// +// //生成java文件 +// +// { +// //生成Controller +// System.out.println("生成模块:controller"); +// generateController(new File(src.getParentFile().getAbsolutePath() + File.separator + "controller"), md, dataBase, option); +// +// { +// //module +// System.out.println("生成模块:Entity"); +// generateEntity(new File(src.getAbsolutePath() + File.separator + "ent"), md, dataBase, option); +// System.out.println("生成模块:Enums"); +// generateEnums(new File(src.getAbsolutePath() + File.separator + "enums"), md, dataBase, option); +// System.out.println("生成模块:Filter"); +// generateFilter(new File(src.getAbsolutePath() + File.separator + "filter"), md, dataBase, option); +// System.out.println("生成模块:Mapper"); +// generateMapper(new File(src.getAbsolutePath() + File.separator + "mpr"), md, dataBase, option); +// System.out.println("生成模块:Manager"); +// generateManager(new File(src.getAbsolutePath() + File.separator + "mgr"), md, dataBase, option); +// System.out.println("生成模块:Requset"); +// generateRequset(new File(src.getAbsolutePath() + File.separator + "req"), md, dataBase, option); +// System.out.println("生成模块:Response"); +// generateResponse(new File(src.getAbsolutePath() + File.separator + "rsp"), md, dataBase, option); +// System.out.println("生成模块:framework"); +// +// } +// +// //framework +// System.out.println("生成模块:framework"); +// generateBase(new File(src.getParentFile().getAbsolutePath() + File.separator + "framework"), md, dataBase, option); +// +// } +// +// {//生成resources文件 +// System.out.println("生成模块:Resources"); +// generateResources(resources, md, dataBase, option); +// } +// +// {//生成webapp +// System.out.println("生成模块:Webapp"); +// generateWebapp(webapp, md, dataBase, option); +// } +// +// {//生成test 和 testResources +// System.out.println("生成模块:Test 和 TestResources"); +// generateResources(testResources, md, dataBase, option); +// generateTest(testSrc, md, dataBase, option); +// } +// System.out.println("finish"); +// return true; +// } +// +// /** +// * 生成POM.xml +// * +// * @param root +// * @param db +// */ +// public void generatePom(File root, Module db, DataBase dataBase, String option) { +// try { +// HashMap ctx = new HashMap(); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "pom.xml"), option + "/pom.ftl", ctx); +// } catch (Exception e) { +// +// } +// } +// +// /** +// * 生成entity +// * +// * @param root +// * @param db +// */ +// public void generateEntity(File root, Module db, DataBase dataBase, String option) { +// if (!root.exists()) { +// root.mkdirs(); +// } else { +// clear(root); +// } +// +// for (Table table : md.getTables()) { +// try { +// HashMap ctx = new HashMap(); +// ctx.put("tool", Tool.class); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("table", table); +// ctx.put("author", md.getAuthor()); +// ctx.put("date", new Date()); +// +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + ".java"), option + "/java/ent/entity.ftl", ctx); +// +// } catch (Exception e) { +// +// } +// } +// } +// +// /** +// * 生成Enums +// * +// * @param root +// * @param db +// */ +// public void generateEnums(File root, Module db, DataBase dataBase, String option) { +// if (!root.exists()) { +// root.mkdirs(); +// } else { +// clear(root); +// } +// +// try { +// HashMap ctx = new HashMap(); +// ctx.put("tool", Tool.class); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("author", md.getAuthor()); +// ctx.put("date", new Date()); +// +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "Type.java"), option + "/java/enums/Type.ftl", ctx); +// +// } catch (Exception e) { +// +// } +// +// } +// +// /** +// * 生成Filter +// * +// * @param root +// * @param db +// */ +// public void generateFilter(File root, Module db, DataBase dataBase, String option) { +// if (!root.exists()) { +// root.mkdirs(); +// } else { +// clear(root); +// } +// +// try { +// HashMap ctx = new HashMap(); +// +// ctx.put("tool", Tool.class); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "Authorizations" + ".java"), option + "/java/filter/Authorizations.ftl", ctx); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// +// } +// +// /** +// * 生成Mapper +// * +// * @param root +// * @param db +// */ +// public void generateMapper(File root, Module db, DataBase dataBase, String option) { +// if (!root.exists()) { +// root.mkdirs(); +// } else { +// clear(root); +// } +// HashMap ctx = new HashMap(); +// +// ctx.put("tool", Tool.class); +// ctx.put("db", db); +// ctx.put("dataBase", dataBase.toString()); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("author", md.getAuthor()); +// ctx.put("date", new Date()); +// +// for (Table table : md.getTables()) { +// try { +// ctx.put("table", table); +// +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "Mapper" + ".java"), option + "/java/mpr/mapperJava.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "Mapper" + ".xml"), option + "/java/mpr/mapper.ftl", ctx); +// +// } catch (Exception e) { +// +// } +// } +// } +// +// public void generateManager(File root, Module db, DataBase dataBase, String option) { +// if (!root.exists()) { +// root.mkdirs(); +// } else { +// clear(root); +// } +// try { +// HashMap ctx = new HashMap(); +// +// ctx.put("tool", Tool.class); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("author", md.getAuthor()); +// ctx.put("date", new Date()); +// +// for (Table table : md.getTables()) { +// ctx.put("table", table); +// +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "Manager" + ".java"), option + "/java/mgr/manager.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "ManagerImpl" + ".java"), option + "/java/mgr/managerImpl.ftl", ctx); +// } +// +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// /** +// * 生成Requset +// * +// * @param root +// * @param db +// */ +// public void generateRequset(File root, Module db, DataBase dataBase, String option) { +// if (!root.exists()) { +// root.mkdirs(); +// } else { +// clear(root); +// } +// +// try { +// +// HashMap ctx = new HashMap(); +// ctx.put("tool", Tool.class); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("author", md.getAuthor()); +// ctx.put("date", new Date()); +// +// for (Table table : md.getTables()) { +// ctx.put("table", table); +// +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "CreateRequest" + ".java"), option + "/java/req/createRequestClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "DeleteRequest" + ".java"), option + "/java/req/deleteRequestClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "UpdateRequest" + ".java"), option + "/java/req/updateRequestClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "FindRequest" + ".java"), option + "/java/req/findRequestClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "SearchRequest" + ".java"), option + "/java/req/searchRequestClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "GetAllRequest" + ".java"), option + "/java/req/GetAllRequestClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "GetRequest" + ".java"), option + "/java/req/getRequestClass.ftl", ctx); +// } +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// /** +// * 生成一般文件 +// * +// * @param root +// * @param db +// */ +// public void generateResponse(File root, Module db, DataBase dataBase, String option) { +// if (!root.exists()) { +// root.mkdirs(); +// } else { +// clear(root); +// } +// +// try { +// HashMap ctx = new HashMap(); +// ctx.put("tool", Tool.class); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("author", md.getAuthor()); +// ctx.put("date", new Date()); +// +// for (Table table : md.getTables()) { +// ctx.put("table", table); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "CreateResponse" + ".java"), option + "/java/rsp/createResponseClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "DeleteResponse" + ".java"), option + "/java/rsp/deleteResponseClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "UpdateResponse" + ".java"), option + "/java/rsp/updateResponseClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "FindResponse" + ".java"), option + "/java/rsp/findResponseClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "SearchResponse" + ".java"), option + "/java/rsp/searchResponseClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "GetAllResponse" + ".java"), option + "/java/rsp/GetAllResponseClass.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "GetResponse" + ".java"), option + "/java/rsp/getResponseClass.ftl", ctx); +// } +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// /** +// * 生成base类 +// * +// * @param root +// * @param db +// */ +// public void generateBase(File root, Module db, DataBase dataBase, String option) { +// if (!root.exists()) { +// root.mkdirs(); +// } else { +// clear(root); +// } +// try { +// HashMap ctx = new HashMap(); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("timestamp", new Date().getTime()); +// +// File base = new File(root.getAbsolutePath() + File.separator + "base"); +// base.mkdirs(); +// File freemarker = new File(root.getAbsolutePath() + File.separator + "freemarker"); +// freemarker.mkdirs(); +// File springmvc = new File(root.getAbsolutePath() + File.separator + "springmvc"); +// springmvc.mkdirs(); +// File utils = new File(root.getAbsolutePath() + File.separator + "utils"); +// utils.mkdirs(); +// +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "BaseEntity.java"), option + "/java/framework/base/BaseEntity.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "BaseFindRequest.java"), option + "/java/framework/base/BaseFindRequest.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "BaseFindResponse.java"), option + "/java/framework/base/BaseFindResponse.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "BaseGetAllRequest.java"), option + "/java/framework/base/BaseGetAllRequest.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "BaseRequest.java"), option + "/java/framework/base/BaseRequest.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "BaseResponse.java"), option + "/java/framework/base/BaseResponse.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "BaseSearchRequest.java"), option + "/java/framework/base/BaseSearchRequest.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "BaseUpdateRequest.java"), option + "/java/framework/base/BaseUpdateRequest.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "Error.java"), option + "/java/framework/base/Error.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "ErrorType.java"), option + "/java/framework/base/ErrorType.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "SortType.java"), option + "/java/framework/base/SortType.java", ctx); +// freeMarkerManager.outputTemp(new File(base.getAbsolutePath() + File.separator + "Token.java"), option + "/java/framework/base/Token.java", ctx); +// +// +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "AESUtil.java"), option + "/java/framework/utils/AESUtil.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "Base64Util.java"), option + "/java/framework/utils/Base64Util.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "CookieUtil.java"), option + "/java/framework/utils/CookieUtil.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "IDgenerator.java"), option + "/java/framework/utils/IDgenerator.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "LocalData.java"), option + "/java/framework/utils/LocalData.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "LogUtil.java"), option + "/java/framework/utils/LogUtil.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "MapperUtil.java"), option + "/java/framework/utils/MapperUtil.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "MD5Util.java"), option + "/java/framework/utils/MD5Util.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "Message.java"), option + "/java/framework/utils/Message.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "ProcessUtil.java"), option + "/java/framework/utils/ProcessUtil.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "RSAUtil.java"), option + "/java/framework/utils/RSAUtil.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "ValidationUtil.java"), option + "/java/framework/utils/ValidationUtil.java", ctx); +// freeMarkerManager.outputTemp(new File(utils.getAbsolutePath() + File.separator + "WebUtils.java"), option + "/java/framework/utils/WebUtils.java", ctx); +// +// +// freeMarkerManager.outputTemp(new File(freemarker.getAbsolutePath() + File.separator + "ViewNameTranslator.java"), option + "/java/framework/freemarker/ViewNameTranslator.java", ctx); +// freeMarkerManager.outputTemp(new File(freemarker.getAbsolutePath() + File.separator + "Layout.java"), option + "/java/framework/freemarker/Layout.java", ctx); +// freeMarkerManager.outputTemp(new File(freemarker.getAbsolutePath() + File.separator + "Url.java"), option + "/java/framework/freemarker/Url.java", ctx); +// +// freeMarkerManager.outputTemp(new File(springmvc.getAbsolutePath() + File.separator + "GlobalHandlerInterceptor.java"), option + "/java/framework/springmvc/GlobalHandlerInterceptor.java", ctx); +// freeMarkerManager.outputTemp(new File(springmvc.getAbsolutePath() + File.separator + "GlobalObjectMapper.java"), option + "/java/framework/springmvc/GlobalObjectMapper.java", ctx); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// /** +// * 生成Controller类 +// * +// * @param root +// * @param db +// */ +// public void generateController(File root, Module db, DataBase dataBase, String option) { +// if (!root.exists()) { +// root.mkdirs(); +// } else { +// clear(root); +// } +// try { +// HashMap ctx = new HashMap(); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("db", db); +// ctx.put("table", md.getTables()); +// ctx.put("author", md.getAuthor()); +// ctx.put("date", new Date()); +// +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "AjaxController.java"), option + "/java/controller/AjaxController.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "GlobalController.java"), option + "/java/controller/GlobalController.ftl", ctx); +// +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// /** +// * 生成Resources spring,spring-mvc,mybatis,jdbc +// * +// * @param root +// * @param db +// */ +// public void generateResources(File root, Module db, DataBase dataBase, String option) { +// try { +// HashMap ctx = new HashMap(); +// +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// if (root.getAbsolutePath().contains("test")) { +// ctx.put("isTest", true); +// } else { +// ctx.put("isTest", false); +// } +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "spring.xml"), option + "/resources/spring.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "spring-mvc.xml"), option + "/resources/spring-mvc.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "spring-mybatis.xml"), option + "/resources/spring-mybatis.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "logback.xml"), option + "/resources/logback.ftl", ctx); +// freeMarkerManager.outputTemp(new File(root.getAbsolutePath() + File.separator + "jdbc.properties"), option + "/resources/jdbc.properties.ftl", ctx); +// +// } catch (Exception e) { +// +// } +// +// if (!root.getAbsolutePath().contains("test")) { +// File tableDir = new File(root.getAbsolutePath() + File.separator + md.getModuleName() + "_table"); +// tableDir.mkdirs(); +// File dbtool = new File(root.getAbsolutePath() + File.separator + "dbtool"); +// dbtool.mkdirs(); +// { +// XmlManager xmlManager = ManagerFactory.getXmlManager(); +// ArrayList dbs = new ArrayList<>(); +// dbs.add(db); +// xmlManager.saveAs(dbtool.getAbsolutePath(), dbs); +// } +// +// try { +// HashMap ctx = new HashMap(); +// ctx.put("tool", Tool.class); +// ctx.put("dataBase", dataBase.toString()); +// ctx.put("db", db); +// ctx.put("author", md.getAuthor()); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("dBmapper", dBmapper); +// ctx.put("date", new Date()); +// +// for (Table table : md.getTables()) { +// ctx.put("table", table); +// freeMarkerManager.outputTemp(new File(tableDir.getAbsolutePath() + File.separator + table.getTableName() + ".sql"), option + "/resources/table.ftl", ctx); +// } +// } catch (Exception e) { +// +// } +// HashMap ctx = new HashMap(); +// ctx.put("tool", Tool.class); +// ctx.put("dataBase", dataBase.toString()); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("db", db); +// ctx.put("dBmapper", dBmapper); +// +// freeMarkerManager.outputTemp(new File(tableDir.getAbsolutePath() + File.separator + "ALL_TABLE.sql"), option + "/resources/tableAll.ftl", ctx); +// } +// } +// +// public void generateTest(File root, Module db, DataBase dataBase, String option) { +// File module = new File(root.getAbsolutePath() + File.separator + md.getModuleName()); +// module.mkdirs(); +// +// HashMap ctx = new HashMap(); +// ctx.put("tool", tool); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("date", new Date()); +// for (Table table : md.getTables()) { +// ctx.put("table", table); +// freeMarkerManager.outputTemp(new File(module.getAbsolutePath() + File.separator + Tool.lineToClassName(table.getTableName()) + "Test" + ".java"), option + "/test/test.ftl", ctx); +// } +// } +// +// /** +// * webapp文件夹及文件生成 +// * +// * @param root +// * @param db +// * @param option +// */ +// public void generateWebapp(File root, Module db, DataBase dataBase, String option) { +// HashMap ctx = new HashMap(); +// ctx.put("basePackage", md.getBasePackage()); +// ctx.put("moduleName", md.getModuleName()); +// ctx.put("tool", Tool.class); +// ctx.put("db", db); +// ctx.put("author", md.getAuthor()); +// ctx.put("date", new Date()); +// try { +// +// File static_ = new File(root.getAbsolutePath() + File.separator + "static"); +// boolean mkdirs = static_.mkdirs(); +// File css = new File(static_.getAbsolutePath() + File.separator + "css"); +// boolean mkdirs1 = css.mkdirs(); +// File dist = new File(static_.getAbsolutePath() + File.separator + "dist"); +// boolean mkdirs5 = dist.mkdirs(); +// File fonts = new File(static_.getAbsolutePath() + File.separator + "fonts"); +// boolean mkdirs6 = fonts.mkdirs(); +// File js = new File(static_.getAbsolutePath() + File.separator + "js"); +// boolean mkdirs2 = js.mkdirs(); +// File img = new File(static_.getAbsolutePath() + File.separator + "img"); +// boolean mkdirs3 = img.mkdirs(); +// +// File lib = new File(static_.getAbsolutePath() + File.separator + "lib"); +// boolean mkdirs4 = lib.mkdirs(); +// +// {//css文件 +// freeMarkerManager.outputTemp(new File(css.getAbsolutePath() + File.separator + "base.css"), option + "/webapp/static/css/base.css", ctx); +// } +// {//dist文件 +// +// Tool.outputResource(option + "/webapp/static/dist/lib.min.css", new File(dist.getAbsolutePath() + File.separator + "lib.min.css")); +// Tool.outputResource(option + "/webapp/static/dist/lib.min.js", new File(dist.getAbsolutePath() + File.separator + "lib.min.js")); +// +// +// Tool.outputResource(option + "/webapp/static/dist/fonts/element-icons.woff", new File(fonts.getAbsolutePath() + File.separator + "element-icons.woff")); +// Tool.outputResource(option + "/webapp/static/dist/fonts/w-e-icon.woff", new File(fonts.getAbsolutePath() + File.separator + "w-e-icon.woff")); +// +// } +// +// {//js文件 +// freeMarkerManager.outputTemp(new File(js.getAbsolutePath() + File.separator + "services.js"), option + "/webapp/static/js/services.ftl", ctx); +// } +// {//img +// Tool.outputResource(option + "/webapp/static/img/favicon.ico", new File(img.getAbsolutePath() + File.separator + "favicon.ico")); +// Tool.outputResource(option + "/webapp/static/img/logo.png", new File(img.getAbsolutePath() + File.separator + "logo.png")); +// } +// +// File WEB_INF_DIR = new File(root.getAbsolutePath() + File.separator + "WEB-INF"); +// WEB_INF_DIR.mkdirs(); +// +// {//生成WEB-INF下的web.xml等文件 +// freeMarkerManager.outputTemp(new File(WEB_INF_DIR.getAbsolutePath() + File.separator + "web.xml"), option + "/webapp/WEB-INF/web.ftl", ctx); +// } +// +// {//生成WEB-INF下的文件夹 +// File views = new File(root.getAbsolutePath() + File.separator + "WEB-INF" + File.separator + "views"); +// views.mkdirs(); +// Tool.outputResource(option + "/webapp/WEB-INF/views/index.ftl", new File(views.getAbsolutePath() + File.separator + "index.jsp")); +// +// File include = new File(views.getAbsolutePath() + File.separator + "include"); +// include.mkdirs(); +// Tool.outputResource(option + "/webapp/WEB-INF/views/include/top.ftl", new File(include.getAbsolutePath() + File.separator + "top.jsp")); +// Tool.outputResource(option + "/webapp/WEB-INF/views/include/foot.ftl", new File(include.getAbsolutePath() + File.separator + "foot.jsp")); +// +// File ftl = new File(root.getAbsolutePath() + File.separator + "WEB-INF" + File.separator + "ftl"); +// ftl.mkdirs(); +// File control = new File(ftl.getAbsolutePath() + File.separator + "control"); +// control.mkdirs(); +// File layout = new File(ftl.getAbsolutePath() + File.separator + "layout"); +// layout.mkdirs(); +// File screen = new File(ftl.getAbsolutePath() + File.separator + "screen"); +// screen.mkdirs(); +// Tool.outputResource(option + "/webapp/WEB-INF/ftl/control/header.ftl", new File(control.getAbsolutePath() + File.separator + "header.ftl")); +// Tool.outputResource(option + "/webapp/WEB-INF/ftl/control/footer.ftl", new File(control.getAbsolutePath() + File.separator + "footer.ftl")); +// Tool.outputResource(option + "/webapp/WEB-INF/ftl/control/macro.ftl", new File(control.getAbsolutePath() + File.separator + "macro.ftl")); +// Tool.outputResource(option + "/webapp/WEB-INF/ftl/layout/default.ftl", new File(layout.getAbsolutePath() + File.separator + "default.ftl")); +// Tool.outputResource(option + "/webapp/WEB-INF/ftl/screen/index.ftl", new File(screen.getAbsolutePath() + File.separator + "index.ftl")); +// } +// +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +//} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/po/AbstractDBmapper.java b/src/main/java/xyz/wbsite/dbtool/javafx/po/AbstractDBmapper.java new file mode 100644 index 00000000..e32323e2 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/po/AbstractDBmapper.java @@ -0,0 +1,25 @@ +package xyz.wbsite.dbtool.javafx.po; + +import xyz.wbsite.dbtool.javafx.enumeration.DataBase; +import xyz.wbsite.dbtool.javafx.enumeration.FieldType; + +public abstract class AbstractDBmapper { + DataBase mDataBase = null; + + private AbstractDBmapper(){ + + } + + public AbstractDBmapper(DataBase mDataBase) { + this.mDataBase = mDataBase; + } + + DataBase getDataBase(){ + return mDataBase; + } + + public abstract String getDataBaseType(FieldType type,int lenght); + public abstract String getDataBaseType(FieldType type); + abstract String getFieldSql(Field field); + public abstract FieldType getType(String type, int lenght, int precision, int scale); +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/po/Api.java b/src/main/java/xyz/wbsite/dbtool/javafx/po/Api.java new file mode 100644 index 00000000..8a233b7b --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/po/Api.java @@ -0,0 +1,107 @@ +package xyz.wbsite.dbtool.javafx.po; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Api { + private boolean check; + + //目标请求对象 + private String targetRequest; + //目标请求响应 + private String targetResponse; + //方法 + private String method; + + private File req; + private File rsp; + + private Set depReq = new HashSet<>(); + private Set depEnt = new HashSet<>(); + private Set depEnum = new HashSet<>(); + + private String error; + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public boolean isCheck() { + return check; + } + + public void setCheck(boolean check) { + this.check = check; + } + + public String getTargetRequest() { + return targetRequest; + } + + public void setTargetRequest(String targetRequest) { + this.targetRequest = targetRequest; + } + + public String getTargetResponse() { + return targetResponse; + } + + public void setTargetResponse(String targetResponse) { + this.targetResponse = targetResponse; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public File getReq() { + return req; + } + + public void setReq(File req) { + this.req = req; + } + + public File getRsp() { + return rsp; + } + + public void setRsp(File rsp) { + this.rsp = rsp; + } + + public Set getDepReq() { + return depReq; + } + + public void setDepReq(Set depReq) { + this.depReq = depReq; + } + + public Set getDepEnt() { + return depEnt; + } + + public void setDepEnt(Set depEnt) { + this.depEnt = depEnt; + } + + public Set getDepEnum() { + return depEnum; + } + + public void setDepEnum(Set depEnum) { + this.depEnum = depEnum; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/po/DTreeItem.java b/src/main/java/xyz/wbsite/dbtool/javafx/po/DTreeItem.java new file mode 100644 index 00000000..d80175b7 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/po/DTreeItem.java @@ -0,0 +1,16 @@ +package xyz.wbsite.dbtool.javafx.po; + +import javafx.scene.control.TreeItem; + + +public class DTreeItem extends TreeItem { + private String id; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/po/Field.java b/src/main/java/xyz/wbsite/dbtool/javafx/po/Field.java new file mode 100644 index 00000000..07d1b3d6 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/po/Field.java @@ -0,0 +1,229 @@ +package xyz.wbsite.dbtool.javafx.po; + +import org.springframework.util.StringUtils; +import xyz.wbsite.dbtool.javafx.enumeration.FieldType; +import xyz.wbsite.dbtool.javafx.tool.Tool; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Field extends Table { + + public Field() { + } + + public Field(String fieldName) { + this.fieldName = fieldName; + } + + /** + * 字段名 + */ + private String fieldName; + + /** + * 字段类型 + */ + private FieldType fieldType = FieldType.String_var50; + /** + * 字段长度 + */ + private int fieldLength = 0; + + /** + * 字段注释 + */ + private String fieldComment = null; + + /** + * 默认值 + */ + private String defaultValue = null; + + /** + * 是否可为NULL + */ + private Boolean isMust = false; + + /** + * 是否是主键 + */ + private Boolean isPrimaryKey = false; + /** + * 是否作为查询条件 + */ + private Boolean isQuery = false; + + + private Boolean isSearch = false; + + private Boolean isSystem = false; + + public String getTestValue() { + String value = ""; + if (fieldType.name().matches("String_\\d+")) { + Pattern compile = Pattern.compile("String_(\\d+)"); + Matcher matcher = compile.matcher(fieldType.name()); + + if (matcher.find()) { + int len = Integer.parseInt(matcher.group(1)); + + if (StringUtils.isEmpty(this.fieldComment)) { + StringBuilder sb = new StringBuilder(""); + for (int i = 0; i < len; i++) { + sb.append("A"); + } + value = sb.toString(); + } else { + value = "\"" + this.fieldComment.substring(0, this.fieldComment.length() > this.fieldLength ? this.fieldLength : this.fieldComment.length()) + "\""; + } + + } + } else if (fieldType.name().matches("String_var\\d+")) { + Pattern compile = Pattern.compile("String_var(\\d+)"); + Matcher matcher = compile.matcher(fieldType.name()); + + if (matcher.find()) { + int len = Integer.parseInt(matcher.group(1)); + + if (StringUtils.isEmpty(this.fieldComment)) { + StringBuilder sb = new StringBuilder(""); + sb.append("\""); + sb.append("A"); + sb.append("\""); + value = sb.toString(); + } else { + value = "\"" + this.fieldComment.substring(0, this.fieldComment.length() > this.fieldLength ? this.fieldLength : this.fieldComment.length()) + "\""; + } + + } + } else if (fieldType.name().equals("String_var")) { + int len = fieldLength; + if (StringUtils.isEmpty(this.fieldComment)) { + StringBuilder sb = new StringBuilder(""); + sb.append("\""); + sb.append("A"); + sb.append("\""); + value = sb.toString(); + } else { + value = "\"" + this.fieldComment.substring(0, this.fieldComment.length() > this.fieldLength ? this.fieldLength : this.fieldComment.length()) + "\""; + } + + } else if (fieldType.name().matches("Boolean")) { + value = "true"; + } else if (fieldType.name().matches("Byte|Short|Integer")) { + value = "1"; + } else if (fieldType.name().matches("Bytes")) { + value = "null"; + } else if (fieldType.name().matches("Long")) { + value = "1L"; + } else if (fieldType.name().matches("Float")) { + value = "1.0f"; + } else if (fieldType.name().matches("Double")) { + value = "1.0"; + } else if (fieldType.name().matches("Character")) { + value = "'A'"; + } else if (fieldType.name().matches("Date")) { + value = "new Date()"; + } else if (fieldType.name().matches("Date")) { + value = "new Date()"; + } else if (fieldType.name().matches("BigDecimal")) { + value = "new BigDecimal()"; + } else if (fieldType.name().matches("String_super")) { + value = "\"content\""; + } + return value; + } + + public Boolean getIsSearch() { + return isSearch; + } + + public void setIsSearch(Boolean isSearch) { + this.isSearch = isSearch; + } + + public Boolean getIsSystem() { + return isSystem; + } + + public void setIsSystem(Boolean isSystem) { + this.isSystem = isSystem; + } + + public String getterName() { + return "get" + Tool.lineToClassName(this.fieldName); + } + + public String setterName() { + return "set" + Tool.lineToClassName(this.fieldName); + } + + public Boolean getIsQuery() { + return isQuery; + } + + public void setIsQuery(Boolean isQuery) { + this.isQuery = isQuery; + } + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public FieldType getFieldType() { + return fieldType; + } + + public void setFieldType(FieldType fieldType) { + this.fieldType = fieldType; + } + + public Integer getFieldLength() { + return fieldLength; + } + + public void setFieldLength(Integer fieldLength) { + this.fieldLength = fieldLength; + } + + public String getFieldComment() { + return fieldComment; + } + + public void setFieldComment(String fieldComment) { + this.fieldComment = fieldComment != null ? fieldComment : ""; + } + + public String getDefaultValue() { + return defaultValue; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public Boolean getIsMust() { + return isMust; + } + + public void setIsMust(Boolean isMust) { + this.isMust = isMust; + } + + public Boolean getIsPrimaryKey() { + return isPrimaryKey; + } + + public void setIsPrimaryKey(Boolean isPrimaryKey) { + this.isPrimaryKey = isPrimaryKey; + } + + public String getFName() { + return Tool.lineToFieldName(this.fieldName); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/po/Module.java b/src/main/java/xyz/wbsite/dbtool/javafx/po/Module.java new file mode 100644 index 00000000..3f38c77d --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/po/Module.java @@ -0,0 +1,111 @@ +package xyz.wbsite.dbtool.javafx.po; + +import javafx.scene.control.TreeItem; + +import java.util.ArrayList; +import java.util.List; + +public class Module extends TreeItem { + public Module() { + } + + public Module(String moduleName) { + this.moduleName = moduleName; + this.setValue(moduleName); + setExpanded(true); + } + + /** + * 模块注释 + */ + private String moduleComment; + + /** + * 模块前缀 + */ + private String modulePrefix; + + /** + * 对象 + */ + private List tables = new ArrayList(); + + private String moduleName; + private boolean hasSysFields; + private String projectName; + private String projectBasePackage; + private String projectAuthor; + + public boolean isHasSysFields() { + return hasSysFields; + } + + public void setHasSysFields(boolean hasSysFields) { + this.hasSysFields = hasSysFields; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + this.setValue(moduleName); + } + + public boolean putTable(Table table) { + if (tables == null) { + tables = new ArrayList
(); + } + tables.add(table); + return true; + } + + public List
getTables() { + return tables; + } + + public void setTables(List
tables) { + this.tables = tables; + } + + public String getModuleComment() { + return moduleComment; + } + + public void setModuleComment(String moduleComment) { + this.moduleComment = moduleComment; + } + + public String getModulePrefix() { + return modulePrefix; + } + + public void setModulePrefix(String modulePrefix) { + this.modulePrefix = modulePrefix!=null?modulePrefix:""; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public String getProjectBasePackage() { + return projectBasePackage; + } + + public void setProjectBasePackage(String projectBasePackage) { + this.projectBasePackage = projectBasePackage; + } + + public String getProjectAuthor() { + return projectAuthor; + } + + public void setProjectAuthor(String projectAuthor) { + this.projectAuthor = projectAuthor; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/po/MySqlDBmapper.java b/src/main/java/xyz/wbsite/dbtool/javafx/po/MySqlDBmapper.java new file mode 100644 index 00000000..d384a7d1 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/po/MySqlDBmapper.java @@ -0,0 +1,232 @@ +package xyz.wbsite.dbtool.javafx.po; + +import xyz.wbsite.dbtool.javafx.enumeration.DataBase; +import xyz.wbsite.dbtool.javafx.enumeration.FieldType; + +public class MySqlDBmapper extends AbstractDBmapper { + + public MySqlDBmapper(DataBase mDataBase) { + super(mDataBase); + } + + @Override + public String getDataBaseType(FieldType type, int lenght) { + if (FieldType.Boolean.name().equals(type.name())) { + return "BIT"; + } else if (FieldType.Byte.name().equals(type.name())) { + return "TINYINT"; + } else if (FieldType.Short.name().equals(type.name())) { + return "SMALLINT"; + } else if (FieldType.Integer.name().equals(type.name())) { + return "INTEGER"; + } else if (FieldType.Long.name().equals(type.name())) { + return "NUMERIC"; + } else if (FieldType.Float.name().equals(type.name())) { + return "REAL"; + } else if (FieldType.Double.name().equals(type.name())) { + return "FLOAT"; + } else if (FieldType.Character.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_1.name().equals(type.name())) { + return "CAHR"; + } else if (FieldType.String_10.name().equals(type.name())) { + return "CAHR"; + } else if (FieldType.String_var.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var50.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var100.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var255.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var500.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var2500.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var4000.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.Date.name().equals(type.name())) { + return "DATE"; + } else if (FieldType.Bytes.name().equals(type.name())) { + return "BLOB"; + } else { + return ""; + } + } + + @Override + public String getFieldSql(Field field) { + StringBuffer sb = new StringBuffer(""); + sb.append("`").append(field.getFieldName()).append("` "); + + FieldType type = field.getFieldType(); + + if (FieldType.Boolean.name().equals(type.name())) { + sb.append("TINYINT(1)"); + } else if (FieldType.Byte.name().equals(type.name())) { + sb.append("TINYINT(3)"); + } else if (FieldType.Short.name().equals(type.name())) { + sb.append("SMALLINT(5)"); + } else if (FieldType.Integer.name().equals(type.name())) { + sb.append("INTEGER(10)"); + } else if (FieldType.Long.name().equals(type.name())) { + sb.append("BIGINT(20)"); + } else if (FieldType.Float.name().equals(type.name())) { + sb.append("FLOAT"); + } else if (FieldType.Double.name().equals(type.name())) { + sb.append("DOUBLE"); + } else if (FieldType.Date.name().equals(type.name())) { + sb.append("DATETIME"); + } else if (FieldType.Bytes.name().equals(type.name())) { + sb.append("BLOB"); + } else if (FieldType.String_1.name().equals(type.name())) { + sb.append("CHAR(1)"); + } else if (FieldType.String_10.name().equals(type.name())) { + sb.append("CHAR(10)"); + } else if (FieldType.String_var.name().equals(type.name())) { + Integer fieldLength = field.getFieldLength(); + sb.append("VARCHAR(" + fieldLength + ")"); + } else if (FieldType.String_var50.name().equals(type.name())) { + sb.append("VARCHAR(50)"); + } else if (FieldType.String_var100.name().equals(type.name())) { + sb.append("VARCHAR(100)"); + } else if (FieldType.String_var255.name().equals(type.name())) { + sb.append("VARCHAR(250)"); + } else if (FieldType.String_var500.name().equals(type.name())) { + sb.append("VARCHAR(500)"); + } else if (FieldType.String_var2500.name().equals(type.name())) { + sb.append("VARCHAR(2500)"); + } else if (FieldType.String_var4000.name().equals(type.name())) { + sb.append("VARCHAR(4000)"); + } else if (FieldType.String_super.name().equals(type.name())) { + sb.append("TEXT"); + } + + if (!field.getIsSystem() && field.getIsMust() && (field.getDefaultValue() == null || field.getDefaultValue().toUpperCase().equals("NULL"))) { + sb.append(" NOT NULL"); + } else if (!field.getIsSystem() && field.getIsMust() && field.getDefaultValue() != null && !field.getDefaultValue().toUpperCase().equals("NULL")) { + if (field.getFieldType().name().contains("String")) {//默认字符 + sb.append(" NOT NULL").append(" DEFAULT '" + field.getDefaultValue() + "'"); + } else {//不是字符就是数字,目前只考虑两张情况 + sb.append(" NOT NULL").append(" DEFAULT " + field.getDefaultValue() + ""); + } + } else if (field.getIsSystem() && field.getFieldName().equals("ID")) { + sb.append(" NOT NULL"); + } else if (field.getIsSystem() && field.getFieldName().equals("ROW_VERSION")) { + sb.append(" NOT NULL").append(" DEFAULT 0"); + } else if (field.getIsSystem() && field.getFieldName().equals("IS_DELETED")) { + sb.append(" NOT NULL").append(" DEFAULT 0"); + } else if (field.getIsSystem() && field.getFieldName().equals("CREATE_BY")) { + sb.append(" NOT NULL"); + } else if (field.getIsSystem() && field.getFieldName().equals("CREATE_TIME")) { + sb.append(" NOT NULL"); + } else if (field.getIsSystem() && field.getFieldName().equals("LAST_UPDATE_BY")) { + sb.append(" DEFAULT NULL"); + } else if (field.getIsSystem() && field.getFieldName().equals("LAST_UPDATE_TIME")) { + sb.append(" DEFAULT NULL"); + } + + if (field.getFieldComment() != null) { + sb.append(" COMMENT '" + field.getFieldComment() + "'"); + } + return sb.toString(); + } + + @Override + DataBase getDataBase() { + return super.getDataBase(); + } + + @Override + public String getDataBaseType(FieldType type) { + if (FieldType.Boolean.name().equals(type.name())) { + return "TINYINT"; + } else if (FieldType.Byte.name().equals(type.name())) { + return "TINYINT"; + } else if (FieldType.Short.name().equals(type.name())) { + return "SMALLINT"; + } else if (FieldType.Integer.name().equals(type.name())) { + return "INTEGER"; + } else if (FieldType.Long.name().equals(type.name())) { + return "NUMERIC"; + } else if (FieldType.Float.name().equals(type.name())) { + return "REAL"; + } else if (FieldType.Double.name().equals(type.name())) { + return "FLOAT"; + } else if (FieldType.Character.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_1.name().equals(type.name())) { + return "CHAR"; + } else if (FieldType.String_10.name().equals(type.name())) { + return "CHAR"; + } else if (FieldType.String_var.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var50.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var100.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var255.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var500.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var2500.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.String_var4000.name().equals(type.name())) { + return "VARCHAR"; + } else if (FieldType.Date.name().equals(type.name())) { + return "DATETIME"; + } else if (FieldType.Bytes.name().equals(type.name())) { + return "BLOB"; + } else { + return ""; + } + } + + @Override + public FieldType getType(String type, int lenght, int precision, int scale) { + if ("bigint".equals(type)) { + return FieldType.Long; + } else if ("varchar".equals(type) && lenght == 50) { + return FieldType.String_var50; + } else if ("varchar".equals(type) && lenght == 100) { + return FieldType.String_var100; + } else if ("varchar".equals(type) && lenght == 255) { + return FieldType.String_var255; + } else if ("varchar".equals(type) && lenght == 500) { + return FieldType.String_var500; + } else if ("varchar".equals(type) && lenght == 2500) { + return FieldType.String_var2500; + } else if ("varchar".equals(type) && lenght == 4000) { + return FieldType.String_var4000; + } else if ("varchar".equals(type)) { + return FieldType.String_var; + } else if ("date".equals(type)) { + return FieldType.Date; + } else if ("datetime".equals(type)) { + return FieldType.Date; + } else if ("timestamp".equals(type)) { + return FieldType.Date; + } else if ("char".equals(type) && lenght == 1) { + return FieldType.String_1; + } else if ("char".equals(type) && lenght == 10) { + return FieldType.String_10; + } else if ("char".equals(type)) { + return FieldType.String_var; + } else if ("tinyint".equals(type)) { + return FieldType.Integer; + } else if ("smallint".equals(type)) { + return FieldType.Integer; + } else if ("mediumint".equals(type)) { + return FieldType.Integer; + } else if ("int".equals(type)) { + return FieldType.Integer; + } else if ("bigint".equals(type)) { + return FieldType.Long; + } else if ("float".equals(type)) { + return FieldType.Float; + } else if ("double".equals(type)) { + return FieldType.Double; + } + return FieldType.String_var50; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/po/OracleDBmapper.java b/src/main/java/xyz/wbsite/dbtool/javafx/po/OracleDBmapper.java new file mode 100644 index 00000000..ef62e88b --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/po/OracleDBmapper.java @@ -0,0 +1,209 @@ +package xyz.wbsite.dbtool.javafx.po; + +import xyz.wbsite.dbtool.javafx.enumeration.DataBase; +import xyz.wbsite.dbtool.javafx.enumeration.FieldType; + +public class OracleDBmapper extends AbstractDBmapper { + + @Override + public String getFieldSql(Field field) { + StringBuffer sb = new StringBuffer(""); + sb.append("\"").append(field.getFieldName()).append("\" "); + + FieldType type = field.getFieldType(); + + if (FieldType.Boolean.name().equals(type.name())) { + sb.append("CHAR(1)"); + } else if (FieldType.Byte.name().equals(type.name())) { + sb.append("NUMBER(3)"); + } else if (FieldType.Short.name().equals(type.name())) { + sb.append("NUMBER(5)"); + } else if (FieldType.Integer.name().equals(type.name())) { + sb.append("NUMBER(10)"); + } else if (FieldType.Long.name().equals(type.name())) { + sb.append("NUMBER(19)"); + } else if (FieldType.Float.name().equals(type.name())) { + sb.append("NUMBER"); + } else if (FieldType.Double.name().equals(type.name())) { + sb.append("NUMBER"); + } else if (FieldType.Date.name().equals(type.name())) { + sb.append("DATE"); + } else if (FieldType.Bytes.name().equals(type.name())) { + sb.append("BLOB"); + } else if (FieldType.String_1.name().equals(type.name())) { + sb.append("CHAR(1)"); + } else if (FieldType.String_10.name().equals(type.name())) { + sb.append("CHAR(10)"); + } else if (FieldType.String_var.name().equals(type.name())) { + Integer fieldLength = field.getFieldLength(); + sb.append("VARCHAR2(" + fieldLength + ")"); + } else if (FieldType.String_var50.name().equals(type.name())) { + sb.append("VARCHAR2(50)"); + } else if (FieldType.String_var100.name().equals(type.name())) { + sb.append("VARCHAR2(100)"); + } else if (FieldType.String_var255.name().equals(type.name())) { + sb.append("VARCHAR2(250)"); + } else if (FieldType.String_var500.name().equals(type.name())) { + sb.append("VARCHAR2(500)"); + } else if (FieldType.String_var2500.name().equals(type.name())) { + sb.append("VARCHAR2(2500)"); + } else if (FieldType.String_var4000.name().equals(type.name())) { + sb.append("VARCHAR2(4000)"); + } else if (FieldType.String_super.name().equals(type.name())) { + //Oracle中LONG最大支持2G字节 + sb.append("LONG"); + } + + if (field.getIsMust() && field.getIsSystem()) { + sb.append(" NOT NULL"); + } else { + sb.append(" NULL"); + } + return sb.toString(); + } + + public OracleDBmapper(DataBase mDataBase) { + super(mDataBase); + } + + @Override + public String getDataBaseType(FieldType type, int lenght) { + if (FieldType.Boolean.name().equals(type.name())) { + return "CHAR"; + } else if (FieldType.Byte.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Short.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Integer.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Long.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Float.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Double.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Date.name().equals(type.name())) { + return "TIMESTAMP"; + } else if (FieldType.Bytes.name().equals(type.name())) { + return "BLOB"; + } else if (FieldType.String_1.name().equals(type.name())) { + return "CHAR"; + } else if (FieldType.String_10.name().equals(type.name())) { + return "CHAR"; + } else if (FieldType.String_var.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var50.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var100.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var255.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var500.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var2500.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var4000.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_super.name().equals(type.name())) { + //Oracle中LONG最大支持2G字节 + return "LONG"; + } + return ""; + } + + @Override + public String getDataBaseType(FieldType type) { + if (FieldType.Boolean.name().equals(type.name())) { + return "CHAR"; + } else if (FieldType.Byte.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Short.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Integer.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Long.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Float.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Double.name().equals(type.name())) { + return "NUMBER"; + } else if (FieldType.Date.name().equals(type.name())) { + return "TIMESTAMP"; + } else if (FieldType.Bytes.name().equals(type.name())) { + return "BLOB"; + } else if (FieldType.String_1.name().equals(type.name())) { + return "CHAR"; + } else if (FieldType.String_10.name().equals(type.name())) { + return "CHAR"; + } else if (FieldType.String_var.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var50.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var255.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var500.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var2500.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_var4000.name().equals(type.name())) { + return "VARCHAR2"; + } else if (FieldType.String_super.name().equals(type.name())) { + //Oracle中LONG最大支持2G字节 + return "LONG"; + } + return ""; + } + + public FieldType getType(String type, int lenght, int precision, int scale) { + if ("CHAR".equals(type) && lenght == 1) { + return FieldType.String_1; + } else if ("CHAR".equals(type) && lenght == 10) { + return FieldType.String_10; + } else if ("CHAR".equals(type)) { + return FieldType.String_var; + } else if ("VARCHAR".equals(type) && lenght == 50) { + return FieldType.String_var50; + } else if ("NVARCHAR".equals(type)) { + return FieldType.String_var50; + } else if ("VARCHAR2".equals(type) && lenght == 50) { + return FieldType.String_var50; + } else if ("VARCHAR2".equals(type) && lenght == 100) { + return FieldType.String_var100; + } else if ("VARCHAR2".equals(type) && lenght == 255) { + return FieldType.String_var255; + } else if ("VARCHAR2".equals(type) && lenght == 500) { + return FieldType.String_var500; + } else if ("VARCHAR2".equals(type) && lenght == 2500) { + return FieldType.String_var2500; + } else if ("VARCHAR2".equals(type) && lenght == 4000) { + return FieldType.String_var4000; + } else if ("VARCHAR2".equals(type)) { + return FieldType.String_var; + } else if ("NVARCHAR2".equals(type)) { + return FieldType.String_var100; + } else if ("CLOB".equals(type)) { + return FieldType.String_var50; + } else if ("NCLOB".equals(type)) { + return FieldType.String_var50; + } else if ("LONG".equals(type)) { + return FieldType.String_super; + } else if ("NUMBER".equals(type)) { + if (precision > 18 && scale == 0) { + return FieldType.Long; + } else if (precision >= 10 && precision <= 18 && scale == 0) { + return FieldType.Long; + } else if (precision >= 1 && precision <= 9 && scale == 0) { + return FieldType.Integer; + } else if (scale > 0) { + return FieldType.Double; + } else { + return FieldType.Long; + } + } else if ("DATE".equals(type)) { + return FieldType.Date; + } else if ("TIMESTAMP".equals(type)) { + return FieldType.Date; + } + return FieldType.String_var50; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/po/Project.java b/src/main/java/xyz/wbsite/dbtool/javafx/po/Project.java new file mode 100644 index 00000000..632dd2bf --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/po/Project.java @@ -0,0 +1,69 @@ +package xyz.wbsite.dbtool.javafx.po; + +import javafx.scene.control.TreeItem; + +import java.util.ArrayList; +import java.util.List; + +public class Project extends TreeItem{ + + public Project() { + this.projectName = "EXAMPLE-WEB"; + this.projectBasePackage = "com.example"; + this.projectAuthor = "author"; + } + + public Project(String projectName) { + this.projectName = projectName; + setValue(projectName); + setExpanded(true); + } + + private String projectName; + private String projectBasePackage; + private String projectAuthor; + + /** + * 对象 + */ + private List modules = new ArrayList(); + + public boolean putModule(Module module) { + modules.add(module); + this.getChildren().add(module); + return true; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + this.setValue(projectName); + } + + public String getProjectBasePackage() { + return projectBasePackage; + } + + public void setProjectBasePackage(String projectBasePackage) { + this.projectBasePackage = projectBasePackage; + } + + public String getProjectAuthor() { + return projectAuthor; + } + + public void setProjectAuthor(String projectAuthor) { + this.projectAuthor = projectAuthor; + } + + public List getModules() { + return modules; + } + + public void setModules(List modules) { + this.modules = modules; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/po/Table.java b/src/main/java/xyz/wbsite/dbtool/javafx/po/Table.java new file mode 100644 index 00000000..542b1217 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/po/Table.java @@ -0,0 +1,186 @@ +package xyz.wbsite.dbtool.javafx.po; + +import javafx.scene.control.TreeItem; +import xyz.wbsite.dbtool.javafx.tool.Tool; + +import java.util.ArrayList; +import java.util.List; + +public class Table extends TreeItem { + private Module dBhandle; + + public Table() { + } + + public Table(String tableName) { + this.tableName = tableName; + setValue(tableName); + setExpanded(true); + } + + public Table(String tableName, String tableComment) { + this.tableName = tableName; + this.tableComment = tableComment; + } + + /** + * 对象名 + */ + private String tableName; + + /** + * 对象注释 + */ + private String tableComment; + + private Boolean create = true; + private Boolean delete = true; + private Boolean update = true; + private Boolean find = true; + private Boolean get = true; + private Boolean search = false; + private Boolean getAll = false; + + /** + * 对象字段 + */ + private List fields = new ArrayList(); + + public boolean has(String type) { + for (Field field : fields) { + if (field.getFieldType().name().equals(type) && !field.getIsSystem()) { + return true; + } + } + return false; + } + + public String getImport() { + StringBuilder sb = new StringBuilder(""); + if (has("Date")) { + sb.append("import java.util.Date;\n"); + } + if (has("BigDecimal")) { + sb.append("import java.math.BigDecimal;\n"); + } + + return sb.toString(); + } + + public boolean putField(Field field) { + if (fields == null) { + fields = new ArrayList(); + } + fields.add(field); + return true; + } + + public boolean putFirstField(Field field) { + if (fields == null) { + fields = new ArrayList(); + } + fields.add(0, field); + return true; + } + + public String getCName() { + return Tool.lineToClassName(this.tableName); + } + + public String getFName() { + return Tool.lineToFieldName(this.tableName); + } + + public String getLName() { + return Tool.lineToLPoint(this.tableName); + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + setValue(tableName); + } + + public String getTableComment() { + return tableComment; + } + + public void setTableComment(String tableComment) { + this.tableComment = tableComment!=null?tableComment:""; + } + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + public Module getdBhandle() { + return dBhandle; + } + + public void setdBhandle(Module dBhandle) { + this.dBhandle = dBhandle; + } + + public Boolean getCreate() { + return create; + } + + public void setCreate(Boolean create) { + this.create = create; + } + + public Boolean getDelete() { + return delete; + } + + public void setDelete(Boolean delete) { + this.delete = delete; + } + + public Boolean getUpdate() { + return update; + } + + public void setUpdate(Boolean update) { + this.update = update; + } + + public Boolean getFind() { + return find; + } + + public void setFind(Boolean find) { + this.find = find; + } + + public Boolean getGet() { + return get; + } + + public void setGet(Boolean get) { + this.get = get; + } + + public Boolean getSearch() { + return search; + } + + public void setSearch(Boolean search) { + this.search = search; + } + + public Boolean getGetAll() { + return getAll; + } + + public void setGetAll(Boolean getAll) { + this.getAll = getAll; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/tool/Dialog.java b/src/main/java/xyz/wbsite/dbtool/javafx/tool/Dialog.java new file mode 100644 index 00000000..eab32e9e --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/tool/Dialog.java @@ -0,0 +1,569 @@ +package xyz.wbsite.dbtool.javafx.tool; + +import xyz.wbsite.dbtool.Application; +import xyz.wbsite.dbtool.javafx.ctrl.ConnectInfoController; +import xyz.wbsite.dbtool.javafx.ctrl.GenerateOptionController; +import xyz.wbsite.dbtool.javafx.ctrl.SdkInfoController; +import xyz.wbsite.dbtool.javafx.enumeration.DataBase; +import xyz.wbsite.dbtool.javafx.listener.GenerateOptionListener; +import xyz.wbsite.dbtool.javafx.manger.ProjectManager; +import xyz.wbsite.dbtool.javafx.manger.ManagerFactory; +import xyz.wbsite.dbtool.javafx.po.Api; +import xyz.wbsite.dbtool.javafx.po.Module; +import javafx.application.Platform; +import javafx.beans.value.ChangeListener; +import javafx.beans.value.ObservableValue; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.event.ActionEvent; +import javafx.event.EventHandler; +import javafx.fxml.FXMLLoader; +import javafx.geometry.Insets; +import javafx.geometry.Pos; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.layout.VBox; +import javafx.stage.DirectoryChooser; +import javafx.stage.Modality; +import javafx.stage.Stage; +import javafx.stage.WindowEvent; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class Dialog { + + private static Stage popup; + + public static void showTimedDialog(final long time, String message) { + popup = new Stage(); + popup.setAlwaysOnTop(true); + popup.initModality(Modality.APPLICATION_MODAL); + final Button closeBtn = new Button("知道了"); + closeBtn.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + popup.close(); + } + }); + + VBox root = new VBox(); + root.setPadding(new Insets(20)); + root.setAlignment(Pos.BASELINE_CENTER); + root.setSpacing(20); + root.getChildren().addAll(new Label(message), closeBtn); + Scene scene = new Scene(root); + popup.setScene(scene); + popup.setTitle("提示信息"); + popup.show(); + + Thread thread = new Thread() { + @Override + public void run() { + try { + Thread.sleep(time); + if (popup.isShowing()) { + Platform.runLater(new Runnable() { + @Override + public void run() { + popup.close(); + } + }); + } + } catch (Exception exp) { + exp.printStackTrace(); + } + } + }; + thread.setDaemon(true); + thread.start(); + } + + public static void showConfirmDialog(String message) { + popup = new Stage(); + popup.setAlwaysOnTop(true); + popup.initModality(Modality.APPLICATION_MODAL); + final Button closeBtn = new Button("确认"); + closeBtn.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + popup.close(); + } + }); + + VBox root = new VBox(); + root.setPadding(new Insets(20)); + root.setAlignment(Pos.BASELINE_CENTER); + root.setSpacing(20); + Label label = new Label(message); + root.getChildren().addAll(label, closeBtn); + Scene scene = new Scene(root); + popup.setScene(scene); + popup.setTitle("提示信息"); + popup.show(); + } + + public static void showError(String message) { + Platform.runLater(new Runnable() { + public void run() { + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle("错误"); + alert.setHeaderText(""); + alert.setContentText(message); + alert.showAndWait(); + } + }); + } + + public static void showSuccess(String message) { + Platform.runLater(new Runnable() { + public void run() { + Alert alert = new Alert(Alert.AlertType.INFORMATION); + alert.setTitle("消息"); + alert.setHeaderText(""); + alert.setContentText(message); + alert.showAndWait(); + } + }); + } + + public static void showProgress(String message) { + if (popup != null) { + popup.close(); + } + popup = new Stage(); + popup.setAlwaysOnTop(true); + popup.initModality(Modality.APPLICATION_MODAL); + + ProgressIndicator indicator = new ProgressIndicator(); + indicator.setPrefSize(30, 30); + + VBox root = new VBox(); + root.setPadding(new Insets(50, 80, 50, 80)); + root.setAlignment(Pos.BASELINE_CENTER); + root.setSpacing(20); + + Label label = new Label(message); + root.getChildren().addAll(indicator, label); + Scene scene = new Scene(root); + + popup.setOnCloseRequest(new EventHandler() { + @Override + public void handle(WindowEvent event) { + event.consume(); + } + }); + popup.setScene(scene); + popup.setTitle("提示"); + popup.show(); + } + + public static void stopPopup() { + if (popup != null) { + Platform.runLater(new Runnable() { + @Override + public void run() { + popup.close(); + } + }); + } + } + + public static void showGenerateOption(GenerateOptionListener listener) { + FXMLLoader dbdetailloader = new FXMLLoader(Application.class.getResource("../../../fxml/generateOption.fxml")); + try { + dbdetailloader.load(); + } catch (IOException e) { + return; + } + Parent root = dbdetailloader.getRoot(); + GenerateOptionController controller = dbdetailloader.getController(); + controller.setListener(listener); + controller.getCancel().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + stopPopup(); + } + }); + controller.getOk().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + listener.onGenerate(controller.getType(), DataBase.valueOf(controller.getDataBase().toUpperCase())); + } + }); + + popup = new Stage(); + popup.setAlwaysOnTop(true); + popup.initModality(Modality.APPLICATION_MODAL); + + Scene scene = new Scene(root); + + popup.setOnCloseRequest(new EventHandler() { + @Override + public void handle(WindowEvent event) { + stopPopup(); + } + }); + popup.setScene(scene); + popup.setTitle("配置"); + popup.show(); + } + + public static void showDBConnectInput() { + Stage stage = new Stage(); + stage.setAlwaysOnTop(true); + stage.initModality(Modality.APPLICATION_MODAL); + + FXMLLoader dbdetailloader = new FXMLLoader(Application.class.getResource("../../../fxml/connectInfo.fxml")); + try { + dbdetailloader.load(); + Parent root = dbdetailloader.getRoot(); + Scene scene = new Scene(root); + stage.setScene(scene); + stage.setTitle("连接信息"); + + ConnectInfoController controller = dbdetailloader.getController(); + + ChoiceBox databaseType = controller.getDatabaseType(); + ObservableList data = FXCollections.observableArrayList(); + data.add("Orcale"); + data.add("Mysql"); + databaseType.setItems(data); + databaseType.setValue("Orcale"); + databaseType.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + String value = (String) databaseType.getValue(); + + if ("Orcale".equals(value)) { + controller.getDriver().setText("oracle.jdbc.OracleDriver"); + controller.getUrl().setText("jdbc:oracle:thin:@127.0.0.1:1521:orcl"); + } else if ("Mysql".equals(value)) { + controller.getDriver().setText("com.mysql.jdbc.Driver"); + controller.getUrl().setText("jdbc:mysql://127.0.0.1:3306/tableName"); + } + } + }); + + TextField driver = controller.getDriver(); + driver.setText(Info.orcle.driver); + TextField url = controller.getUrl(); + url.setText(Info.orcle.url); + + Button test = controller.getTest(); + test.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + String type = (String) controller.getDatabaseType().getValue(); + String driver = controller.getDriver().getText(); + String url = controller.getUrl().getText(); + String userName = controller.getUserName().getText(); + String password = controller.getPassword().getText(); + + Map map = new HashMap(); + map.put("type", type); + map.put("url", url); + map.put("username", userName); + map.put("password", password); + map.put("driverClassName", driver); + boolean b = ProjectManager.testConnect(map); + if (b) { + Dialog.showConfirmDialog("连接成功!"); + } else { + Dialog.showConfirmDialog("连接失败!"); + } + } + }); + Button load = controller.getLoad(); + load.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + String type = (String) controller.getDatabaseType().getValue(); + String driver = controller.getDriver().getText(); + String url = controller.getUrl().getText(); + String userName = controller.getUserName().getText(); + String password = controller.getPassword().getText(); + + if (driver == null || driver.equals("")) { + Dialog.showConfirmDialog("驱动名称不能为空!"); + return; + } else if (url == null || url.equals("")) { + Dialog.showConfirmDialog("连接不能为空!"); + return; + } else if (userName == null || userName.equals("")) { + Dialog.showConfirmDialog("用户名不能为空!"); + return; + } else if (password == null || password.equals("")) { + Dialog.showConfirmDialog("密码不能为空!"); + return; + } + + for (Module db : ManagerFactory.getdBManager().getMds()) { + if (db.getModuleName().equals(userName)) { + Dialog.showConfirmDialog("已经存的模块!"); + return; + } + } + + Map map = new HashMap(); + map.put("type", type); + map.put("url", url); + map.put("username", userName); + map.put("password", password); + map.put("driverClassName", driver); + + Dialog.showProgress("加载中,请稍等..."); + new Thread() { + @Override + public void run() { + if (popup.isShowing() && ProjectManager.loadMD(map)) { + Platform.runLater(new Runnable() { + @Override + public void run() { + Dialog.stopPopup(); + stage.close(); + } + }); + } + } + }.start(); + } + }); + Button cancel = controller.getCancel(); + cancel.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + stage.close(); + } + }); + + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void showApi() { + Stage stage = new Stage(); + stage.initModality(Modality.APPLICATION_MODAL); + + FXMLLoader dbdetailloader = new FXMLLoader(Application.class.getResource("../../../fxml/api.fxml")); + try { + dbdetailloader.load(); + Parent root = dbdetailloader.getRoot(); + Scene scene = new Scene(root); + + stage.setScene(scene); + stage.setTitle("API生成"); + + SdkInfoController controller = dbdetailloader.getController(); + TextField modulePath = controller.getModulePath(); + TextField sdkPath = controller.getSdkPath(); + TableView apis = controller.getApis(); + + controller.getSelectModulePath().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + DirectoryChooser directoryChooser = new DirectoryChooser(); + Stage stage = new Stage(); + stage.setAlwaysOnTop(true); + File file = directoryChooser.showDialog(stage); + + if (file == null) { + return; + } + modulePath.setText(file.getAbsolutePath()); + + + File api = new File(sdkPath.getText()); + sdkPath.setText(new File(api.getParentFile().getAbsolutePath(),file.getName()+"-api").getAbsolutePath()); + + + System.out.println(file.getAbsolutePath()); + } + }); + + controller.getSelectSdkPath().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + DirectoryChooser directoryChooser = new DirectoryChooser(); + Stage stage = new Stage(); + File file = directoryChooser.showDialog(stage); + + if (file == null) { + return; + } + String text = modulePath.getText(); + File moduleFile = new File(text); + + sdkPath.setText(new File(file.getAbsolutePath(),moduleFile.getName()+"-api").getAbsolutePath()); + System.out.println(file.getAbsolutePath()); + } + }); + + controller.getAll().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + check(controller, controller.getAll().isSelected(), ""); + } + }); + controller.getApi().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + check(controller, controller.getApi().isSelected(), ".api."); + } + }); + controller.getCreate().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + check(controller, controller.getCreate().isSelected(), ".create"); + } + }); + controller.getDelete().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + check(controller, controller.getDelete().isSelected(), ".delete"); + } + }); + controller.getUpdate().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + check(controller, controller.getUpdate().isSelected(), ".update"); + } + }); + controller.getFind().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + check(controller, controller.getFind().isSelected(), ".find"); + } + }); + controller.getSearch().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + check(controller, controller.getSearch().isSelected(), ".search"); + } + }); + controller.getGet().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + check(controller, controller.getGet().isSelected(), ".get"); + } + }); + controller.getGetAll().setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + check(controller, controller.getGetAll().isSelected(), ".get.all"); + } + }); + + sdkPath.requestFocus(); + modulePath.textProperty().addListener(new ChangeListener() { + @Override + public void changed(ObservableValue observable, String oldValue, String newValue) { + controller.load(); + } + }); + + ProjectManager dBmanger = ManagerFactory.getdBManager(); + String path = dBmanger.getPath(); + + File file = new File(path); + File[] files = file.listFiles(); + s: + for (File f : files) { + if (!f.getName().contains(".")) { + File modul = findModul(f); + if (modul == null) { + modulePath.setText(""); + sdkPath.setText(""); + } else { + modulePath.setText(modul.getAbsolutePath()); + sdkPath.setText(new File(f.getParentFile().getAbsolutePath(),modul.getName() + "-api").getAbsolutePath()); + break s; + } + + } + } + + Button start = controller.getStart(); + start.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + String module = controller.getModulePath().getText(); + String sdk = controller.getSdkPath().getText(); + + if (new File(module).exists()) { + Dialog.showProgress("生成中..."); + dBmanger.generateSDK(new File(module), new File(sdk), controller.getData()); + Dialog.stopPopup(); + Platform.runLater(new Runnable() { + @Override + public void run() { + stage.close(); + } + }); + } else { + Dialog.showConfirmDialog("项目不存在!"); + } + } + }); + + Button cancel = controller.getCancel(); + cancel.setOnAction(new EventHandler() { + @Override + public void handle(ActionEvent event) { + stage.close(); + } + }); + + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void check(SdkInfoController controller, boolean check, String key) { + for (Api api : controller.getData()) { + if (api.getMethod().endsWith(key) || (key.equals(".api.") && api.getMethod().contains(".api."))) { + api.setCheck(check); + } + } + controller.initData(); + } + + private static boolean hasChild(File file, String child) { + if (file == null || child == null || "".equals(child) || file.listFiles() == null) { + return false; + } + + for (File f : file.listFiles()) { + if (f.getName().equals(child)) { + return true; + } + } + + return false; + } + + private static File findModul(File file) { + if (file == null) { + return null; + } else if (hasChild(file, "ent") && hasChild(file, "req") && hasChild(file, "rsp")) { + return file; + } + + if (file.listFiles() != null) { + for (File f : file.listFiles()) { + File modul = findModul(f); + if (modul != null) { + return modul; + } + } + } + + return null; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/tool/Info.java b/src/main/java/xyz/wbsite/dbtool/javafx/tool/Info.java new file mode 100644 index 00000000..27b6a880 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/tool/Info.java @@ -0,0 +1,24 @@ +package xyz.wbsite.dbtool.javafx.tool; + +public class Info { + static DBInfo orcle = new DBInfo(); + static DBInfo mysql = new DBInfo(); + + static { + orcle.url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; + orcle.userName = "userName"; + orcle.password = ""; + orcle.driver = "oracle.jdbc.OracleDriver"; + mysql.url = "jdbc:mysql://119.23.203.111:3306/test"; + mysql.userName = "userName"; + mysql.password = ""; + mysql.driver = "com.mysql.jdbc.Driver"; + } + +} +class DBInfo{ + String url; + String userName; + String password; + String driver; +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/tool/JavaClassReader.java b/src/main/java/xyz/wbsite/dbtool/javafx/tool/JavaClassReader.java new file mode 100644 index 00000000..b84fc5dc --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/tool/JavaClassReader.java @@ -0,0 +1,236 @@ +package xyz.wbsite.dbtool.javafx.tool; + +import java.io.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class JavaClassReader { + private File javaClass; + + private String packageName; + private String domainName; + private String moduleName; + private List annotationList; + private List importList; + private String className; + private String fatherName; + private List body; + private boolean hasList = false; + private String findOrSearchflag = "0"; + private String Tclass = null; + + public JavaClassReader(File javaClass) throws IOException { + this.javaClass = javaClass; + importList = new ArrayList<>(); + annotationList = new ArrayList<>(); + domainName = ""; + read(); + } + + private void read() throws IOException { + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(javaClass), "utf-8")); + + int step = 1;//1-读取package,2-读取import,3-读取类注释,4-读取类名、父类,5-读取类体 + + String line = null; + StringBuffer zs = new StringBuffer(); + StringBuffer sb = new StringBuffer(); + while ((line = bufferedReader.readLine()) != null) { + if (line.startsWith("package")) { + packageName = line; + + String s = line.replaceAll("package ", ""); + s = s.replaceAll(";", ""); + String[] split = s.split("\\."); + + if ("req".equals(split[split.length - 1]) || "rsp".equals(split[split.length - 1])|| "ent".equals(split[split.length - 1])) { + moduleName = split[split.length - 2]; + for (int i = 0; i < split.length - 2; i++) { + domainName += split[i] + "."; + } + domainName = domainName.substring(0, domainName.length() - 1); + } + + continue; + } + if (line.startsWith("import")) { + if (!line.contains("framework")) { + if (line.contains(".ent.")){ + line = line.replaceAll("\\.ent\\.",".entity."); + } + importList.add(line); + } + + continue; + } + if (line.contains("/**") || line.contains("*") || line.contains("*/")) { + if (zs != null) { + zs.append(line + "\n"); + annotationList.add(line); + if (line.contains("*/")) { + zs = null; + } + } + } + if (line.contains("class")) { + line = line.replaceAll("\\{", " { "); + line = line.replaceAll("}", " } "); + line = line.replaceAll("\\s+", " "); + String[] split = line.split("\\s"); + for (int i = 0; i < split.length; i++) { + if ("class".equals(split[i])) { + className = split[i + 1]; + } + if ("extends".equals(split[i])) { + fatherName = split[i + 1]; + + if (fatherName.contains("FindResponse") || fatherName.contains("GetAllResponse")){ + hasList = true; + + Pattern pattern = Pattern.compile("<(.*?)>"); + Matcher matcher = pattern.matcher(fatherName); + if (matcher.find()){ + String group = matcher.group(1); + Tclass = group; + } + } + if (fatherName.contains("FindRequest")){ + findOrSearchflag = "1"; + }else if( fatherName.contains("SearchRequest")){ + findOrSearchflag = "2"; + }else { + findOrSearchflag = "0"; + } + } + } + } + sb.append(line + "\n"); + } + + body = new ArrayList<>(Arrays.asList(sb.substring(sb.indexOf("{")).split("\n"))); + + for (int i = 0; i < body.size(); i++) { + if (body.get(i).contains("{")) { + body.set(i, body.get(i).replaceAll("\\{", "")); + String s = body.get(i); + if (s.length() <= 1){ + body.remove(i); + } + break; + } + } + for (int i = body.size() - 1; i >= 0; i--) { + if (body.get(i).contains("}")) { + body.set(i, body.get(i).replaceAll("}", "")); + break; + } + } + + bufferedReader.close(); + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public List getAnnotationList() { + return annotationList; + } + + public void setAnnotationList(List annotationList) { + this.annotationList = annotationList; + } + + public List getImportList() { + return importList; + } + + public void setImportList(List importList) { + this.importList = importList; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public String getFatherName() { + return fatherName; + } + + public void setFatherName(String fatherName) { + this.fatherName = fatherName; + } + + public List getBody() { + return body; + } + + public void setBody(List body) { + this.body = body; + } + + public File getJavaClass() { + return javaClass; + } + + public void setJavaClass(File javaClass) { + this.javaClass = javaClass; + } + + public boolean isHasList() { + return hasList; + } + + public void setHasList(boolean hasList) { + this.hasList = hasList; + } + + public String getTclass() { + return Tclass; + } + + public String getFindOrSearchflag() { + return findOrSearchflag; + } + + public void setFindOrSearchflag(String findOrSearchflag) { + this.findOrSearchflag = findOrSearchflag; + } + + public void setTclass(String tclass) { + Tclass = tclass; + } + + public static void main(String[] args) throws IOException { + JavaClassReader javaClassReader = new JavaClassReader(new File("C:\\dbtool\\auth\\src\\main\\java\\edu\\services\\auth\\rsp\\FileFindResponse.java")); + + System.out.println(); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/tool/JavaEnumReader.java b/src/main/java/xyz/wbsite/dbtool/javafx/tool/JavaEnumReader.java new file mode 100644 index 00000000..b3bba1d1 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/tool/JavaEnumReader.java @@ -0,0 +1,153 @@ +package xyz.wbsite.dbtool.javafx.tool; + +import java.io.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class JavaEnumReader { + private File javaClass; + + private String packageName; + private String domainName; + private String moduleName; + private List annotationList; + private String className; + private List body; + + public JavaEnumReader(File javaClass) throws IOException { + this.javaClass = javaClass; + annotationList = new ArrayList<>(); + domainName = ""; + read(); + } + + private void read() throws IOException { + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(javaClass), "utf-8")); + + int step = 1;//1-读取package,2-读取import,3-读取类注释,4-读取类名、父类,5-读取类体 + + String line = null; + StringBuffer zs = new StringBuffer(); + StringBuffer sb = new StringBuffer(); + while ((line = bufferedReader.readLine()) != null) { + if (line.startsWith("package")) { + packageName = line; + + String s = line.replaceAll("package ", ""); + s = s.replaceAll(";", ""); + String[] split = s.split("\\."); + + if ("enums".equals(split[split.length - 1])) { + moduleName = split[split.length - 2]; + for (int i = 0; i < split.length - 2; i++) { + domainName += split[i] + "."; + } + domainName = domainName.substring(0, domainName.length() - 1); + } + + continue; + } + + if (line.contains("/**") || line.contains("*") || line.contains("*/")) { + if (zs != null) { + zs.append(line + "\n"); + annotationList.add(line); + if (line.contains("*/")) { + zs = null; + } + } + } + if (line.contains("enum")) { + line = line.replaceAll("\\{", " { "); + line = line.replaceAll("}", " } "); + line = line.replaceAll("\\s+", " "); + String[] split = line.split("\\s"); + for (int i = 0; i < split.length; i++) { + if ("enum".equals(split[i])) { + className = split[i + 1]; + } + } + } + sb.append(line + "\n"); + } + + body = new ArrayList<>(Arrays.asList(sb.substring(sb.indexOf("{")).split("\n"))); + + for (int i = 0; i < body.size(); i++) { + if (body.get(i).contains("{")) { + body.set(i, body.get(i).replaceAll("\\{", "")); + break; + } + } + for (int i = body.size() - 1; i > 0; i--) { + if (body.get(i).contains("}")) { + body.set(i, body.get(i).replaceAll("\\}", "")); + break; + } + } + + bufferedReader.close(); + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public List getAnnotationList() { + return annotationList; + } + + public void setAnnotationList(List annotationList) { + this.annotationList = annotationList; + } + + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public List getBody() { + return body; + } + + public void setBody(List body) { + this.body = body; + } + + public File getJavaClass() { + return javaClass; + } + + public void setJavaClass(File javaClass) { + this.javaClass = javaClass; + } + + public static void main(String[] args) throws IOException { + JavaEnumReader javaClassReader = new JavaEnumReader(new File("C:\\dbtool\\example\\src\\main\\java\\com\\example\\example\\enums\\Type.java")); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/javafx/tool/Tool.java b/src/main/java/xyz/wbsite/dbtool/javafx/tool/Tool.java new file mode 100644 index 00000000..f0029b9a --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/javafx/tool/Tool.java @@ -0,0 +1,356 @@ +package xyz.wbsite.dbtool.javafx.tool; + +import java.io.*; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Tool { + + public static final char UNDERLINE = '_'; + + /** + * abbCdd --> abb_cdd + * + * @param param + * @return + */ + public static String camelToUnderline(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + int len = param.length(); + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + char c = param.charAt(i); + if (Character.isUpperCase(c)) { + sb.append(UNDERLINE); + sb.append(Character.toLowerCase(c)); + } else { + sb.append(c); + } + } + return sb.toString().toUpperCase(); + } + + /** + * abbCdd --> abb.cdd + * AbbCdd --> abb.cdd + * + * @param param + * @return + */ + public static String camelToPoint(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + param = Character.toLowerCase(param.charAt(0)) + param.substring(1, param.length()); + int len = param.length(); + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + char c = param.charAt(i); + if (Character.isUpperCase(c)) { + sb.append("."); + sb.append(Character.toLowerCase(c)); + } else { + sb.append(c); + } + } + return sb.toString().toLowerCase(); + } + + + /** + * FileCreateRequest -> file + * + * @param requestName + * @return + */ + public static String getRequestTarget(String requestName) { + if (requestName.contains("GetAllRequest")) { + return Abb2abb(requestName.substring(0, requestName.indexOf("GetAllRequest"))); + } + if (requestName.startsWith("Api")) { + return "api"; + } + + String s = camelToPoint(requestName); + String[] split = s.split("\\."); + if (split.length > 2) { + String target = split[0]; + for (int i = 1; i < split.length - 2; i++) { + target += abb2Abb(split[i]); + } + return target; + } + return ""; + } + + /** + * FileCreateRequest -> create + * + * @param requestName + * @return + */ + public static String getRequestAction(String requestName) { + String s = camelToPoint(requestName); + + if (requestName.contains("GetAllRequest")) { + return "getAll"; + } + if (requestName.startsWith("Api")) { + return Abb2abb(requestName.substring(3, requestName.indexOf("Request"))); + } + + String[] split = s.split("\\."); + if (split.length > 2) { + String action = split[split.length - 2]; + return action; + } + return ""; + } + + /** + * @param param + * @return + */ + public static String Abb2abb(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + param = Character.toLowerCase(param.charAt(0)) + param.substring(1, param.length()); + return param; + } + + public static String abb2Abb(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + param = Character.toUpperCase(param.charAt(0)) + param.substring(1, param.length()); + return param; + } + + /** + * 下划线转首字母大写驼峰式 + * ABB_CDD --> AbbCdd + * + * @param param + * @return + */ + public static String lineToClassName(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + //全部转小写 + param = param.toLowerCase(); + int len = param.length(); + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + char c = param.charAt(i); + if (c == UNDERLINE) { + if (++i < len) { + sb.append(Character.toUpperCase(param.charAt(i))); + } + } else { + sb.append(c); + } + } + //首字符转大写 + return (new StringBuilder()).append(Character.toUpperCase(sb.charAt(0))).append(sb.substring(1)).toString(); + } + + /** + * 下划线转首字母小写驼峰样式 + * ABB_CDD --> abbCdd + * + * @param param + * @return + */ + public static String lineToFieldName(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + //全部转小写 + param = param.toLowerCase(); + int len = param.length(); + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + char c = param.charAt(i); + if (c == UNDERLINE) { + if (++i < len) { + sb.append(Character.toUpperCase(param.charAt(i))); + } + } else { + sb.append(c); + } + } + return sb.toString(); + } + + /** + * 下划线转首字母小写驼峰样式 + * ABB_CDD --> abbcdd + * + * @param param + * @return + */ + public static String lineToLowercase(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + //全部转小写 + param = param.toLowerCase(); + int len = param.length(); + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + char c = param.charAt(i); + if (c == UNDERLINE) { + + } else { + sb.append(c); + } + } + return sb.toString(); + } + + /** + * 下划线转点分割小写样式 + * ABB_CDD --> abb.cdd + * + * @param param + * @return + */ + public static String lineToLPoint(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + //全部转小写 + param = param.toLowerCase(); + int len = param.length(); + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { + char c = param.charAt(i); + if (c == UNDERLINE) { + sb.append("."); + } else { + sb.append(c); + } + } + return sb.toString(); + } + + public static String lineToCamel2(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + StringBuilder sb = new StringBuilder(param); + Matcher mc = Pattern.compile("_").matcher(param); + int i = 0; + while (mc.find()) { + int position = mc.end() - (i++); + //String.valueOf(Character.toUpperCase(sb.charAt(position))); + sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase()); + } + return sb.toString(); + } + + public static String pointToPath(String param) { + if (param == null || "".equals(param.trim())) { + return ""; + } + + return param.replaceAll("\\.", "/"); + } + + public static String print(String param) { + return param; + } + + public static void outputResource(String url, File file) { + if (!file.exists()) { + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + return; + } + } + if (url != null && url.startsWith("/")) { + url = url.substring(1); + } + url = "modules/" + url; + + InputStream resourceAsStream = null; + FileOutputStream fileOutputStream = null; + try { + URL resource = Tool.class.getClassLoader().getResource("/"); + resourceAsStream = Tool.class.getClassLoader().getResourceAsStream(url); + fileOutputStream = new FileOutputStream(file); + if (resourceAsStream == null) { + resourceAsStream = Tool.class.getResourceAsStream("../../../../" + url); + } + + int b = -1; + + while ((b = resourceAsStream.read()) != -1) { + fileOutputStream.write(b); + } + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + resourceAsStream.close(); + } catch (IOException e) { + } + try { + fileOutputStream.close(); + } catch (IOException e) { + } + } + } + + public static void clear(File f) { + clear(f, ".idea|.*iml"); + } + + /** + * @param f 目录 + * @param exclude 排除 + */ + public static void clear(File f, String exclude) { + if (f.isDirectory()) { + File[] files = f.listFiles(new FileFilter() { + @Override + public boolean accept(File pathname) { + if (exclude == null) { + return true; + } + return !pathname.getName().matches(exclude); + } + }); + for (File file : files) { + if (file.isDirectory()) { + clear(file, exclude); + System.out.println("删除文件夹" + file.getName() + (file.delete() ? "成功" : "失败")); + } else { + System.out.println("删除" + file.getName() + (file.delete() ? "成功" : "失败")); + } + } + } + } + + public static void exchange(List list, int i, int j) { + Object o1 = list.get(i); + Object o2 = list.get(j); + + list.add(i, o2); + list.remove(i + 1); + list.add(j, o1); + list.remove(j + 1); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/controller/AjaxController.java b/src/main/java/xyz/wbsite/dbtool/web/controller/AjaxController.java new file mode 100644 index 00000000..2e7aea54 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/controller/AjaxController.java @@ -0,0 +1,70 @@ +package xyz.wbsite.dbtool.web.controller; + +import xyz.wbsite.dbtool.web.framework.LocalData; +import xyz.wbsite.dbtool.web.framework.Message; +import xyz.wbsite.dbtool.web.framework.base.BaseResponse; +import xyz.wbsite.dbtool.web.framework.base.Error; +import xyz.wbsite.dbtool.web.framework.base.ErrorType; +import xyz.wbsite.dbtool.web.framework.base.Token; +import xyz.wbsite.dbtool.web.framework.utils.LogUtil; +import xyz.wbsite.dbtool.web.framework.utils.MapperUtil; +import com.fasterxml.jackson.core.TreeNode; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class AjaxController { + + @RequestMapping("/ajax") + public BaseResponse ajax(@RequestParam("method") String method, HttpServletRequest request, HttpServletResponse response) { + + BaseResponse baseResponse = new BaseResponse(); + String line = null; + TreeNode treeNode = null; + try { + if (method == null) { + baseResponse.addError(new xyz.wbsite.dbtool.web.framework.base.Error(ErrorType.BUSINESS_ERROR, "请求方法不能为空!")); + return baseResponse; + } + Token token = LocalData.getToken(); + if (token == null) { + token = LocalData.getTempToken(); + } + if (!token.hasResource(method)) { + baseResponse.addError(new Error(ErrorType.BUSINESS_ERROR, "无权调用该接口!")); + return baseResponse; + } + + InputStreamReader isr = new InputStreamReader(request.getInputStream()); + BufferedReader in = new BufferedReader(isr); + line = in.readLine(); + treeNode = MapperUtil.toTree(line); + + switch (method) { + // 创建注释 + case "ajax.example.user.create": +// baseResponse = createUser(treeNode, token); + break; + default: + baseResponse.addError(ErrorType.INVALID_PARAMETER, Message.NOT_EXIST_METHOD); + break; + } + + } catch (Exception ex) { + baseResponse.addError(ErrorType.SYSTEM_ERROR, Message.ERROR_500); + LogUtil.dumpException(ex); + } finally { + if (baseResponse.hasError()) { + LogUtil.e("请求方法" + method + ", 请求参数:" + line); + LogUtil.e("返回结果包含异常" + MapperUtil.toJson(baseResponse)); + } + } + return baseResponse; + } + + +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/controller/GlobalController.java b/src/main/java/xyz/wbsite/dbtool/web/controller/GlobalController.java new file mode 100644 index 00000000..355b2462 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/controller/GlobalController.java @@ -0,0 +1,77 @@ +package xyz.wbsite.dbtool.web.controller; + +import xyz.wbsite.dbtool.web.framework.utils.LogUtil; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; + +@Controller +@ControllerAdvice +public class GlobalController { + + /** + * 全局异常捕捉 + * + * @param request + * @param response + * @param exception 要捕获的异常 + * @return + */ + @ExceptionHandler(Exception.class) + public String excepitonHandler(HttpServletRequest request, HttpServletResponse response, Model model, Exception exception) { + StringBuffer msg = new StringBuffer(""); + if (exception != null) { + msg = new StringBuffer(""); + String message = exception.toString(); + int length = exception.getStackTrace().length; + if (length > 0) { + msg.append("").append(message).append("
"); + for (int i = 0; i < length; i++) { + msg.append("").append(exception.getStackTrace()[i]).append("
"); + } + } else { + msg.append(message); + } + } + model.addAttribute("msg", msg.toString()); + return "500"; + } + + /** + * 当未明确指定控制器时,走该请求,默认返回对应的layout布局和screen视图 + * + * @param model + * @param request + */ + @RequestMapping("**^\\.*") + public void hold(HttpServletRequest request, HttpServletResponse response, Model model) { + + LogUtil.i("未明确指定控制器访问路径:" + request.getRequestURI()); + + //todo 可在此获取公共部分数据,例如用户信息等。其他业务数据在页面渲染后通过Ajax请求 + } + + /** + * 当需要使用layout时,不需要返回值,ViewNameTranslator会处理对应关系 + * + * @param model + * @param request + */ + @RequestMapping({"/", "index"}) + public void index(Model model, HttpServletRequest request) throws Exception { + model.addAttribute("hello", "Hello world!!!"); + model.addAttribute("status", 0); + + ArrayList citys = new ArrayList<>(); + citys.add("北京"); + citys.add("上海"); + citys.add("深圳"); + model.addAttribute("citys", citys); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/IDgenerator.java b/src/main/java/xyz/wbsite/dbtool/web/framework/IDgenerator.java new file mode 100644 index 00000000..2fd64cb7 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/IDgenerator.java @@ -0,0 +1,94 @@ +package xyz.wbsite.dbtool.web.framework; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * IDgenerator - ID生成器 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class IDgenerator { + + private static long workerId = 1L; + private static long datacenterId = 1L; + private static long sequence = 0L; + // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动) + private static long twepoch = 1531130104852L; + // 机器标识位数 + private static long workerIdBits = 2L;//分布应用可设置为5,这里减少占位增加可支持时间 + // 数据中心标识位数 + private static long datacenterIdBits = 2L;//分布应用可设置为5,这里减少占位增加可支持时间 + // 机器ID最大值 + private static long maxWorkerId = -1L ^ (-1L << workerIdBits); + // 数据中心ID最大值 + private static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); + // 毫秒内自增位 + private static long sequenceBits = 12L; + // 机器ID偏左移12位 + private static long workerIdShift = sequenceBits; + // 数据中心ID左移17位 + private static long datacenterIdShift = sequenceBits + workerIdBits; + // 时间毫秒左移22位 + private static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; + private static long sequenceMask = -1L ^ (-1L << sequenceBits); + // 上次生产id时间戳 + private static long lastTimestamp = -1L; + + public static synchronized long nextId() { + long timestamp = timeGen(); + + if (timestamp < lastTimestamp) { + throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); + } + + if (lastTimestamp == timestamp) { + sequence = (sequence + 1) & sequenceMask; + if (sequence == 0) { + timestamp = tilNextMillis(lastTimestamp); + } + } else { + sequence = 0L; + } + + lastTimestamp = timestamp; + + return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; + } + + protected static long tilNextMillis(long lastTimestamp) { + long timestamp = timeGen(); + while (timestamp <= lastTimestamp) { + timestamp = timeGen(); + } + return timestamp; + } + + protected static long timeGen() { + return System.currentTimeMillis(); + } + + public static void main(String[] args) { + + Process p; + try { + p = Runtime.getRuntime().exec("E:\\windows_amd64\\sunny.exe clientid 213609147996,201822147996"); + System.out.println(":::::::::::::::::::开始在控制台打印日志::::::::::::::::::::::>>>>>>"); + //p.waitFor(); + BufferedReader bReader=new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk")); + String line=null; + while((line=bReader.readLine())!=null) + System.out.println(line); + } catch (IOException e) { + e.printStackTrace(); + } +// +// for (int i = 0; i < 10; i++) { +// long l = IDgenerator.nextId(); +// System.out.println(l); +// } + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/LocalData.java b/src/main/java/xyz/wbsite/dbtool/web/framework/LocalData.java new file mode 100644 index 00000000..2579646a --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/LocalData.java @@ -0,0 +1,48 @@ +package xyz.wbsite.dbtool.web.framework; + + +import xyz.wbsite.dbtool.web.framework.base.Token; + +import java.io.Serializable; + +/** + * LocalData - 本地数据存放类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class LocalData implements Serializable{ + private static final long serialVersionUID = 1L; + + private static Token temp = null; + + static { + temp = new Token(); + temp.setId(-1); + temp.setUserId(-1); + temp.setUserName("游客"); + temp.putResource("/"); + temp.putResource("/index"); + temp.putResource("/login"); + temp.putResource("/ajax"); + temp.putResource("ajax.example.example"); + } + + public static Token getTempToken(){ + return temp; + } + + /** + * 当前用户的通行证 + */ + private static final ThreadLocal tokenHolder = new ThreadLocal(); + + public static Token getToken() { + return tokenHolder.get(); + } + + public static void setToken(Token token) { + tokenHolder.set(token); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/Message.java b/src/main/java/xyz/wbsite/dbtool/web/framework/Message.java new file mode 100644 index 00000000..fa545c4f --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/Message.java @@ -0,0 +1,21 @@ +package xyz.wbsite.dbtool.web.framework; + + +/** + * Message - 基本消息类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class Message { + public static final String ERROR_500 = "服务器走了下神,稍后再试一次"; + public static final String NOT_EXIST_METHOD = "调用的方法不存在"; + + public static String CREATE_FAILURE = "创建失败,请刷新后重新尝试"; + public static String DELETE_FAILURE = "删除失败,请刷新后重新尝试"; + public static String UPDATE_FAILURE = "更新失败,请刷新后重新尝试"; + public static String FIND_FAILURE = "查询失败,请刷新后重新尝试"; + public static String GET_FAILURE = "未获取相应内容"; + public static String INSERT_DUPLICATE = "已经存在相同数据,返回列表页面确认"; +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/Base64Util.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/Base64Util.java new file mode 100644 index 00000000..777c3853 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/Base64Util.java @@ -0,0 +1,507 @@ +package xyz.wbsite.dbtool.web.framework.base; + +import java.util.Arrays; + +/** + * Base64Util + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class Base64Util { + private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); + private static final int[] IA = new int[256]; + + static { + Arrays.fill(IA, -1); + for(int i = 0, iS = CA.length; i < iS; i++) + IA[CA[i]] = i; + IA['='] = 0; + } + + public final static char[] encodeToChar(byte[] sArr, boolean lineSep) { + // Check special case + int sLen = sArr != null ? sArr.length : 0; + if(sLen == 0) + return new char[0]; + + int eLen = (sLen / 3) * 3; // Length of even 24-bits. + int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count + int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array + char[] dArr = new char[dLen]; + + // Encode even 24-bits + for(int s = 0, d = 0, cc = 0; s < eLen; ) { + // Copy next three bytes into lower 24 bits of int, paying attension to sign. + int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); + + // Encode the int into four chars + dArr[d++] = CA[(i >>> 18) & 0x3f]; + dArr[d++] = CA[(i >>> 12) & 0x3f]; + dArr[d++] = CA[(i >>> 6) & 0x3f]; + dArr[d++] = CA[i & 0x3f]; + + // Add optional line separator + if(lineSep && ++cc == 19 && d < dLen - 2) { + dArr[d++] = '\r'; + dArr[d++] = '\n'; + cc = 0; + } + } + + // Pad and encode last bits if source isn't even 24 bits. + int left = sLen - eLen; // 0 - 2. + if(left > 0) { + // Prepare the int + int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); + + // Set last four chars + dArr[dLen - 4] = CA[i >> 12]; + dArr[dLen - 3] = CA[(i >>> 6) & 0x3f]; + dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '='; + dArr[dLen - 1] = '='; + } + return dArr; + } + + public final static byte[] decode(char[] sArr) { + // Check special case + int sLen = sArr != null ? sArr.length : 0; + if(sLen == 0) + return new byte[0]; + + // Count illegal characters (including '\r', '\n') to know what size the returned array will be, + // so we don't have to reallocate & copy it later. + int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...) + for(int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out. + if(IA[sArr[i]] < 0) + sepCnt++; + + // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045. + if((sLen - sepCnt) % 4 != 0) + return null; + + int pad = 0; + for(int i = sLen; i > 1 && IA[sArr[--i]] <= 0; ) + if(sArr[i] == '=') + pad++; + + int len = ((sLen - sepCnt) * 6 >> 3) - pad; + + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + for(int s = 0, d = 0; d < len; ) { + // Assemble three bytes into an int from four "valid" characters. + int i = 0; + for(int j = 0; j < 4; j++) { // j only increased if a valid char was found. + int c = IA[sArr[s++]]; + if(c >= 0) + i |= c << (18 - j * 6); + else + j--; + } + // Add the bytes + dArr[d++] = (byte) (i >> 16); + if(d < len) { + dArr[d++] = (byte) (i >> 8); + if(d < len) + dArr[d++] = (byte) i; + } + } + return dArr; + } + + /** + * Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as + * fast as {@link #decode(char[])}. The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + * + The array must not contain illegal characters within the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.
+ * + * @param sArr The source array. Length 0 will return an empty array. null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public final static byte[] decodeFast(char[] sArr) { + // Check special case + int sLen = sArr.length; + if(sLen == 0) + return new byte[0]; + + int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while(sIx < eIx && IA[sArr[sIx]] < 0) + sIx++; + + // Trim illegal chars from end + while(eIx > 0 && IA[sArr[eIx]] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for(int cc = 0, eLen = (len / 3) * 3; d < eLen; ) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + dArr[d++] = (byte) (i >> 8); + dArr[d++] = (byte) i; + + // If line separator, jump over it. + if(sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if(d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for(int j = 0; sIx <= eIx - pad; j++) + i |= IA[sArr[sIx++]] << (18 - j * 6); + + for(int r = 16; d < len; r -= 8) + dArr[d++] = (byte) (i >> r); + } + + return dArr; + } + + /** + * Encodes a raw byte array into a BASE64 byte[] representation i accordance with RFC 2045. + * + * @param sArr The bytes to convert. If null or length 0 an empty array will be returned. + * @param lineSep Optional "\r\n" after 76 characters, unless end of file.
+ * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a + * little faster. + * @return A BASE64 encoded array. Never null. + */ + public final static byte[] encodeToByte(byte[] sArr, boolean lineSep) { + // Check special case + int sLen = sArr != null ? sArr.length : 0; + if(sLen == 0) + return new byte[0]; + + int eLen = (sLen / 3) * 3; // Length of even 24-bits. + int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count + int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array + byte[] dArr = new byte[dLen]; + + // Encode even 24-bits + for(int s = 0, d = 0, cc = 0; s < eLen; ) { + // Copy next three bytes into lower 24 bits of int, paying attension to sign. + int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); + + // Encode the int into four chars + dArr[d++] = (byte) CA[(i >>> 18) & 0x3f]; + dArr[d++] = (byte) CA[(i >>> 12) & 0x3f]; + dArr[d++] = (byte) CA[(i >>> 6) & 0x3f]; + dArr[d++] = (byte) CA[i & 0x3f]; + + // Add optional line separator + if(lineSep && ++cc == 19 && d < dLen - 2) { + dArr[d++] = '\r'; + dArr[d++] = '\n'; + cc = 0; + } + } + + // Pad and encode last bits if source isn't an even 24 bits. + int left = sLen - eLen; // 0 - 2. + if(left > 0) { + // Prepare the int + int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); + + // Set last four chars + dArr[dLen - 4] = (byte) CA[i >> 12]; + dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f]; + dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '='; + dArr[dLen - 1] = '='; + } + return dArr; + } + + /** + * Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with + * and without line separators. + * + * @param sArr The source array. Length 0 will return an empty array. null will throw an exception. + * @return The decoded array of bytes. May be of length 0. Will be null if the legal characters + * (including '=') isn't divideable by 4. (I.e. definitely corrupted). + */ + public final static byte[] decode(byte[] sArr) { + // Check special case + int sLen = sArr.length; + + // Count illegal characters (including '\r', '\n') to know what size the returned array will be, + // so we don't have to reallocate & copy it later. + int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...) + for(int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out. + if(IA[sArr[i] & 0xff] < 0) + sepCnt++; + + // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045. + if((sLen - sepCnt) % 4 != 0) + return null; + + int pad = 0; + for(int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0; ) + if(sArr[i] == '=') + pad++; + + int len = ((sLen - sepCnt) * 6 >> 3) - pad; + + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + for(int s = 0, d = 0; d < len; ) { + // Assemble three bytes into an int from four "valid" characters. + int i = 0; + for(int j = 0; j < 4; j++) { // j only increased if a valid char was found. + int c = IA[sArr[s++] & 0xff]; + if(c >= 0) + i |= c << (18 - j * 6); + else + j--; + } + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + if(d < len) { + dArr[d++] = (byte) (i >> 8); + if(d < len) + dArr[d++] = (byte) i; + } + } + + return dArr; + } + + + /** + * Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as + * fast as {@link #decode(byte[])}. The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + * + The array must not contain illegal characters within the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.
+ * + * @param sArr The source array. Length 0 will return an empty array. null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public final static byte[] decodeFast(byte[] sArr) { + // Check special case + int sLen = sArr.length; + if(sLen == 0) + return new byte[0]; + + int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while(sIx < eIx && IA[sArr[sIx] & 0xff] < 0) + sIx++; + + // Trim illegal chars from end + while(eIx > 0 && IA[sArr[eIx] & 0xff] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for(int cc = 0, eLen = (len / 3) * 3; d < eLen; ) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]]; + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + dArr[d++] = (byte) (i >> 8); + dArr[d++] = (byte) i; + + // If line separator, jump over it. + if(sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if(d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for(int j = 0; sIx <= eIx - pad; j++) + i |= IA[sArr[sIx++]] << (18 - j * 6); + + for(int r = 16; d < len; r -= 8) + dArr[d++] = (byte) (i >> r); + } + + return dArr; + } + + // **************************************************************************************** + // * String version + // **************************************************************************************** + + /** + * Encodes a raw byte array into a BASE64 String representation i accordance with RFC 2045. + * + * @param sArr The bytes to convert. If null or length 0 an empty array will be returned. + * @param lineSep Optional "\r\n" after 76 characters, unless end of file.
+ * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a + * little faster. + * @return A BASE64 encoded array. Never null. + */ + public final static String encodeToString(byte[] sArr, boolean lineSep) { + // Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower. + return new String(encodeToChar(sArr, lineSep)); + } + + /** + * Decodes a BASE64 encoded String. All illegal characters will be ignored and can handle both strings with + * and without line separators.
+ * Note! It can be up to about 2x the speed to call decode(str.toCharArray()) instead. That + * will create a temporary array though. This version will use str.charAt(i) to iterate the string. + * + * @param str The source string. null or length 0 will return an empty array. + * @return The decoded array of bytes. May be of length 0. Will be null if the legal characters + * (including '=') isn't divideable by 4. (I.e. definitely corrupted). + */ + public final static byte[] decode(String str) { + // Check special case + int sLen = str != null ? str.length() : 0; + if(sLen == 0) + return new byte[0]; + + // Count illegal characters (including '\r', '\n') to know what size the returned array will be, + // so we don't have to reallocate & copy it later. + int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...) + for(int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out. + if(IA[str.charAt(i)] < 0) + sepCnt++; + + // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045. + if((sLen - sepCnt) % 4 != 0) + return null; + + // Count '=' at end + int pad = 0; + for(int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0; ) + if(str.charAt(i) == '=') + pad++; + + int len = ((sLen - sepCnt) * 6 >> 3) - pad; + + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + for(int s = 0, d = 0; d < len; ) { + // Assemble three bytes into an int from four "valid" characters. + int i = 0; + for(int j = 0; j < 4; j++) { // j only increased if a valid char was found. + int c = IA[str.charAt(s++)]; + if(c >= 0) + i |= c << (18 - j * 6); + else + j--; + } + // Add the bytes + dArr[d++] = (byte) (i >> 16); + if(d < len) { + dArr[d++] = (byte) (i >> 8); + if(d < len) + dArr[d++] = (byte) i; + } + } + return dArr; + } + + /** + * Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as + * fast as {@link #decode(String)}. The preconditions are:
+ * + The array must have a line length of 76 chars OR no line separators at all (one line).
+ * + Line separator must be "\r\n", as specified in RFC 2045 + * + The array must not contain illegal characters within the encoded string
+ * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.
+ * + * @param s The source string. Length 0 will return an empty array. null will throw an exception. + * @return The decoded array of bytes. May be of length 0. + */ + public final static byte[] decodeFast(String s) { + // Check special case + int sLen = s.length(); + if(sLen == 0) + return new byte[0]; + + int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. + + // Trim illegal chars from start + while(sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0) + sIx++; + + // Trim illegal chars from end + while(eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0) + eIx--; + + // get the padding count (=) (0, 1 or 2) + int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end. + int cCnt = eIx - sIx + 1; // Content count including possible separators + int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; + + int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes + byte[] dArr = new byte[len]; // Preallocate byte[] of exact length + + // Decode all but the last 0 - 2 bytes. + int d = 0; + for(int cc = 0, eLen = (len / 3) * 3; d < eLen; ) { + // Assemble three bytes into an int from four "valid" characters. + int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)]; + + // Add the bytes + dArr[d++] = (byte) (i >> 16); + dArr[d++] = (byte) (i >> 8); + dArr[d++] = (byte) i; + + // If line separator, jump over it. + if(sepCnt > 0 && ++cc == 19) { + sIx += 2; + cc = 0; + } + } + + if(d < len) { + // Decode last 1-3 bytes (incl '=') into 1-3 bytes + int i = 0; + for(int j = 0; sIx <= eIx - pad; j++) + i |= IA[s.charAt(sIx++)] << (18 - j * 6); + + for(int r = 16; d < len; r -= 8) + dArr[d++] = (byte) (i >> r); + } + + return dArr; + } + + public static void main(String[] args) { + String s = Base64Util.encodeToString("我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1我搜搜1".getBytes(), false); + System.out.println(s); + + byte[] decode = Base64Util.decode(s); + System.out.println(new String(decode)); + + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseEntity.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseEntity.java new file mode 100644 index 00000000..5e57478a --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseEntity.java @@ -0,0 +1,95 @@ +package xyz.wbsite.dbtool.web.framework.base; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Date; + +/** + * Base - 基类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ + +public class BaseEntity { + + /** + * 行版本 + */ + private long rowVersion; + + /** + * 创建用户 + */ + private long createBy; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 最后更新用户 + */ + private long lastUpdateBy; + + /** + * 最后更新时间 + */ + private Date lastUpdateTime; + + /** + * 是否删除 + */ + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + private boolean isDeleted; + + public boolean getIsDeleted() { + return isDeleted; + } + + public void setIsDeleted(boolean isDeleted) { + this.isDeleted = isDeleted; + } + + public long getRowVersion() { + return rowVersion; + } + + public void setRowVersion(long rowVersion) { + this.rowVersion = rowVersion; + } + + public long getCreateBy() { + return createBy; + } + + public void setCreateBy(long createBy) { + this.createBy = createBy; + } + + public long getLastUpdateBy() { + return lastUpdateBy; + } + + public void setLastUpdateBy(long lastUpdateBy) { + this.lastUpdateBy = lastUpdateBy; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getLastUpdateTime() { + return lastUpdateTime; + } + + public void setLastUpdateTime(Date lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseFindRequest.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseFindRequest.java new file mode 100644 index 00000000..bba87423 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseFindRequest.java @@ -0,0 +1,75 @@ +package xyz.wbsite.dbtool.web.framework.base; + +/** + * BaseFindRequest - 基类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class BaseFindRequest extends BaseRequest { + private long pageNumber = 1L; + private long pageSize = 10L; + private long beginIndex = 0; + private long endIndex = 10; + private String sortKey; + private SortType sortType; + + public String getSortKey() { + return sortKey; + } + + public void setSortKey(String sortKey) { + this.sortKey = sortKey; + } + + public SortType getSortType() { + return sortType; + } + + public void setSortType(SortType sortType) { + this.sortType = sortType; + } + + public long getPageNumber() { + return pageNumber; + } + + public void setPageNumber(long pageNumber) { + this.pageNumber = pageNumber; + } + + public long getPageSize() { + return pageSize; + } + + public void setPageSize(long pageSize) { + this.pageSize = pageSize; + } + + public long getBeginIndex() { + beginIndex = pageSize * (pageNumber - 1); + return beginIndex; + } + + public void setBeginIndex(long beginIndex) { + this.beginIndex = beginIndex; + } + + public long getEndIndex() { + endIndex = pageSize * (pageNumber - 1) + pageSize; + return endIndex; + } + + public void setEndIndex(long endIndex) { + this.endIndex = endIndex; + } + + public void updatePageNumber(Long totalCount){ + long maxPage = totalCount / pageSize + (totalCount % pageSize > 0 ? 1 : 0); + + if (pageNumber > maxPage){ + pageNumber = maxPage; + } + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseFindResponse.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseFindResponse.java new file mode 100644 index 00000000..f95b5a74 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseFindResponse.java @@ -0,0 +1,33 @@ +package xyz.wbsite.dbtool.web.framework.base; + +import java.util.List; + +/** + * BaseFindResponse - 基类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class BaseFindResponse extends BaseResponse{ + + private List result; + + private Long totalCount; + + public List getResult() { + return result; + } + + public void setResult(List result) { + this.result = result; + } + + public Long getTotalCount() { + return totalCount; + } + + public void setTotalCount(Long totalCount) { + this.totalCount = totalCount; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseRequest.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseRequest.java new file mode 100644 index 00000000..fa8e98a5 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseRequest.java @@ -0,0 +1,12 @@ +package xyz.wbsite.dbtool.web.framework.base; + +/** + * BaseRequest - 基类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class BaseRequest { + +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseResponse.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseResponse.java new file mode 100644 index 00000000..2b9620d1 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseResponse.java @@ -0,0 +1,38 @@ +package xyz.wbsite.dbtool.web.framework.base; + +import java.util.ArrayList; +import java.util.List; + +/** + * BaseResponse - 基类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class BaseResponse { + private List errors = new ArrayList(); + + public void addError(Error error){ + this.errors.add(error); + } + + public void addError(ErrorType type,String message){ + this.errors.add(new Error(type,message)); + } + + public void addErrors(List errors){ + this.errors.addAll(errors); + } + + public boolean hasError(){ + return this.errors.size() > 0; + } + + /** + * 获取全部的错误信息,返回的是副本 + */ + public List getErrors() { + return new ArrayList(errors); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseSearchRequest.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseSearchRequest.java new file mode 100644 index 00000000..a99b790e --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseSearchRequest.java @@ -0,0 +1,24 @@ +package xyz.wbsite.dbtool.web.framework.base; + +/** + * BaseSearchRequest - 基类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class BaseSearchRequest extends BaseFindRequest { + + /** + * 模糊查询的关键字。 + */ + private String keyword; + + public String getKeyword() { + return keyword; + } + + public void setKeyword(String keyword) { + this.keyword = keyword; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseUpdateRequest.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseUpdateRequest.java new file mode 100644 index 00000000..4f7e27a7 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/BaseUpdateRequest.java @@ -0,0 +1,24 @@ +package xyz.wbsite.dbtool.web.framework.base; + +/** + * BaseUpdateRequest - 基类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class BaseUpdateRequest extends BaseRequest{ + + /** + * 版本戳 + */ + private long rowVersion; + + public long getRowVersion() { + return rowVersion; + } + + public void setRowVersion(long rowVersion) { + this.rowVersion = rowVersion; + } +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/Error.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/Error.java new file mode 100644 index 00000000..bcc8884f --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/Error.java @@ -0,0 +1,38 @@ +package xyz.wbsite.dbtool.web.framework.base; + +/** + * Error - 错误基类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class Error { + + /*错误类型*/ + private ErrorType type; + + /*错误内容*/ + private String message; + + public Error(ErrorType type, String message) { + this.type = type; + this.message = message; + } + + public ErrorType getType() { + return type; + } + + public void setType(ErrorType type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/ErrorType.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/ErrorType.java new file mode 100644 index 00000000..5adb0be5 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/ErrorType.java @@ -0,0 +1,17 @@ +package xyz.wbsite.dbtool.web.framework.base; + +/** + * ErrorType - 错误类型 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public enum ErrorType { + BUSINESS_ERROR, + SYSTEM_ERROR, + UNKNOWN_ERROR, + UNIQUENESS_ERROR, + EXPECTATION_NULL, + INVALID_PARAMETER +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/SortType.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/SortType.java new file mode 100644 index 00000000..8fc0476e --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/SortType.java @@ -0,0 +1,17 @@ +package xyz.wbsite.dbtool.web.framework.base; + +/** + * SortTypeEnum - 排序方式 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public enum SortType { + + //升序 + ASC, + + //降序 + DESC +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/base/Token.java b/src/main/java/xyz/wbsite/dbtool/web/framework/base/Token.java new file mode 100644 index 00000000..7e092108 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/base/Token.java @@ -0,0 +1,58 @@ +package xyz.wbsite.dbtool.web.framework.base; + +import java.io.Serializable; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +/** + * Token - 通行证类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class Token implements Serializable { + private static final Long serialVersionUID = 1L; + /** ID */ + private long id; + /** 用户ID */ + private long userId; + /** 用户名称 */ + private String userName; + + private Set resourceSet = new HashSet<>(); + + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public boolean hasResource(String resource){ + return resourceSet.contains(resource); + } + + public void putResource(String resource){ + resourceSet.add(resource); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/config/FreeMarkerConfig.java b/src/main/java/xyz/wbsite/dbtool/web/framework/config/FreeMarkerConfig.java new file mode 100644 index 00000000..9ae6e7ef --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/config/FreeMarkerConfig.java @@ -0,0 +1,57 @@ +package xyz.wbsite.dbtool.web.framework.config; + +import xyz.wbsite.dbtool.web.framework.freemarker.FreemarkerViewNameTranslator; +import xyz.wbsite.dbtool.web.framework.freemarker.Layout; +import xyz.wbsite.dbtool.web.framework.freemarker.Url; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator; +import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; +import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; + +import javax.annotation.PostConstruct; +import java.util.Map; + +/** + * FreemarkerViewName解析器 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +@Configuration +public class FreeMarkerConfig { + + @Autowired + private Layout layout; + + @Autowired + private Url url; + + @Autowired + protected FreeMarkerViewResolver resolver; + + @Autowired + protected FreeMarkerConfigurer freeMarkerConfigurer; + + @PostConstruct + public void setSharedVariable() { + //设置基本工具类 + Map attributesMap = resolver.getAttributesMap(); + attributesMap.put("Layout", layout); + attributesMap.put("Url", url); + } + + /** + * 解析器 + * + * @return + */ + @Bean(name = "viewNameTranslator") + public DefaultRequestToViewNameTranslator getViewNameTranslator() { + FreemarkerViewNameTranslator nameTranslator = new FreemarkerViewNameTranslator(); + nameTranslator.setViewResolver(resolver); + return nameTranslator; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/config/TaskConfig.java b/src/main/java/xyz/wbsite/dbtool/web/framework/config/TaskConfig.java new file mode 100644 index 00000000..7dec0372 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/config/TaskConfig.java @@ -0,0 +1,40 @@ +package xyz.wbsite.dbtool.web.framework.config; + +import xyz.wbsite.dbtool.web.framework.utils.LogUtil; +import xyz.wbsite.dbtool.web.framework.utils.ProcessUtil; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.scheduling.annotation.SchedulingConfigurer; +import org.springframework.scheduling.config.ScheduledTaskRegistrar; + +import java.util.concurrent.Executors; + +/** + * Task配置,默认只在开发环境生效,根据实际情况是否需要Task选择开启 + * 开启方法:将@Profile("dev") 删除(所有环境生效) 或改为 @Profile("prod")(只对生产环境生效) + */ +@Configuration +@EnableScheduling +@Profile("prod") +public class TaskConfig implements SchedulingConfigurer { + + @Scheduled(cron="0/30 * * * * ? ") + public void task(){ + LogUtil.i("--------------------Task--------------------"); + boolean process = ProcessUtil.findProcess("sunny.exe"); + if (!process){ + ProcessUtil.execExe("D:/windows_amd64/sunny.exe clientid 201822147996"); + } + } + + /** + * 开启多线程执行任务 + * @param scheduledTaskRegistrar + */ + @Override + public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { + scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(3)); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/config/ThreadPoolConfig.java b/src/main/java/xyz/wbsite/dbtool/web/framework/config/ThreadPoolConfig.java new file mode 100644 index 00000000..cc56f613 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/config/ThreadPoolConfig.java @@ -0,0 +1,56 @@ +package xyz.wbsite.dbtool.web.framework.config; + +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Configuration; +import org.springframework.lang.Nullable; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.lang.reflect.Method; +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadPoolExecutor; + +@Configuration +@EnableAsync +public class ThreadPoolConfig implements AsyncConfigurer { + private ThreadPoolTaskExecutor executor; + + private int corePoolSize = 10;//线程池维护线程的最少数量 + + private int maxPoolSize = 30;//线程池维护线程的最大数量 + + private int queueCapacity = 8; //缓存队列 + + private int keepAlive = 60;//允许的空闲时间 + + @Nullable + @Override + public Executor getAsyncExecutor() { + executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(corePoolSize); + executor.setMaxPoolSize(maxPoolSize); + executor.setQueueCapacity(queueCapacity); + executor.setThreadNamePrefix("mqExecutor-"); + // rejection-policy:当pool已经达到max size的时候,如何处理新任务 + // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行 + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //对拒绝task的处理策略 + executor.setKeepAliveSeconds(keepAlive); + executor.initialize(); + return executor; + } + + + @Nullable + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return new AsyncUncaughtExceptionHandler() { + + @Override + public void handleUncaughtException(Throwable throwable, Method method, Object... objects) { + System.out.println("-------------》》》捕获线程异常信息"); + } + }; + } + +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/config/WebMvcConfig.java b/src/main/java/xyz/wbsite/dbtool/web/framework/config/WebMvcConfig.java new file mode 100644 index 00000000..e13fbaf4 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/config/WebMvcConfig.java @@ -0,0 +1,44 @@ +package xyz.wbsite.dbtool.web.framework.config; + +import xyz.wbsite.dbtool.web.framework.interceptor.GlobalInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.CharacterEncodingFilter; +import org.springframework.web.servlet.config.annotation.*; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + @Autowired + private CharacterEncodingFilter characterEncodingFilter; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + //增加全局拦截器 + registry.addInterceptor(new GlobalInterceptor()).addPathPatterns("/*"); + } + + @Bean + public FilterRegistrationBean characterEncodingFilterRegistration() { + FilterRegistrationBean registration = new FilterRegistrationBean(); + //注入过滤器 + registration.setFilter(characterEncodingFilter); + //拦截规则 + registration.addUrlPatterns("/*"); + //过滤器名称 + registration.setName("CharacterEncodingFilter"); + //过滤器顺序 + registration.setOrder(1); + return registration; + } + + @Bean + public CharacterEncodingFilter characterEncodingFilter() { + CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); + characterEncodingFilter.setEncoding("UTF-8"); + characterEncodingFilter.setForceEncoding(true); + return characterEncodingFilter; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/freemarker/FreemarkerViewNameTranslator.java b/src/main/java/xyz/wbsite/dbtool/web/framework/freemarker/FreemarkerViewNameTranslator.java new file mode 100644 index 00000000..845bad89 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/freemarker/FreemarkerViewNameTranslator.java @@ -0,0 +1,75 @@ +package xyz.wbsite.dbtool.web.framework.freemarker; + +import xyz.wbsite.dbtool.web.framework.utils.LogUtil; +import org.springframework.web.servlet.DispatcherServlet; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.View; +import org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator; +import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; + +import javax.servlet.http.HttpServletRequest; +import java.io.File; +import java.util.Locale; + +/** + * FreemarkerViewName解析器 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class FreemarkerViewNameTranslator extends DefaultRequestToViewNameTranslator { + + private FreeMarkerViewResolver viewResolver; + + @Override + public String getViewName(HttpServletRequest request) { + String viewName = ""; + try { + LocaleResolver localeResolver = (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE); + String servletPath = request.getServletPath(); + if (servletPath != null && "/".equals(servletPath)) { + servletPath = "index"; + }else { + servletPath = servletPath.replaceAll("^/",""); + } + Locale locale = localeResolver.resolveLocale(request); + + {//查询View + viewName = "screen" + File.separator + servletPath; + View view = viewResolver.resolveViewName(viewName, locale); + if (view == null) { + LogUtil.e("can not find screen."); + return "404"; + } + } + + {//查找layout + viewName = "layout" + File.separator + servletPath; + + View view = viewResolver.resolveViewName(viewName, locale); + //无法找到对应layout,使用默认layout + if (view == null) { + viewName = "layout" + File.separator + "default"; + View defaultView = viewResolver.resolveViewName(viewName, locale); + if (defaultView == null) { + System.err.println("can not find layout/default.ftl"); + viewName = ""; + } + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + return viewName; + } + + public FreeMarkerViewResolver getViewResolver() { + return viewResolver; + } + + public void setViewResolver(FreeMarkerViewResolver viewResolver) { + this.viewResolver = viewResolver; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/freemarker/Layout.java b/src/main/java/xyz/wbsite/dbtool/web/framework/freemarker/Layout.java new file mode 100644 index 00000000..81761c1a --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/freemarker/Layout.java @@ -0,0 +1,66 @@ +package xyz.wbsite.dbtool.web.framework.freemarker; + +import freemarker.template.TemplateModelException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.DispatcherServlet; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.View; +import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; + +import javax.servlet.http.HttpServletRequest; +import java.io.File; +import java.util.Locale; + +/** + * 布局帮助类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +@Component +public class Layout { + + @Value("${web.welcome.page}") + private String homePage; + + @Autowired + private FreeMarkerViewResolver viewResolver; + + private String screenPrefix = "/screen/"; + private String controlPrefix = "/control/"; + private String suffix = ".ftl"; + + public String setScreen() throws TemplateModelException { + try { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + LocaleResolver localeResolver = (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE); + String servletPath = request.getServletPath(); + if ("/".equals(servletPath)) { + servletPath = this.homePage; + } + servletPath = servletPath.replaceAll("^/", ""); + Locale locale = localeResolver.resolveLocale(request); + String viewName = "screen" + File.separator + servletPath; + View view = viewResolver.resolveViewName(viewName, locale); + //无法找到对应screen + if (view == null) { + return ""; + } else { + return screenPrefix + servletPath + suffix; + } + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + public String setControl(String control) { + return controlPrefix + control + suffix; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/freemarker/Url.java b/src/main/java/xyz/wbsite/dbtool/web/framework/freemarker/Url.java new file mode 100644 index 00000000..737df1fc --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/freemarker/Url.java @@ -0,0 +1,34 @@ +package xyz.wbsite.dbtool.web.framework.freemarker; + +import freemarker.template.TemplateModelException; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + +/** + * Url帮助类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +@Component +public class Url { + + public String setUrl(String url) throws TemplateModelException { + if (url == null) { + return ""; + } + + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + String contextPath = request.getContextPath(); + + if (url.startsWith("/")) { + return contextPath + url; + } else { + return contextPath + "/" + url; + } + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/interceptor/GlobalInterceptor.java b/src/main/java/xyz/wbsite/dbtool/web/framework/interceptor/GlobalInterceptor.java new file mode 100644 index 00000000..6ee9965e --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/interceptor/GlobalInterceptor.java @@ -0,0 +1,31 @@ +package xyz.wbsite.dbtool.web.framework.interceptor; + + +import org.springframework.lang.Nullable; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class GlobalInterceptor implements HandlerInterceptor { + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + + // todo do something + + + return true; + } + + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { + + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { + + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/springmvc/GlobalHandlerInterceptor.java b/src/main/java/xyz/wbsite/dbtool/web/framework/springmvc/GlobalHandlerInterceptor.java new file mode 100644 index 00000000..e71328f0 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/springmvc/GlobalHandlerInterceptor.java @@ -0,0 +1,54 @@ +package xyz.wbsite.dbtool.web.framework.springmvc; + +import xyz.wbsite.dbtool.web.framework.LocalData; +import xyz.wbsite.dbtool.web.framework.base.Token; +import xyz.wbsite.dbtool.web.framework.utils.LogUtil; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * SpringMVC 全局拦截器 全局处理,日志记录 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class GlobalHandlerInterceptor extends HandlerInterceptorAdapter { + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + return super.preHandle(request, response, handler); + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + super.postHandle(request, response, handler, modelAndView); + + //当请求为@ResponseBody,modelAndView为null + if (modelAndView == null){ + return; + } + + //获取当前用户信息 + Token token = LocalData.getToken(); + modelAndView.addObject("token", token); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + super.afterCompletion(request, response, handler, ex); + + LogUtil.i("请求地址" + request.getServletPath()); + if (ex != null) { + LogUtil.dumpException(ex); + } + } + + @Override + public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + super.afterConcurrentHandlingStarted(request, response, handler); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/springmvc/GlobalObjectMapper.java b/src/main/java/xyz/wbsite/dbtool/web/framework/springmvc/GlobalObjectMapper.java new file mode 100644 index 00000000..90037b45 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/springmvc/GlobalObjectMapper.java @@ -0,0 +1,27 @@ +package xyz.wbsite.dbtool.web.framework.springmvc; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; + +/** + * SpringMVC 对象JSON化自定义转换器 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class GlobalObjectMapper extends ObjectMapper { + + /** + * 设置@ResponseBody 返回的JSON格式 + */ + public GlobalObjectMapper() { + super(); + // 将所有的Long变成String以兼容js + SimpleModule simpleModule = new SimpleModule("LongModule"); + simpleModule.addSerializer(Long.class, ToStringSerializer.instance); + simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); + registerModule(simpleModule); + } +} \ No newline at end of file diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/utils/CookieUtil.java b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/CookieUtil.java new file mode 100644 index 00000000..0dca7fbf --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/CookieUtil.java @@ -0,0 +1,60 @@ +package xyz.wbsite.dbtool.web.framework.utils; + +import javax.servlet.http.Cookie; + +/** + * Created on 2017-04-25 + * + * @author 王兵 + */ +public class CookieUtil { + + public static String getTokenCookieName(String deployMode){ + if (deployMode.equals("production")) { + return "TOKEN_ID"; + } else { + return "TOKEN_ID_" + deployMode.toUpperCase(); + } + } + + /** + * 通过Cookies获取passport的ID + * @param cookies Cookies + * @return passportID + */ + public static Long getTokenId(Cookie[] cookies, String deployMode) { + if(cookies != null) { + for (Cookie cookie : cookies) { + // Cookie中存放的为Token的id ,Cookie名称通过ConfigToolObject获取 + if (cookie != null && cookie.getName().equals(getTokenCookieName(deployMode))) { + try { + // 将cookie中的passportId转换为Long型 + return Long.parseLong(cookie.getValue()); + } catch (Exception ignored) { + } + } + } + } + return null; + } + + /** + * 通过Cookies获取内容 + * @param cookies Cookies + * @return passportID + */ + public static String getCookieValue(Cookie[] cookies, String key) { + if(cookies != null) { + for (Cookie cookie : cookies) { + // Cookie中存放的为passport的id ,Cookie名称通过ConfigToolObject获取 + if (cookie != null && cookie.getName().equals(key)) { + try { + return cookie.getValue(); + } catch (Exception ignored) { + } + } + } + } + return null; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/utils/LogUtil.java b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/LogUtil.java new file mode 100644 index 00000000..9c1af616 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/LogUtil.java @@ -0,0 +1,70 @@ +package xyz.wbsite.dbtool.web.framework.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * LogUtil - 日志记录工具类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class LogUtil { + + //定义一个全局的记录器,通过LoggerFactory获取 + private final static Logger logger = LoggerFactory.getLogger(LogUtil.class); + + /** + * 输出info日志 + * @param context 日志内容 + */ + public static void i(String context){ + logger.info(context); + } + + /** + * 输出debug日志 + * @param context 日志内容 + */ + public static void d(String context){ + logger.debug(context); + } + + /** + * 输出warn日志 + * @param context 日志内容 + */ + public static void w(String context){ + logger.warn(context); + } + + /** + * 输出error日志 + * @param context 日志内容 + */ + public static void e(String context){ + logger.error(context); + } + + /** + * 获取异常详细堆栈信息 + */ + public static void dumpException(Throwable e){ + StringBuffer msg = new StringBuffer("null"); + if (e != null) { + msg = new StringBuffer(""); + String message = e.toString(); + int length = e.getStackTrace().length; + if (length > 0) { + msg.append(message).append("\n"); + for (int i = 0; i < length; i++) { + msg.append("\t").append(e.getStackTrace()[i]).append("\n"); + } + } else { + msg.append(message); + } + } + logger.error(msg.toString()); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/utils/MD5Util.java b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/MD5Util.java new file mode 100644 index 00000000..58761966 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/MD5Util.java @@ -0,0 +1,114 @@ +package xyz.wbsite.dbtool.web.framework.utils;//package com.example.demo.framework.utils; + + +import com.fasterxml.jackson.core.TreeNode; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Iterator; + +/** + * MD5Util - MD5工具类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class MD5Util { + + /** + * 加密 + * + * @param value + * @return + */ + public static String encode(String value) { + try { + MessageDigest md = MessageDigest.getInstance("md5"); + byte[] e = md.digest(value.getBytes()); + return toHexString(e); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + return value; + } + } + + public static String encode(byte[] bytes) { + try { + MessageDigest md = MessageDigest.getInstance("md5"); + byte[] e = md.digest(bytes); + return toHexString(e); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + return ""; + } + } + + private static String toHexString(byte bytes[]) { + StringBuilder hs = new StringBuilder(); + String stmp = ""; + for (int n = 0; n < bytes.length; n++) { + stmp = Integer.toHexString(bytes[n] & 0xff); + if (stmp.length() == 1) + hs.append("0").append(stmp); + else + hs.append(stmp); + } + + return hs.toString(); + } + + /** + * 对json数据排序并签名 + * @param appSecret + * @param currentTime + * @return + */ + public static String toSign(TreeNode treeNode, String appSecret, String currentTime) { + String typesetting = sortAndJson(treeNode); + System.out.println(typesetting); + return MD5Util.encode(appSecret + typesetting + currentTime); + } + + private static String sortAndJson(TreeNode treeNode) { + StringBuffer sb = new StringBuffer(); + Iterator keyIterator = treeNode.fieldNames(); + while (keyIterator.hasNext()){ + String next = keyIterator.next(); + sb.append(next).append(treeNode.get(next)); + } + return sb.toString(); + } + +// +// private static String sortAndJson(JSONObject jsonObject) { +// List data = new ArrayList(jsonObject.keySet()); +// Collections.sort(data); +// StringBuffer sb = new StringBuffer(); +// +// for (String s : data) { +// sb.append(s); +// Object o = jsonObject.get(s); +// if (o == null) { +// sb.append(""); +// } else if (o instanceof JSONArray) { +// sb.append(sortAndJson((JSONArray) o)); +// } else if (o instanceof JSONObject) { +// sb.append(sortAndJson((JSONObject) o)); +// } else { +// sb.append(o.toString()); +// } +// } +// return sb.toString(); +// } + + + /** + * 测试实例 + * + * @param args + */ + public static void main(String[] args) { + + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/utils/MapperUtil.java b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/MapperUtil.java new file mode 100644 index 00000000..fd700bfe --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/MapperUtil.java @@ -0,0 +1,117 @@ +package xyz.wbsite.dbtool.web.framework.utils; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.TreeNode; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.springframework.cglib.beans.BeanCopier; +import org.springframework.cglib.core.Converter; + +import java.io.IOException; + +/** + * MapUtil - 映射转化工具类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class MapperUtil { + private static ObjectMapper om; + + static { + //初始化 + om = new ObjectMapper(); + //序列化时忽略null属性 + om.setSerializationInclusion(JsonInclude.Include.NON_NULL); + //序列化时排序 + om.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); + } + + public static TreeNode toTree(String json) { + try { + return om.readTree(json); + } catch (IOException e) { + e.printStackTrace(); + return om.createObjectNode(); + } + } + + public static TreeNode toTree(Object json) { + return om.valueToTree(json); + } + + public static String toJson(Object object) { + return toJson(object, false); + } + + public static String toJson(Object object, boolean pretty) { + try { + if (pretty) { + return om.writerWithDefaultPrettyPrinter().writeValueAsString(object); + } else { + return om.writeValueAsString(object); + } + } catch (JsonProcessingException e) { + e.printStackTrace(); + return "{}"; + } + } + + public static String toJson(JsonNode jsonNode) { + return jsonNode.asText(); + } + + public static T toJava(String json, Class cls) { + try { + if (json == null || "".equals(json)) { + return cls.newInstance(); + } + return om.readValue(json, cls); + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } + return null; + } + + public static T toJava(String json, TypeReference valueTypeRef) { + try { + return om.readValue(json, valueTypeRef); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + public static T map(Object object, Class tClass) { + try { + T t = tClass.newInstance(); + map(object, t); + return t; + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + public static void map(Object object, Object target) { + map(object, target, null); + } + + public static void map(Object object, Object target, Converter converter) { + BeanCopier copier = BeanCopier.create(object.getClass(), target.getClass(), converter != null); + copier.copy(object, target, converter); + } + +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/utils/ProcessUtil.java b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/ProcessUtil.java new file mode 100644 index 00000000..d3450539 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/ProcessUtil.java @@ -0,0 +1,135 @@ +package xyz.wbsite.dbtool.web.framework.utils; + +import java.awt.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * 程序操作工具 + * + * @author + * @version 0.0.1 + * @since 2017-01-01 + */ +public class ProcessUtil { + /** + * 启动windows系统下的exe文件 + * @param path 可执行exe文件路径 + */ + public static void execExe(String path) { + Runtime rn = Runtime.getRuntime(); + Process p = null; + try { + p = rn.exec(path); + } catch (Exception e) { + System.out.println("Error exec!"); + } + } + + /** + * 执行windows批处理文件路 + * @param path 可执行批处理文件路径 + */ + public static void execBat(String path) { + Runtime rn = Runtime.getRuntime(); + Process p = null; + try { + p = rn.exec(path); + } catch (Exception e) { + System.out.println("Error exec!"); + } + } + + /** + * 执行windows cmd命令 + * @param command cmd命令 + */ + public static String execCmd(String command) { + return exec("cmd /c " + command); + } + + + /** + * 执行运行环境命令 + * @param command cmd命令 + */ + public static String exec(String command) { + StringBuilder build = new StringBuilder(); + Runtime runtime = Runtime.getRuntime(); + Process process = null; + try { + process = runtime.exec(command); + BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); + String line = null; + while ((line = br.readLine()) != null) { + build.append(line); + } + process.destroy(); + } catch (IOException e) { + e.printStackTrace(); + } + return build.toString(); + } + + /** + * @throws IOException + * @desc 杀死进程 + * @author zp + * @date 2018-3-29 + */ + public static void killProc(String processName) throws IOException { + if (processName != null && !"".equals(processName)) { + execCmd("taskkill /F /IM " + processName); + } + } + + /** + * @desc 判断进程是否开启 + * @author zp + * @date 2018-3-29 + */ + public static boolean findProcess(String processName) { + BufferedReader bufferedReader = null; + try { + Process proc = Runtime.getRuntime().exec("tasklist -fi " + '"' + "imagename eq " + processName + '"'); + bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream())); + String line = null; + while ((line = bufferedReader.readLine()) != null) { + if (line.contains(processName)) { + return true; + } + } + return false; + } catch (Exception ex) { + ex.printStackTrace(); + return false; + } finally { + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (Exception ex) { + } + } + } + } + + public static void main(String[] args) { +// try {//调用bat文件,出现黑窗口 +// executeCmd("cmd /k start E:\\windows_amd64\\sunny.bat"); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// try { +// executeCmd("E:\\windows_amd64\\sunny.exe clientid 213609147996,201822147996"); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// execExe("D:\\windows_amd64\\sunny.exe clientid 213609147996,201822147996"); +// execBat("D:\\windows_amd64\\exec.bat"); +// System.out.println("==================="); +// System.out.println(s); +// System.out.println("==================="); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/utils/RSAUtil.java b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/RSAUtil.java new file mode 100644 index 00000000..deeaa581 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/RSAUtil.java @@ -0,0 +1,225 @@ +package xyz.wbsite.dbtool.web.framework.utils; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import javax.crypto.Cipher; +import java.security.*; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.Arrays; + +/** + * RSAUtil - RSA工具类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class RSAUtil { + + private static String cryptPublicKeyBase64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTrwfsrJjCF+pP4S3A/wrD4U1txg53EuBC1mPt" + + "3vGXvSK2U0YNRVR3Q65ooHnPKmk4LwI8v+7+ATTxUg3qkuRiDuzBa5zLkYKM50LOgEWSdOKzbnbx" + + "a5FnE7IXawNt1p8+MVN1TTI7J/fZy6g1x0WBy1odE5Osru4WfZNOqQtjHwIDAQAB"; + private static String cryptPrivateKeyBase64 = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJOvB+ysmMIX6k/hLcD/CsPhTW3G" + + "DncS4ELWY+3e8Ze9IrZTRg1FVHdDrmigec8qaTgvAjy/7v4BNPFSDeqS5GIO7MFrnMuRgoznQs6A" + + "RZJ04rNudvFrkWcTshdrA23Wnz4xU3VNMjsn99nLqDXHRYHLWh0Tk6yu7hZ9k06pC2MfAgMBAAEC" + + "gYBjLRjKRMI1HfBZgmPChsPI9YWU4XuXVVLLL8Rd2uktOHOWM2gIw3VMvmPimVoT2GxesZr0BwTN" + + "CSxvnuX/kHPTqtsIu1r5Iup3mGbvlj3sn8RvG0yvUDglDN7QVDqqN7XWvHJSBVfBzDXeExA/WGnE" + + "6BOocNT9qkqA/UWNbCXGKQJBAN0Fd/P2D6EvCd2RztHhzVE6V8s/LwOTDnGn/YhdMpddy9TwZpBi" + + "r7I6lzcLWQ1HfDUive3t+DGXqPqr/4FfkG0CQQCrDlZKf216QrXOmJ70LQSbflgvGYU+b6kLFyEh" + + "+15HcIBfKUQCU+XUK4UzLMQDYxdngTNMNyq4AQ9Sh0tUTUI7AkEAtkq9XayzxWhLhcCtyTOoqPcq" + + "1Aqf1x3iCuHYXTEo+ek1pcJFhY6vhJuIfrDQWQB9tEGcTvI4A4cnquBTkzvjnQJAYid58ImqYmuB" + + "M6l0HJzwdeFL7MryIF+mWozNIFjDQq8VmoVtVwCZcuP+LN1VJLRpq6UBsIw/YRKKnkqwORGUHQJA" + + "UuR0G/3Hai+vKDA14tIYIH6C4zNmbULxAEuQVh9thfafWNmiDcifApvkxQ2ewXwEGeJtz44zv6iY" + + "3f3yq+a2OQ=="; + + private static String signPublicKeyBase64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTrwfsrJjCF+pP4S3A/wrD4U1txg53EuBC1mPt" + + "3vGXvSK2U0YNRVR3Q65ooHnPKmk4LwI8v+7+ATTxUg3qkuRiDuzBa5zLkYKM50LOgEWSdOKzbnbx" + + "a5FnE7IXawNt1p8+MVN1TTI7J/fZy6g1x0WBy1odE5Osru4WfZNOqQtjHwIDAQAB"; + private static String signPrivateKeyBase64 = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJOvB+ysmMIX6k/hLcD/CsPhTW3G" + + "DncS4ELWY+3e8Ze9IrZTRg1FVHdDrmigec8qaTgvAjy/7v4BNPFSDeqS5GIO7MFrnMuRgoznQs6A" + + "RZJ04rNudvFrkWcTshdrA23Wnz4xU3VNMjsn99nLqDXHRYHLWh0Tk6yu7hZ9k06pC2MfAgMBAAEC" + + "gYBjLRjKRMI1HfBZgmPChsPI9YWU4XuXVVLLL8Rd2uktOHOWM2gIw3VMvmPimVoT2GxesZr0BwTN" + + "CSxvnuX/kHPTqtsIu1r5Iup3mGbvlj3sn8RvG0yvUDglDN7QVDqqN7XWvHJSBVfBzDXeExA/WGnE" + + "6BOocNT9qkqA/UWNbCXGKQJBAN0Fd/P2D6EvCd2RztHhzVE6V8s/LwOTDnGn/YhdMpddy9TwZpBi" + + "r7I6lzcLWQ1HfDUive3t+DGXqPqr/4FfkG0CQQCrDlZKf216QrXOmJ70LQSbflgvGYU+b6kLFyEh" + + "+15HcIBfKUQCU+XUK4UzLMQDYxdngTNMNyq4AQ9Sh0tUTUI7AkEAtkq9XayzxWhLhcCtyTOoqPcq" + + "1Aqf1x3iCuHYXTEo+ek1pcJFhY6vhJuIfrDQWQB9tEGcTvI4A4cnquBTkzvjnQJAYid58ImqYmuB" + + "M6l0HJzwdeFL7MryIF+mWozNIFjDQq8VmoVtVwCZcuP+LN1VJLRpq6UBsIw/YRKKnkqwORGUHQJA" + + "UuR0G/3Hai+vKDA14tIYIH6C4zNmbULxAEuQVh9thfafWNmiDcifApvkxQ2ewXwEGeJtz44zv6iY" + + "3f3yq+a2OQ=="; + + /** + * 创建密钥和私钥 + */ + public static void createKey() { + try { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(1024); + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + + //公钥 + RSAPublicKey aPublic = (RSAPublicKey) keyPair.getPublic(); + //私钥 + RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate(); + //把密钥对象对应的字节转为Base64字符存储 + System.err.println("publicKeyBase64-->" + new BASE64Encoder().encode(aPublic.getEncoded())); + System.err.println("privateKeyBase64-->" + new BASE64Encoder().encode(aPrivate.getEncoded())); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + } + + /** + * 加密 + * + * @param data 待加密明文 + */ + public static String encrypt(String data) { + try { + //生成公钥对象 + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(cryptPublicKeyBase64)); + PublicKey aPublic = keyFactory.generatePublic(x509EncodedKeySpec); + + StringBuffer miwen = new StringBuffer(); + //分段加密开始 + Cipher rsa = Cipher.getInstance("RSA"); + rsa.init(Cipher.ENCRYPT_MODE, aPublic); + int offset = 0; + byte[] b = data.getBytes(); + while (offset < b.length) { + byte[] bytes = rsa.doFinal(Arrays.copyOfRange(b, offset, Math.min(offset + 117, b.length))); + miwen.append(new BASE64Encoder().encode(bytes)); + offset += 117; + } + return miwen.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 解密 + * + * @param miwen base64密文 + */ + public static String decrypt(String miwen) { + try { + //生成私钥对象 + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(cryptPrivateKeyBase64)); + PrivateKey aPrivate = keyFactory.generatePrivate(pkcs8EncodedKeySpec); + + Cipher rsa = Cipher.getInstance("RSA"); + rsa.init(Cipher.DECRYPT_MODE, aPrivate); + //获得密文字节 + byte[] data = new BASE64Decoder().decodeBuffer(miwen.toString()); + int offset = 0; + StringBuffer getMing = new StringBuffer(); + while (offset < data.length) { + byte[] bytes = rsa.doFinal(Arrays.copyOfRange(data, offset, Math.min(offset + 128, data.length))); + getMing.append(new String(bytes)); + offset += 128; + } + return getMing.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * RSA签名 + * + * @param content 待签名数据 + * @param privateKey 私钥 + * @param encode 字符集编码 + * @return 签名值 + */ + public static String sign(String content, String privateKey, String encode) { + try { + + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKey)); + PrivateKey aPrivate = keyFactory.generatePrivate(priPKCS8); + + Signature signature = Signature.getInstance("SHA1WithRSA"); + + signature.initSign(aPrivate); + signature.update(content.getBytes(encode)); + + byte[] signed = signature.sign(); + + return new BASE64Encoder().encode(signed); + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + /** + * RSA验签名检查 + * + * @param content 待签名数据 + * @param sign 签名值 + * @param publicKey 公钥 + * @param encode 字符集编码 + * @return 布尔值 + */ + public static boolean doCheck(String content, String sign, String publicKey, String encode) { + try { + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + byte[] encodedKey = new BASE64Decoder().decodeBuffer(publicKey); + PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); + + + Signature signature = Signature.getInstance("SHA1WithRSA"); + + signature.initVerify(pubKey); + signature.update(content.getBytes(encode)); + + boolean bverify = signature.verify(new BASE64Decoder().decodeBuffer(sign)); + return bverify; + + } catch (Exception e) { + e.printStackTrace(); + } + + return false; + } + + /** + * 测试实例 + * + * @param args + */ + public static void main(String[] args) { + {//创建秘钥对 + RSAUtil.createKey(); + } + + {//加解密 + + //加密 + String encrypt = RSAUtil.encrypt("我有一个苹果"); + System.out.println(encrypt); + + //解密 + String decrypt = RSAUtil.decrypt(encrypt); + System.out.println(decrypt); + } + + + String sign = sign("我有一个苹果", signPrivateKeyBase64, "utf-8"); + System.out.println(sign); + + boolean b = doCheck("我有一个苹果", sign, signPublicKeyBase64, "utf-8"); + System.out.println(b); + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/utils/ValidationUtil.java b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/ValidationUtil.java new file mode 100644 index 00000000..1c09aa56 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/ValidationUtil.java @@ -0,0 +1,270 @@ +package xyz.wbsite.dbtool.web.framework.utils; + + +import xyz.wbsite.dbtool.web.framework.base.BaseRequest; +import xyz.wbsite.dbtool.web.framework.base.BaseResponse; +import xyz.wbsite.dbtool.web.framework.base.ErrorType; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +/** + * 验证工具类。提供一些通用简单的数据验证功能。 + */ +public class ValidationUtil { + + private static Validator validator; + + /** + * 检查ID是否合法 + * + * @param id 要检查的ID + * @return true, ID合法 + */ + public static Boolean checkId(Long id) { + return !(null == id || id < 1); + } + + public static Boolean checkDate(String value) { + try { + Double.valueOf(value); + } catch (Exception e) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + sdf.parse(value); + return true; + } catch (ParseException e1) { + e1.printStackTrace(); + } + return false; + } + return true; + } + + public static Boolean checkDatetime(String value) { + try { + Double.valueOf(value); + } catch (Exception e) { + List sdfList = new ArrayList<>(); + sdfList.add("yyyy-MM-dd HH:mm:ss"); + sdfList.add("yyyy-MM-dd hh:mm:ss"); + sdfList.add("yyyy/MM/dd HH:mm:ss"); + sdfList.add("yyyy/MM/dd hh:mm:ss"); + + for (int i = 0; i < sdfList.size(); i++) { + String sdfValue = sdfList.get(i); + SimpleDateFormat sdf = new SimpleDateFormat(sdfValue); + try { + sdf.parse(value); + return true; + } catch (ParseException ignored) { + } + } + return false; + } + return true; + } + + public static Boolean checkDouble(String value) { + try { + Double.parseDouble(value); + } catch (Exception e) { + return false; + } + return true; + } + + /** + * 检查一个字符串是否可以转为整数。 + * + * @param value 要检查的字符串 + * @return true || false + */ + public static Boolean checkInteger(String value) { + try { + Double d = Double.parseDouble(value); + int i = d.intValue(); + return d == i; + } catch (Exception e) { + return false; + } + } + + /** + * 检查一个字符串是否可以转为长整数。 + * + * @param value 要检查的字符串 + * @return true || false + */ + public static boolean checkLong(String value) { + try { + Double d = Double.parseDouble(value); + long l = d.longValue(); + return d == l; + } catch (Exception e) { + return false; + } + } + + /** + * 检查用户ID的列表是否合法 + * + * @param ids 要检查的ID列表 + * @return true, 输入的ID列表合法 + */ + public static Boolean checkIdList(List ids) { + return !(null == ids || ids.size() == 0); + } + + /** + * 检查字符串。不为空返回true;为空返回false。
+ * 内容为空也认为是空 + * + * @param str 要检查的字符串 + * @return 检查的结果。true,检查通过;false,检查不通过。 + */ + public static Boolean checkString(String str) { + return !(null == str || 0 == str.trim().length()); + } + + /** + * 检查字符串的长度是否符合要求。
该方法不会删除字符串前后的空格 + * + * @param str 要进行判断的字符串 + * @param minLength 字符串限制的最小长度(包含) + * @param maxLength 字符串限制的最大长度(包含) + * @return 例如:限制长度 2,50。字符串为"aa"返回true,字符串为"a"返回false + */ + public static Boolean checkStringLength(String str, int minLength, int maxLength) { + if (null == str) { + return false; + } else { + if (str.length() >= minLength && str.length() <= maxLength) { + return true; + } + } + return false; + } + + /** + * 检查邮箱格式是否正确
+ * + * @param email 要检查的邮箱地址 + * @return true, 格式正确;false,格式不正确
+ * 例如:
+ * 0123-abcd_ABCD@0123-abcd_ABCD.00aaBB--__.cc true
+ * a@a.a true
+ * tony@sina@qq.com false + */ + public static Boolean checkEmail(String email) { + //验证邮箱地址的正则表达式 + Pattern p; + p = Pattern.compile( + "^([a-zA-Z0-9]+[_|_|-|-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|-|-|.]?)*[a-zA-Z0-9]+.[a-zA-Z]{2,3}$"); + Matcher m = p.matcher(email); + return m.matches(); + } + + + /** + * 检查文件路径格式是否正确
+ * + * @param filePath 要检查的文件路径 + * @return true, 格式正确;false,格式不正确
+ * 例如:
+ * C:\b.txt true
+ * C:\abc\a.txt true
+ * C:\windows\sys<\mfc.dll false + */ + public static Boolean checkFilePath(String filePath) { + //验证文件路径格式的正则表达式 + Pattern p = Pattern.compile("^(?(?:[a-zA-Z]:)?\\\\(?:[^\\\\\\?\\/\\*\\|<>:\"]+\\\\)+)(?(?[^\\\\\\?\\/\\*\\|<>:\"]+?)\\.(?[^.\\\\\\?\\/\\*\\|<>:\"]+))$"); + Matcher m = p.matcher(filePath); + return m.matches(); + } + + /** + * 检查电话号码格式是否正确。 + * + * @param phone 要检查的电话号码 + * @return true, 格式正确;false,格式不正确
+ * 例如:
+ * 13345661234 true
+ * 16812341234 false
+ * 0512-123456 false
+ * 0512-2345678 true
+ * 12345678 false
+ * 22345678 true + */ + public static Boolean checkPhone(String phone) { + List list = new LinkedList<>(); + list.add(Pattern.compile("^[1][3,4,5,8][0-9]{9}$")); //验证手机号 + list.add(Pattern.compile("^[0][1-9]{1,2}[0-9]-[2-9][0-9]{6,7}$")); //验证带区号固定电话,区号后加“-” + list.add(Pattern.compile("^[2-9][0-9]{6,7}$")); //验证不带区号的固定电话 + list.add(Pattern.compile("([0][1-9]{1,2}[0-9])[2-9][0-9]{6,7}$")); + + Matcher matcher; + Boolean result = false; + for (Pattern pattern : list) { + matcher = pattern.matcher(phone); //遍历匹配 + result |= matcher.matches(); //对所有的匹配结果做或运算。 + } + return result; + } + + /** + * 检查URL是否正确 + * + * @param url + * @return + */ + public static Boolean checkUrl(String url) { + List list = new LinkedList<>(); + list.add(Pattern.compile("^(http|www|ftp|)?(://)?(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*((:\\d+)?)(/(\\w+(-\\w+)*))*(\\.?(\\w)*)(\\?)?(((\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*(\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*)*(\\w*)*)$")); + + Matcher matcher; + Boolean result = false; + for (Pattern pattern : list) { + matcher = pattern.matcher(url); //遍历匹配 + result |= matcher.matches(); //对所有的匹配结果做或运算。 + } + return result; + } + + public static T validate(BaseRequest req, T response) { + + if (req == null) { + response.addError(ErrorType.EXPECTATION_NULL, "请求对象不能为空"); + return response; + } + + try { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + validator = factory.getValidator(); + + Set> constraintViolations = validator.validate(req); + + if (constraintViolations.size() > 0) { + for (ConstraintViolation violation : constraintViolations) { + response.addError(ErrorType.INVALID_PARAMETER, violation.getMessage()); + } + } + } catch (Exception e) { + e.printStackTrace(); + LogUtil.dumpException(e); + response.addError(ErrorType.BUSINESS_ERROR, e.getMessage()); + } + return response; + } +} diff --git a/src/main/java/xyz/wbsite/dbtool/web/framework/utils/WebUtils.java b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/WebUtils.java new file mode 100644 index 00000000..991b33f3 --- /dev/null +++ b/src/main/java/xyz/wbsite/dbtool/web/framework/utils/WebUtils.java @@ -0,0 +1,459 @@ +package xyz.wbsite.dbtool.web.framework.utils; + +import javax.net.ssl.*; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * WebUtils - 模拟http访问工具类 + * + * @author wangbing + * @version 0.0.1 + * @since 2017-01-01 + */ +public class WebUtils { + private static final String DEFAULT_CHARSET = "UTF-8"; + private static final String METHOD_POST = "POST"; + private static final String METHOD_GET = "GET"; + //private static final Certificate verisign; // + private static boolean ignoreSSLCheck; // 忽略SSL检查 + + private static class TrustAllTrustManager implements X509TrustManager { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + } + + private WebUtils() { + } + + public static void setIgnoreSSLCheck(boolean ignoreSSLCheck) { + WebUtils.ignoreSSLCheck = ignoreSSLCheck; + } + + /** + * 执行HTTP POST请求。 + * + * @param url 请求地址 + * @param params 请求参数 + * @return 响应字符串 + */ + public static String doPost(String url, Map params, int connectTimeout, int readTimeout) throws IOException { + return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout); + } + + /** + * 执行HTTP POST请求。 + * + * @param url 请求地址 + * @param params 请求参数 + * @param charset 字符集,如UTF-8, GBK, GB2312 + * @return 响应字符串 + */ + public static String doPost(String url, Map params, String charset, int connectTimeout, int readTimeout) throws IOException { + return doPost(url, params, charset, connectTimeout, readTimeout, null); + } + + public static String doPost(String url, Map params, String charset, int connectTimeout, int readTimeout, Map headerMap) throws IOException { + String ctype = "application/x-www-form-urlencoded;charset=" + charset; + String query = buildQuery(params, charset); + byte[] content = {}; + if (query != null) { + content = query.getBytes(charset); + } + return _doPost(url, ctype, content, connectTimeout, readTimeout, headerMap); + } + + /** + * 执行HTTP POST请求。 + * + * @param url 请求地址 + * @param ctype 请求类型 + * @param content 请求字节数组 + * @return 响应字符串 + */ + public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws IOException { + return _doPost(url, ctype, content, connectTimeout, readTimeout, null); + } + + private static String _doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout, Map headerMap) throws IOException { + HttpURLConnection conn = null; + OutputStream out = null; + String rsp = null; + try { + try { + conn = getConnection(new URL(url), METHOD_POST, ctype, headerMap); + conn.setConnectTimeout(connectTimeout); + conn.setReadTimeout(readTimeout); + } catch (IOException e) { + throw e; + } + try { + out = conn.getOutputStream(); + out.write(content); + rsp = getResponseAsString(conn); + } catch (IOException e) { + throw e; + } + } finally { + if (out != null) { + out.close(); + } + if (conn != null) { + conn.disconnect(); + } + } + + return rsp; + } + + private static byte[] getTextEntry(String fieldName, String fieldValue, String charset) throws IOException { + StringBuilder entry = new StringBuilder(); + entry.append("Content-Disposition:form-data;name=\""); + entry.append(fieldName); + entry.append("\"\r\nContent-Type:text/plain\r\n\r\n"); + entry.append(fieldValue); + return entry.toString().getBytes(charset); + } + + private static byte[] getFileEntry(String fieldName, String fileName, String mimeType, String charset) throws IOException { + StringBuilder entry = new StringBuilder(); + entry.append("Content-Disposition:form-data;name=\""); + entry.append(fieldName); + entry.append("\";filename=\""); + entry.append(fileName); + entry.append("\"\r\nContent-Type:"); + entry.append(mimeType); + entry.append("\r\n\r\n"); + return entry.toString().getBytes(charset); + } + + /** + * 执行HTTP GET请求。 + * + * @param url 请求地址 + * @param params 请求参数 + * @return 响应字符串 + */ + public static String doGet(String url, Map params) throws IOException { + return doGet(url, params, DEFAULT_CHARSET); + } + + /** + * 执行HTTP GET请求。 + * + * @param url 请求地址 + * @param params 请求参数 + * @param charset 字符集,如UTF-8, GBK, GB2312 + * @return 响应字符串 + */ + public static String doGet(String url, Map params, String charset) throws IOException { + HttpURLConnection conn = null; + String rsp = null; + + try { + String ctype = "application/x-www-form-urlencoded;charset=" + charset; + String query = buildQuery(params, charset); + try { + conn = getConnection(buildGetUrl(url, query), METHOD_GET, ctype, null); + } catch (IOException e) { + throw e; + } + + try { + rsp = getResponseAsString(conn); + } catch (IOException e) { + throw e; + } + } finally { + if (conn != null) { + conn.disconnect(); + } + } + + return rsp; + } + + private static HttpURLConnection getConnection(URL url, String method, String ctype, Map headerMap) throws IOException { + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + if (conn instanceof HttpsURLConnection) { + HttpsURLConnection connHttps = (HttpsURLConnection) conn; + if (ignoreSSLCheck) { + try { + SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(null, new TrustManager[]{new TrustAllTrustManager()}, new SecureRandom()); + connHttps.setSSLSocketFactory(ctx.getSocketFactory()); + connHttps.setHostnameVerifier(new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); + } catch (Exception e) { + throw new IOException(e); + } + } else { + try { + //SSLContext ctx = SSLContext.getInstance("TLS"); + //ctx.init(null, new TrustManager[] { new VerisignTrustManager() }, new SecureRandom()); + //connHttps.setSSLSocketFactory(ctx.getSocketFactory()); + } catch (Exception e) { + throw new IOException(e); + } + } + conn = connHttps; + } + + conn.setRequestMethod(method); + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setRequestProperty("Accept", "text/xml,text/javascript"); + conn.setRequestProperty("User-Agent", "top-sdk-java"); + conn.setRequestProperty("Content-Type", ctype); + if (headerMap != null) { + for (Map.Entry entry : headerMap.entrySet()) { + conn.setRequestProperty(entry.getKey(), entry.getValue()); + } + } + return conn; + } + + private static URL buildGetUrl(String strUrl, String query) throws IOException { + URL url = new URL(strUrl); + if (isEmpty(query)) { + return url; + } + + if (isEmpty(url.getQuery())) { + if (strUrl.endsWith("?")) { + strUrl = strUrl + query; + } else { + strUrl = strUrl + "?" + query; + } + } else { + if (strUrl.endsWith("&")) { + strUrl = strUrl + query; + } else { + strUrl = strUrl + "&" + query; + } + } + + return new URL(strUrl); + } + + public static String buildQuery(Map params, String charset) throws IOException { + if (params == null || params.isEmpty()) { + return null; + } + + StringBuilder query = new StringBuilder(); + Set> entries = params.entrySet(); + boolean hasParam = false; + + for (Map.Entry entry : entries) { + String name = entry.getKey(); + String value = entry.getValue(); + // 忽略参数名或参数值为空的参数 + if (areNotEmpty(name, value)) { + if (hasParam) { + query.append("&"); + } else { + hasParam = true; + } + + query.append(name).append("=").append(URLEncoder.encode(value, charset)); + } + } + + return query.toString(); + } + + public static boolean isEmpty(String value) { + int strLen; + if (value == null || (strLen = value.length()) == 0) { + return true; + } + for (int i = 0; i < strLen; i++) { + if ((Character.isWhitespace(value.charAt(i)) == false)) { + return false; + } + } + return true; + } + + /** + * 检查指定的字符串列表是否不为空。 + */ + public static boolean areNotEmpty(String... values) { + boolean result = true; + if (values == null || values.length == 0) { + result = false; + } else { + for (String value : values) { + result &= !isEmpty(value); + } + } + return result; + } + + protected static String getResponseAsString(HttpURLConnection conn) throws IOException { + String charset = getResponseCharset(conn.getContentType()); + InputStream es = conn.getErrorStream(); + if (es == null) { + return getStreamAsString(conn.getInputStream(), charset); + } else { + String msg = getStreamAsString(es, charset); + if (isEmpty(msg)) { + throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage()); + } else { + throw new IOException(msg); + } + } + } + + private static String getStreamAsString(InputStream stream, String charset) throws IOException { + try { + Reader reader = new InputStreamReader(stream, charset); + StringBuilder response = new StringBuilder(); + + final char[] buff = new char[1024]; + int read = 0; + while ((read = reader.read(buff)) > 0) { + response.append(buff, 0, read); + } + + return response.toString(); + } finally { + if (stream != null) { + stream.close(); + } + } + } + + private static String getResponseCharset(String ctype) { + String charset = DEFAULT_CHARSET; + + if (!isEmpty(ctype)) { + String[] params = ctype.split(";"); + for (String param : params) { + param = param.trim(); + if (param.startsWith("charset")) { + String[] pair = param.split("=", 2); + if (pair.length == 2) { + if (!isEmpty(pair[1])) { + charset = pair[1].trim(); + } + } + break; + } + } + } + + return charset; + } + + /** + * 使用默认的UTF-8字符集反编码请求参数值。 + * + * @param value 参数值 + * @return 反编码后的参数值 + */ + public static String decode(String value) { + return decode(value, DEFAULT_CHARSET); + } + + /** + * 使用默认的UTF-8字符集编码请求参数值。 + * + * @param value 参数值 + * @return 编码后的参数值 + */ + public static String encode(String value) { + return encode(value, DEFAULT_CHARSET); + } + + /** + * 使用指定的字符集反编码请求参数值。 + * + * @param value 参数值 + * @param charset 字符集 + * @return 反编码后的参数值 + */ + public static String decode(String value, String charset) { + String result = null; + if (!isEmpty(value)) { + try { + result = URLDecoder.decode(value, charset); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + return result; + } + + /** + * 使用指定的字符集编码请求参数值。 + * + * @param value 参数值 + * @param charset 字符集 + * @return 编码后的参数值 + */ + public static String encode(String value, String charset) { + String result = null; + if (!isEmpty(value)) { + try { + result = URLEncoder.encode(value, charset); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + return result; + } + + private static Map getParamsFromUrl(String url) { + Map map = null; + if (url != null && url.indexOf('?') != -1) { + map = splitUrlQuery(url.substring(url.indexOf('?') + 1)); + } + if (map == null) { + map = new HashMap(); + } + return map; + } + + /** + * 从URL中提取所有的参数。 + * + * @param query URL地址 + * @return 参数映射 + */ + public static Map splitUrlQuery(String query) { + Map result = new HashMap(); + + String[] pairs = query.split("&"); + if (pairs != null && pairs.length > 0) { + for (String pair : pairs) { + String[] param = pair.split("=", 2); + if (param != null && param.length == 2) { + result.put(param[0], param[1]); + } + } + } + + return result; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..30f1bb25 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,34 @@ +# 开发环境 +server.port=80 +server.servlet.context-path=/ +spring.mvc.static-path-pattern=/static/** +spring.resources.static-locations=classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources +spring.application.name=SpringBoot +# 根路径、欢迎页 +web.welcome.page = index +# 排除的不需要验证的URL +web.url.excluded = /static/**,/open/**,/api,/index,/,/login +# 默认的登录URL +web.url.login = /login +# 日志配置 +logging.config=classpath:logback-config.xml +# 热部署生效 +spring.devtools.restart.enabled=true +# freemarker +spring.freemarker.enabled=true +spring.freemarker.allow-request-override=false +spring.freemarker.cache=true +spring.freemarker.check-template-location=true +spring.freemarker.charset=UTF-8 +spring.freemarker.content-type=text/html +spring.freemarker.expose-request-attributes=false +spring.freemarker.expose-session-attributes=false +spring.freemarker.expose-spring-macro-helpers=false +spring.freemarker.settings.template_update_delay=1 +spring.freemarker.settings.locale=zh_CN +spring.freemarker.settings.datetime_format=yyyy-MM-dd +spring.freemarker.settings.date_format=yyyy-MM-dd +spring.freemarker.settings.number_format=#.## +spring.freemarker.settings.classic_compatible=true +spring.freemarker.settings.whitespace_stripping=true +spring.freemarker.settings.url_escaping_charset=utf-8 diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt new file mode 100644 index 00000000..93c62af3 --- /dev/null +++ b/src/main/resources/banner.txt @@ -0,0 +1,33 @@ +${AnsiColor.BRIGHT_YELLOW} +////////////////////////////////////////////////////////////////////////////////////////////////////////// +// _ooOoo_ // // +// o8888888o 佛 代 // ┏┓   ┏┓ 神 代 // +// 88" . "88 祖 码 // ┏┛┻━━━┛┻┓ 兽 码 // +// (| ^_^ |) 保 无 // ┃       ┃ 保 无 // +// O\ = /O 佑 BUG // ┃   ━   ┃ 佑 BUG // +// ____/`---'\____ // ┃ ┳┛ ┗┳ ┃ // +// .' \\| |// `. // ┃       ┃ // +// / \\||| : |||// \ // ┃   ┻   ┃ // +// / _||||| -:- |||||- \ // ┃       ┃ // +// | | \\\ - /// | | // ┗━┓   ┏━┛ // +// | \_| ''\---/'' | | // ┃   ┃ // +// \ .-\__ `-` ___/-. / // ┃   ┃ // +// ___`. .' /--.--\ `. . ___ // ┃   ┗━━━┓ // +// ."" '< `.___\_<|>_/___.' >'"". // ┃       ┣┓ // +// | | : `- \`.;`\ _ /`;.`/ - ` : | | // ┃       ┏┛ // +// \ \ `-. \_ __\ /__ _/ .-` / / // ┗┓┓┏━┳┓┏┛ // +// ========`-.____`-.___\_____/___.-`____.-'======== // ┃┫┫ ┃┫┫ // +// `=---=' // // +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // +////////////////////////////////////////////////////////////////////////////////////////////////////////// + _ _ _ + | | | | (_) + | |__ _ _ __ __ __ _ _ __ __ _ | |__ _ _ __ __ _ + | '_ \ | | | | \ \ /\ / / / _` || '_ \ / _` | | '_ \ | || '_ \ / _` | + | |_) || |_| | \ V V / | (_| || | | || (_| | | |_) || || | | || (_| | + |_.__/ \__, | \_/\_/ \__,_||_| |_| \__, | |_.__/ |_||_| |_| \__, | + __/ | __/ | __/ | + |___/ |___/ |___/ + + :: Spring Boot :: ${spring-boot.formatted-version} (${spring.profiles.active}) + diff --git a/src/main/resources/fxml/api.fxml b/src/main/resources/fxml/api.fxml new file mode 100644 index 00000000..485479fc --- /dev/null +++ b/src/main/resources/fxml/api.fxml @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + +
","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ue(e,t){var n;return n=void 0!==e.getElementsByTagName?e.getElementsByTagName(t||"*"):void 0!==e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&$(e,t)?S.merge([e],n):n}function ce(e,t){for(var n=0,i=e.length;nx",v.noCloneChecked=!!de.cloneNode(!0).lastChild.defaultValue;var me=k.documentElement,ve=/^key/,ge=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ye=/^([^.]*)(?:\.(.+)|)/;function be(){return!0}function _e(){return!1}function xe(){try{return k.activeElement}catch(e){}}function we(e,t,n,i,r,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(i=i||n,n=void 0),t)we(e,s,n,i,t[s],o);return e}if(null==i&&null==r?(r=n,i=n=void 0):null==r&&("string"==typeof n?(r=i,i=void 0):(r=i,i=n,n=void 0)),!1===r)r=_e;else if(!r)return e;return 1===o&&(a=r,(r=function(e){return S().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=S.guid++)),e.each(function(){S.event.add(this,t,r,i,n)})}S.event={global:{},add:function(t,e,n,i,r){var o,a,s,l,u,c,d,f,h,p,m,v=K.get(t);if(v)for(n.handler&&(n=(o=n).handler,r=o.selector),r&&S.find.matchesSelector(me,r),n.guid||(n.guid=S.guid++),(l=v.events)||(l=v.events={}),(a=v.handle)||(a=v.handle=function(e){return void 0!==S&&S.event.triggered!==e.type?S.event.dispatch.apply(t,arguments):void 0}),u=(e=(e||"").match(F)||[""]).length;u--;)h=m=(s=ye.exec(e[u])||[])[1],p=(s[2]||"").split(".").sort(),h&&(d=S.event.special[h]||{},h=(r?d.delegateType:d.bindType)||h,d=S.event.special[h]||{},c=S.extend({type:h,origType:m,data:i,handler:n,guid:n.guid,selector:r,needsContext:r&&S.expr.match.needsContext.test(r),namespace:p.join(".")},o),(f=l[h])||((f=l[h]=[]).delegateCount=0,d.setup&&!1!==d.setup.call(t,i,p,a)||t.addEventListener&&t.addEventListener(h,a)),d.add&&(d.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),r?f.splice(f.delegateCount++,0,c):f.push(c),S.event.global[h]=!0)},remove:function(e,t,n,i,r){var o,a,s,l,u,c,d,f,h,p,m,v=K.hasData(e)&&K.get(e);if(v&&(l=v.events)){for(u=(t=(t||"").match(F)||[""]).length;u--;)if(h=m=(s=ye.exec(t[u])||[])[1],p=(s[2]||"").split(".").sort(),h){for(d=S.event.special[h]||{},f=l[h=(i?d.delegateType:d.bindType)||h]||[],s=s[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=f.length;o--;)c=f[o],!r&&m!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||i&&i!==c.selector&&("**"!==i||!c.selector)||(f.splice(o,1),c.selector&&f.delegateCount--,d.remove&&d.remove.call(e,c));a&&!f.length&&(d.teardown&&!1!==d.teardown.call(e,p,v.handle)||S.removeEvent(e,h,v.handle),delete l[h])}else for(h in l)S.event.remove(e,h+t[u],n,i,!0);S.isEmptyObject(l)&&K.remove(e,"handle events")}},dispatch:function(e){var t,n,i,r,o,a,s=S.event.fix(e),l=new Array(arguments.length),u=(K.get(this,"events")||{})[s.type]||[],c=S.event.special[s.type]||{};for(l[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,ke=/\s*$/g;function Ee(e,t){return $(e,"table")&&$(11!==t.nodeType?t:t.firstChild,"tr")&&S(">tbody",e)[0]||e}function Te(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function De(e){var t=Me.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Oe(e,t){var n,i,r,o,a,s,l,u;if(1===t.nodeType){if(K.hasData(e)&&(o=K.access(e),a=K.set(t,o),u=o.events))for(r in delete a.handle,a.events={},u)for(n=0,i=u[r].length;n")},clone:function(e,t,n){var i,r,o,a,s,l,u,c=e.cloneNode(!0),d=S.contains(e.ownerDocument,e);if(!(v.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||S.isXMLDoc(e)))for(a=ue(c),i=0,r=(o=ue(e)).length;i").prop({charset:n.scriptCharset,src:n.url}).on("load error",r=function(e){i.remove(),r=null,e&&t("error"===e.type?404:200,e.type)}),k.head.appendChild(i[0])},abort:function(){r&&r()}}});var jt,Rt=[],Bt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Rt.pop()||S.expando+"_"+vt++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var i,r,o,a=!1!==e.jsonp&&(Bt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return i=e.jsonpCallback=S.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Bt,"$1"+i):!1!==e.jsonp&&(e.url+=(gt.test(e.url)?"&":"?")+e.jsonp+"="+i),e.converters["script json"]=function(){return o||S.error(i+" was not called"),o[0]},e.dataTypes[0]="json",r=C[i],C[i]=function(){o=arguments},n.always(function(){void 0===r?S(C).removeProp(i):C[i]=r,e[i]&&(e.jsonpCallback=t.jsonpCallback,Rt.push(i)),o&&S.isFunction(r)&&r(o[0]),o=r=void 0}),"script"}),v.createHTMLDocument=((jt=k.implementation.createHTMLDocument("").body).innerHTML="
",2===jt.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(v.createHTMLDocument?((i=(t=k.implementation.createHTMLDocument("")).createElement("base")).href=k.location.href,t.head.appendChild(i)):t=k),o=!n&&[],(r=E.exec(e))?[t.createElement(r[1])]:(r=pe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],r.childNodes)));var i,r,o},S.fn.load=function(e,t,n){var i,r,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(i):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var i,r,o,a,s,l,u=S.css(e,"position"),c=S(e),d={};"static"===u&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),l=S.css(e,"left"),("absolute"===u||"fixed"===u)&&-1<(o+l).indexOf("auto")?(a=(i=c.position()).top,r=i.left):(a=parseFloat(o)||0,r=parseFloat(l)||0),S.isFunction(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(d.top=t.top-s.top+a),null!=t.left&&(d.left=t.left-s.left+r),"using"in t?t.using.call(e,d):c.css(d)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,i,r,o=this[0];return o?o.getClientRects().length?(i=o.getBoundingClientRect(),n=(e=o.ownerDocument).documentElement,r=e.defaultView,{top:i.top+r.pageYOffset-n.clientTop,left:i.left+r.pageXOffset-n.clientLeft}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n=this[0],i={top:0,left:0};return"fixed"===S.css(n,"position")?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),$(e[0],"html")||(i=e.offset()),i={top:i.top+S.css(e[0],"borderTopWidth",!0),left:i.left+S.css(e[0],"borderLeftWidth",!0)}),{top:t.top-i.top-S.css(n,"marginTop",!0),left:t.left-i.left-S.css(n,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent;e&&"static"===S.css(e,"position");)e=e.offsetParent;return e||me})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,r){var o="pageYOffset"===r;S.fn[t]=function(e){return z(this,function(e,t,n){var i;return S.isWindow(e)?i=e:9===e.nodeType&&(i=e.defaultView),void 0===n?i?i[r]:e[t]:void(i?i.scrollTo(o?i.pageXOffset:n,o?n:i.pageYOffset):e[t]=n)},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=je(v.pixelPosition,function(e,t){if(t)return t=Le(e,n),Ie.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(i,o){S.fn[o]=function(e,t){var n=arguments.length&&(i||"boolean"!=typeof e),r=i||(!0===e||!0===t?"margin":"border");return z(this,function(e,t,n){var i;return S.isWindow(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(i=e.documentElement,Math.max(e.body["scroll"+a],i["scroll"+a],e.body["offset"+a],i["offset"+a],i["client"+a])):void 0===n?S.css(e,t,r):S.style(e,t,n,r)},s,n?e:void 0,n)}})}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,i){return this.on(t,e,n,i)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),S.holdReady=function(e){e?S.readyWait++:S.ready(!0)},S.isArray=Array.isArray,S.parseJSON=JSON.parse,S.nodeName=$,"function"==typeof define&&define.amd&&define("jquery",[],function(){return S});var Vt=C.jQuery,Ht=C.$;return S.noConflict=function(e){return C.$===S&&(C.$=Ht),e&&C.jQuery===S&&(C.jQuery=Vt),S},e||(C.jQuery=C.$=S),S}),function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Vue=t()}(this,function(){"use strict";var g=Object.freeze({});function I(e){return null==e}function F(e){return null!=e}function A(e){return!0===e}function m(e){return"string"==typeof e||"number"==typeof e||"symbol"==typeof e||"boolean"==typeof e}function L(e){return null!==e&&"object"==typeof e}var t=Object.prototype.toString;function d(e){return t.call(e).slice(8,-1)}function u(e){return"[object Object]"===t.call(e)}function r(e){return"[object RegExp]"===t.call(e)}function o(e){var t=parseFloat(String(e));return 0<=t&&Math.floor(t)===t&&isFinite(e)}function n(e){return null==e?"":"object"==typeof e?JSON.stringify(e,null,2):String(e)}function j(e){var t=parseFloat(e);return isNaN(t)?e:t}function s(e,t){for(var n=Object.create(null),i=e.split(","),r=0;r";var n="function"==typeof e&&null!=e.cid?e.options:e._isVue?e.$options||e.constructor.options:e||{},i=n.name||n._componentTag,r=n.__file;if(!i&&r){var o=r.match(/([^/\\]+)\.vue$/);i=o&&o[1]}return(i?"<"+i.replace(fe,function(e){return e.toUpperCase()}).replace(/[-_]/g,"")+">":"")+(r&&!1!==t?" at "+r:"")};ue=function(e){if(e._isVue&&e.$parent){for(var t=[],n=0;e;){if(0>=1;return n}(" ",5+2*t))+(Array.isArray(e)?ce(e[0])+"... ("+e[1]+" recursive calls)":ce(e))}).join("\n")}return"\n\n(found in "+ce(e)+")"};var he=0,pe=function(){this.id=he++,this.subs=[]};pe.prototype.addSub=function(e){this.subs.push(e)},pe.prototype.removeSub=function(e){f(this.subs,e)},pe.prototype.depend=function(){pe.target&&pe.target.addDep(this)},pe.prototype.notify=function(){for(var e=this.subs.slice(),t=0,n=e.length;tqt)){se("You may have an infinite update loop "+(e.user?'in watcher with expression "'+e.expression+'"':"in a component render function."),e.vm);break}var n=Kt.slice(),i=Wt.slice();Jt=Wt.length=Kt.length=0,Ut={},Gt=Xt=!(Yt={}),function(e){for(var t=0;te.id;)n--;Wt.splice(n+1,0,e)}else Wt.push(e);Gt||(Gt=!0,dt(Zt))}}(this)},en.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||L(e)||this.deep){var t=this.value;if(this.value=e,this.user)try{this.cb.call(this.vm,e,t)}catch(e){Je(e,this.vm,'callback for watcher "'+this.expression+'"')}else this.cb.call(this.vm,e,t)}}},en.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},en.prototype.depend=function(){for(var e=this.deps.length;e--;)this.deps[e].depend()},en.prototype.teardown=function(){if(this.active){this.vm._isBeingDestroyed||f(this.vm._watchers,this);for(var e=this.deps.length;e--;)this.deps[e].removeSub(this);this.active=!1}};var tn={enumerable:!0,configurable:!0,get:k,set:k};function nn(e,t,n){tn.get=function(){return this[t][n]},tn.set=function(e){this[t][n]=e},Object.defineProperty(e,n,tn)}function rn(e){e._watchers=[];var t=e.$options;t.props&&function(i,r){var o=i.$options.propsData||{},a=i._props={},s=i.$options._propKeys=[];i.$parent&&$e(!1);var e=function(e){s.push(e);var t=We(e,r,o,i),n=_(e);(c(n)||V.isReservedAttr(n))&&se('"'+n+'" is a reserved attribute and cannot be used as component prop.',i),Pe(a,e,t,function(){i.$parent&&!Bt&&se("Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: \""+e+'"',i)}),e in i||nn(i,"_props",e)};for(var t in r)e(t);$e(!0)}(e,t.props),t.methods&&function(e,t){var n=e.$options.props;for(var i in t)null==t[i]&&se('Method "'+i+'" has an undefined value in the component definition. Did you reference the function correctly?',e),n&&y(n,i)&&se('Method "'+i+'" has already been defined as a prop.',e),i in e&&O(i)&&se('Method "'+i+'" conflicts with an existing Vue instance method. Avoid defining component methods that start with _ or $.'),e[i]=null==t[i]?k:v(t[i],e)}(e,t.methods),t.data?function(e){var t=e.$options.data;u(t=e._data="function"==typeof t?function(e,t){ve();try{return e.call(t,t)}catch(e){return Je(e,t,"data()"),{}}finally{ge()}}(t,e):t||{})||(t={},se("data functions should return an object:\nhttps://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function",e));var n=Object.keys(t),i=e.$options.props,r=e.$options.methods,o=n.length;for(;o--;){var a=n[o];r&&y(r,a)&&se('Method "'+a+'" has already been defined as a data property.',e),i&&y(i,a)?se('The data property "'+a+'" is already declared as a prop. Use prop default value instead.',e):O(a)||nn(e,"_data",a)}Oe(t,!0)}(e):Oe(e._data={},!0),t.computed&&function(e,t){var n=e._computedWatchers=Object.create(null),i=ne();for(var r in t){var o=t[r],a="function"==typeof o?o:o.get;null==a&&se('Getter is missing for computed property "'+r+'".',e),i||(n[r]=new en(e,a||k,k,on)),r in e?r in e.$data?se('The computed property "'+r+'" is already defined in data.',e):e.$options.props&&r in e.$options.props&&se('The computed property "'+r+'" is already defined as a prop.',e):an(e,r,o)}}(e,t.computed),t.watch&&t.watch!==Q&&function(e,t){for(var n in t){var i=t[n];if(Array.isArray(i))for(var r=0;rparseInt(this.max)&&Kn(a,s[0],s,this._vnode)),t.data.keepAlive=!0}return t||e&&e[0]}}};Un=Vn,Gn={get:function(){return V},set:function(){se("Do not replace the Vue.config object, set individual fields instead.")}},Object.defineProperty(Un,"config",Gn),Un.util={warn:se,extend:w,mergeOptions:ze,defineReactive:Pe},Un.set=Ne,Un.delete=Ae,Un.nextTick=dt,Un.options=Object.create(null),T.forEach(function(e){Un.options[e+"s"]=Object.create(null)}),w((Un.options._base=Un).options.components,Jn),Un.use=function(e){var t=this._installedPlugins||(this._installedPlugins=[]);if(-1=a&&u()};setTimeout(function(){l explicit "+t+" duration is not a valid number - got "+JSON.stringify(e)+".",n.context):isNaN(e)&&se(" explicit "+t+" duration is NaN - the duration expression might be incorrect.",n.context)}function Zr(e){return"number"==typeof e&&!isNaN(e)}function Qr(e){if(I(e))return!1;var t=e.fns;return F(t)?Qr(Array.isArray(t)?t[0]:t):1<(e._length||e.length)}function eo(e,t){!0!==t.data.show&&Gr(t)}var to=function(e){var i,t,y={},n=e.modules,b=e.nodeOps;for(i=0;i - did you register the component correctly? For recursive components, make sure to provide the "name" option.',e.context),e.elm=e.ns?b.createElementNS(e.ns,u):b.createElement(u,e),f(e),x(e,l,t),F(s)&&C(e,t),d(n,e.elm,i),s&&s.pre&&c--):(A(e.isComment)?e.elm=b.createComment(e.text):e.elm=b.createTextNode(e.text),d(n,e.elm,i))}}function g(e,t){F(e.data.pendingInsert)&&(t.push.apply(t,e.data.pendingInsert),e.data.pendingInsert=null),e.elm=e.componentInstance.$el,w(e)?(C(e,t),f(e)):(xi(e),t.push(e))}function d(e,t,n){F(e)&&(F(n)?n.parentNode===e&&b.insertBefore(e,t,n):b.appendChild(e,t))}function x(e,t,n){if(Array.isArray(t)){$(t);for(var i=0;i, or missing . Bailing hydration and performing full client-side render.")}a=e,e=new ye(b.tagName(a).toLowerCase(),{},[],void 0,a)}var c=e.elm,d=b.parentNode(c);if(_(t,l,c._leaveCb?null:d,b.nextSibling(c)),F(t.parent))for(var f=t.parent,h=w(t);f;){for(var p=0;p expects an Array value for its binding, but got '+Object.prototype.toString.call(i).slice(8,-1),n)}function oo(t,e){return e.every(function(e){return!M(e,t)})}function ao(e){return"_value"in e?e._value:e.value}function so(e){e.target.composing=!0}function lo(e){e.target.composing&&(e.target.composing=!1,uo(e.target,"input"))}function uo(e,t){var n=document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),e.dispatchEvent(n)}function co(e){return!e.componentInstance||e.data&&e.data.transition?e:co(e.componentInstance._vnode)}var fo={model:no,show:{bind:function(e,t,n){var i=t.value,r=(n=co(n)).data&&n.data.transition,o=e.__vOriginalDisplay="none"===e.style.display?"":e.style.display;i&&r?(n.data.show=!0,Gr(n,function(){e.style.display=o})):e.style.display=i?o:"none"},update:function(e,t,n){var i=t.value;!i!=!t.oldValue&&((n=co(n)).data&&n.data.transition?(n.data.show=!0,i?Gr(n,function(){e.style.display=e.__vOriginalDisplay}):Xr(n,function(){e.style.display="none"})):e.style.display=i?e.__vOriginalDisplay:"none")},unbind:function(e,t,n,i,r){r||(e.style.display=e.__vOriginalDisplay)}}},ho={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,String,Object]};function po(e){var t=e&&e.componentOptions;return t&&t.Ctor.options.abstract?po(Pt(t.children)):e}function mo(e){var t={},n=e.$options;for(var i in n.propsData)t[i]=e[i];var r=n._parentListeners;for(var o in r)t[b(o)]=r[o];return t}function vo(e,t){if(/\d-keep-alive$/.test(t.tag))return e("keep-alive",{props:t.componentOptions.propsData})}var go={name:"transition",props:ho,abstract:!0,render:function(e){var t=this,n=this.$slots.default;if(n&&(n=n.filter(function(e){return e.tag||Ot(e)})).length){1 can only be used on a single element. Use for lists.",this.$parent);var i=this.mode;i&&"in-out"!==i&&"out-in"!==i&&se("invalid mode: "+i,this.$parent);var r=n[0];if(function(e){for(;e=e.parent;)if(e.data.transition)return!0}(this.$vnode))return r;var o=po(r);if(!o)return r;if(this._leaving)return vo(e,r);var a="__transition-"+this._uid+"-";o.key=null==o.key?o.isComment?a+"comment":a+o.tag:m(o.key)?0===String(o.key).indexOf(a)?o.key:a+o.key:o.key;var s,l,u=(o.data||(o.data={})).transition=mo(this),c=this._vnode,d=po(c);if(o.data.directives&&o.data.directives.some(function(e){return"show"===e.name})&&(o.data.show=!0),d&&d.data&&(s=o,(l=d).key!==s.key||l.tag!==s.tag)&&!Ot(d)&&(!d.componentInstance||!d.componentInstance._vnode.isComment)){var f=d.data.transition=w({},u);if("out-in"===i)return this._leaving=!0,Mt(f,"afterLeave",function(){t._leaving=!1,t.$forceUpdate()}),vo(e,r);if("in-out"===i){if(Ot(o))return c;var h,p=function(){h()};Mt(u,"afterEnter",p),Mt(u,"enterCancelled",p),Mt(f,"delayLeave",function(e){h=e})}}return r}}},yo=w({tag:String,moveClass:String},ho);function bo(e){e.elm._moveCb&&e.elm._moveCb(),e.elm._enterCb&&e.elm._enterCb()}function _o(e){e.data.newPos=e.elm.getBoundingClientRect()}function xo(e){var t=e.data.pos,n=e.data.newPos,i=t.left-n.left,r=t.top-n.top;if(i||r){e.data.moved=!0;var o=e.elm.style;o.transform=o.WebkitTransform="translate("+i+"px,"+r+"px)",o.transitionDuration="0s"}}delete yo.mode;var wo={Transition:go,TransitionGroup:{props:yo,render:function(e){for(var t=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),i=this.prevChildren=this.children,r=this.$slots.default||[],o=this.children=[],a=mo(this),s=0;s children must be keyed: <"+c+">")}}if(i){for(var d=[],f=[],h=0;h, use
.'),i&&(e.staticClass=JSON.stringify(i));var r=er(e,"class",!1);r&&(e.classBinding=r)},genData:function(e){var t="";return e.staticClass&&(t+="staticClass:"+e.staticClass+","),e.classBinding&&(t+="class:"+e.classBinding+","),t}};var Eo,To={staticKeys:["staticStyle"],transformNode:function(e,t){var n=t.warn||Yi,i=tr(e,"style");i&&(Mo(i,t.delimiters)&&n('style="'+i+'": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of
, use
.'),e.staticStyle=JSON.stringify(yr(i)));var r=er(e,"style",!1);r&&(e.styleBinding=r)},genData:function(e){var t="";return e.staticStyle&&(t+="staticStyle:"+e.staticStyle+","),e.styleBinding&&(t+="style:("+e.styleBinding+"),"),t}},Do=function(e){return(Eo=Eo||document.createElement("div")).innerHTML=e,Eo.textContent},Oo=s("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr"),Po=s("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source"),No=s("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track"),Ao=/^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,Io="[a-zA-Z_][\\w\\-\\.]*",Fo="((?:"+Io+"\\:)?"+Io+")",Lo=new RegExp("^<"+Fo),jo=/^\s*(\/?)>/,Ro=new RegExp("^<\\/"+Fo+"[^>]*>"),Bo=/^]+>/i,Vo=/^",""":'"',"&":"&"," ":"\n"," ":"\t"},Uo=/&(?:lt|gt|quot|amp);/g,Yo=/&(?:lt|gt|quot|amp|#10|#9);/g,Go=s("pre,textarea",!0),Xo=function(e,t){return e&&Go(e)&&"\n"===t[0]};var Jo,Zo,Qo,ea,ta,na,ia,ra,oa=/^@|^v-on:/,aa=/^v-|^@|^:/,sa=/([^]*?)\s+(?:in|of)\s+([^]*)/,la=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/,ua=/^\(|\)$/g,ca=/:(.*)$/,da=/^:|^v-bind:/,fa=/\.[^.]+/g,ha=e(Do);function pa(e,t,n){return{type:1,tag:e,attrsList:t,attrsMap:function(e){for(var t={},n=0,i=e.length;n]*>)","i")),n=r.replace(t,function(e,t,n){return i=n.length,qo(o)||"noscript"===o||(t=t.replace(//g,"$1").replace(//g,"$1")),Xo(o,t)&&(t=t.slice(1)),h.chars&&h.chars(t),""});a+=r.length-n.length,r=n,M(o,a-i,a)}else{var s=r.indexOf("<");if(0===s){if(Vo.test(r)){var l=r.indexOf("--\x3e");if(0<=l){h.shouldKeepComment&&h.comment(r.substring(4,l)),C(l+3);continue}}if(Ho.test(r)){var u=r.indexOf("]>");if(0<=u){C(u+2);continue}}var c=r.match(Bo);if(c){C(c[0].length);continue}var d=r.match(Ro);if(d){var f=a;C(d[0].length),M(d[1],f,a);continue}var b=k();if(b){S(b),Xo(p,r)&&C(1);continue}}var _=void 0,x=void 0,w=void 0;if(0<=s){for(x=r.slice(s);!(Ro.test(x)||Lo.test(x)||Vo.test(x)||Ho.test(x)||(w=x.indexOf("<",1))<0);)s+=w,x=r.slice(s);_=r.substring(0,s),C(s)}s<0&&(_=r,r=""),h.chars&&_&&h.chars(_)}if(r===e){h.chars&&h.chars(r),!m.length&&h.warn&&h.warn('Mal-formatted tag at end of template: "'+r+'"');break}}function C(e){a+=e,r=r.substring(e)}function k(){var e=r.match(Lo);if(e){var t,n,i={tagName:e[1],attrs:[],start:a};for(C(e[0].length);!(t=r.match(jo))&&(n=r.match(Ao));)C(n[0].length),i.attrs.push(n);if(t)return i.unarySlash=t[1],C(t[0].length),i.end=a,i}}function S(e){var t=e.tagName,n=e.unarySlash;v&&("p"===p&&No(t)&&M(p),y(t)&&p===t&&M(t));for(var i,r,o,a=g(t)||!!n,s=e.attrs.length,l=new Array(s),u=0;u has no matching end tag."),h.end&&h.end(m[o].tag,t,n);m.length=i,p=i&&m[i-1].tag}else"br"===r?h.start&&h.start(e,[],!0,t,n):"p"===r&&(h.start&&h.start(e,[],!1,t,n),h.end&&h.end(e,t,n))}M()}(r,{warn:Jo,expectHTML:h.expectHTML,isUnaryTag:h.isUnaryTag,canBeLeftOpenTag:h.canBeLeftOpenTag,shouldDecodeNewlines:h.shouldDecodeNewlines,shouldDecodeNewlinesForHref:h.shouldDecodeNewlinesForHref,shouldKeepComment:h.comments,start:function(e,t,n){var i=m&&m.ns||ra(e);Y&&"svg"===i&&(t=function(e){for(var t=[],n=0;n, as they will not be parsed."));for(var c=0;c as component root element because it may contain multiple nodes."),e.attrsMap.hasOwnProperty("v-for")&&b("Cannot use v-for on stateful component root element because it renders multiple elements.")}if(g||(null!=tr(o=u,"v-pre")&&(o.pre=!0),u.pre&&(g=!0)),na(u.tag)&&(y=!0),g?function(e){var t=e.attrsList.length;if(t)for(var n=e.attrs=new Array(t),i=0;i without corresponding v-if.");else if(u.slotScope){m.plain=!1;var f=u.slotTarget||'"default"';(m.scopedSlots||(m.scopedSlots={}))[f]=u}else m.children.push(u),u.parent=m;n?_(u):(m=u,v.push(u))},end:function(){var e=v[v.length-1],t=e.children[e.children.length-1];t&&3===t.type&&" "===t.text&&!y&&e.children.pop(),v.length-=1,m=v[v.length-1],_(e)},chars:function(e){if(m){if(!Y||"textarea"!==m.tag||m.attrsMap.placeholder!==e){var t,n,i=m.children;if(e=y||e.trim()?"script"===(t=m).tag||"style"===t.tag?e:ha(e):o&&i.length?" ":"")!g&&" "!==e&&(n=Mo(e,Zo))?i.push({type:2,expression:n.expression,tokens:n.tokens,text:e}):" "===e&&i.length&&" "===i[i.length-1].text||i.push({type:3,text:e})}}else e===r?b("Component template requires a root element, rather than just text."):(e=e.trim())&&b('text "'+e+'" outside root element will be ignored.')},comment:function(e){m.children.push({type:3,text:e,isComment:!0})}}),p}function va(e,t){var n,i,r,o;(i=er(n=e,"key"))&&("template"===n.tag&&Jo("