Search in sources :

Example 1 with MenuBar

use of javafx.scene.control.MenuBar in project DistributedFractalNetwork by Budder21.

the class FractalEditor method initialize.

/**
	 * Initializes the menus and fractal
	 *
	 * @author David
	 *
	 * @throws FileNotFoundException
	 * @throws AWTException
	 */
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
public void initialize() throws FileNotFoundException, AWTException {
    // initializing stuff
    Layer.initializeFractalRegistry();
    File fractalDirectory = new File(Constants.FRACTAL_FILEPATH);
    if (!fractalDirectory.exists()) {
        fractalDirectory.mkdirs();
        try {
            fractalDirectory.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    fractal = new RenderManager();
    MenuBar menu = new MenuBar();
    SwingNode fractalEditor = new SwingNode();
    TreeView parameters = new TreeView();
    layers = new TreeView();
    VBox trees = new VBox();
    trees.minHeightProperty().bind(bp.minHeightProperty().subtract(menu.minHeightProperty()));
    trees.minWidthProperty().bind(bp.minWidthProperty().divide(6));
    Button render = new Button("Update");
    render.minWidthProperty().bind(trees.minWidthProperty());
    render.minHeightProperty().bind(trees.minHeightProperty().divide(6));
    fractalView = new ImageView();
    fractalView.setOnMouseClicked(e -> {
        Point p = new Point(e.getScreenX(), e.getScreenY() - 52);
        double screenDistX = fractalView.getFitWidth() / 2 - p.x;
        double screenDistY = fractalView.getFitHeight() / 2 - p.y;
        double realDistX = -screenDistX * fractal.getRealResolution().x / fractal.getScreenResolution().width;
        double realDistY = screenDistY * fractal.getRealResolution().y / fractal.getScreenResolution().height;
        fractal.setLocation(new Point(fractal.getLocation().x + realDistX * 2, fractal.getLocation().y + realDistY * 2));
        this.updateFractalImage();
    });
    fractalView.setOnMouseEntered(e -> {
        zoom = true;
    });
    fractalView.setOnMouseExited(e -> {
        zoom = false;
    });
    this.setOnKeyPressed(e -> {
        if (zoom)
            if (e.getCode() == KeyCode.COMMA) {
                this.fractal.setZoom(this.fractal.getZoom() * 1.5);
                updateFractalImage();
            } else if (e.getCode() == KeyCode.PERIOD) {
                this.fractal.setZoom(this.fractal.getZoom() / 1.5);
                updateFractalImage();
            }
    });
    fractalView.setOnScroll(e -> {
        double zoom = e.getDeltaY() > 0 ? 1 / .9 : .9;
        this.fractal.setZoom(this.fractal.getZoom() * zoom);
        this.updateFractalImage();
    });
    this.fractal = new RenderManager();
    render.setOnAction(e -> {
        updateFractalImage();
    });
    // Fitting the image to the screen
    fractalView.fitWidthProperty().bind(bp.minWidthProperty().subtract(trees.minWidthProperty()));
    fractalView.fitHeightProperty().bind(bp.heightProperty().subtract(menu.minHeightProperty()).subtract(220));
    {
        // Fitting gradientEditor to full screen
        Dimension p = new Dimension((int) (Toolkit.getDefaultToolkit().getScreenSize().width * 0.75), 200);
        System.out.println("Gradient Dimensions: " + p);
        gradient = new Window(p, 50, this.fractal.getLayers().get(0));
    }
    {
        // Tree Stuff
        parameters.setRoot(new TreeItem("params"));
        parameters.getRoot().setExpanded(true);
        TreeItem xPos = new TreeItem();
        parameters.getRoot().getChildren().addAll(xPos);
        layers.setRoot(new TreeItem());
        layers.getRoot().setExpanded(true);
        layers.setShowRoot(false);
        layers.setEditable(true);
        /**
			 * layers.setCellFactory(new Callback<TreeView,CheckBoxTreeCell>(){
			 *
			 * @Override public CheckBoxTreeCell call(TreeView p) { return new
			 *           CheckBoxTreeCell(); } });
			 */
        // Use a custom callback to determine the style of the tree item
        layers.setCellFactory(new Callback<TreeView, TreeCell>() {

            @Override
            public TreeCell call(TreeView param) {
                return new CheckBoxTreeCell() {

                    @Override
                    public void updateItem(Object item, boolean empty) {
                        super.updateItem(item, empty);
                        // empty
                        if (empty) {
                            setGraphic(null);
                            setText(null);
                        // Otherwise if it's not representation as an
                        // item of the tree
                        // is not a CheckBoxTreeItem, remove the
                        // checkbox item
                        } else if (!(getTreeItem() instanceof CheckBoxTreeItem)) {
                            BufferedImage image;
                            try {
                                image = ImageIO.read(new File("textures\\plusButton.png"));
                                Image plusImage = SwingFXUtils.toFXImage(image, null);
                                ImageView plusView = new ImageView(plusImage);
                                plusView.setFitHeight(16);
                                plusView.setFitWidth(16);
                                setGraphic(plusView);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
            }
        });
        TreeItem add = new TreeItem();
        /**
			 * try{ BufferedImage image = ImageIO.read(new
			 * File("textures\\plusButton.jpg")); Image plusImage =
			 * SwingFXUtils.toFXImage(image, null); ImageView plusView = new
			 * ImageView(plusImage); plusView.setFitWidth(16);
			 * plusView.setFitHeight(16); add.setGraphic(plusView);
			 * }catch(Exception e){ e.printStackTrace(); }
			 */
        layerIndex = 1;
        CheckBoxTreeItem item = getNewTreeItem();
        /**
			 * add.addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(),
			 * e -> { if(((CheckBoxTreeItem)(e.getSource())).isSelected()){
			 * ((CheckBoxTreeItem)(e.getSource())).getParent().getChildren().add(0,
			 * new CheckBoxTreeItem(new
			 * MetaLayer("Layer"+incrementLayers(),null)));
			 * ((CheckBoxTreeItem)(e.getSource())).setSelected(false); }});
			 */
        layers.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent mouseEvent) {
                if (mouseEvent.getClickCount() == 2) {
                    if (layers.getSelectionModel().getSelectedItem() == add) {
                        CheckBoxTreeItem i = getNewTreeItem();
                        layers.getRoot().getChildren().add(0, i);
                        fractal.addLayer("HistogramLayer");
                    } else {
                        ((TreeItem) layers.getSelectionModel().getSelectedItem()).setValue(LayerBox.display((TreeItem<MetaLayer>) layers.getSelectionModel().getSelectedItem()));
                        MetaLayer meta = ((MetaLayer) ((TreeItem) layers.getSelectionModel().getSelectedItem()).getValue());
                        int index = layers.getRoot().getChildren().size() - 2 - layers.getRoot().getChildren().indexOf(layers.getSelectionModel().getSelectedItem());
                        Layer l = fractal.getLayers().get(index);
                        if (meta.getType() != l.getClass().getSimpleName()) {
                            Layer newLayer = Layer.getLayerByType(meta.getType());
                            newLayer.init(new Palette(), index + 1);
                            fractal.getLayers().set(index, newLayer);
                            fractal.update();
                        }
                        fractal.getLayers().get(index).setName(meta.getName());
                        updateFractalImage();
                    }
                } else if (mouseEvent.getClickCount() == 1 && layers.getSelectionModel().getSelectedItem() != add) {
                    int index = layers.getRoot().getChildren().size() - 2 - layers.getRoot().getChildren().indexOf(layers.getSelectionModel().getSelectedItem());
                    Layer l = fractal.getLayers().get(index);
                    gradient.updateLayer(l);
                }
            }
        });
        layers.getRoot().getChildren().addAll(item, add);
        {
        // TODO I DONT KNOW WHY THIS ISNT WORKING IUEAWBIUBFAI
        /**
				 * layers.getRoot().addEventHandler(layers.getRoot().childrenModificationEvent(),e
				 * -> { for(Object i :((TreeItem)e.getSource()).getChildren()){
				 * if(i!=add)
				 * if(((MetaLayer)((TreeItem)(i)).getValue()).isDelete()){
				 * layers.getSelectionModel().select(i);
				 * layers.getSelectionModel().clearSelection(); } } });
				 */
        }
    }
    // Trying to get this to work
    fractalEditor.setOnMouseEntered(e -> gradient.repaint());
    {
        // This is the menu stuff
        Menu network = new Menu("Network");
        Menu fractal = new Menu("Fractal");
        Menu system = new Menu("System");
        MenuItem newNet = new MenuItem("Create New Network");
        MenuItem viewNetLog = new MenuItem("View Network Log");
        MenuItem viewNet = new MenuItem("View Network");
        MenuItem endNet = new MenuItem("Close Network");
        newNet.setOnAction(e -> {
            NetworkCreationTool createNet = new NetworkCreationTool();
            if (createNet.createNetwork()) {
                this.network = createNet.getServer();
                this.network.init(log);
                Alert alert = new Alert(AlertType.INFORMATION);
                alert.setTitle("Network Message");
                alert.setHeaderText(null);
                alert.setContentText("Network succesfully created.");
                viewNet.setDisable(false);
                endNet.setDisable(false);
                newNet.setDisable(true);
                viewNetLog.setDisable(false);
                alert.showAndWait();
            }
        });
        viewNet.setDisable(true);
        endNet.setDisable(true);
        viewNetLog.setDisable(true);
        viewNet.setOnAction(e -> {
            Display display = new Display(this.network);
            this.network.setDisplay(display);
            display.updateNetworkView(this.network.getChildren(), this.network.getUncompletedJobs());
        });
        endNet.setOnAction(e -> {
            this.network.kill();
            viewNet.setDisable(true);
            endNet.setDisable(true);
            viewNetLog.setDisable(true);
            newNet.setDisable(false);
        });
        viewNetLog.setOnAction(e -> {
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Network Log");
            alert.setHeaderText(null);
            alert.setContentText(this.network.getLog().getLog());
            alert.showAndWait();
        });
        network.getItems().addAll(newNet, viewNet, viewNetLog, endNet);
        MenuItem newFract = new MenuItem("New Fractal");
        newFract.setOnAction(e -> {
            this.fractal = new RenderManager();
            gradient.updateLayer(this.fractal.getLayers().get(0));
            this.updateFractalImage();
        });
        MenuItem openFract = new MenuItem("Open Fractal");
        openFract.setOnAction(e -> {
            FileChooser chooser = new FileChooser();
            chooser.setTitle("Open Fractal");
            chooser.setInitialDirectory(new File("fractals"));
            FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Fractals (*.fractal)", "*.fractal");
            chooser.getExtensionFilters().add(filter);
            File f = chooser.showOpenDialog(null);
            this.fractal = new RenderManager(f);
            gradient.updateLayer(this.fractal.getLayers().get(0));
            this.updateFractalImage();
        });
        MenuItem saveFract = new MenuItem("Save Fractal");
        saveFract.setOnAction(e -> {
            this.fractal.saveFractal();
        });
        MenuItem saveFractAs = new MenuItem("Save Fractal As");
        saveFractAs.setOnAction(e -> {
            this.fractal.saveFractalAs();
        });
        MenuItem exportFract = new MenuItem("Export Fractal");
        exportFract.setOnAction(e -> {
            ExportImageTool export = new ExportImageTool();
            export.exportImage(this.fractal);
        });
        fractal.getItems().addAll(newFract, openFract, saveFract, saveFractAs, exportFract);
        MenuItem newLayer = new MenuItem("New Layer Type");
        newLayer.setOnAction(e -> {
            RegisterLayerTool register = new RegisterLayerTool();
            register.registerLayer();
            Layer.registerLayer(register.getFile());
        });
        MenuItem changeLog = new MenuItem("Edit Log Options");
        changeLog.setOnAction(e -> {
        });
        system.getItems().addAll(newLayer, changeLog);
        menu.getMenus().addAll(fractal);
        menu.getMenus().addAll(network);
        menu.getMenus().addAll(system);
    }
    VBox center = new VBox();
    center.getChildren().addAll(fractalView, fractalEditor);
    trees.getChildren().addAll(parameters, layers, render);
    bp.setCenter(center);
    bp.setRight(trees);
    // This is where the menu is located on the border pane
    bp.setTop(menu);
    bp.minWidthProperty().bind(this.widthProperty());
    bp.minHeightProperty().bind(this.heightProperty());
    fractalEditor.setContent(gradient);
    fractalEditor.minHeight(200);
}
Also used : EventHandler(javafx.event.EventHandler) Button(javafx.scene.control.Button) Scene(javafx.scene.Scene) RegisterLayerTool(menus.RegisterLayerTool) Server(server.Server) TreeItem(javafx.scene.control.TreeItem) MouseEvent(javafx.scene.input.MouseEvent) Log(util.Log) ChoiceDialog(javafx.scene.control.ChoiceDialog) VBox(javafx.scene.layout.VBox) TreeModificationEvent(javafx.scene.control.CheckBoxTreeItem.TreeModificationEvent) Constants(util.Constants) ArrayList(java.util.ArrayList) AlertType(javafx.scene.control.Alert.AlertType) ImageIO(javax.imageio.ImageIO) Layer(fractal.Layer) Callback(javafx.util.Callback) Alert(javafx.scene.control.Alert) KeyCode(javafx.scene.input.KeyCode) MenuBar(javafx.scene.control.MenuBar) MenuItem(javafx.scene.control.MenuItem) BufferedImage(java.awt.image.BufferedImage) IOException(java.io.IOException) RenderManager(fractal.RenderManager) ExportImageTool(menus.ExportImageTool) CheckBoxTreeCell(javafx.scene.control.cell.CheckBoxTreeCell) Point(util.Point) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) TreeView(javafx.scene.control.TreeView) Menu(javafx.scene.control.Menu) Display(menus.Display) NetworkCreationTool(menus.NetworkCreationTool) CheckBoxTreeItem(javafx.scene.control.CheckBoxTreeItem) FileChooser(javafx.stage.FileChooser) Dimension(java.awt.Dimension) List(java.util.List) Palette(fractal.Palette) ImageView(javafx.scene.image.ImageView) AWTException(java.awt.AWTException) SwingFXUtils(javafx.embed.swing.SwingFXUtils) TreeCell(javafx.scene.control.TreeCell) BorderPane(javafx.scene.layout.BorderPane) Image(javafx.scene.image.Image) SwingNode(javafx.embed.swing.SwingNode) Toolkit(java.awt.Toolkit) Palette(fractal.Palette) TreeItem(javafx.scene.control.TreeItem) CheckBoxTreeItem(javafx.scene.control.CheckBoxTreeItem) MenuBar(javafx.scene.control.MenuBar) EventHandler(javafx.event.EventHandler) BufferedImage(java.awt.image.BufferedImage) Image(javafx.scene.image.Image) BufferedImage(java.awt.image.BufferedImage) SwingNode(javafx.embed.swing.SwingNode) CheckBoxTreeCell(javafx.scene.control.cell.CheckBoxTreeCell) Button(javafx.scene.control.Button) FileChooser(javafx.stage.FileChooser) ImageView(javafx.scene.image.ImageView) Menu(javafx.scene.control.Menu) RenderManager(fractal.RenderManager) MouseEvent(javafx.scene.input.MouseEvent) CheckBoxTreeItem(javafx.scene.control.CheckBoxTreeItem) MenuItem(javafx.scene.control.MenuItem) IOException(java.io.IOException) Point(util.Point) Dimension(java.awt.Dimension) Layer(fractal.Layer) Point(util.Point) ExportImageTool(menus.ExportImageTool) Callback(javafx.util.Callback) NetworkCreationTool(menus.NetworkCreationTool) TreeView(javafx.scene.control.TreeView) Alert(javafx.scene.control.Alert) File(java.io.File) VBox(javafx.scene.layout.VBox) RegisterLayerTool(menus.RegisterLayerTool) Display(menus.Display)

Example 2 with MenuBar

use of javafx.scene.control.MenuBar in project Media-Library by The-Rain-Goddess.

the class ApplicationWindow method setupMenuBar.

//private menu mutators / accessors	
private MenuBar setupMenuBar() {
    MenuBar menuBar = new MenuBar();
    // --- Menu File
    Menu menuFile = getMenuFileOption();
    // --- Menu Edit
    Menu menuEdit = getMenuEditOption();
    // --- Menu View
    Menu menuView = getMenuViewOption();
    menuBar.setMinWidth(WINDOW_MIN_WIDTH);
    menuBar.getMenus().addAll(menuFile, menuEdit, menuView);
    menuBar.autosize();
    return menuBar;
}
Also used : MenuBar(javafx.scene.control.MenuBar) ContextMenu(javafx.scene.control.ContextMenu) Menu(javafx.scene.control.Menu)

Example 3 with MenuBar

use of javafx.scene.control.MenuBar in project Gargoyle by callakrsos.

the class DesignerFx method createFxMenuBar.

//	private JMenuBar createMenuBar() {
//		JMenuBar menuBar = new JMenuBar();
//		JMenu menu = new JMenu("Language");
//		ButtonGroup group = new ButtonGroup();
//
//		LanguageVersion[] languageVersions = getSupportedLanguageVersions();
//		for (int i = 0; i < languageVersions.length; i++) {
//			LanguageVersion languageVersion = languageVersions[i];
//			MenuItem button = new MenuItem(languageVersion.getShortName());
//			languageVersionMenuItems[i] = button;
//			group.add(button);
//			menu.add(button);
//		}
//		languageVersionMenuItems[DEFAULT_LANGUAGE_VERSION_SELECTION_INDEX].setSelected(true);
//		menuBar.add(menu);
//
//		JMenu actionsMenu = new JMenu("Actions");
//		JMenuItem copyXMLItem = new JMenuItem("Copy xml to clipboard");
//		copyXMLItem.addActionListener(new ActionListener() {
//			public void actionPerformed(ActionEvent e) {
//				copyXmlToClipboard();
//			}
//		});
//		actionsMenu.add(copyXMLItem);
//		JMenuItem createRuleXMLItem = new JMenuItem("Create rule XML");
//		createRuleXMLItem.addActionListener(new ActionListener() {
//			public void actionPerformed(ActionEvent e) {
//				createRuleXML();
//			}
//		});
//		actionsMenu.add(createRuleXMLItem);
//		menuBar.add(actionsMenu);
//
//		return menuBar;
//	}
private MenuBar createFxMenuBar() {
    MenuBar menuBar = new MenuBar();
    Menu menu = new Menu("Language");
    ToggleGroup group = new ToggleGroup();
    LanguageVersion[] languageVersions = getSupportedLanguageVersions();
    for (int i = 0; i < languageVersions.length; i++) {
        LanguageVersion languageVersion = languageVersions[i];
        //			JRadioButtonMenuItem button = new JRadioButtonMenuItem(languageVersion.getShortName());
        RadioMenuItem button = new RadioMenuItem(languageVersion.getShortName());
        button.setToggleGroup(group);
        languageVersionMenuItems[i] = button;
        //			group.add(button);
        menu.getItems().add(button);
    }
    //		languageVersionMenuItems[DEFAULT_LANGUAGE_VERSION_SELECTION_INDEX].setSelected(true);
    languageVersionMenuItems[getDefaultLanguageVersionSelectionIndex()].setSelected(true);
    menuBar.getMenus().add(menu);
    Menu actionsMenu = new Menu("Actions");
    MenuItem copyXMLItem = new MenuItem("Copy xml to clipboard");
    copyXMLItem.setOnAction(e -> copyXmlToClipboard());
    actionsMenu.getItems().add(copyXMLItem);
    MenuItem createRuleXMLItem = new MenuItem("Create rule XML");
    createRuleXMLItem.setOnAction(e -> createRuleXML());
    actionsMenu.getItems().add(createRuleXMLItem);
    menuBar.getMenus().add(actionsMenu);
    return menuBar;
}
Also used : ToggleGroup(javafx.scene.control.ToggleGroup) JMenuBar(javax.swing.JMenuBar) MenuBar(javafx.scene.control.MenuBar) LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) MenuItem(javafx.scene.control.MenuItem) RadioMenuItem(javafx.scene.control.RadioMenuItem) Menu(javafx.scene.control.Menu) RadioMenuItem(javafx.scene.control.RadioMenuItem)

Example 4 with MenuBar

use of javafx.scene.control.MenuBar in project Gargoyle by callakrsos.

the class SqlTabPanExample method start.

@Override
public void start(Stage primaryStage) throws NotYetSupportException, GargoyleConnectionFailException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    primaryStage.setTitle("Database Exam");
    CommonsSqllPan sqlPane = CommonsSqllPan.getSqlPane();
    sqlPane.getStylesheets().add(SkinManager.getInstance().getSkin());
    BorderPane root = new BorderPane(sqlPane);
    Menu menu = new Menu("Exam");
    MenuItem e = new MenuItem("exam");
    e.setOnAction(System.out::println);
    e.setAccelerator(new KeyCodeCombination(KeyCode.E, KeyCombination.CONTROL_DOWN));
    menu.getItems().add(e);
    root.setTop(new MenuBar(menu));
    primaryStage.setScene(new Scene(root, 1100, 700));
    primaryStage.show();
// Application.setUserAgentStylesheet(Application.STYLESHEET_MODENA);
// DockPane.initializeDefaultUserAgentStylesheet();
}
Also used : BorderPane(javafx.scene.layout.BorderPane) CommonsSqllPan(com.kyj.fx.voeditor.visual.component.sql.view.CommonsSqllPan) MenuBar(javafx.scene.control.MenuBar) MenuItem(javafx.scene.control.MenuItem) KeyCodeCombination(javafx.scene.input.KeyCodeCombination) Menu(javafx.scene.control.Menu) Scene(javafx.scene.Scene)

Example 5 with MenuBar

use of javafx.scene.control.MenuBar in project Gargoyle by callakrsos.

the class PostgreSqlPane method menuExportMergeScriptOnAction.

/* (non-Javadoc)
	 * @see com.kyj.fx.voeditor.visual.component.sql.view.SqlPane#menuExportMergeScriptOnAction(javafx.event.ActionEvent)
	 */
@Override
public void menuExportMergeScriptOnAction(ActionEvent e) {
    //		TableView<Map<String, Object>> tbResult = getTbResult();
    List<Map<String, Object>> items = getSelectedTabResultItems();
    //		TreeView<DatabaseItemTree<String>> schemaTree = getSchemaTree();
    //
    //		List<String> schemaList = schemaTree.getRoot().getChildren().stream().map(v -> v.getValue().getName()).collect(Collectors.toList());
    //
    String defaultSchema = "";
    try {
        Map<String, Object> findOne = DbUtil.findOne(connectionSupplier.get(), "select current_schema() as currentschema");
        if (findOne != null && !findOne.isEmpty()) {
            defaultSchema = ValueUtil.decode(findOne.get("currentschema"), "").toString();
        }
    } catch (Exception e4) {
        e4.printStackTrace();
    }
    //
    final String _defaultSchema = defaultSchema;
    //
    //		if (items.isEmpty())
    //			return;
    //
    //		// TODO :: DBMS에 따라 Merge문 생성 로직 분기 처리 필요.
    //
    //		Optional<Pair<String, String[]>> showInputDialog = DialogUtil.showInputCustomDialog(tbResult.getScene().getWindow(), "table Name",
    //				"테이블명을 입력하세요.", new CustomInputDialogAction<GridPane, String[]>() {
    //
    //					TextField txtSchema;
    //					TextField txtTable;
    //
    //					@Override
    //					public GridPane getNode() {
    //						GridPane gridPane = new GridPane();
    //						txtSchema = new TextField();
    //						txtTable = new TextField();
    //
    //						FxUtil.installAutoTextFieldBinding(txtSchema, () -> {
    //							return schemaList;
    //						});
    //
    //						FxUtil.installAutoTextFieldBinding(txtTable, () -> {
    //							return searchPattern(txtSchema.getText(), txtTable.getText()).stream().map(v -> v.getValue().getName())
    //									.collect(Collectors.toList());
    //						});
    //						txtSchema.setText(_defaultSchema);
    //
    //						//Default TableName
    //						TreeItem<DatabaseItemTree<String>> selectedItem = getSchemaTree().getSelectionModel().getSelectedItem();
    //						if (null != selectedItem) {
    //							DatabaseItemTree<String> value = selectedItem.getValue();
    //							if (value instanceof TableItemTree) {
    //								txtTable.setText(value.getName());
    //							}
    //						}
    //
    //						Label label = new Label("Schema : ");
    //						Label label2 = new Label("Table : ");
    //						gridPane.add(label, 0, 0);
    //						gridPane.add(label2, 1, 0);
    //						gridPane.add(txtSchema, 0, 1);
    //						gridPane.add(txtTable, 1, 1);
    //						return gridPane;
    //					}
    //
    //					@Override
    //					public String[] okClickValue() {
    //
    //						String schema = txtSchema.getText().trim();
    //						String table = txtTable.getText().trim();
    //
    //						String[] okValue = new String[2];
    //						okValue[0] = schema;
    //						okValue[1] = table;
    //						return okValue;
    //					}
    //
    //					@Override
    //					public String[] cancelClickValue() {
    //						return null;
    //					}
    //
    //				});
    Optional<Pair<String, String[]>> showTableInputDialog = showTableInputDialog(v -> v.getName());
    showTableInputDialog.ifPresent(op -> {
        if (!"OK".equals(op.getKey()))
            return;
        String[] resultValue = op.getValue();
        try {
            StringBuilder clip = new StringBuilder();
            PostgreTableItemTree dirtyTreeItem = new PostgreTableItemTree();
            String schemaName = (resultValue[0] == null || resultValue[0].isEmpty()) ? _defaultSchema : resultValue[0];
            String tableName = resultValue[1];
            String childrenSQL = dirtyTreeItem.getChildrenSQL(schemaName, tableName);
            List<Map<String, Object>> select = DbUtil.select(childrenSQL);
            List<String> pkList = new ArrayList<>();
            List<String> notPkList = new ArrayList<>();
            List<String> columnList = new ArrayList<>();
            for (Map<String, Object> map : select) {
                String columnName = map.get("column_name").toString();
                Object primaryKeyYn = map.get("primary_yn");
                columnList.add(columnName);
                if ("Y".equals(primaryKeyYn)) {
                    pkList.add(columnName);
                } else {
                    notPkList.add(columnName);
                }
            }
            String mergePreffix = String.format("with upsert as ( update %s set  ", tableName);
            String mergeMiddle = " returning * )\n";
            String collect = columnList.stream().collect(Collectors.joining(", ", "(", ")"));
            String insertPreffix = String.format("insert into %s", tableName);
            String insertend = " where not exists (select * from upsert);\n";
            List<String> valueList = items.stream().map(v -> {
                return ValueUtil.toJSONObject(v);
            }).map(v -> {
                String updateSetSql = notPkList.stream().map(str -> {
                    if (str == null)
                        return null;
                    else {
                        JsonElement jsonElement = v.get(str);
                        if (jsonElement == null) {
                            return str.concat("=").concat("null");
                        } else {
                            String dataValue = jsonElement.toString();
                            dataValue = dataValue.substring(1, dataValue.length() - 1);
                            if (dataValue.indexOf("'") >= 0) {
                                dataValue = StringUtils.replace(dataValue, "'", "''");
                            }
                            return str.concat("=").concat("'").concat(dataValue).concat("'");
                        }
                    }
                }).collect(Collectors.joining(", "));
                String updateWhereSql = pkList.stream().map(str -> {
                    if (str == null)
                        return null;
                    else {
                        if (null == v.get(str))
                            return null;
                        String dataValue = v.get(str).toString();
                        dataValue = dataValue.substring(1, dataValue.length() - 1);
                        if (dataValue.indexOf("'") >= 0) {
                            try {
                                dataValue = StringUtils.replace(dataValue, "'", "''");
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                        return str.concat(" = ").concat("'").concat(dataValue).concat("'");
                    }
                }).filter(str -> str != null).collect(Collectors.joining(" and "));
                String insertValueSql = columnList.stream().map(str -> {
                    if (str == null)
                        return null;
                    else {
                        JsonElement jsonElement = v.get(str);
                        if (jsonElement == null) {
                            return "null";
                        } else {
                            String dataValue = jsonElement.toString();
                            dataValue = dataValue.substring(1, dataValue.length() - 1);
                            if (dataValue.indexOf("'") >= 0) {
                                dataValue = StringUtils.replace(dataValue, "'", "''");
                            }
                            return "'".concat(dataValue).concat("'");
                        }
                    }
                }).collect(Collectors.joining(", "));
                return new StringBuilder().append(mergePreffix).append(updateSetSql).append(" where ").append(updateWhereSql).append(mergeMiddle).append(insertPreffix).append(collect).append(" select ").append(insertValueSql).append(insertend).toString();
            }).collect(Collectors.toList());
            valueList.forEach(str -> {
                clip.append(str);
            });
            SqlKeywords parent = new SqlKeywords();
            {
                MenuBar menuBar = new MenuBar();
                Menu menuFile = new Menu("File");
                MenuItem miSaveAs = new MenuItem("Save As");
                miSaveAs.setOnAction(ev -> {
                    File saveAsFile = DialogUtil.showFileSaveCheckDialog(getScene().getWindow(), chooser -> {
                        chooser.getExtensionFilters().add(new ExtensionFilter(GargoyleExtensionFilters.SQL_NAME, GargoyleExtensionFilters.SQL));
                    });
                    if (saveAsFile != null) {
                        ThreadUtil.createNewThreadAndRun("Saveas", () -> {
                            SaveSQLFileFunction function = new SaveSQLFileFunction();
                            function.apply(saveAsFile, parent.getText());
                        });
                    }
                });
                menuFile.getItems().add(miSaveAs);
                menuBar.getMenus().add(menuFile);
                parent.setTop(menuBar);
            }
            parent.setContent(clip.toString());
            parent.setWrapText(false);
            parent.setPrefSize(1200d, 800d);
            FxUtil.createStageAndShow(parent, stage -> {
                stage.initOwner(getScene().getWindow());
                stage.setTitle(String.format("[Merge Script] Table : %s", tableName));
            });
        } catch (Exception e2) {
            LOGGER.error(ValueUtil.toString(e2));
            DialogUtil.showExceptionDailog(e2, "에러발생, 테이블을 잘못 선택하셨을 수 있습니다.");
        }
    });
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Connection(java.sql.Connection) DbUtil(com.kyj.fx.voeditor.visual.util.DbUtil) TreeItem(javafx.scene.control.TreeItem) LoggerFactory(org.slf4j.LoggerFactory) DialogUtil(com.kyj.fx.voeditor.visual.util.DialogUtil) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) JsonElement(com.google.gson.JsonElement) ThreadUtil(com.kyj.fx.voeditor.visual.util.ThreadUtil) Map(java.util.Map) GargoyleExtensionFilters(com.kyj.fx.voeditor.visual.util.GargoyleExtensionFilters) SaveSQLFileFunction(com.kyj.fx.voeditor.visual.component.sql.functions.SaveSQLFileFunction) SqlKeywords(com.kyj.fx.voeditor.visual.component.text.SqlKeywords) Pair(javafx.util.Pair) Logger(org.slf4j.Logger) MenuBar(javafx.scene.control.MenuBar) MenuItem(javafx.scene.control.MenuItem) DatabaseTreeNode(com.kyj.fx.voeditor.visual.component.sql.dbtree.DatabaseTreeNode) ValueUtil(com.kyj.fx.voeditor.visual.util.ValueUtil) Collectors(java.util.stream.Collectors) File(java.io.File) PostgreDatabaseItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.postgre.PostgreDatabaseItemTree) Menu(javafx.scene.control.Menu) FxUtil(com.kyj.fx.voeditor.visual.util.FxUtil) List(java.util.List) ResourceLoader(com.kyj.fx.voeditor.visual.momory.ResourceLoader) ActionEvent(javafx.event.ActionEvent) DatabaseItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.DatabaseItemTree) PostgreTableItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.postgre.PostgreTableItemTree) Optional(java.util.Optional) ExtensionFilter(javafx.stage.FileChooser.ExtensionFilter) SqlKeywords(com.kyj.fx.voeditor.visual.component.text.SqlKeywords) ArrayList(java.util.ArrayList) MenuBar(javafx.scene.control.MenuBar) MenuItem(javafx.scene.control.MenuItem) JsonElement(com.google.gson.JsonElement) ExtensionFilter(javafx.stage.FileChooser.ExtensionFilter) Menu(javafx.scene.control.Menu) SaveSQLFileFunction(com.kyj.fx.voeditor.visual.component.sql.functions.SaveSQLFileFunction) Map(java.util.Map) File(java.io.File) Pair(javafx.util.Pair) PostgreTableItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.postgre.PostgreTableItemTree)

Aggregations

MenuBar (javafx.scene.control.MenuBar)7 Menu (javafx.scene.control.Menu)6 MenuItem (javafx.scene.control.MenuItem)6 File (java.io.File)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Platform (javafx.application.Platform)2 Scene (javafx.scene.Scene)2 TreeItem (javafx.scene.control.TreeItem)2 BorderPane (javafx.scene.layout.BorderPane)2 FxPlugin (jgnash.plugin.FxPlugin)2 MainView (jgnash.uifx.views.main.MainView)2 JsonElement (com.google.gson.JsonElement)1 DatabaseTreeNode (com.kyj.fx.voeditor.visual.component.sql.dbtree.DatabaseTreeNode)1 DatabaseItemTree (com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.DatabaseItemTree)1 PostgreDatabaseItemTree (com.kyj.fx.voeditor.visual.component.sql.dbtree.postgre.PostgreDatabaseItemTree)1 PostgreTableItemTree (com.kyj.fx.voeditor.visual.component.sql.dbtree.postgre.PostgreTableItemTree)1 SaveSQLFileFunction (com.kyj.fx.voeditor.visual.component.sql.functions.SaveSQLFileFunction)1 CommonsSqllPan (com.kyj.fx.voeditor.visual.component.sql.view.CommonsSqllPan)1 SqlKeywords (com.kyj.fx.voeditor.visual.component.text.SqlKeywords)1