<commit_before>/*
 * Copyright 2012-2016 MarkLogic Corporation
 *
 * 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.marklogic.hub;

import com.fasterxml.jackson.databind.JsonNode;
import com.marklogic.appdeployer.AppConfig;
import com.marklogic.appdeployer.ConfigDir;
import com.marklogic.appdeployer.command.Command;
import com.marklogic.appdeployer.command.alert.DeployAlertActionsCommand;
import com.marklogic.appdeployer.command.alert.DeployAlertConfigsCommand;
import com.marklogic.appdeployer.command.alert.DeployAlertRulesCommand;
import com.marklogic.appdeployer.command.appservers.DeployOtherServersCommand;
import com.marklogic.appdeployer.command.cpf.DeployCpfConfigsCommand;
import com.marklogic.appdeployer.command.cpf.DeployDomainsCommand;
import com.marklogic.appdeployer.command.cpf.DeployPipelinesCommand;
import com.marklogic.appdeployer.command.databases.DeployOtherDatabasesCommand;
import com.marklogic.appdeployer.command.databases.DeploySchemasDatabaseCommand;
import com.marklogic.appdeployer.command.databases.DeployTriggersDatabaseCommand;
import com.marklogic.appdeployer.command.flexrep.DeployConfigsCommand;
import com.marklogic.appdeployer.command.flexrep.DeployFlexrepCommand;
import com.marklogic.appdeployer.command.flexrep.DeployTargetsCommand;
import com.marklogic.appdeployer.command.forests.ConfigureForestReplicasCommand;
import com.marklogic.appdeployer.command.groups.DeployGroupsCommand;
import com.marklogic.appdeployer.command.mimetypes.DeployMimetypesCommand;
import com.marklogic.appdeployer.command.schemas.LoadSchemasCommand;
import com.marklogic.appdeployer.command.security.*;
import com.marklogic.appdeployer.command.tasks.DeployScheduledTasksCommand;
import com.marklogic.appdeployer.command.triggers.DeployTriggersCommand;
import com.marklogic.appdeployer.command.viewschemas.DeployViewSchemasCommand;
import com.marklogic.appdeployer.impl.SimpleAppDeployer;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.extensions.ResourceManager;
import com.marklogic.client.extensions.ResourceServices.ServiceResult;
import com.marklogic.client.extensions.ResourceServices.ServiceResultIterator;
import com.marklogic.client.io.JacksonHandle;
import com.marklogic.client.modulesloader.impl.PropertiesModuleManager;
import com.marklogic.client.util.RequestParameters;
import com.marklogic.hub.commands.LoadHubModulesCommand;
import com.marklogic.hub.commands.LoadUserModulesCommand;
import com.marklogic.hub.util.PerformanceLogger;
import com.marklogic.mgmt.ManageClient;
import com.marklogic.mgmt.ManageConfig;
import com.marklogic.mgmt.admin.AdminConfig;
import com.marklogic.mgmt.admin.AdminManager;
import com.marklogic.mgmt.appservers.ServerManager;
import com.marklogic.mgmt.databases.DatabaseManager;
import com.marklogic.rest.util.Fragment;
import com.marklogic.rest.util.ResourcesFragment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.ResourceAccessException;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataHub {

    static final private Logger LOGGER = LoggerFactory.getLogger(DataHub.class);

    private ManageConfig config;
    private ManageClient client;

    private HubConfig hubConfig;

    public DataHub(HubConfig hubConfig) {
        init(hubConfig);
    }

    public DataHub(String host, String username, String password) {
        hubConfig = new HubConfig();
        hubConfig.host = host;
        hubConfig.adminUsername = username;
        hubConfig.adminPassword = password;
        init(hubConfig);
    }

    private void init(HubConfig hubConfig) {
        this.hubConfig = hubConfig;
        config = new ManageConfig(hubConfig.host, 8002, hubConfig.adminUsername, hubConfig.adminPassword);
        client = new ManageClient(config);
    }

    /**
     * Determines if the data hub is installed in MarkLogic
     * @return true if installed, false otherwise
     */
    public boolean isInstalled() {
        long startTime = PerformanceLogger.monitorTimeInsideMethod();

        ServerManager sm = new ServerManager(client);
        DatabaseManager dm = new DatabaseManager(client);

        ResourcesFragment srf = sm.getAsXml();
        boolean stagingAppServerExists = srf.resourceExists(hubConfig.stagingHttpName);
        boolean finalAppServerExists = srf.resourceExists(hubConfig.finalHttpName);
        boolean tracingAppServerExists = srf.resourceExists(hubConfig.tracingHttpName);
        boolean appserversOk = (stagingAppServerExists && finalAppServerExists && tracingAppServerExists);

        ResourcesFragment drf = dm.getAsXml();
        boolean stagingDbExists = drf.resourceExists(hubConfig.stagingDbName);
        boolean finalDbExists = drf.resourceExists(hubConfig.finalDbName);
        boolean tracingDbExists = drf.resourceExists(hubConfig.stagingDbName);

        boolean stagingForestsExist = false;
        boolean finalForestsExist = false;
        boolean tracingForestsExist = false;

        boolean stagingIndexesOn = false;
        boolean finalIndexesOn = false;
        boolean tracingIndexesOn = false;

        if (stagingDbExists) {
            Fragment f = dm.getPropertiesAsXml(hubConfig.stagingDbName);
            stagingIndexesOn = Boolean.parseBoolean(f.getElementValue("//m:triple-index"));
            stagingIndexesOn = stagingIndexesOn && Boolean.parseBoolean(f.getElementValue("//m:collection-lexicon"));
            stagingForestsExist = (f.getElements("//m:forest").size() == hubConfig.stagingForestsPerHost);
        }

        if (finalDbExists) {
            Fragment f = dm.getPropertiesAsXml(hubConfig.finalDbName);
            finalIndexesOn = Boolean.parseBoolean(f.getElementValue("//m:triple-index"));
            finalIndexesOn = finalIndexesOn && Boolean.parseBoolean(f.getElementValue("//m:collection-lexicon"));
            finalForestsExist = (f.getElements("//m:forest").size() == hubConfig.finalForestsPerHost);
        }

        if (tracingDbExists) {
            tracingIndexesOn = true;
            Fragment f = dm.getPropertiesAsXml(hubConfig.tracingDbName);
            tracingForestsExist = (f.getElements("//m:forest").size() == hubConfig.tracingForestsPerHost);
        }

        boolean dbsOk = (stagingDbExists && stagingIndexesOn &&
                finalDbExists && finalIndexesOn &&
                tracingDbExists && tracingIndexesOn);
        boolean forestsOk = (stagingForestsExist && finalForestsExist && tracingForestsExist);

        PerformanceLogger.logTimeInsideMethod(startTime, "DataHub.isInstalled");

        return (appserversOk && dbsOk && forestsOk);
    }

    /**
     * Validates the MarkLogic server to ensure compatibility with the hub
     * @throws ServerValidationException if the server is not compatible
     */
    public void validateServer() throws ServerValidationException {
        long startTime = PerformanceLogger.monitorTimeInsideMethod();
        try {
            AdminManager am = getAdminManager();
            String versionString = am.getServerVersion();
            int major = Integer.parseInt(versionString.substring(0, 1));
            int minor = Integer.parseInt(versionString.substring(2, 3) + versionString.substring(4, 5));
            if (major < 8 || minor < 4) {
                throw new ServerValidationException("Invalid MarkLogic Server Version: " + versionString);
            }
        }<commit_msg>fixed #216 - will now install on ML 9<commit_after>/*
 * Copyright 2012-2016 MarkLogic Corporation
 *
 * 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.marklogic.hub;

import com.fasterxml.jackson.databind.JsonNode;
import com.marklogic.appdeployer.AppConfig;
import com.marklogic.appdeployer.ConfigDir;
import com.marklogic.appdeployer.command.Command;
import com.marklogic.appdeployer.command.alert.DeployAlertActionsCommand;
import com.marklogic.appdeployer.command.alert.DeployAlertConfigsCommand;
import com.marklogic.appdeployer.command.alert.DeployAlertRulesCommand;
import com.marklogic.appdeployer.command.appservers.DeployOtherServersCommand;
import com.marklogic.appdeployer.command.cpf.DeployCpfConfigsCommand;
import com.marklogic.appdeployer.command.cpf.DeployDomainsCommand;
import com.marklogic.appdeployer.command.cpf.DeployPipelinesCommand;
import com.marklogic.appdeployer.command.databases.DeployOtherDatabasesCommand;
import com.marklogic.appdeployer.command.databases.DeploySchemasDatabaseCommand;
import com.marklogic.appdeployer.command.databases.DeployTriggersDatabaseCommand;
import com.marklogic.appdeployer.command.flexrep.DeployConfigsCommand;
import com.marklogic.appdeployer.command.flexrep.DeployFlexrepCommand;
import com.marklogic.appdeployer.command.flexrep.DeployTargetsCommand;
import com.marklogic.appdeployer.command.forests.ConfigureForestReplicasCommand;
import com.marklogic.appdeployer.command.groups.DeployGroupsCommand;
import com.marklogic.appdeployer.command.mimetypes.DeployMimetypesCommand;
import com.marklogic.appdeployer.command.schemas.LoadSchemasCommand;
import com.marklogic.appdeployer.command.security.*;
import com.marklogic.appdeployer.command.tasks.DeployScheduledTasksCommand;
import com.marklogic.appdeployer.command.triggers.DeployTriggersCommand;
import com.marklogic.appdeployer.command.viewschemas.DeployViewSchemasCommand;
import com.marklogic.appdeployer.impl.SimpleAppDeployer;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.extensions.ResourceManager;
import com.marklogic.client.extensions.ResourceServices.ServiceResult;
import com.marklogic.client.extensions.ResourceServices.ServiceResultIterator;
import com.marklogic.client.io.JacksonHandle;
import com.marklogic.client.modulesloader.impl.PropertiesModuleManager;
import com.marklogic.client.util.RequestParameters;
import com.marklogic.hub.commands.LoadHubModulesCommand;
import com.marklogic.hub.commands.LoadUserModulesCommand;
import com.marklogic.hub.util.PerformanceLogger;
import com.marklogic.mgmt.ManageClient;
import com.marklogic.mgmt.ManageConfig;
import com.marklogic.mgmt.admin.AdminConfig;
import com.marklogic.mgmt.admin.AdminManager;
import com.marklogic.mgmt.appservers.ServerManager;
import com.marklogic.mgmt.databases.DatabaseManager;
import com.marklogic.rest.util.Fragment;
import com.marklogic.rest.util.ResourcesFragment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.ResourceAccessException;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataHub {

    static final private Logger LOGGER = LoggerFactory.getLogger(DataHub.class);

    private ManageConfig config;
    private ManageClient client;

    private HubConfig hubConfig;

    public DataHub(HubConfig hubConfig) {
        init(hubConfig);
    }

    public DataHub(String host, String username, String password) {
        hubConfig = new HubConfig();
        hubConfig.host = host;
        hubConfig.adminUsername = username;
        hubConfig.adminPassword = password;
        init(hubConfig);
    }

    private void init(HubConfig hubConfig) {
        this.hubConfig = hubConfig;
        config = new ManageConfig(hubConfig.host, 8002, hubConfig.adminUsername, hubConfig.adminPassword);
        client = new ManageClient(config);
    }

    /**
     * Determines if the data hub is installed in MarkLogic
     * @return true if installed, false otherwise
     */
    public boolean isInstalled() {
        long startTime = PerformanceLogger.monitorTimeInsideMethod();

        ServerManager sm = new ServerManager(client);
        DatabaseManager dm = new DatabaseManager(client);

        ResourcesFragment srf = sm.getAsXml();
        boolean stagingAppServerExists = srf.resourceExists(hubConfig.stagingHttpName);
        boolean finalAppServerExists = srf.resourceExists(hubConfig.finalHttpName);
        boolean tracingAppServerExists = srf.resourceExists(hubConfig.tracingHttpName);
        boolean appserversOk = (stagingAppServerExists && finalAppServerExists && tracingAppServerExists);

        ResourcesFragment drf = dm.getAsXml();
        boolean stagingDbExists = drf.resourceExists(hubConfig.stagingDbName);
        boolean finalDbExists = drf.resourceExists(hubConfig.finalDbName);
        boolean tracingDbExists = drf.resourceExists(hubConfig.stagingDbName);

        boolean stagingForestsExist = false;
        boolean finalForestsExist = false;
        boolean tracingForestsExist = false;

        boolean stagingIndexesOn = false;
        boolean finalIndexesOn = false;
        boolean tracingIndexesOn = false;

        if (stagingDbExists) {
            Fragment f = dm.getPropertiesAsXml(hubConfig.stagingDbName);
            stagingIndexesOn = Boolean.parseBoolean(f.getElementValue("//m:triple-index"));
            stagingIndexesOn = stagingIndexesOn && Boolean.parseBoolean(f.getElementValue("//m:collection-lexicon"));
            stagingForestsExist = (f.getElements("//m:forest").size() == hubConfig.stagingForestsPerHost);
        }

        if (finalDbExists) {
            Fragment f = dm.getPropertiesAsXml(hubConfig.finalDbName);
            finalIndexesOn = Boolean.parseBoolean(f.getElementValue("//m:triple-index"));
            finalIndexesOn = finalIndexesOn && Boolean.parseBoolean(f.getElementValue("//m:collection-lexicon"));
            finalForestsExist = (f.getElements("//m:forest").size() == hubConfig.finalForestsPerHost);
        }

        if (tracingDbExists) {
            tracingIndexesOn = true;
            Fragment f = dm.getPropertiesAsXml(hubConfig.tracingDbName);
            tracingForestsExist = (f.getElements("//m:forest").size() == hubConfig.tracingForestsPerHost);
        }

        boolean dbsOk = (stagingDbExists && stagingIndexesOn &&
                finalDbExists && finalIndexesOn &&
                tracingDbExists && tracingIndexesOn);
        boolean forestsOk = (stagingForestsExist && finalForestsExist && tracingForestsExist);

        PerformanceLogger.logTimeInsideMethod(startTime, "DataHub.isInstalled");

        return (appserversOk && dbsOk && forestsOk);
    }

    /**
     * Validates the MarkLogic server to ensure compatibility with the hub
     * @throws ServerValidationException if the server is not compatible
     */
    public void validateServer() throws ServerValidationException {
        long startTime = PerformanceLogger.monitorTimeInsideMethod();
        try {
            AdminManager am = getAdminManager();
            String versionString = am.getServerVersion();
            float version = Float.valueOf(versionString.substring(0, 1) + "." + versionString.substring(2, 3));
            if (version < 8.4) {
                throw new ServerValidationException("Invalid MarkLogic Server Version: " + versionString);
            }
        }
{'fraction_non_alphanumeric': 0.08920012449424214, 'fraction_numerical': 0.0033613445378151263, 'mean_word_length': 4.194309731652118, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, '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': '2768284', 'n_tokens_mistral': 4622, 'n_tokens_neox': 4372, 'n_words': 863}