Example usage for java.sql DatabaseMetaData getUserName

List of usage examples for java.sql DatabaseMetaData getUserName

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getUserName.

Prototype

String getUserName() throws SQLException;

Source Link

Document

Retrieves the user name as known to this database.

Usage

From source file:org.sonar.server.platform.monitoring.DatabaseMonitor.java

private void completeDbAttributes(Map<String, Object> attributes) {
    try (DbSession dbSession = dbClient.openSession(false); Connection connection = dbSession.getConnection()) {
        DatabaseMetaData metadata = connection.getMetaData();
        attributes.put("Database", metadata.getDatabaseProductName());
        attributes.put("Database Version", metadata.getDatabaseProductVersion());
        attributes.put("Username", metadata.getUserName());
        attributes.put("URL", metadata.getURL());
        attributes.put("Driver", metadata.getDriverName());
        attributes.put("Driver Version", metadata.getDriverVersion());
        attributes.put("Version Status", getMigrationStatus());
    } catch (SQLException e) {
        throw new IllegalStateException("Fail to get DB metadata", e);
    }/*from  w w  w. ja v a2 s . com*/
}

From source file:org.springframework.jdbc.core.metadata.GenericCallMetaDataProvider.java

/**
 * Constructor used to initialize with provided database meta data.
 * @param databaseMetaData meta data to be used
 *///from w  ww.  ja  v  a2  s .  c om
protected GenericCallMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
    this.userName = databaseMetaData.getUserName();
}

From source file:org.springframework.jdbc.core.metadata.GenericTableMetaDataProvider.java

/**
 * Constructor used to initialize with provided database metadata.
 * @param databaseMetaData metadata to be used
 *///from w  w w. j  av  a  2  s  .  c o m
protected GenericTableMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
    this.userName = databaseMetaData.getUserName();
}

From source file:org.wso2.carbon.registry.core.config.RegistryConfigurationProcessor.java

/**
 * Read XML configuration from the passed InputStream, or from the classpath.
 *
 * @param in              an InputStream containing XML data, or null.
 * @param registryContext the RegistryContext to populate
 *
 * @throws RegistryException if there's a problem
 *//*from   w  ww  . java 2 s .c  om*/
public static void populateRegistryConfig(InputStream in, RegistryContext registryContext)
        throws RegistryException {
    if (in == null) {
        in = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("org/wso2/carbon/registry/core/servlet/registry.xml");
        if (in == null) {
            return;
        }
    }

    try {
        StAXOMBuilder builder = new StAXOMBuilder(CarbonUtils.replaceSystemVariablesInXml(in));
        OMElement configElement = builder.getDocumentElement();
        if (configElement != null) {

            OMElement registryRootEle = configElement.getFirstChildWithName(new QName("registryRoot"));
            if (registryRootEle != null) {
                String registryRoot = registryRootEle.getText();
                if (registryRoot != null && !registryRoot.equals(RegistryConstants.ROOT_PATH)) {
                    if (registryRoot.endsWith(RegistryConstants.PATH_SEPARATOR)) {
                        registryRoot = registryRoot.substring(0, registryRoot.length() - 1);
                    } else if (!registryRoot.startsWith(RegistryConstants.PATH_SEPARATOR)) {
                        registryRoot = RegistryConstants.ROOT_PATH + registryRoot;
                    }
                } else {
                    registryRoot = null;
                }
                registryContext.setRegistryRoot(registryRoot);
            }

            OMElement readOnlyEle = configElement.getFirstChildWithName(new QName("readOnly"));
            if (readOnlyEle != null) {
                registryContext
                        .setReadOnly(CarbonUtils.isReadOnlyNode() || "true".equals(readOnlyEle.getText()));
            }

            OMElement enableCachingEle = configElement.getFirstChildWithName(new QName("enableCache"));
            if (enableCachingEle != null) {
                registryContext.setCacheEnabled("true".equals(enableCachingEle.getText()));
            }

            SecretResolver secretResolver = SecretResolverFactory.create(configElement, false);
            Iterator dbConfigs = configElement.getChildrenWithName(new QName("dbConfig"));
            // Read Database configurations
            while (dbConfigs.hasNext()) {
                OMElement dbConfig = (OMElement) dbConfigs.next();
                DataBaseConfiguration dataBaseConfiguration = new DataBaseConfiguration();

                dataBaseConfiguration.setPasswordManager(secretResolver);
                String dbName = dbConfig.getAttributeValue(new QName("name"));
                if (dbName == null) {
                    throw new RegistryException("The database configuration name cannot be " + "null.");
                }
                dataBaseConfiguration.setConfigName(dbName);
                OMElement dataSource = dbConfig.getFirstChildWithName(new QName("dataSource"));
                if (dataSource != null) {
                    String dataSourceName = dataSource.getText();
                    dataBaseConfiguration.setDataSourceName(dataSourceName);
                    try {
                        Context context = new InitialContext();
                        Connection connection = null;
                        try {
                            connection = ((DataSource) context.lookup(dataSourceName)).getConnection();
                            DatabaseMetaData metaData = connection.getMetaData();

                            // We need to obtain the connection URL and the username, which is
                            // required for building the cache key.
                            dataBaseConfiguration.setDbUrl(metaData.getURL());
                            dataBaseConfiguration.setUserName(metaData.getUserName());
                        } finally {
                            if (connection != null) {
                                connection.close();
                            }
                        }
                    } catch (NamingException ignored) {
                        log.warn("Unable to look-up JNDI name " + dataSourceName);
                    } catch (SQLException e) {
                        e.printStackTrace();
                        throw new RegistryException("Unable to connect to Data Source", e);
                    }
                } else {
                    OMElement userName = dbConfig.getFirstChildWithName(new QName("userName"));
                    if (userName != null) {
                        dataBaseConfiguration.setUserName(userName.getText());
                    }

                    OMElement password = dbConfig.getFirstChildWithName(new QName("password"));
                    if (password != null) {
                        dataBaseConfiguration.setPassWord(password.getText());
                    }

                    OMElement url = dbConfig.getFirstChildWithName(new QName("url"));
                    String dbUrl = url.getText();
                    if (dbUrl != null) {
                        // If the connection URL contains ${carbon.home}, replace it with the
                        // corresponding value.
                        if (dbUrl.contains(CarbonConstants.CARBON_HOME_PARAMETER)) {
                            File carbonHomeDir;
                            carbonHomeDir = new File(CarbonUtils.getCarbonHome());
                            String path = carbonHomeDir.getPath();
                            path = path.replaceAll(Pattern.quote("\\"), "/");
                            if (carbonHomeDir.exists() && carbonHomeDir.isDirectory()) {
                                dbUrl = dbUrl.replaceAll(Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER),
                                        path);
                            } else {
                                log.warn("carbon home invalid");
                                String[] tempStrings1 = dbUrl
                                        .split(Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER));
                                String tempUrl = tempStrings1[1];
                                String[] tempStrings2 = tempUrl.split("/");
                                for (int i = 0; i < tempStrings2.length - 1; i++) {
                                    dbUrl = tempStrings1[0] + tempStrings2[i] + "/";
                                }
                                dbUrl = dbUrl + tempStrings2[tempStrings2.length - 1];
                            }

                            url.setText(dbUrl);
                        }
                    }
                    dataBaseConfiguration.setDbUrl(url.getText());

                    OMElement driverName = dbConfig.getFirstChildWithName(new QName("driverName"));
                    if (driverName != null) {
                        dataBaseConfiguration.setDriverName(driverName.getText());
                    }

                    OMElement maxWait = dbConfig.getFirstChildWithName(new QName("maxWait"));
                    if (maxWait != null) {
                        dataBaseConfiguration.setMaxWait(maxWait.getText());
                    }

                    OMElement testWhileIdle = dbConfig.getFirstChildWithName(new QName("testWhileIdle"));
                    if (testWhileIdle != null) {
                        dataBaseConfiguration.setTestWhileIdle(testWhileIdle.getText());
                    }

                    OMElement timeBetweenEvictionRunsMillis = dbConfig
                            .getFirstChildWithName(new QName("timeBetweenEvictionRunsMillis"));
                    if (timeBetweenEvictionRunsMillis != null) {
                        dataBaseConfiguration
                                .setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis.getText());
                    }

                    OMElement minEvictableIdleTimeMillis = dbConfig
                            .getFirstChildWithName(new QName("minEvictableIdleTimeMillis"));
                    if (minEvictableIdleTimeMillis != null) {
                        dataBaseConfiguration
                                .setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis.getText());
                    }

                    OMElement numTestsPerEvictionRun = dbConfig
                            .getFirstChildWithName(new QName("numTestsPerEvictionRun"));
                    if (numTestsPerEvictionRun != null) {
                        dataBaseConfiguration.setNumTestsPerEvictionRun(numTestsPerEvictionRun.getText());
                    }

                    OMElement maxActive = dbConfig.getFirstChildWithName(new QName("maxActive"));
                    if (maxActive != null) {
                        dataBaseConfiguration.setMaxActive(maxActive.getText());
                    }

                    OMElement maxIdle = dbConfig.getFirstChildWithName(new QName("maxIdle"));
                    if (maxIdle != null) {
                        dataBaseConfiguration.setMaxIdle(maxIdle.getText());
                    }

                    OMElement minIdle = dbConfig.getFirstChildWithName(new QName("minIdle"));
                    if (minIdle != null) {
                        dataBaseConfiguration.setMinIdle(minIdle.getText());
                    }

                    OMElement validationQuery = dbConfig.getFirstChildWithName(new QName("validationQuery"));
                    if (validationQuery != null) {
                        dataBaseConfiguration.setValidationQuery(validationQuery.getText());
                    }
                }
                registryContext.addDBConfig(dbName, dataBaseConfiguration);
            }

            // loading one-time start-up configurations
            OMElement staticConfigElement = configElement
                    .getFirstChildWithName(new QName("staticConfiguration"));
            if (staticConfigElement != null) {
                Iterator staticConfigs = staticConfigElement.getChildElements();
                while (staticConfigs.hasNext()) {
                    OMElement staticConfig = (OMElement) staticConfigs.next();

                    if (staticConfig.getLocalName().equals("versioningProperties")) {
                        String versioningProperties = staticConfig.getText();
                        StaticConfiguration.setVersioningProperties(versioningProperties.equals("true"));
                    } else if (staticConfig.getLocalName().equals("versioningComments")) {
                        String versioningComments = staticConfig.getText();
                        StaticConfiguration.setVersioningComments(versioningComments.equals("true"));
                    } else if (staticConfig.getLocalName().equals("versioningTags")) {
                        String versioningTags = staticConfig.getText();
                        StaticConfiguration.setVersioningTags(versioningTags.equals("true"));
                    } else if (staticConfig.getLocalName().equals("versioningRatings")) {
                        String versioningRatings = staticConfig.getText();
                        StaticConfiguration.setVersioningRatings(versioningRatings.equals("true"));
                    } else if (staticConfig.getLocalName().equals("versioningAssociations")) {
                        String versioningAssociations = staticConfig.getText();
                        StaticConfiguration.setVersioningAssociations(versioningAssociations.equals("true"));
                    } else if (staticConfig.getLocalName().equals("profilesPath")) {
                        String profilesPath = staticConfig.getText();
                        if (!profilesPath.startsWith(RegistryConstants.PATH_SEPARATOR)) {
                            //if user give the path like test or test/
                            profilesPath = RegistryConstants.PATH_SEPARATOR + profilesPath;
                        }
                        if (profilesPath.endsWith(RegistryConstants.PATH_SEPARATOR)) {
                            profilesPath = profilesPath.substring(0, (profilesPath.length() - 1)); //if user give the path like this /test/
                        }

                        if (profilesPath != null) {
                            if (profilesPath.startsWith(RegistryConstants.CONFIG_REGISTRY_BASE_PATH)) {
                                registryContext.setProfilesPath(profilesPath);
                            } else {
                                registryContext.setProfilesPath(
                                        RegistryConstants.CONFIG_REGISTRY_BASE_PATH + profilesPath);
                            }
                        }
                    } else if (staticConfig.getLocalName().equals("servicePath")) {
                        String servicePath = staticConfig.getText();
                        if (!servicePath.startsWith(RegistryConstants.PATH_SEPARATOR)) {
                            //if user give the path like test or test/
                            servicePath = RegistryConstants.PATH_SEPARATOR + servicePath;
                        }
                        if (servicePath.endsWith(RegistryConstants.PATH_SEPARATOR)) {
                            servicePath = servicePath.substring(0, (servicePath.length() - 1)); //if user give the path like this /test/
                        }

                        if (servicePath != null) {
                            if (servicePath.startsWith(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH)) {
                                registryContext.setServicePath(servicePath);
                            } else {
                                registryContext.setServicePath(
                                        RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + servicePath);
                            }
                        }
                    }
                }
            }

            OMElement currentConfigElement = configElement.getFirstChildWithName(new QName("currentDBConfig"));
            if (currentConfigElement == null) {
                throw new RegistryException("The current database configuration is not " + "defined.");
            }

            String currentConfigName = currentConfigElement.getText();
            readRemoteInstances(configElement, registryContext, secretResolver);
            readMounts(configElement, registryContext);
            DataBaseConfiguration dbConfiguration = registryContext.selectDBConfig(currentConfigName);
            registryContext.setDefaultDataBaseConfiguration(dbConfiguration);

            OMElement versionConfig = configElement
                    .getFirstChildWithName(new QName("versionResourcesOnChange"));
            if (versionConfig != null && "true".equals(versionConfig.getText())) {
                registryContext.setVersionOnChange(true);
            } else {
                registryContext.setVersionOnChange(false);
            }
            initializeHandlers(configElement, registryContext);

            // process query processor config
            Iterator queryProcessors = configElement.getChildrenWithName(new QName("queryProcessor"));
            while (queryProcessors.hasNext()) {

                QueryProcessorConfiguration queryProcessorConfiguration = new QueryProcessorConfiguration();

                OMElement queryProcessorElement = (OMElement) queryProcessors.next();
                OMElement queryType = queryProcessorElement.getFirstChildWithName(new QName("queryType"));
                if (queryType != null) {
                    queryProcessorConfiguration.setQueryType(queryType.getText());
                }

                OMElement processorName = queryProcessorElement.getFirstChildWithName(new QName("processor"));
                if (processorName != null) {
                    queryProcessorConfiguration.setProcessorClassName(processorName.getText());
                }

                registryContext.addQueryProcessor(queryProcessorConfiguration);
            }

            initializeAspects(configElement, registryContext);

        }

    } catch (XMLStreamException e) {
        throw new RegistryException(e.getMessage());
    } catch (CarbonException e) {
        log.error("An error occurred during system variable replacement", e);
    }
}

From source file:org.wso2.carbon.registry.core.utils.RegistryUtils.java

/**
 * Method to obtain a unique identifier for the database connection.
 *
 * @param connection the database connection.
 *
 * @return the unique identifier.//from   ww  w . jav  a2  s .  co m
 */
public static String getConnectionId(Connection connection) {
    String connectionId = null;
    try {
        // The connection URL is unique enough to be used as an identifier since one thread
        // makes one connection to the given URL according to our model.
        DatabaseMetaData connectionMetaData = connection.getMetaData();
        if (connectionMetaData != null) {
            String productName = connectionMetaData.getDatabaseProductName();
            if (MY_SQL_PRODUCT_NAME.equals(productName)) {
                /*
                 For MySQL getUserName() method executes 'SELECT USER()' query on DB via mysql connector
                 causing a huge number of 'SELECT USER()' queries to be executed.
                 Hence removing username when the DB in use is MySQL.
                 */
                connectionId = connectionMetaData.getURL();
            } else {
                connectionId = (connectionMetaData.getUserName() != null
                        ? connectionMetaData.getUserName().split("@")[0]
                        : connectionMetaData.getUserName()) + "@" + connectionMetaData.getURL();
            }
        }
    } catch (SQLException e) {
        log.error("Failed to construct the connectionId.", e);
    }
    return connectionId;
}

From source file:org.wso2.carbon.repository.core.config.RepositoryConfigurationProcessor.java

/**
 * Read XML configuration from the passed InputStream, or from the classpath.
 *
 * @param in              an InputStream containing XML data, or null.
 * @param repositoryContext the RegistryContext to populate
 *
 * @throws RepositoryException if there's a problem
 *//* ww  w . j  a v  a 2 s .c  om*/
public static void populateRepositoryConfig(InputStream in, RepositoryContext repositoryContext,
        RepositoryService registryService) throws RepositoryException {

    try {
        InputStream replacedStream = CarbonUtils.replaceSystemVariablesInXml(in);
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

        Document document = documentBuilder.parse(replacedStream);
        Element documentElement = document.getDocumentElement();
        documentElement.normalize();

        NodeList rootLists = documentElement.getElementsByTagName("registryRoot");

        if (rootLists != null && rootLists.getLength() > 0) {
            Node node = rootLists.item(0);

            if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
                String registryRoot = ((Element) node).getTextContent();

                if (registryRoot != null && !registryRoot.equals(RepositoryConstants.ROOT_PATH)) {
                    if (registryRoot.endsWith(RepositoryConstants.PATH_SEPARATOR)) {
                        registryRoot = registryRoot.substring(0, registryRoot.length() - 1);
                    } else if (!registryRoot.startsWith(RepositoryConstants.PATH_SEPARATOR)) {
                        registryRoot = RepositoryConstants.ROOT_PATH + registryRoot;
                    }
                } else {
                    registryRoot = null;
                }

                repositoryContext.setRegistryRoot(registryRoot);
            }
        }

        NodeList readOnlyElements = documentElement.getElementsByTagName("readOnly");

        if (readOnlyElements != null && readOnlyElements.getLength() > 0) {
            Node node = readOnlyElements.item(0);

            if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
                String isReadOnly = ((Element) node).getTextContent();
                repositoryContext.setReadOnly(CarbonUtils.isReadOnlyNode() || "true".equals(isReadOnly));
            }
        }

        NodeList enableCacheElements = documentElement.getElementsByTagName("enableCache");

        if (enableCacheElements != null && enableCacheElements.getLength() > 0) {
            Node node = enableCacheElements.item(0);

            if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
                String enableCacheElement = ((Element) node).getTextContent();
                repositoryContext.setCacheEnabled("true".equals(enableCacheElement));
            }
        }

        SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false);

        NodeList dbConfigElements = documentElement.getElementsByTagName("dbConfig");

        for (int index = 0; index < dbConfigElements.getLength(); index++) {
            Node dbConfig = dbConfigElements.item(index);
            DataBaseConfiguration dataBaseConfiguration = new DataBaseConfiguration();

            dataBaseConfiguration.setPasswordManager(secretResolver);

            if (dbConfig != null && dbConfig.getNodeType() == Node.ELEMENT_NODE) {
                Element dbConfigElement = (Element) dbConfig;
                String dbName = dbConfigElement.getAttribute("name");

                if (dbName == null) {
                    throw new RepositoryConfigurationException(
                            "The database configuration name cannot be null.");
                }

                dataBaseConfiguration.setConfigName(dbName);

                NodeList dbConfigDataSources = dbConfigElement.getChildNodes();

                for (int content = 0; content < dbConfigDataSources.getLength(); content++) {
                    Node dbConfigNode = dbConfigDataSources.item(content);

                    if (dbConfigNode != null && dbConfigNode.getNodeType() == Node.ELEMENT_NODE) {
                        if (dbConfigNode.getNodeName() == "dataSource") {
                            String dataSourceName = dbConfigNode.getTextContent();
                            dataBaseConfiguration.setDataSourceName(dataSourceName);
                            try {
                                Context context = new InitialContext();
                                Connection connection = null;

                                try {
                                    connection = ((DataSource) context.lookup(dataSourceName)).getConnection();
                                    DatabaseMetaData metaData = connection.getMetaData();

                                    dataBaseConfiguration.setDbUrl(metaData.getURL());
                                    dataBaseConfiguration.setUserName(metaData.getUserName());
                                } finally {
                                    if (connection != null) {
                                        connection.close();
                                    }
                                }
                            } catch (NamingException ignored) {
                                log.warn("Unable to look-up JNDI name " + dataSourceName);
                            } catch (SQLException e) {
                                e.printStackTrace();
                                throw new RepositoryDBException("Unable to connect to Data Source", e);
                            }
                        } else {
                            if (dbConfigNode.getNodeName() == "userName") {
                                dataBaseConfiguration.setUserName(dbConfigNode.getTextContent());
                            } else if (dbConfigNode.getNodeName() == "password") {
                                dataBaseConfiguration.setPassWord(dbConfigNode.getTextContent());
                            } else if (dbConfigNode.getNodeName() == "url") {
                                String dbUrl = dbConfigNode.getTextContent();

                                if (dbUrl != null) {
                                    if (dbUrl.contains(CarbonConstants.CARBON_HOME_PARAMETER)) {
                                        File carbonHomeDir;
                                        carbonHomeDir = new File(CarbonUtils.getCarbonHome());
                                        String path = carbonHomeDir.getPath();
                                        path = path.replaceAll(Pattern.quote("\\"), "/");

                                        if (carbonHomeDir.exists() && carbonHomeDir.isDirectory()) {
                                            dbUrl = dbUrl.replaceAll(
                                                    Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER), path);
                                        } else {
                                            log.warn("carbon home invalid");

                                            String[] tempStrings1 = dbUrl.split(
                                                    Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER));
                                            String tempUrl = tempStrings1[1];
                                            String[] tempStrings2 = tempUrl.split("/");

                                            for (int i = 0; i < tempStrings2.length - 1; i++) {
                                                dbUrl = tempStrings1[0] + tempStrings2[i] + "/";
                                            }

                                            dbUrl = dbUrl + tempStrings2[tempStrings2.length - 1];
                                        }
                                    }
                                }

                                dataBaseConfiguration.setDbUrl(dbUrl);
                            } else if (dbConfigNode.getNodeName() == "maxWait") {
                                dataBaseConfiguration.setMaxWait(dbConfigNode.getTextContent());
                            } else if (dbConfigNode.getNodeName() == "maxActive") {
                                dataBaseConfiguration.setMaxActive(dbConfigNode.getTextContent());
                            } else if (dbConfigNode.getNodeName() == "minIdle") {
                                dataBaseConfiguration.setMinIdle(dbConfigNode.getTextContent());
                            } else if (dbConfigNode.getNodeName() == "driverName") {
                                dataBaseConfiguration.setDriverName(dbConfigNode.getTextContent());
                            }
                        }
                    }
                }

                repositoryContext.addDBConfig(dbName, dataBaseConfiguration);
            }
        }

        NodeList staticConfigNodes = documentElement.getElementsByTagName("staticConfiguration");

        if (staticConfigNodes != null && staticConfigNodes.getLength() > 0) {
            Node staticConfigNode = staticConfigNodes.item(0);
            NodeList staticConfigItems = staticConfigNode.getChildNodes();

            for (int index = 0; index < staticConfigItems.getLength(); index++) {
                Node staticConfig = staticConfigItems.item(index);

                if (staticConfig != null && staticConfig.getNodeType() == Node.ELEMENT_NODE) {
                    if (staticConfig.getNodeName().equals("versioningProperties")) {
                        String versioningProperties = staticConfig.getTextContent();
                        StaticConfiguration.setVersioningProperties(versioningProperties.equals("true"));
                    } else if (staticConfig.getNodeName().equals("profilesPath")) {
                        String profilesPath = staticConfig.getTextContent();

                        if (!profilesPath.startsWith(RepositoryConstants.PATH_SEPARATOR)) {
                            profilesPath = RepositoryConstants.PATH_SEPARATOR + profilesPath;
                        }

                        if (profilesPath.endsWith(RepositoryConstants.PATH_SEPARATOR)) {
                            profilesPath = profilesPath.substring(0, (profilesPath.length() - 1));
                        }

                        if (profilesPath != null) {
                            if (profilesPath.startsWith(RepositoryConstants.CONFIG_REGISTRY_BASE_PATH)) {
                                repositoryContext.setProfilesPath(profilesPath);
                            } else {
                                repositoryContext.setProfilesPath(
                                        RepositoryConstants.CONFIG_REGISTRY_BASE_PATH + profilesPath);
                            }
                        }
                    } else if (staticConfig.getNodeName().equals("servicePath")) {
                        String servicePath = staticConfig.getTextContent();

                        if (!servicePath.startsWith(RepositoryConstants.PATH_SEPARATOR)) {
                            servicePath = RepositoryConstants.PATH_SEPARATOR + servicePath;
                        }

                        if (servicePath.endsWith(RepositoryConstants.PATH_SEPARATOR)) {
                            servicePath = servicePath.substring(0, (servicePath.length() - 1));
                        }

                        if (servicePath != null) {
                            if (servicePath.startsWith(RepositoryConstants.GOVERNANCE_REGISTRY_BASE_PATH)) {
                                repositoryContext.setServicePath(servicePath);
                            } else {
                                repositoryContext.setServicePath(
                                        RepositoryConstants.GOVERNANCE_REGISTRY_BASE_PATH + servicePath);
                            }
                        }
                    }
                }
            }
        }

        NodeList currentDBConfigs = documentElement.getElementsByTagName("currentDBConfig");

        if (currentDBConfigs == null) {
            throw new RepositoryConfigurationException("The current database configuration is not defined.");
        }

        String currentConfigName = currentDBConfigs.item(0).getTextContent();

        readRemoteInstances(documentElement, repositoryContext, secretResolver);

        readMounts(documentElement, repositoryContext);

        DataBaseConfiguration dbConfiguration = repositoryContext.selectDBConfig(currentConfigName);
        repositoryContext.setDefaultDataBaseConfiguration(dbConfiguration);

        NodeList versionConfigList = documentElement.getElementsByTagName("versionResourcesOnChange");

        if (versionConfigList != null && versionConfigList.getLength() > 0) {
            Node versionConfig = versionConfigList.item(0);
            if (versionConfig != null && "true".equals(versionConfig.getTextContent())) {
                repositoryContext.setVersionOnChange(true);
            } else {
                repositoryContext.setVersionOnChange(false);
            }
        }

        initializeHandlers(documentElement, repositoryContext);

        // process query processor configuration
        NodeList queryProcessors = documentElement.getElementsByTagName("queryProcessor");

        for (int index = 0; index < queryProcessors.getLength(); index++) {
            QueryProcessorConfiguration queryProcessorConfiguration = new QueryProcessorConfiguration();

            Node queryProcessorNode = queryProcessors.item(index);
            NodeList queryProcessorChildren = queryProcessorNode.getChildNodes();

            for (int childIndex = 0; childIndex < queryProcessorChildren.getLength(); childIndex++) {
                Node queryProcessorChild = queryProcessorChildren.item(childIndex);

                if (queryProcessorChild != null && queryProcessorChild.getNodeType() == Node.ELEMENT_NODE) {
                    if (queryProcessorChild.getNodeName() == "queryType") {
                        queryProcessorConfiguration.setQueryType(queryProcessorChild.getTextContent());
                    } else if (queryProcessorChild.getNodeName() == "processor") {
                        queryProcessorConfiguration.setProcessorClassName(queryProcessorChild.getTextContent());
                    }
                }
            }

            repositoryContext.addQueryProcessor(queryProcessorConfiguration);
        }
    } catch (SAXException e1) {
        throw new RepositoryInitException(e1.getMessage());
    } catch (IOException e1) {
        throw new RepositoryInitException(e1.getMessage());
    } catch (ParserConfigurationException e1) {
        throw new RepositoryInitException(e1.getMessage());
    } catch (CarbonException e) {
        log.error("An error occurred during system variable replacement", e);
    }
}

From source file:org.wso2.carbon.repository.core.utils.InternalUtils.java

/**
 * Method to obtain a unique identifier for the database connection.
 *
 * @param connection the database connection.
 *
 * @return the unique identifier./* w  ww. jav a2 s . c o m*/
 */
public static String getConnectionId(Connection connection) {
    try {
        // The connection URL is unique enough to be used as an identifier since one thread
        // makes one connection to the given URL according to our model.
        DatabaseMetaData connectionMetaData = connection.getMetaData();

        if (connectionMetaData != null) {
            return connectionMetaData.getUserName() + "@" + connectionMetaData.getURL();
        }
    } catch (SQLException ignore) {
    }
    return null;
}

From source file:telephony.test.TestDatabaseConnectionFactory.java

@Override
public IDatabaseConnection createConnection(final Connection con, final DatabaseMetaData databaseMetaData)
        throws SQLException, DatabaseUnitException {

    logger.warn(String.format(">>>>> %s invoked to create a connection!\n", this.getClass().getSimpleName()));

    IDatabaseConnection connection = null;

    // FIXME not nice I found not a fast possibility to generate inside H2
    // the tables inside a
    // schema as oracle do.
    final String driverName = databaseMetaData.getDriverName();

    if (driverName.toLowerCase().contains("oracle")) {
        // oracle schema name is the user name
        connection = new DatabaseConnection(con, databaseMetaData.getUserName().toUpperCase());
    } else {// w ww  .  j a  va 2 s.  c o m
        if (driverName.contains("H2")) {
            // H2
            connection = new DatabaseConnection(con);
        } else if (driverName.contains("postgresql")) {
            // postgresql
            connection = new DatabaseConnection(con, "public");
        } else {
            // all other
            connection = new DatabaseConnection(con);
        }
    }

    logger.warn(
            String.format("<<<<<  %s returns connection %s!\n", this.getClass().getSimpleName(), connection));

    // final DatabaseConfig config = connection.getConfig();
    // // oracle 10g
    // // FIXME at the moment we have a hard coded oracle notation
    // config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new
    // Oracle10DataTypeFactory());

    return connection;

}

From source file:uk.ac.ebi.bioinvindex.utils.test.DBUnitTest.java

/**
 * A facility to clean all the tables in the database, independently on the fact they appear or not in the dataset.
 *
 * TODO: Not completely sure it works with Oracle... :-\
 *
 * @throws SQLException//from  ww w.j a  va  2  s  .c o  m
 */
protected void cleanAll() throws SQLException {
    setReferentialIntegrityCheckings(false);

    try {
        Statement delstmt = connection.createStatement();
        DatabaseMetaData dbmsMeta = connection.getMetaData();
        String dbmsName = dbmsMeta.getDatabaseProductName().toLowerCase();
        String dbmsCatalog = connection.getCatalog();
        if (dbmsCatalog == null)
            // Let's try with the user name
            dbmsCatalog = dbmsMeta.getUserName().toUpperCase();

        String dbmsSchema = null;
        if (dbmsName.contains("oracle")) {
            // The damn Oracle needs the schema in getTables(), otherwise it returns undeletable
            // system tables too.
            //
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt
                    .executeQuery("select sys_context('USERENV', 'CURRENT_SCHEMA') CURRENT_SCHEMA from dual");
            if (rs.next())
                dbmsSchema = rs.getString(1);
            stmt.close();
        }

        log.debug("DBMSUnitTest.cleanAll(), DBMS Name: '" + dbmsName + "' Catalog: '" + dbmsCatalog
                + "' Schema: '" + dbmsSchema + "'");

        ResultSet tbrs = dbmsMeta.getTables(dbmsCatalog, dbmsSchema, null, new String[] { "TABLE" });

        while (tbrs.next()) {
            String tbname = StringUtils.trimToNull(tbrs.getString("TABLE_NAME"));
            if (tbname == null)
                continue;
            // Oracle system tables
            String sql = "DROP TABLE " + tbname;
            if (!dbmsName.contains("mysql"))
                sql += " CASCADE CONSTRAINTS";
            log.debug("DBUnitTest, adding sql: " + sql);
            delstmt.addBatch(sql);
        }
        delstmt.executeBatch();
    } finally {
        setReferentialIntegrityCheckings(true);
        connection.close();
        // All tables were deleted, we need this to force schema recreation.
        initEntityManager(true);
    }
}

From source file:uk.ac.ebi.bioinvindex.utils.test.DBUnitTest.java

/**
 * Enables/disables the referential integrity checkings in the database.
 *
 * @param isset/*  ww  w .j av a 2 s.c  om*/
 * @throws SQLException
 */
protected void setReferentialIntegrityCheckings(boolean isset) throws SQLException {

    String sql = null;

    DatabaseMetaData dbmsMeta = connection.getMetaData();
    String dbmsName = dbmsMeta.getDatabaseProductName().toLowerCase();
    String dbmsCatalog = connection.getCatalog();
    if (dbmsCatalog == null)
        // Let's try with the user name
        dbmsCatalog = dbmsMeta.getUserName().toUpperCase();

    log.debug("DBUnitTest.setReferentialIntegrityCheckings(), DBMS Name: '" + dbmsName + "' Catalog: '"
            + dbmsCatalog + "'");

    if (dbmsName.contains("h2"))
        sql = "SET REFERENTIAL_INTEGRITY " + isset;
    else if (dbmsName.contains("mysql"))
        sql = "set FOREIGN_KEY_CHECKS = " + (isset ? "1" : "0");
    else if (dbmsName.contains("oracle")) {
        // Oracle is quite messy...
        String sqlCs = "select css.*, decode(CONSTRAINT_TYPE, 'P', '0', 'C', '1', 'U', 2, 'R', '3', 1000) ctype "
                + "from sys.all_constraints css where owner = '" + dbmsCatalog + "' order by ctype "
                + (isset ? "ASC" : "DESC");

        ResultSet rs = connection.createStatement().executeQuery(sqlCs);
        Statement csDelStmt = connection.createStatement();
        while (rs.next()) {
            String sqlCsCmd = isset ? "enable" : "disable";
            String tbname = rs.getString("TABLE_NAME");
            String csname = rs.getString("CONSTRAINT_NAME");

            String sqlCsDel = "alter table " + dbmsCatalog + "." + tbname + " " + sqlCsCmd + " constraint "
                    + csname;
            log.debug("DBUnitTest, adding sql: " + sqlCsDel);
            csDelStmt.addBatch(sqlCsDel);
        }
        csDelStmt.executeBatch();
        return;
    }

    if (sql == null)
        throw new SQLException(
                "Don't know how to change referential integrity checks for the database: '" + dbmsName + "'");

    connection.createStatement().execute(sql);
}