<commit_before>/**
 *
 * Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); You may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.speedment.tool.core.internal.controller;

import com.speedment.common.injector.annotation.Inject;
import com.speedment.generator.core.component.EventComponent;
import com.speedment.runtime.config.Dbms;
import com.speedment.runtime.config.exception.SpeedmentConfigException;
import com.speedment.runtime.core.component.DbmsHandlerComponent;
import com.speedment.runtime.core.component.PasswordComponent;
import com.speedment.runtime.core.db.DbmsType;
import com.speedment.runtime.core.internal.util.Settings;
import static com.speedment.runtime.core.util.DatabaseUtil.dbmsTypeOf;
import com.speedment.tool.config.DbmsProperty;
import com.speedment.tool.core.component.UserInterfaceComponent;
import static com.speedment.tool.core.component.UserInterfaceComponent.ReuseStage.USE_EXISTING_STAGE;
import com.speedment.tool.core.event.UIEvent;
import com.speedment.tool.core.exception.SpeedmentToolException;
import static com.speedment.tool.core.internal.controller.ToolbarController.ICON_SIZE;
import com.speedment.tool.core.internal.util.ConfigFileHelper;
import com.speedment.tool.core.internal.util.InjectionLoader;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.stream.Collectors.toCollection;
import java.util.stream.Stream;
import javafx.beans.binding.Bindings;
import static javafx.beans.binding.Bindings.createBooleanBinding;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.util.StringConverter;

/**
 *
 * @author <NAME>
 */
public final class ConnectController implements Initializable {
    
    private final static String 
        DEFAULT_HOST = "127.0.0.1",
        DEFAULT_USER = "root",
        DEFAULT_NAME = "db0";
    
    @Inject private UserInterfaceComponent userInterfaceComponent;
    @Inject private DbmsHandlerComponent dbmsHandlerComponent;
    @Inject private PasswordComponent passwordComponent;
    @Inject private ConfigFileHelper configFileHelper;
    @Inject private EventComponent eventComponent;
    @Inject private InjectionLoader loader;
    
    @FXML private Button buttonOpen;
    @FXML private TextField fieldHost;
    @FXML private TextField fieldPort;
    @FXML private ChoiceBox<String> fieldType;
    @FXML private TextField fieldName;
    @FXML private TextField fieldSchema;
    @FXML private TextField fieldUser;
    @FXML private PasswordField fieldPass;
    @FXML private Button buttonConnect;
    @FXML private HBox container;
    @FXML private StackPane openContainer;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        if (Settings.inst().get("hide_open_option", true)) {
            container.getChildren().remove(openContainer);
        }

        buttonOpen.setGraphic(GlyphsDude.createIcon(FontAwesomeIcon.FOLDER_OPEN, ICON_SIZE));
        buttonConnect.setGraphic(GlyphsDude.createIcon(FontAwesomeIcon.SIGN_IN, ICON_SIZE));
        
        fieldType.setItems(
            getDbmsTypes()
                .collect(toCollection(FXCollections::observableArrayList))
        );
        
        final DbmsProperty dbms = userInterfaceComponent.projectProperty()
            .mutator().addNewDbms();
        
        final AtomicReference<String> generatedHost = new AtomicReference<>("");
        final AtomicReference<String> generatedUser = new AtomicReference<>("");
        final AtomicReference<String> generatedName = new AtomicReference<>("");
        
        fieldType.getSelectionModel().selectedItemProperty()
            .addListener((observable, old, typeName) -> {
                
            dbms.stringPropertyOf(Dbms.TYPE_NAME, () -> typeName)
                .setValue(typeName);
            
            if (!typeName.isEmpty()) {
                final DbmsType item = dbmsTypeOf(dbmsHandlerComponent, dbms);

                if (fieldHost.getText().isEmpty()
                ||  fieldHost.getText().equals(generatedHost.get())) {
                    fieldHost.textProperty().setValue(DEFAULT_HOST);
                    generatedHost.set(DEFAULT_HOST);
                }

                if (fieldUser.getText().isEmpty()
                ||  fieldUser.getText().equals(generatedUser.get())) {
                    fieldUser.textProperty().setValue(DEFAULT_USER);
                    generatedUser.set(DEFAULT_USER);
                }
                
                if (fieldName.getText().isEmpty()
                ||  fieldName.getText().equals(generatedName.get())) {
                    final String name = item.getDefaultDbmsName()
                        .orElse(DEFAULT_NAME);
                    
                    fieldName.textProperty().setValue(name);
                    generatedName.set(name);
                }

                fieldName.getTooltip().setText(item.getDbmsNameMeaning());
                
                dbms.portProperty().setValue(item.getDefaultPort());
                fieldPort.textProperty().setValue(
                    Integer.toString(item.getDefaultPort())
                );
            }
        });
        
        Bindings.bindBidirectional(
                fieldPort.textProperty(), 
                dbms.portProperty(), 
                new StringConverter<Number>() {
                    
            @Override
            public String toString(Number number) {
                if (number == null) {
                    try {
                        return Integer.toString(defaultPort(dbms));
                    } catch (SpeedmentConfigException ex) {
                        return "";
                    }
                } else {
                    return number.toString();
                }
            }

            @Override
            public Number fromString(String string) {
                if (string == null || "".equals(string.trim())) {
                    return defaultPort(dbms);
                } else return Integer.parseInt(string);
            }
        });
        
        try {
            // Find the prefered dbms-type
            final String prefered = Settings.inst().get(
                "last_known_dbtype",
                getDbmsTypes()
                    .findFirst()
                    .orElseThrow(() -> new SpeedmentToolException(
                        "Could not find any installed JDBC drivers. Make " + 
                        "sure to include at least one JDBC driver as a " + 
                        "dependency in the projects pom.xml-file under the " + 
                        "speedment-maven-plugin <plugin> tag."
                    ))
            );
            
            // If the prefered dbms-type isn't loaded, select the first one.
            if (getDbmsTypes().anyMatch(prefered::equals)) {
                
                fieldType.getSelectionModel().select(prefered);
                
                final int port = Integer.parseInt(
                    Settings.inst().get(
                        "last_known_port", 
                        Integer.toString(defaultPort(dbms))
                    )
                );
                
                final String host = Settings.inst().get("last_known_host", DEFAULT_HOST);
                final String user = Settings.inst().get("last_known_user", DEFAULT_USER);
                final String name = Settings.inst().get("last_known_name", defaultName(dbms));
                <commit_msg>tool-core: Fix #404<commit_after>/**
 *
 * Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); You may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.speedment.tool.core.internal.controller;

import com.speedment.common.injector.annotation.Inject;
import com.speedment.generator.core.component.EventComponent;
import com.speedment.runtime.config.Dbms;
import com.speedment.runtime.config.exception.SpeedmentConfigException;
import com.speedment.runtime.core.component.DbmsHandlerComponent;
import com.speedment.runtime.core.component.PasswordComponent;
import com.speedment.runtime.core.db.DbmsType;
import com.speedment.runtime.core.internal.util.Settings;
import static com.speedment.runtime.core.util.DatabaseUtil.dbmsTypeOf;
import com.speedment.tool.config.DbmsProperty;
import com.speedment.tool.core.component.UserInterfaceComponent;
import static com.speedment.tool.core.component.UserInterfaceComponent.ReuseStage.USE_EXISTING_STAGE;
import com.speedment.tool.core.event.UIEvent;
import com.speedment.tool.core.exception.SpeedmentToolException;
import static com.speedment.tool.core.internal.controller.ToolbarController.ICON_SIZE;
import com.speedment.tool.core.internal.util.ConfigFileHelper;
import com.speedment.tool.core.internal.util.InjectionLoader;
import de.jensd.fx.glyphs.GlyphsDude;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.stream.Collectors.toCollection;
import java.util.stream.Stream;
import static javafx.beans.binding.Bindings.createBooleanBinding;
import javafx.beans.property.ObjectProperty;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.util.StringConverter;

/**
 *
 * @author <NAME>
 */
public final class ConnectController implements Initializable {
    
    private final static String 
        DEFAULT_HOST = "127.0.0.1",
        DEFAULT_USER = "root",
        DEFAULT_NAME = "db0";
    
    @Inject private UserInterfaceComponent userInterfaceComponent;
    @Inject private DbmsHandlerComponent dbmsHandlerComponent;
    @Inject private PasswordComponent passwordComponent;
    @Inject private ConfigFileHelper configFileHelper;
    @Inject private EventComponent eventComponent;
    @Inject private InjectionLoader loader;
    
    @FXML private Button buttonOpen;
    @FXML private TextField fieldHost;
    @FXML private TextField fieldPort;
    @FXML private ChoiceBox<String> fieldType;
    @FXML private TextField fieldName;
    @FXML private TextField fieldSchema;
    @FXML private TextField fieldUser;
    @FXML private PasswordField fieldPass;
    @FXML private Button buttonConnect;
    @FXML private HBox container;
    @FXML private StackPane openContainer;
    
    private ObjectProperty<Integer> portProperty;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        if (Settings.inst().get("hide_open_option", true)) {
            container.getChildren().remove(openContainer);
        }

        buttonOpen.setGraphic(GlyphsDude.createIcon(FontAwesomeIcon.FOLDER_OPEN, ICON_SIZE));
        buttonConnect.setGraphic(GlyphsDude.createIcon(FontAwesomeIcon.SIGN_IN, ICON_SIZE));
        
        fieldType.setItems(
            getDbmsTypes()
                .collect(toCollection(FXCollections::observableArrayList))
        );
        
        final DbmsProperty dbms = userInterfaceComponent.projectProperty()
            .mutator().addNewDbms();
        
        final AtomicReference<String> generatedHost = new AtomicReference<>("");
        final AtomicReference<String> generatedUser = new AtomicReference<>("");
        final AtomicReference<String> generatedName = new AtomicReference<>("");
        
        fieldType.getSelectionModel().selectedItemProperty()
            .addListener((observable, old, typeName) -> {
                
            dbms.stringPropertyOf(Dbms.TYPE_NAME, () -> typeName)
                .setValue(typeName);
            
            if (!typeName.isEmpty()) {
                final DbmsType item = dbmsTypeOf(dbmsHandlerComponent, dbms);

                if (fieldHost.getText().isEmpty()
                ||  fieldHost.getText().equals(generatedHost.get())) {
                    fieldHost.textProperty().setValue(DEFAULT_HOST);
                    generatedHost.set(DEFAULT_HOST);
                }

                if (fieldUser.getText().isEmpty()
                ||  fieldUser.getText().equals(generatedUser.get())) {
                    fieldUser.textProperty().setValue(DEFAULT_USER);
                    generatedUser.set(DEFAULT_USER);
                }
                
                if (fieldName.getText().isEmpty()
                ||  fieldName.getText().equals(generatedName.get())) {
                    final String name = item.getDefaultDbmsName()
                        .orElse(DEFAULT_NAME);
                    
                    fieldName.textProperty().setValue(name);
                    generatedName.set(name);
                }

                fieldName.getTooltip().setText(item.getDbmsNameMeaning());
                
                dbms.portProperty().setValue(item.getDefaultPort());
                fieldPort.textProperty().setValue(
                    Integer.toString(item.getDefaultPort())
                );
            }
        });
        
        portProperty = dbms.portProperty().asObject();
        fieldPort.textProperty().bindBidirectional(portProperty, new StringConverter<Integer>() {
            @Override
            public String toString(Integer number) {
                if (number == null) {
                    try {
                        return Integer.toString(defaultPort(dbms));
                    } catch (SpeedmentConfigException ex) {
                        return "";
                    }
                } else {
                    return number.toString();
                }
            }

            @Override
            public Integer fromString(String string) {
                if (string == null || "".equals(string.trim())) {
                    return defaultPort(dbms);
                } else return Integer.parseInt(string);
            }
        });

        dbms.portProperty().addListener((ob, o, n) -> {
            System.out.println("Port changed to: " + n);
        });
        
        try {
            // Find the preferred dbms-type
            final String prefered = Settings.inst().get(
                "last_known_dbtype",
                getDbmsTypes()
                    .findFirst()
                    .orElseThrow(() -> new SpeedmentToolException(
                        "Could not find any installed JDBC drivers. Make " + 
                        "sure to include at least one JDBC driver as a " + 
                        "dependency in the projects pom.xml-file under the " + 
                        "speedment-maven-plugin <plugin> tag."
                    ))
            );
            
            // If the preferred dbms-type isn't loaded, select the first one.
            if (getDbmsTypes().anyMatch(prefered::equals)) {
                
                fieldType.getSelectionModel().select(prefered);
                
                final int port = Integer.parseInt(
                    Settings.inst().get(
                        "last_known_port", 
                        Integer.toString(defaultPort(dbms))
                    )
                );
                
                final String host = Settings.inst().get("last_known_host", DEFAULT_HOST);
                final String user = Settings.inst().get("last_known_user", DEFAULT_USER);
                final String name = Settings.inst().get("last_known_name", defaultName(dbms));
                
{'fraction_non_alphanumeric': 0.09466062282922234, 'fraction_numerical': 0.0024136104079590273, 'mean_word_length': 2.233961545783362, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 6}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '988805', 'n_tokens_mistral': 4395, 'n_tokens_neox': 4219, 'n_words': 898}