/*
(non-Javadoc)

@see
com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties
(com.impetus.kundera.client.Client, java.util.Map)
501824
@Override
    public void populateClientProperties(Client client, Map<String, Object> properties)
    {
        setConfig(properties);
        for (String key : properties.keySet())
        {
            Object value = properties.get(key);
            if (key.equals(PersistenceProperties.KUNDERA_BATCH_SIZE) && value instanceof Integer)
            {
                Integer batchSize = (Integer) value;
                ((RedisClient) client).setBatchSize(batchSize);
            }
        }
    }
942148
public <T> T populate(Class<T> clazz, Set<Class> resolvedConfigs) {
        return populate(null, clazz, resolvedConfigs);
    }
452569
private void populateCqlVersion(Map<String, Object> externalProperties) {
        String cqlVersion =
            externalProperties != null ? (String) externalProperties.get(CassandraConstants.CQL_VERSION) : null;
        if (cqlVersion == null || !(cqlVersion != null && (cqlVersion.equals(CassandraConstants.CQL_VERSION_2_0)
            || cqlVersion.equals(CassandraConstants.CQL_VERSION_3_0)))) {
            cqlVersion = (CassandraPropertyReader.csmd != null ? CassandraPropertyReader.csmd.getCqlVersion()
                : CassandraConstants.CQL_VERSION_2_0);
        }

        if (cqlVersion.equals(CassandraConstants.CQL_VERSION_3_0)) {
            setCqlVersion(CassandraConstants.CQL_VERSION_3_0);
        } else {
            setCqlVersion(CassandraConstants.CQL_VERSION_2_0);
        }
    }
300102
private void populateManagedSchemaMap() {
    Collection<ManagedSchema> schemas = managedSchemaDao.getManagedSchemas();
    for (ManagedSchema managedSchema : schemas) {
      getManagedSchemaMap().put(
          getManagedSchemaMapKey(managedSchema.getTable(),
              managedSchema.getName()), managedSchema);
    }
  }
496938
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        if (kunderaQuery.isNative())
        {
            return ((CouchbaseClient) client).executeNativeQuery(getJPAQuery(), m);
        }
        else
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                    .getMetamodel(m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());
            JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();
            List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);
            AsPath asPath;
            if (selectColumns.isEmpty())
            {
                asPath = select(CouchbaseConstants.STAR).from(i(m.getSchema()));
            }
            else
            {
                asPath = select(selectColumns.toArray(new String[selectColumns.size()])).from(i(m.getSchema()));
            }
            Statement statement;

            if (KunderaQueryUtils.hasWhereClause(jpqlExp))
            {
                WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);
                Expression whereExp = whereClause.getConditionalExpression();

                if (whereExp instanceof ComparisonExpression)
                {
                    String left = ((ComparisonExpression) whereExp).getLeftExpression().toActualText();
                    String right = ((ComparisonExpression) whereExp).getRightExpression().toActualText();
                    if (right.startsWith(CouchbaseConstants.POSITIONAL_PREFIX)
                            || right.startsWith(CouchbaseConstants.PARAMETERIZED_PREFIX))
                    {
                        right = kunderaQuery.getParametersMap().get(right) + "";
                    }
                    Attribute attribute = entityType.getAttribute(left.split(CouchbaseConstants.DOT_REGEX)[1]);

                    statement = addWhereCondition(asPath, ((ComparisonExpression) whereExp).getActualIdentifier(),
                            ((AbstractAttribute) attribute).getJPAColumnName(), right, m.getTableName());
                }

            }
            else
            {
                asPath.where(x(CouchbaseConstants.KUNDERA_ENTITY).eq(x("'" + m.getTableName() + "'")));
            }

            statement = asPath;
            return ((CouchbaseClient) client).executeQuery(statement, m);
        }
    }
746702
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client) {
        if (log.isDebugEnabled()) {
            log.debug("Populating entities for Cassandra query {}.", getJPAQuery());
        }
        List<Object> result = new ArrayList<Object>();
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        externalProperties = ((CassandraClientBase) client).getExternalProperties();

        // if id attribute is embeddable, it is meant for CQL translation.
        // make it independent of embedded stuff and allow even to add non
        // composite into where clause and let cassandra complain for it.

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m != null ? m.getPersistenceUnit() : client.getPersistenceUnit());

        String query = appMetadata.getQuery(getJPAQuery());
        boolean isNative = kunderaQuery.isNative();
        if (!isNative && !MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {
            result = populateUsingLucene(m, client, result, getKunderaQuery().getResult());
        }
        // change for embeddable
        else if (!isNative && ((CassandraClientBase) client).isCql3Enabled(m)
            && MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {
            result = ((CassandraClientBase) client).executeQuery(m.getEntityClazz(), null, isNative,
                onQueryOverCQL3(m, client, metaModel, null));
        } else {
            if (isNative) {
                // XXX
                if (!kunderaQuery.getBindParameters().isEmpty()) {
                    result = ((CassandraClientBase) client).executeQuery(null, null, isNative,
                        query != null ? query : getJPAQuery(), kunderaQuery.getBindParameters());
                } else {
                    result = ((CassandraClientBase) client).executeQuery(m != null ? m.getEntityClazz() : null, null,
                        isNative, query != null ? query : getJPAQuery());
                }
            } else {
                if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {
                    // Index in Inverted Index table if applicable
                    boolean useInvertedIndex = CassandraIndexHelper.isInvertedIndexingApplicable(m,
                        MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()));
                    Map<Boolean, List<IndexClause>> ixClause = prepareIndexClause(m, useInvertedIndex);
                    if (useInvertedIndex && !getKunderaQuery().getFilterClauseQueue().isEmpty()) {
                        result = (List) ((CassandraEntityReader) getReader()).readFromIndexTable(m, client, ixClause);
                    } else {
                        boolean isRowKeyQuery = ixClause.keySet().iterator().next();
                        if (!isRowKeyQuery) {
                            result = ((CassandraClientBase) client).find(ixClause.get(isRowKeyQuery), m, false, null,
                                isSingleResult ? 1 : this.maxResult,
                                getColumnList(m, metaModel, getKunderaQuery().getResult(), null));
                        } else {
                            result =
                                ((CassandraEntityReader) getReader()).handleFindByRange(m, client, result, ixClause,
                                    isRowKeyQuery, getColumnList(m, metaModel, getKunderaQuery().getResult(), null),
                                    isSingleResult ? 1 : this.maxResult);
                        }
                    }
                }

            }
        }
        return result;
    }
770856
public void populate(Map<String, String[]> map)
    {
        for (Entry<String, String[]> entry : map.entrySet())
        {
            String property = entry.getKey();
            if (model.typeMap.containsKey(property))
            {
                String[] values = entry.getValue();
                if (values.length > 1)
                {
                    throw new UnsupportedOperationException(property + " has multivalue " + values);
                }
                if (values.length == 1)
                {
                    set(property, values[0]);
                }
            }
        }
    }
834685
private static void loadClientProperties(String propertiesPath, String clazzName,
            Map<?, Map<String, String>> clientProperties, Map<String, Map<String, String>> entityConfigurations)
    {

        InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream(propertiesPath);
        clientProperties = JsonUtil.readJson(inputStream, Map.class);

        if (clientProperties != null)
        {
            if (clientProperties.get("all") != null)
            {
                entityConfigurations.put(clazzName, clientProperties.get("all"));
            }
            else
            {

                Iterator iter = clientProperties.keySet().iterator();

                while (iter.hasNext())
                {
                    Object key = iter.next();
                    if (((String) key).indexOf(',') > 0)
                    {
                        StringTokenizer tokenizer = new StringTokenizer((String) key, ",");
                        while (tokenizer.hasMoreElements())
                        {
                            String token = tokenizer.nextToken();
                            entityConfigurations.put(token, clientProperties.get(key));
                        }
                    }
                    else
                    {
                        entityConfigurations.put((String) key, clientProperties.get(key));
                    }
                }
            }
        }

    }
865458
private <X extends Class, T extends Object> void populateMetadata(EntityMetadata metadata, Class<X> clazz,
            Map puProperties)
    {
        // process for metamodelImpl

        if (metadata.getPersistenceUnit() != null)
        {
            MetaModelBuilder<X, T> metaModelBuilder = kunderaMetadata.getApplicationMetadata().getMetaModelBuilder(
                    metadata.getPersistenceUnit());

            onBuildMetaModelSuperClass(clazz.getSuperclass(), metaModelBuilder);

            metaModelBuilder.process(clazz);

            for (Field f : clazz.getDeclaredFields())
            {
                if (f != null && !Modifier.isStatic(f.getModifiers()) && !Modifier.isTransient(f.getModifiers())
                        && !f.isAnnotationPresent(Transient.class))
                {
                    // construct metamodel.
                    metaModelBuilder.construct(clazz, f);

                    // on id attribute.
                    onIdAttribute(metaModelBuilder, metadata, clazz, f);

                    // determine if it is a column family or super column
                    // family.
                    onFamilyType(metadata, clazz, f);
                }
            }

            EntityType entityType = (EntityType) metaModelBuilder.getManagedTypes().get(metadata.getEntityClazz());

            validateAndSetId(metadata, clazz, metaModelBuilder);
            validateandSetEntityType(metadata, clazz, metaModelBuilder);
            MetadataUtils.onJPAColumnMapping(entityType, metadata);

            /* Scan for Relationship field */
            populateRelationMetaData(entityType, clazz, metadata);
        }
    }
1063029
@Override
    public void populateCredentials(Map<String, String> credentials) {
        // This is run on the submission client. We won't end up doing anything here since everything important will run on Nimbus.
        if (LOG.isDebugEnabled()) {
            LOG.debug("Auto Credential Class Loaded on submission client");
        }
        credentials.put(ELASTICSEARCH_CREDENTIALS, "placeholder");
    }
241020
public <T> T populate(String prefix, Class<T> clazz, Set<Class> resolvedConfigs) {
        checkConfigurationClass(clazz);
        Map<Method, PropertyInfo> properties = resolve(prefix, clazz.getMethods(), resolvedConfigs);
        //noinspection unchecked
        return (T) Proxy.newProxyInstance(classLoader, new Class[]{clazz},
                new PropertiesProxy(properties));
    }
233265
public <V> Reflecter<T> populate(Map<String, V> properties, String... excludes) {
		return populate(properties, Arrays.asList(excludes));
	}
405242
public EntityBuilder addProperties(Map<String, Object> properties) {
    	if(MapUtils.isEmpty(properties)) {
    		throw new IllegalArgumentException("properties cannot be null or empty.");
    	}
        for (String key : properties.keySet()) {
            addProperty(key, properties.get(key));
        }
        return this;
    }
572513
public void updateProperties(Map<Object, Object> properties) {
        this.commonProperties = properties;
        try {
            new TCPFactoryConfiguration(properties);
        } catch (ChannelFactoryException e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Unable to consume property updates");
            }
        }
    }
243037
@Override
    protected void populateSettings() throws BuildException {
        super.populateSettings();
        getSettings().setStringIfNotEmpty(Settings.KEYS.PROXY_SERVER, proxyServer);
        getSettings().setStringIfNotEmpty(Settings.KEYS.PROXY_PORT, proxyPort);
        getSettings().setStringIfNotEmpty(Settings.KEYS.PROXY_USERNAME, proxyUsername);
        getSettings().setStringIfNotEmpty(Settings.KEYS.PROXY_PASSWORD, proxyPassword);
        getSettings().setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
        getSettings().setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName);
        getSettings().setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath);
        getSettings().setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
        getSettings().setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser);
        getSettings().setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword);
        getSettings().setStringIfNotEmpty(Settings.KEYS.CVE_MODIFIED_JSON, cveUrlModified);
        getSettings().setStringIfNotEmpty(Settings.KEYS.CVE_BASE_JSON, cveUrlBase);
        if (cveValidForHours != null) {
            if (cveValidForHours >= 0) {
                getSettings().setInt(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours);
            } else {
                throw new BuildException("Invalid setting: `cpeValidForHours` must be 0 or greater");
            }
        }
    }
475738
protected void loadClientMetadata(Map<String, Object> puProperties)
    {
        clientMetadata = new ClientMetadata();
        String luceneDirectoryPath = puProperties != null ? (String) puProperties
                .get(PersistenceProperties.KUNDERA_INDEX_HOME_DIR) : null;

        String indexerClass = puProperties != null ? (String) puProperties
                .get(PersistenceProperties.KUNDERA_INDEXER_CLASS) : null;
                
        String autoGenClass = puProperties != null ? (String) puProperties
                        .get(PersistenceProperties.KUNDERA_AUTO_GENERATOR_CLASS) : null;


        if (indexerClass == null)
        {
            indexerClass = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit)
                    .getProperties().getProperty(PersistenceProperties.KUNDERA_INDEXER_CLASS);
        }
        if (autoGenClass == null)
        {
            autoGenClass = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit)
                    .getProperties().getProperty(PersistenceProperties.KUNDERA_AUTO_GENERATOR_CLASS);
        }

        if (luceneDirectoryPath == null)
        {
            luceneDirectoryPath = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit)
                    .getProperty(PersistenceProperties.KUNDERA_INDEX_HOME_DIR);
        }
        
        if (autoGenClass != null) 
        {
            clientMetadata.setAutoGenImplementor(autoGenClass);    
        }

        // in case set empty via external property, means want to avoid lucene
        // directory set up.
        if (luceneDirectoryPath != null && !StringUtils.isEmpty(luceneDirectoryPath))
        {
            // Add client metadata
            clientMetadata.setLuceneIndexDir(luceneDirectoryPath);

            // Set Index Manager

            try
            {
                Method method = Class.forName(IndexingConstants.LUCENE_INDEXER).getDeclaredMethod("getInstance",
                        String.class);

                Indexer indexer = (Indexer) method.invoke(null, luceneDirectoryPath);
                indexManager = new IndexManager(indexer, kunderaMetadata);
            }
            catch (Exception e)
            {
                logger.error(
                        "Missing lucene from classpath. Please make sure those are available to load lucene directory {}!",
                        luceneDirectoryPath);
                throw new InvalidConfigurationException(e);
            }

            // indexManager = new IndexManager(LuceneIndexer.getInstance(new
            // StandardAnalyzer(Version.LUCENE_CURRENT),
            // luceneDirectoryPath));
        }
        else if (indexerClass != null)
        {
            try
            {
                Class<?> indexerClazz = Class.forName(indexerClass);
                Indexer indexer = (Indexer) indexerClazz.newInstance();
                indexManager = new IndexManager(indexer, kunderaMetadata);
                clientMetadata.setIndexImplementor(indexerClass);
            }
            catch (Exception cnfex)
            {
                logger.error("Error while initialzing indexer:" + indexerClass, cnfex);
                throw new KunderaException(cnfex);
            }
        }
        else
        {
            indexManager = new IndexManager(null, kunderaMetadata);
        }
        // if
        // (kunderaMetadata.getClientMetadata(persistenceUnit)
        // ==
        // null)
        // {
        // kunderaMetadata.addClientMetadata(persistenceUnit,
        // clientMetadata);
        // }
    }
421465
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();

        try
        {
            String query = appMetadata.getQuery(getJPAQuery());

            boolean isNative = kunderaQuery.isNative();

            if (isNative)
            { // Native Query Support is enabled
                return ((MongoDBClient) client).executeQuery(query == null ? getJPAQuery() : query, m);
            }

            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
            {
                if (kunderaQuery.isAggregated())
                {
                    return ((MongoDBClient) client).aggregate(m,
                            createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), createAggregationLookup(m),
                            createAggregation(m), getAggregationOrderByClause(m), isSingleResult ? 1 : maxResult);
                }
                else
                {
                    BasicDBObject orderByClause = getOrderByClause(m);
                    return ((MongoDBClient) client).loadData(m,
                            createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), null, orderByClause,
                            isSingleResult ? 1 : maxResult, firstResult, isCountQuery(),
                            getKeys(m, getKunderaQuery().getResult()), getKunderaQuery().getResult());
                }
            }
            else
            {
                return populateUsingLucene(m, client, null, getKunderaQuery().getResult());
            }

        }
        catch (Exception e)
        {

            log.error("Error during executing query, Caused by:", e);
            throw new QueryHandlerException(e);
        }
    }