Search in sources :

Example 51 with DBWHandlerConfiguration

use of org.jkiss.dbeaver.model.net.DBWHandlerConfiguration in project dbeaver by serge-rider.

the class DataSourceSerializerModern method saveDataSource.

private void saveDataSource(@NotNull JsonWriter json, @NotNull DataSourceDescriptor dataSource) throws IOException {
    json.name(dataSource.getId());
    json.beginObject();
    JSONUtils.field(json, RegistryConstants.ATTR_PROVIDER, dataSource.getDriver().getProviderDescriptor().getId());
    JSONUtils.field(json, RegistryConstants.ATTR_DRIVER, dataSource.getDriver().getId());
    DBPDataSourceOrigin origin = dataSource.getOrigin();
    if (origin != DataSourceOriginLocal.INSTANCE) {
        Map<String, Object> originProps = new LinkedHashMap<>();
        originProps.put(ATTR_ORIGIN_TYPE, origin.getType());
        originProps.putAll(origin.getConfiguration());
        JSONUtils.serializeProperties(json, TAG_ORIGIN, originProps);
    }
    JSONUtils.field(json, RegistryConstants.ATTR_NAME, dataSource.getName());
    JSONUtils.fieldNE(json, RegistryConstants.TAG_DESCRIPTION, dataSource.getDescription());
    JSONUtils.field(json, RegistryConstants.ATTR_SAVE_PASSWORD, dataSource.isSavePassword());
    if (dataSource.isTemplate()) {
        JSONUtils.field(json, RegistryConstants.ATTR_TEMPLATE, dataSource.isTemplate());
    }
    DataSourceNavigatorSettings navSettings = dataSource.getNavigatorSettings();
    if (navSettings.isShowSystemObjects())
        JSONUtils.field(json, ATTR_NAVIGATOR_SHOW_SYSTEM_OBJECTS, true);
    if (navSettings.isShowUtilityObjects())
        JSONUtils.field(json, ATTR_NAVIGATOR_SHOW_UTIL_OBJECTS, true);
    if (navSettings.isShowOnlyEntities())
        JSONUtils.field(json, ATTR_NAVIGATOR_SHOW_ONLY_ENTITIES, true);
    if (navSettings.isHideFolders())
        JSONUtils.field(json, ATTR_NAVIGATOR_HIDE_FOLDERS, true);
    if (navSettings.isHideSchemas())
        JSONUtils.field(json, ATTR_NAVIGATOR_HIDE_SCHEMAS, true);
    if (navSettings.isHideVirtualModel())
        JSONUtils.field(json, ATTR_NAVIGATOR_HIDE_VIRTUAL, true);
    if (navSettings.isMergeEntities())
        JSONUtils.field(json, ATTR_NAVIGATOR_MERGE_ENTITIES, true);
    JSONUtils.field(json, RegistryConstants.ATTR_READ_ONLY, dataSource.isConnectionReadOnly());
    if (dataSource.getFolder() != null) {
        JSONUtils.field(json, RegistryConstants.ATTR_FOLDER, dataSource.getFolder().getFolderPath());
    }
    final String lockPasswordHash = dataSource.getLockPasswordHash();
    if (!CommonUtils.isEmpty(lockPasswordHash)) {
        JSONUtils.field(json, RegistryConstants.ATTR_LOCK_PASSWORD, lockPasswordHash);
    }
    if (dataSource.hasSharedVirtualModel()) {
        JSONUtils.field(json, "virtual-model-id", dataSource.getVirtualModel().getId());
    }
    {
        // Connection info
        DBPConnectionConfiguration connectionInfo = dataSource.getConnectionConfiguration();
        json.name("configuration");
        json.beginObject();
        JSONUtils.fieldNE(json, RegistryConstants.ATTR_HOST, connectionInfo.getHostName());
        JSONUtils.fieldNE(json, RegistryConstants.ATTR_PORT, connectionInfo.getHostPort());
        JSONUtils.fieldNE(json, RegistryConstants.ATTR_SERVER, connectionInfo.getServerName());
        JSONUtils.fieldNE(json, RegistryConstants.ATTR_DATABASE, connectionInfo.getDatabaseName());
        JSONUtils.fieldNE(json, RegistryConstants.ATTR_URL, connectionInfo.getUrl());
        saveSecuredCredentials(dataSource, null, null, new SecureCredentials(dataSource));
        JSONUtils.fieldNE(json, RegistryConstants.ATTR_HOME, connectionInfo.getClientHomeId());
        if (connectionInfo.getConnectionType() != null) {
            JSONUtils.field(json, RegistryConstants.ATTR_TYPE, connectionInfo.getConnectionType().getId());
        }
        JSONUtils.fieldNE(json, RegistryConstants.ATTR_COLOR, connectionInfo.getConnectionColor());
        // Save other
        if (connectionInfo.getKeepAliveInterval() > 0) {
            JSONUtils.field(json, RegistryConstants.ATTR_KEEP_ALIVE, connectionInfo.getKeepAliveInterval());
        }
        JSONUtils.fieldNE(json, "config-profile", connectionInfo.getConfigProfileName());
        JSONUtils.serializeProperties(json, RegistryConstants.TAG_PROPERTIES, connectionInfo.getProperties());
        JSONUtils.serializeProperties(json, RegistryConstants.TAG_PROVIDER_PROPERTIES, connectionInfo.getProviderProperties());
        JSONUtils.fieldNE(json, RegistryConstants.ATTR_AUTH_MODEL, connectionInfo.getAuthModelId());
        JSONUtils.serializeProperties(json, "auth-properties", connectionInfo.getAuthProperties());
        // Save events
        if (!ArrayUtils.isEmpty(connectionInfo.getDeclaredEvents())) {
            json.name(RegistryConstants.TAG_EVENTS);
            json.beginObject();
            for (DBPConnectionEventType eventType : connectionInfo.getDeclaredEvents()) {
                DBRShellCommand command = connectionInfo.getEvent(eventType);
                if (!command.isEnabled()) {
                    continue;
                }
                json.name(eventType.name());
                json.beginObject();
                JSONUtils.field(json, RegistryConstants.ATTR_ENABLED, command.isEnabled());
                JSONUtils.field(json, RegistryConstants.ATTR_SHOW_PANEL, command.isShowProcessPanel());
                JSONUtils.field(json, RegistryConstants.ATTR_WAIT_PROCESS, command.isWaitProcessFinish());
                if (command.isWaitProcessFinish()) {
                    JSONUtils.field(json, RegistryConstants.ATTR_WAIT_PROCESS_TIMEOUT, command.getWaitProcessTimeoutMs());
                }
                JSONUtils.field(json, RegistryConstants.ATTR_TERMINATE_AT_DISCONNECT, command.isTerminateAtDisconnect());
                JSONUtils.field(json, RegistryConstants.ATTR_PAUSE_AFTER_EXECUTE, command.getPauseAfterExecute());
                JSONUtils.fieldNE(json, RegistryConstants.ATTR_WORKING_DIRECTORY, command.getWorkingDirectory());
                JSONUtils.fieldNE(json, RegistryConstants.ATTR_COMMAND, command.getCommand());
                json.endObject();
            }
            json.endObject();
        }
        // Save network handlers' configurations
        if (!CommonUtils.isEmpty(connectionInfo.getHandlers())) {
            json.name(RegistryConstants.TAG_HANDLERS);
            json.beginObject();
            for (DBWHandlerConfiguration configuration : connectionInfo.getHandlers()) {
                if (configuration.isEnabled()) {
                    saveNetworkHandlerConfiguration(json, dataSource, null, configuration);
                }
            }
            json.endObject();
        }
        // Save bootstrap info
        {
            DBPConnectionBootstrap bootstrap = connectionInfo.getBootstrap();
            if (bootstrap.hasData()) {
                json.name(RegistryConstants.TAG_BOOTSTRAP);
                json.beginObject();
                if (bootstrap.getDefaultAutoCommit() != null) {
                    JSONUtils.field(json, RegistryConstants.ATTR_AUTOCOMMIT, bootstrap.getDefaultAutoCommit());
                }
                if (bootstrap.getDefaultTransactionIsolation() != null) {
                    JSONUtils.field(json, RegistryConstants.ATTR_TXN_ISOLATION, bootstrap.getDefaultTransactionIsolation());
                }
                JSONUtils.fieldNE(json, RegistryConstants.ATTR_DEFAULT_CATALOG, bootstrap.getDefaultCatalogName());
                JSONUtils.fieldNE(json, RegistryConstants.ATTR_DEFAULT_SCHEMA, bootstrap.getDefaultSchemaName());
                if (bootstrap.isIgnoreErrors()) {
                    JSONUtils.field(json, RegistryConstants.ATTR_IGNORE_ERRORS, true);
                }
                JSONUtils.serializeStringList(json, RegistryConstants.TAG_QUERY, bootstrap.getInitQueries());
                json.endObject();
            }
        }
        json.endObject();
    }
    // Permissions
    serializeModifyPermissions(json, dataSource);
    {
        // Filters
        Collection<FilterMapping> filterMappings = dataSource.getObjectFilters();
        if (!CommonUtils.isEmpty(filterMappings)) {
            json.name(RegistryConstants.TAG_FILTERS);
            json.beginArray();
            for (FilterMapping filter : filterMappings) {
                if (filter.defaultFilter != null && !filter.defaultFilter.isEmpty()) {
                    saveObjectFiler(json, filter.typeName, null, filter.defaultFilter);
                }
                for (Map.Entry<String, DBSObjectFilter> cf : filter.customFilters.entrySet()) {
                    if (!cf.getValue().isEmpty()) {
                        saveObjectFiler(json, filter.typeName, cf.getKey(), cf.getValue());
                    }
                }
            }
            json.endArray();
        }
    }
    // Preferences
    {
        // Save only properties who are differs from default values
        SimplePreferenceStore prefStore = dataSource.getPreferenceStore();
        Map<String, String> props = new TreeMap<>();
        for (String propName : prefStore.preferenceNames()) {
            String propValue = prefStore.getString(propName);
            String defValue = prefStore.getDefaultString(propName);
            if (propValue != null && !CommonUtils.equalObjects(propValue, defValue)) {
                props.put(propName, propValue);
            }
        }
        if (!props.isEmpty()) {
            JSONUtils.serializeProperties(json, RegistryConstants.TAG_CUSTOM_PROPERTIES, props);
        }
    }
    json.endObject();
}
Also used : SimplePreferenceStore(org.jkiss.dbeaver.model.impl.preferences.SimplePreferenceStore) DBPDataSourceOrigin(org.jkiss.dbeaver.model.DBPDataSourceOrigin) DBRShellCommand(org.jkiss.dbeaver.model.runtime.DBRShellCommand) DBWHandlerConfiguration(org.jkiss.dbeaver.model.net.DBWHandlerConfiguration)

Example 52 with DBWHandlerConfiguration

use of org.jkiss.dbeaver.model.net.DBWHandlerConfiguration in project dbeaver by serge-rider.

the class DataSourceSerializerModern method parseNetworkHandlerConfig.

@Nullable
private DBWHandlerConfiguration parseNetworkHandlerConfig(@Nullable DataSourceDescriptor dataSource, @Nullable DBWNetworkProfile profile, @NotNull Map.Entry<String, Map<String, Object>> handlerObject) {
    String handlerId = handlerObject.getKey();
    Map<String, Object> handlerCfg = handlerObject.getValue();
    NetworkHandlerDescriptor handlerDescriptor = NetworkHandlerRegistry.getInstance().getDescriptor(handlerId);
    if (handlerDescriptor == null) {
        log.warn("Can't find network handler '" + handlerId + "'");
        return null;
    } else {
        DBWHandlerConfiguration curNetworkHandler = new DBWHandlerConfiguration(handlerDescriptor, dataSource);
        curNetworkHandler.setEnabled(JSONUtils.getBoolean(handlerCfg, RegistryConstants.ATTR_ENABLED));
        curNetworkHandler.setSavePassword(JSONUtils.getBoolean(handlerCfg, RegistryConstants.ATTR_SAVE_PASSWORD));
        if (!passwordReadCanceled) {
            final SecureCredentials creds = readSecuredCredentials(dataSource, profile, "network/" + handlerId + (profile == null ? "" : "/profile/" + profile.getProfileName()));
            curNetworkHandler.setUserName(creds.getUserName());
            if (curNetworkHandler.isSavePassword()) {
                curNetworkHandler.setPassword(creds.getUserPassword());
            }
        }
        {
            // Still try to read credentials directly from configuration (#6564)
            String userName = JSONUtils.getString(handlerCfg, RegistryConstants.ATTR_USER);
            if (!CommonUtils.isEmpty(userName))
                curNetworkHandler.setUserName(userName);
            String userPassword = JSONUtils.getString(handlerCfg, RegistryConstants.ATTR_PASSWORD);
            if (!CommonUtils.isEmpty(userPassword))
                curNetworkHandler.setPassword(userPassword);
        }
        Map<String, Object> properties = JSONUtils.deserializeProperties(handlerCfg, RegistryConstants.TAG_PROPERTIES);
        if (properties != null) {
            curNetworkHandler.setProperties(properties);
        }
        return curNetworkHandler;
    }
}
Also used : DBWHandlerConfiguration(org.jkiss.dbeaver.model.net.DBWHandlerConfiguration) NetworkHandlerDescriptor(org.jkiss.dbeaver.registry.network.NetworkHandlerDescriptor) Nullable(org.jkiss.code.Nullable)

Example 53 with DBWHandlerConfiguration

use of org.jkiss.dbeaver.model.net.DBWHandlerConfiguration in project dbeaver by serge-rider.

the class DataSourceSerializerModern method parseDataSources.

@Override
public void parseDataSources(File configFile, DBPDataSourceConfigurationStorage configurationStorage, boolean refresh, DataSourceRegistry.ParseResults parseResults) throws IOException {
    // Read secured creds file
    File mdFolder = registry.getProject().getMetadataFolder(false);
    if (mdFolder.exists()) {
        File credFile = new File(mdFolder, DBPDataSourceRegistry.CREDENTIALS_CONFIG_FILE_PREFIX + configurationStorage.getConfigurationFileSuffix() + DBPDataSourceRegistry.CREDENTIALS_CONFIG_FILE_EXT);
        if (credFile.exists()) {
            try {
                String credJson = loadConfigFile(credFile, true);
                Map<String, Map<String, Map<String, String>>> res = CONFIG_GSON.fromJson(credJson, new TypeToken<Map<String, Map<String, Map<String, String>>>>() {
                }.getType());
                secureProperties.putAll(res);
            } catch (Exception e) {
                log.error("Error decrypting secure credentials", e);
            }
        }
    }
    boolean decryptProject = CommonUtils.toBoolean(registry.getProject().getProjectProperty(DBPProject.PROP_SECURE_PROJECT));
    String configJson = loadConfigFile(configFile, decryptProject);
    {
        Map<String, Object> jsonMap = JSONUtils.parseMap(CONFIG_GSON, new StringReader(configJson));
        // Folders
        for (Map.Entry<String, Map<String, Object>> folderMap : JSONUtils.getNestedObjects(jsonMap, "folders")) {
            String name = folderMap.getKey();
            String description = JSONUtils.getObjectProperty(folderMap.getValue(), RegistryConstants.ATTR_DESCRIPTION);
            String parentFolder = JSONUtils.getObjectProperty(folderMap.getValue(), RegistryConstants.ATTR_PARENT);
            DataSourceFolder parent = parentFolder == null ? null : registry.findFolderByPath(parentFolder, true);
            DataSourceFolder folder = parent == null ? registry.findFolderByPath(name, true) : parent.getChild(name);
            if (folder == null) {
                folder = new DataSourceFolder(registry, parent, name, description);
                registry.addDataSourceFolder(folder);
            } else {
                folder.setDescription(description);
            }
        }
        // Connection types
        for (Map.Entry<String, Map<String, Object>> ctMap : JSONUtils.getNestedObjects(jsonMap, "connection-types")) {
            String id = ctMap.getKey();
            Map<String, Object> ctConfig = ctMap.getValue();
            String name = JSONUtils.getObjectProperty(ctConfig, RegistryConstants.ATTR_NAME);
            String description = JSONUtils.getObjectProperty(ctConfig, RegistryConstants.ATTR_DESCRIPTION);
            String color = JSONUtils.getObjectProperty(ctConfig, RegistryConstants.ATTR_COLOR);
            Boolean autoCommit = JSONUtils.getObjectProperty(ctConfig, "auto-commit");
            Boolean confirmExecute = JSONUtils.getObjectProperty(ctConfig, "confirm-execute");
            Boolean confirmDataChange = JSONUtils.getObjectProperty(ctConfig, "confirm-data-change");
            DBPConnectionType ct = DBWorkbench.getPlatform().getDataSourceProviderRegistry().getConnectionType(id, null);
            if (ct == null) {
                ct = new DBPConnectionType(id, name, color, description, CommonUtils.toBoolean(autoCommit), CommonUtils.toBoolean(confirmExecute), CommonUtils.toBoolean(confirmDataChange));
                DBWorkbench.getPlatform().getDataSourceProviderRegistry().addConnectionType(ct);
            }
            deserializeModifyPermissions(ctConfig, ct);
        }
        // Drivers
        // TODO: add drivers deserialization
        // Virtual models
        Map<String, DBVModel> modelMap = new LinkedHashMap<>();
        for (Map.Entry<String, Map<String, Object>> vmMap : JSONUtils.getNestedObjects(jsonMap, "virtual-models")) {
            String id = vmMap.getKey();
            DBVModel model = new DBVModel(id, vmMap.getValue());
            modelMap.put(id, model);
        }
        // Network profiles
        for (Map.Entry<String, Map<String, Object>> vmMap : JSONUtils.getNestedObjects(jsonMap, "network-profiles")) {
            String profileId = vmMap.getKey();
            Map<String, Object> profileMap = vmMap.getValue();
            DBWNetworkProfile profile = new DBWNetworkProfile();
            profile.setProfileName(profileId);
            profile.setProfileName(profileId);
            profile.setProperties(JSONUtils.deserializeStringMap(profileMap, "properties"));
            for (Map.Entry<String, Map<String, Object>> handlerMap : JSONUtils.getNestedObjects(profileMap, "handlers")) {
                DBWHandlerConfiguration configuration = parseNetworkHandlerConfig(null, profile, handlerMap);
                if (configuration != null) {
                    profile.updateConfiguration(configuration);
                }
            }
            registry.updateNetworkProfile(profile);
        }
        // Auth profiles
        for (Map.Entry<String, Map<String, Object>> vmMap : JSONUtils.getNestedObjects(jsonMap, "auth-profiles")) {
            String profileId = vmMap.getKey();
            Map<String, Object> profileMap = vmMap.getValue();
            DBAAuthProfile profile = new DBAAuthProfile();
            profile.setProfileId(profileId);
            profile.setProfileName(JSONUtils.getString(profileMap, RegistryConstants.ATTR_NAME));
            profile.setAuthModelId(JSONUtils.getString(profileMap, RegistryConstants.ATTR_AUTH_MODEL));
            profile.setSavePassword(JSONUtils.getBoolean(profileMap, RegistryConstants.ATTR_SAVE_PASSWORD));
            SecureCredentials authCreds = readSecuredCredentials(null, profile, null);
            profile.setUserName(authCreds.getUserName());
            profile.setUserPassword(authCreds.getUserPassword());
            profile.setProperties(authCreds.getProperties());
            registry.updateAuthProfile(profile);
        }
        // Connections
        for (Map.Entry<String, Map<String, Object>> conMap : JSONUtils.getNestedObjects(jsonMap, "connections")) {
            Map<String, Object> conObject = conMap.getValue();
            // Primary settings
            String id = conMap.getKey();
            String dsProviderID = CommonUtils.toString(conObject.get(RegistryConstants.ATTR_PROVIDER));
            if (CommonUtils.isEmpty(dsProviderID)) {
                log.warn("Empty datasource provider for datasource '" + id + "'");
                continue;
            }
            DataSourceProviderDescriptor provider = DataSourceProviderRegistry.getInstance().getDataSourceProvider(dsProviderID);
            if (provider == null) {
                log.warn("Can't find datasource provider " + dsProviderID + " for datasource '" + id + "'");
                provider = (DataSourceProviderDescriptor) DataSourceProviderRegistry.getInstance().makeFakeProvider(dsProviderID);
            }
            String driverId = CommonUtils.toString(conObject.get(RegistryConstants.ATTR_DRIVER));
            DriverDescriptor driver = provider.getDriver(driverId);
            if (driver == null) {
                log.warn("Can't find driver " + driverId + " in datasource provider " + provider.getId() + " for datasource '" + id + "'. Create new driver");
                driver = provider.createDriver(driverId);
                driver.setName(driverId);
                driver.setDescription("Missing driver " + driverId);
                driver.setDriverClassName("java.sql.Driver");
                driver.setTemporary(true);
                provider.addDriver(driver);
            }
            DataSourceDescriptor dataSource = registry.getDataSource(id);
            boolean newDataSource = (dataSource == null);
            if (newDataSource) {
                DBPDataSourceOrigin origin;
                Map<String, Object> originProperties = JSONUtils.deserializeProperties(conObject, TAG_ORIGIN);
                if (CommonUtils.isEmpty(originProperties) || !originProperties.containsKey(ATTR_ORIGIN_TYPE)) {
                    origin = DataSourceOriginLocal.INSTANCE;
                } else {
                    String originID = CommonUtils.toString(originProperties.remove(ATTR_ORIGIN_TYPE));
                    origin = new DataSourceOriginLazy(originID, originProperties);
                }
                dataSource = new DataSourceDescriptor(registry, configurationStorage, origin, id, driver, new DBPConnectionConfiguration());
            } else {
                // Clean settings - they have to be loaded later by parser
                dataSource.getConnectionConfiguration().setProperties(Collections.emptyMap());
                dataSource.getConnectionConfiguration().setHandlers(Collections.emptyList());
                dataSource.clearFilters();
            }
            dataSource.setName(JSONUtils.getString(conObject, RegistryConstants.ATTR_NAME));
            dataSource.setDescription(JSONUtils.getString(conObject, RegistryConstants.TAG_DESCRIPTION));
            dataSource.setSavePassword(JSONUtils.getBoolean(conObject, RegistryConstants.ATTR_SAVE_PASSWORD));
            dataSource.setTemplate(JSONUtils.getBoolean(conObject, RegistryConstants.ATTR_TEMPLATE));
            DataSourceNavigatorSettings navSettings = dataSource.getNavigatorSettings();
            navSettings.setShowSystemObjects(JSONUtils.getBoolean(conObject, DataSourceSerializerModern.ATTR_NAVIGATOR_SHOW_SYSTEM_OBJECTS));
            navSettings.setShowUtilityObjects(JSONUtils.getBoolean(conObject, DataSourceSerializerModern.ATTR_NAVIGATOR_SHOW_UTIL_OBJECTS));
            navSettings.setShowOnlyEntities(JSONUtils.getBoolean(conObject, DataSourceSerializerModern.ATTR_NAVIGATOR_SHOW_ONLY_ENTITIES));
            navSettings.setHideFolders(JSONUtils.getBoolean(conObject, DataSourceSerializerModern.ATTR_NAVIGATOR_HIDE_FOLDERS));
            navSettings.setHideSchemas(JSONUtils.getBoolean(conObject, DataSourceSerializerModern.ATTR_NAVIGATOR_HIDE_SCHEMAS));
            navSettings.setHideVirtualModel(JSONUtils.getBoolean(conObject, DataSourceSerializerModern.ATTR_NAVIGATOR_HIDE_VIRTUAL));
            navSettings.setMergeEntities(JSONUtils.getBoolean(conObject, DataSourceSerializerModern.ATTR_NAVIGATOR_MERGE_ENTITIES));
            dataSource.setConnectionReadOnly(JSONUtils.getBoolean(conObject, RegistryConstants.ATTR_READ_ONLY));
            final String folderPath = JSONUtils.getString(conObject, RegistryConstants.ATTR_FOLDER);
            if (folderPath != null) {
                dataSource.setFolder(registry.findFolderByPath(folderPath, true));
            }
            dataSource.setLockPasswordHash(CommonUtils.toString(conObject.get(RegistryConstants.ATTR_LOCK_PASSWORD)));
            // Connection settings
            {
                Map<String, Object> cfgObject = JSONUtils.getObject(conObject, "configuration");
                DBPConnectionConfiguration config = dataSource.getConnectionConfiguration();
                config.setHostName(JSONUtils.getString(cfgObject, RegistryConstants.ATTR_HOST));
                config.setHostPort(JSONUtils.getString(cfgObject, RegistryConstants.ATTR_PORT));
                config.setServerName(JSONUtils.getString(cfgObject, RegistryConstants.ATTR_SERVER));
                config.setDatabaseName(JSONUtils.getString(cfgObject, RegistryConstants.ATTR_DATABASE));
                config.setUrl(JSONUtils.getString(cfgObject, RegistryConstants.ATTR_URL));
                if (!passwordReadCanceled) {
                    final SecureCredentials creds = readSecuredCredentials(dataSource, null, null);
                    config.setUserName(creds.getUserName());
                    if (dataSource.isSavePassword()) {
                        config.setUserPassword(creds.getUserPassword());
                    }
                }
                {
                    // Still try to read credentials directly from configuration (#6564)
                    String userName = JSONUtils.getString(cfgObject, RegistryConstants.ATTR_USER);
                    if (!CommonUtils.isEmpty(userName))
                        config.setUserName(userName);
                    String userPassword = JSONUtils.getString(cfgObject, RegistryConstants.ATTR_PASSWORD);
                    if (!CommonUtils.isEmpty(userPassword))
                        config.setUserPassword(userPassword);
                }
                config.setClientHomeId(JSONUtils.getString(cfgObject, RegistryConstants.ATTR_HOME));
                config.setConfigProfileName(JSONUtils.getString(cfgObject, "config-profile"));
                config.setConnectionType(DataSourceProviderRegistry.getInstance().getConnectionType(JSONUtils.getString(cfgObject, RegistryConstants.ATTR_TYPE), DBPConnectionType.DEFAULT_TYPE));
                String colorValue = JSONUtils.getString(cfgObject, RegistryConstants.ATTR_COLOR);
                if (!CommonUtils.isEmpty(colorValue)) {
                    config.setConnectionColor(colorValue);
                }
                int keepAlive = JSONUtils.getInteger(cfgObject, RegistryConstants.ATTR_KEEP_ALIVE);
                if (keepAlive > 0) {
                    config.setKeepAliveInterval(keepAlive);
                }
                config.setProperties(JSONUtils.deserializeStringMap(cfgObject, RegistryConstants.TAG_PROPERTIES));
                config.setProviderProperties(JSONUtils.deserializeStringMap(cfgObject, RegistryConstants.TAG_PROVIDER_PROPERTIES));
                config.setAuthModelId(JSONUtils.getString(cfgObject, RegistryConstants.ATTR_AUTH_MODEL));
                config.setAuthProperties(JSONUtils.deserializeStringMapOrNull(cfgObject, "auth-properties"));
                // Events
                for (Map.Entry<String, Map<String, Object>> eventObject : JSONUtils.getNestedObjects(cfgObject, RegistryConstants.TAG_EVENTS)) {
                    DBPConnectionEventType eventType = CommonUtils.valueOf(DBPConnectionEventType.class, eventObject.getKey(), DBPConnectionEventType.BEFORE_CONNECT);
                    Map<String, Object> eventCfg = eventObject.getValue();
                    DBRShellCommand command = new DBRShellCommand("");
                    command.setEnabled(JSONUtils.getBoolean(eventCfg, RegistryConstants.ATTR_ENABLED));
                    command.setShowProcessPanel(JSONUtils.getBoolean(eventCfg, RegistryConstants.ATTR_SHOW_PANEL));
                    command.setWaitProcessFinish(JSONUtils.getBoolean(eventCfg, RegistryConstants.ATTR_WAIT_PROCESS));
                    if (command.isWaitProcessFinish()) {
                        command.setWaitProcessTimeoutMs(JSONUtils.getInteger(eventCfg, RegistryConstants.ATTR_WAIT_PROCESS_TIMEOUT));
                    }
                    command.setTerminateAtDisconnect(JSONUtils.getBoolean(eventCfg, RegistryConstants.ATTR_TERMINATE_AT_DISCONNECT));
                    command.setPauseAfterExecute(JSONUtils.getInteger(eventCfg, RegistryConstants.ATTR_PAUSE_AFTER_EXECUTE));
                    command.setWorkingDirectory(JSONUtils.getString(eventCfg, RegistryConstants.ATTR_WORKING_DIRECTORY));
                    command.setCommand(JSONUtils.getString(eventCfg, RegistryConstants.ATTR_COMMAND));
                    config.setEvent(eventType, command);
                }
                // Handlers
                for (Map.Entry<String, Map<String, Object>> handlerObject : JSONUtils.getNestedObjects(cfgObject, RegistryConstants.TAG_HANDLERS)) {
                    DBWHandlerConfiguration configuration = parseNetworkHandlerConfig(dataSource, null, handlerObject);
                    if (configuration != null) {
                        dataSource.getConnectionConfiguration().updateHandler(configuration);
                    }
                }
                // Bootstrap
                Map<String, Object> bootstrapCfg = JSONUtils.getObject(cfgObject, RegistryConstants.TAG_BOOTSTRAP);
                DBPConnectionBootstrap bootstrap = config.getBootstrap();
                if (bootstrapCfg.containsKey(RegistryConstants.ATTR_AUTOCOMMIT)) {
                    bootstrap.setDefaultAutoCommit(JSONUtils.getBoolean(bootstrapCfg, RegistryConstants.ATTR_AUTOCOMMIT));
                }
                if (bootstrapCfg.containsKey(RegistryConstants.ATTR_TXN_ISOLATION)) {
                    bootstrap.setDefaultTransactionIsolation(JSONUtils.getInteger(bootstrapCfg, RegistryConstants.ATTR_TXN_ISOLATION));
                }
                bootstrap.setDefaultCatalogName(JSONUtils.getString(bootstrapCfg, RegistryConstants.ATTR_DEFAULT_CATALOG));
                bootstrap.setDefaultSchemaName(JSONUtils.getString(bootstrapCfg, RegistryConstants.ATTR_DEFAULT_SCHEMA));
                String defObjectName = JSONUtils.getString(bootstrapCfg, RegistryConstants.ATTR_DEFAULT_OBJECT);
                if (!CommonUtils.isEmpty(defObjectName) && CommonUtils.isEmpty(bootstrap.getDefaultSchemaName())) {
                    bootstrap.setDefaultSchemaName(JSONUtils.getString(bootstrapCfg, defObjectName));
                }
                if (bootstrapCfg.containsKey(RegistryConstants.ATTR_IGNORE_ERRORS)) {
                    bootstrap.setIgnoreErrors(JSONUtils.getBoolean(bootstrapCfg, RegistryConstants.ATTR_IGNORE_ERRORS));
                }
                bootstrap.setInitQueries(JSONUtils.deserializeStringList(bootstrapCfg, RegistryConstants.TAG_QUERY));
            }
            // Permissions
            {
                deserializeModifyPermissions(conObject, dataSource);
            }
            // Filters
            for (Map<String, Object> filterCfg : JSONUtils.getObjectList(conObject, RegistryConstants.TAG_FILTERS)) {
                String typeName = JSONUtils.getString(filterCfg, RegistryConstants.ATTR_TYPE);
                String objectID = JSONUtils.getString(filterCfg, RegistryConstants.ATTR_ID);
                if (!CommonUtils.isEmpty(typeName)) {
                    DBSObjectFilter filter = readObjectFiler(filterCfg);
                    dataSource.updateObjectFilter(typeName, objectID, filter);
                }
            }
            // Preferences
            dataSource.getPreferenceStore().getProperties().putAll(JSONUtils.deserializeStringMap(conObject, RegistryConstants.TAG_CUSTOM_PROPERTIES));
            // Virtual model
            String vmID = CommonUtils.toString(conObject.get("virtual-model-id"), id);
            DBVModel dbvModel = modelMap.get(vmID);
            if (dbvModel != null) {
                dataSource.setVirtualModel(dbvModel);
            }
            // Add to the list
            if (newDataSource) {
                registry.addDataSourceToList(dataSource);
                parseResults.addedDataSources.add(dataSource);
            } else {
                parseResults.updatedDataSources.add(dataSource);
            }
        }
        // Saved filters
        for (Map<String, Object> ctMap : JSONUtils.getObjectList(jsonMap, "saved-filters")) {
            DBSObjectFilter filter = readObjectFiler(ctMap);
            registry.addSavedFilter(filter);
        }
    }
}
Also used : DBWNetworkProfile(org.jkiss.dbeaver.model.net.DBWNetworkProfile) DBSObjectFilter(org.jkiss.dbeaver.model.struct.DBSObjectFilter) DBRShellCommand(org.jkiss.dbeaver.model.runtime.DBRShellCommand) DriverDescriptor(org.jkiss.dbeaver.registry.driver.DriverDescriptor) DBPDataSourceOrigin(org.jkiss.dbeaver.model.DBPDataSourceOrigin) DBVModel(org.jkiss.dbeaver.model.virtual.DBVModel) DBException(org.jkiss.dbeaver.DBException) DBAAuthProfile(org.jkiss.dbeaver.model.access.DBAAuthProfile) DBWHandlerConfiguration(org.jkiss.dbeaver.model.net.DBWHandlerConfiguration) TypeToken(com.google.gson.reflect.TypeToken)

Example 54 with DBWHandlerConfiguration

use of org.jkiss.dbeaver.model.net.DBWHandlerConfiguration in project dbeaver by serge-rider.

the class DataSourceUtils method getDataSourceBySpec.

public static DBPDataSourceContainer getDataSourceBySpec(@NotNull DBPProject project, @NotNull String connectionSpec, @Nullable GeneralUtils.IParameterHandler parameterHandler, boolean searchByParameters, boolean createNewDataSource) {
    String driverName = null, url = null, host = null, port = null, server = null, database = null, user = null, password = null, authModelId = null;
    boolean showSystemObjects = false, showUtilityObjects = false, showOnlyEntities = false, hideFolders = false, hideSchemas = false, mergeEntities = false, savePassword = true;
    Boolean autoCommit = null;
    Map<String, String> conProperties = new HashMap<>();
    Map<String, Map<String, String>> handlerProps = new HashMap<>();
    Map<String, String> authProperties = new HashMap<>();
    DBPDataSourceFolder folder = null;
    String dsId = null, dsName = null;
    DBPDataSourceRegistry dsRegistry = project == null ? null : project.getDataSourceRegistry();
    if (dsRegistry == null) {
        log.debug("No datasource registry for project '" + project.getName() + "'");
        return null;
    }
    String[] conParams = connectionSpec.split("\\|");
    for (String cp : conParams) {
        int divPos = cp.indexOf('=');
        if (divPos == -1) {
            continue;
        }
        String paramName = cp.substring(0, divPos);
        String paramValue = cp.substring(divPos + 1);
        switch(paramName) {
            case PARAM_ID:
                dsId = paramValue;
                break;
            case PARAM_DRIVER:
                driverName = paramValue;
                break;
            case PARAM_NAME:
                dsName = paramValue;
                break;
            case PARAM_URL:
                url = paramValue;
                break;
            case PARAM_HOST:
                host = paramValue;
                break;
            case PARAM_PORT:
                port = paramValue;
                break;
            case PARAM_SERVER:
                server = paramValue;
                break;
            case PARAM_DATABASE:
                database = paramValue;
                break;
            case PARAM_USER:
                user = paramValue;
                break;
            case PARAM_PASSWORD:
                password = paramValue;
                break;
            case PARAM_AUTH_MODEL:
                authModelId = paramValue;
                break;
            case PARAM_SAVE_PASSWORD:
                savePassword = CommonUtils.toBoolean(paramValue);
                break;
            case PARAM_SHOW_SYSTEM_OBJECTS:
                showSystemObjects = CommonUtils.toBoolean(paramValue);
                break;
            case PARAM_SHOW_UTILITY_OBJECTS:
                showUtilityObjects = CommonUtils.toBoolean(paramValue);
                break;
            case PARAM_SHOW_ONLY_ENTITIES:
                showOnlyEntities = CommonUtils.toBoolean(paramValue);
                break;
            case PARAM_HIDE_FOLDERS:
                hideFolders = CommonUtils.toBoolean(paramValue);
                break;
            case PARAM_HIDE_SCHEMAS:
                hideSchemas = CommonUtils.toBoolean(paramValue);
                break;
            case PARAM_MERGE_ENTITIES:
                mergeEntities = CommonUtils.toBoolean(paramValue);
                break;
            case PARAM_FOLDER:
                folder = dsRegistry.getFolder(paramValue);
                break;
            case PARAM_AUTO_COMMIT:
                autoCommit = CommonUtils.toBoolean(paramValue);
                break;
            default:
                boolean handled = false;
                if (paramName.length() > PREFIX_PROP.length() && paramName.startsWith(PREFIX_PROP)) {
                    paramName = paramName.substring(PREFIX_PROP.length());
                    conProperties.put(paramName, paramValue);
                    handled = true;
                } else if (paramName.length() > PREFIX_AUTH_PROP.length() && paramName.startsWith(PREFIX_AUTH_PROP)) {
                    paramName = paramName.substring(PREFIX_AUTH_PROP.length());
                    authProperties.put(paramName, paramValue);
                    handled = true;
                } else if (paramName.length() > PREFIX_HANDLER.length() && paramName.startsWith(PREFIX_HANDLER)) {
                    // network handler prop
                    paramName = paramName.substring(PREFIX_HANDLER.length());
                    divPos = paramName.indexOf('.');
                    if (divPos == -1) {
                        log.debug("Wrong handler parameter: '" + paramName + "'");
                        continue;
                    }
                    String handlerId = paramName.substring(0, divPos);
                    paramName = paramName.substring(divPos + 1);
                    Map<String, String> handlerPopMap = handlerProps.computeIfAbsent(handlerId, k -> new HashMap<>());
                    handlerPopMap.put(paramName, paramValue);
                    handled = true;
                } else if (parameterHandler != null) {
                    handled = parameterHandler.setParameter(paramName, paramValue);
                }
                if (!handled) {
                    log.debug("Unknown connection parameter '" + paramName + "'");
                }
        }
    }
    DBPDataSourceContainer dataSource = null;
    if (dsId != null) {
        dataSource = dsRegistry.getDataSource(dsId);
    }
    if (dsName != null) {
        dataSource = dsRegistry.findDataSourceByName(dsName);
    }
    if (dataSource != null) {
        DBPConnectionConfiguration connConfig = dataSource.getConnectionConfiguration();
        if (!CommonUtils.isEmpty(database))
            connConfig.setDatabaseName(database);
        if (!CommonUtils.isEmpty(user))
            connConfig.setUserName(user);
        if (!CommonUtils.isEmpty(password))
            connConfig.setUserPassword(password);
        if (!CommonUtils.isEmpty(conProperties))
            connConfig.setProperties(conProperties);
        if (!CommonUtils.isEmpty(authProperties))
            connConfig.setAuthProperties(authProperties);
        if (!CommonUtils.isEmpty(authModelId))
            connConfig.setAuthModelId(authModelId);
        return dataSource;
    }
    if (searchByParameters) {
        // Try to find by parameters / handler props
        if (url != null) {
            for (DBPDataSourceContainer ds : dsRegistry.getDataSources()) {
                if (url.equals(ds.getConnectionConfiguration().getUrl())) {
                    if (user == null || user.equals(ds.getConnectionConfiguration().getUserName())) {
                        return ds;
                    }
                }
            }
        } else {
            for (DBPDataSourceContainer ds : dsRegistry.getDataSources()) {
                DBPConnectionConfiguration cfg = ds.getConnectionConfiguration();
                if (server != null && !server.equals(cfg.getServerName()) || host != null && !host.equals(cfg.getHostName()) || port != null && !port.equals(cfg.getHostPort()) || database != null && !database.equals(cfg.getDatabaseName()) || user != null && !user.equals(cfg.getUserName())) {
                    continue;
                }
                boolean matched = true;
                if (!conProperties.isEmpty()) {
                    for (Map.Entry<String, String> prop : conProperties.entrySet()) {
                        if (!CommonUtils.equalObjects(cfg.getProperty(prop.getKey()), prop.getValue())) {
                            matched = false;
                            break;
                        }
                    }
                    if (!matched) {
                        continue;
                    }
                }
                if (!handlerProps.isEmpty()) {
                    for (Map.Entry<String, Map<String, String>> handlerProp : handlerProps.entrySet()) {
                        DBWHandlerConfiguration handler = cfg.getHandler(handlerProp.getKey());
                        if (handler == null) {
                            matched = false;
                            break;
                        }
                        for (Map.Entry<String, String> prop : handlerProp.getValue().entrySet()) {
                            if (!CommonUtils.equalObjects(handler.getProperty(prop.getKey()), prop.getValue())) {
                                matched = false;
                                break;
                            }
                        }
                        if (!matched) {
                            break;
                        }
                    }
                    if (!matched) {
                        continue;
                    }
                }
                return ds;
            }
        }
    }
    if (!createNewDataSource) {
        return null;
    }
    if (driverName == null) {
        log.error("Driver name not specified - can't create new datasource");
        return null;
    }
    DBPDriver driver = DBWorkbench.getPlatform().getDataSourceProviderRegistry().findDriver(driverName);
    if (driver == null) {
        log.error("Driver '" + driverName + "' not found");
        return null;
    }
    // Create new datasource with specified parameters
    if (dsName == null) {
        dsName = "Ext: " + driver.getName();
        if (database != null) {
            dsName += " - " + database;
        } else if (server != null) {
            dsName += " - " + server;
        }
    }
    DBPConnectionConfiguration connConfig = new DBPConnectionConfiguration();
    connConfig.setUrl(url);
    connConfig.setHostName(host);
    connConfig.setHostPort(port);
    connConfig.setServerName(server);
    connConfig.setDatabaseName(database);
    connConfig.setUserName(user);
    connConfig.setUserPassword(password);
    connConfig.setProperties(conProperties);
    if (!CommonUtils.isEmpty(authProperties)) {
        connConfig.setAuthProperties(authProperties);
    }
    if (!CommonUtils.isEmpty(authModelId)) {
        connConfig.setAuthModelId(authModelId);
    }
    if (autoCommit != null) {
        connConfig.getBootstrap().setDefaultAutoCommit(autoCommit);
    }
    DBPDataSourceContainer newDS = dsRegistry.createDataSource(driver, connConfig);
    newDS.setName(dsName);
    ((DataSourceDescriptor) newDS).setTemporary(true);
    if (savePassword) {
        newDS.setSavePassword(true);
    }
    if (folder != null) {
        newDS.setFolder(folder);
    }
    DataSourceNavigatorSettings navSettings = ((DataSourceDescriptor) newDS).getNavigatorSettings();
    navSettings.setShowSystemObjects(showSystemObjects);
    navSettings.setShowUtilityObjects(showUtilityObjects);
    navSettings.setShowOnlyEntities(showOnlyEntities);
    navSettings.setHideSchemas(hideSchemas);
    navSettings.setHideFolders(hideFolders);
    navSettings.setMergeEntities(mergeEntities);
    // ds.set
    dsRegistry.addDataSource(newDS);
    return newDS;
}
Also used : HashMap(java.util.HashMap) DBPConnectionConfiguration(org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration) DBWHandlerConfiguration(org.jkiss.dbeaver.model.net.DBWHandlerConfiguration) DBPDriver(org.jkiss.dbeaver.model.connection.DBPDriver) DBPDataSourceFolder(org.jkiss.dbeaver.model.DBPDataSourceFolder) DBPDataSourceRegistry(org.jkiss.dbeaver.model.app.DBPDataSourceRegistry) HashMap(java.util.HashMap) Map(java.util.Map) DBPDataSourceContainer(org.jkiss.dbeaver.model.DBPDataSourceContainer)

Example 55 with DBWHandlerConfiguration

use of org.jkiss.dbeaver.model.net.DBWHandlerConfiguration in project dbeaver by serge-rider.

the class GlobalProxySelector method getProxiesForDataSource.

@Nullable
protected List<Proxy> getProxiesForDataSource(@NotNull URI uri, @NotNull DBPDataSourceContainer dataSourceContainer) {
    if (SocksConstants.SOCKET_SCHEME.equals(uri.getScheme())) {
        // 2. Check for connections' proxy config
        List<Proxy> proxies = null;
        for (DBWHandlerConfiguration networkHandler : dataSourceContainer.getConnectionConfiguration().getHandlers()) {
            if (networkHandler.isEnabled() && networkHandler.getType() == DBWHandlerType.PROXY) {
                String proxyHost = networkHandler.getStringProperty(SocksConstants.PROP_HOST);
                int proxyPort = networkHandler.getIntProperty(SocksConstants.PROP_PORT);
                if (!CommonUtils.isEmpty(proxyHost) && proxyPort != 0) {
                    InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
                    Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
                    if (proxies == null) {
                        proxies = new ArrayList<>();
                    }
                    proxies.add(proxy);
                    log.debug("Use SOCKS proxy [" + proxyAddr + "]");
                }
            }
        }
        if (proxies != null) {
            return proxies;
        }
    }
    return null;
}
Also used : DBWHandlerConfiguration(org.jkiss.dbeaver.model.net.DBWHandlerConfiguration) Nullable(org.jkiss.code.Nullable)

Aggregations

DBWHandlerConfiguration (org.jkiss.dbeaver.model.net.DBWHandlerConfiguration)64 DBException (org.jkiss.dbeaver.DBException)20 DBPDataSourceContainer (org.jkiss.dbeaver.model.DBPDataSourceContainer)12 DBPConnectionConfiguration (org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration)12 NetworkHandlerDescriptor (org.jkiss.dbeaver.registry.network.NetworkHandlerDescriptor)12 SQLException (java.sql.SQLException)8 DBWNetworkProfile (org.jkiss.dbeaver.model.net.DBWNetworkProfile)8 DBRShellCommand (org.jkiss.dbeaver.model.runtime.DBRShellCommand)8 SelectionAdapter (org.eclipse.swt.events.SelectionAdapter)6 SelectionEvent (org.eclipse.swt.events.SelectionEvent)6 GridData (org.eclipse.swt.layout.GridData)6 GridLayout (org.eclipse.swt.layout.GridLayout)6 Nullable (org.jkiss.code.Nullable)6 DBPDataSourceOrigin (org.jkiss.dbeaver.model.DBPDataSourceOrigin)6 DBPDriver (org.jkiss.dbeaver.model.connection.DBPDriver)6 SimplePreferenceStore (org.jkiss.dbeaver.model.impl.preferences.SimplePreferenceStore)6 UIPropertyConfiguratorDescriptor (org.jkiss.dbeaver.registry.configurator.UIPropertyConfiguratorDescriptor)6 TypeToken (com.google.gson.reflect.TypeToken)4 MalformedURLException (java.net.MalformedURLException)4 ArrayList (java.util.ArrayList)4