Build cassandra entity metadata

@param clazz           Entity class
@param cassandraClient Cassandra Client from which will be retrieved table information
@param <V>             Entity class type

@return Entity metadata

@throws MetadataException
544416
static <V> EntityMetadata buildEntityMetadata(@NotNull Class<V> clazz, @NotNull CassandraClient cassandraClient) throws MetadataException {
        Table tableAnnotation = clazz.getAnnotation(Table.class);

        if (tableAnnotation == null) {
            throw new MetadataException(String.format("Table annotation is missing for %s", clazz.getName()));
        }

        String tableKeyspace = StringUtils.isEmpty(tableAnnotation.keyspace()) ? cassandraClient.getDefaultKeyspace() : tableAnnotation.keyspace();

        String tableName = tableAnnotation.name();

        TableMetadata tableMetadata = cassandraClient.getTableMetadata(tableKeyspace, tableName);

        EntityMetadata entityMetadata = new EntityMetadata(
                tableName,
                tableKeyspace,
                tableAnnotation.compactStorage(),
                tableAnnotation.fetchSize(),
                tableAnnotation.readConsistencyLevel(),
                tableAnnotation.writeConsistencyLevel(),
                tableMetadata
        );

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

            for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {

                ColumnMetadata columnMetadata = buildColumnMetadata(propertyDescriptor, clazz, cassandraClient, tableMetadata);

                if (columnMetadata != null) {
                    entityMetadata.addColumnMetadata(columnMetadata);
                }

                LOGGER.debug("Property descriptor: {} {}", propertyDescriptor.getName(), propertyDescriptor.getDisplayName());
            }
        } catch (IntrospectionException e) {
            LOGGER.warn("Can't build column metadata", e);
        }

        EntityMetadata.validate(entityMetadata);

        return entityMetadata;
    }
509330
protected final void populateIdAccessorMethods(EntityMetadata metadata, Class<?> clazz, Field f)
    {
        try
        {
            BeanInfo info = Introspector.getBeanInfo(clazz);

            for (PropertyDescriptor descriptor : info.getPropertyDescriptors())
            {
                if (descriptor.getName().equals(f.getName()))
                {
                    metadata.setReadIdentifierMethod(descriptor.getReadMethod());
                    metadata.setWriteIdentifierMethod(descriptor.getWriteMethod());
                    return;
                }
            }
        }
        catch (IntrospectionException e)
        {
            throw new RuntimeException(e);
        }
    }
804110
@Override
    protected List<Object> populateEntities(EntityMetadata entityMetadata, Client client)
    {
        /**
         * Multiple clause: like two columns with and cluase For multiple
         * andTranslate jpa clause into temp store based on clause if it is for
         * multiple data set. and fetch from there and then finally delete that
         * temp storage. Query translator will translate queries into key value
         */

        /**
         * Limitations: 1) Multiple AND/OR clause not possible 2) Only equal
         * clause possible with AND/OR clause.
         * 
         */

        Set<Object> results = new LinkedHashSet<Object>();

        ClientMetadata clientMetadata = ((ClientBase) client).getClientMetadata();

        if (!MetadataUtils.useSecondryIndex(clientMetadata)
                && !(clientMetadata.getIndexImplementor() != null && clientMetadata.getIndexImplementor().equals(
                        RedisIndexer.class.getName())))
        {
            results.addAll(populateUsingLucene(entityMetadata, client, null,
                    getColumns(getKunderaQuery().getResult(), entityMetadata)));
        }
        else
        {
            RedisQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), entityMetadata);
            results.addAll((List<Object>) ((RedisClient) client).onExecuteQuery(interpreter,
                    entityMetadata.getEntityClazz()));
        }

        List<Object> output = new ArrayList<Object>();
        output.addAll(results);

        return output;
    }
567374
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        List results = new ArrayList();

        if (!MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
        {
            results.addAll(populateUsingLucene(m, client, null, getKunderaQuery().getResult()));
        }

        else
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());

            KuduClient kuduClient = ((KuduDBClient) client).getKuduClient();
            KuduTable table;
            try
            {
                table = kuduClient.openTable(m.getTableName());
            }
            catch (Exception e)
            {
                logger.error("Cannot open table : " + m.getTableName(), e);
                throw new KunderaException("Cannot open table : " + m.getTableName(), e);
            }

            KuduScannerBuilder scannerBuilder = kuduClient.newScannerBuilder(table);
            JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();
            List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);
            if (!selectColumns.isEmpty())
            {
                // select by specific columns, set projection
                scannerBuilder.setProjectedColumnNames(selectColumns);
            }
            if (KunderaQueryUtils.hasWhereClause(jpqlExp))
            {
                // add predicate filters
                WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);
                Expression whereExp = whereClause.getConditionalExpression();
                parseAndBuildFilters(entityType, scannerBuilder, whereExp);
            }

            KuduScanner scanner = scannerBuilder.build();

            Object entity;
            while (scanner.hasMoreRows())
            {
                RowResultIterator rowResultIter;
                try
                {
                    rowResultIter = scanner.nextRows();
                }
                catch (Exception e)
                {
                    logger.error("Cannot get results from table : " + m.getTableName(), e);
                    throw new KunderaException("Cannot get results from table : " + m.getTableName(), e);
                }

                while (rowResultIter.hasNext())
                {
                    RowResult result = rowResultIter.next();
                    entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
                    // populate RowResult to entity object and return
                    ((KuduDBClient) client).populateEntity(entity, result, entityType, metaModel);
                    results.add(entity);
                    logger.debug(result.rowToString());
                }
            }
        }
        return results;
    }
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);
        }
    }
827240
protected List<ColumnDef> getColumnMetadata(Cassandra.Client client)
    throws TException, CharacterCodingException, InvalidRequestException, ConfigurationException
    {   
        return getColumnMeta(client, true, true);
    }
610168
private String getColumnName(EntityMetadata metadata, String property) {
        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());
        String jpaColumnName = null;

        if (property.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())) {
            jpaColumnName = CassandraUtilities.getIdColumnName(kunderaMetadata, metadata,
                ((CassandraClientBase) persistenceDelegeator.getClient(metadata)).getExternalProperties(),
                ((CassandraClientBase) persistenceDelegeator.getClient(metadata)).isCql3Enabled(metadata));
        } else {
            jpaColumnName = ((AbstractAttribute) metaModel.getEntityAttribute(metadata.getEntityClazz(), property))
                .getJPAColumnName();
        }
        return jpaColumnName;
    }
1044888
private EntityType buildEntityType(SessionFactory sessionFactory, String entityName) {
    EntityType entityType = (EntityType) entityTypes.get(entityName);
    if (null == entityType) {
      ClassMetadata cm = sessionFactory.getClassMetadata(entityName);
      if (null == cm) {
        logger.error("Cannot find ClassMetadata for {}", entityName);
        return null;
      }
      entityType = new EntityType(cm.getEntityName(), cm.getMappedClass(), cm.getIdentifierPropertyName(),
          new IdentifierType(cm.getIdentifierType().getReturnedClass()));
      entityTypes.put(cm.getEntityName(), entityType);

      Map<String, Type> propertyTypes = entityType.getPropertyTypes();
      String[] ps = cm.getPropertyNames();
      for (int i = 0; i < ps.length; i++) {
        org.hibernate.type.Type type = cm.getPropertyType(ps[i]);
        if (type.isEntityType()) {
          propertyTypes.put(ps[i], buildEntityType(sessionFactory, type.getName()));
        } else if (type.isComponentType()) {
          propertyTypes.put(ps[i], buildComponentType(sessionFactory, entityName, ps[i]));
        } else if (type.isCollectionType()) {
          propertyTypes.put(ps[i],
              buildCollectionType(sessionFactory, defaultCollectionClass(type), entityName + "." + ps[i]));
        }
      }
    }
    return entityType;
  }
299837
private <T extends TypeMetadata> T getMetadata(Class<?> type, Class<T> metadataType) {
        TypeMetadata typeMetadata = metadataByType.get(type);
        if (typeMetadata == null) {
            throw new XOException("Cannot resolve metadata for type " + type.getName() + ".");
        }
        if (!metadataType.isAssignableFrom(typeMetadata.getClass())) {
            throw new XOException(
                    "Expected metadata of type '" + metadataType.getName() + "' but got '" + typeMetadata.getClass() + "' for type '" + type + "'");
        }
        return metadataType.cast(typeMetadata);
    }
95776
public EntityType getEntityType(Class<?> clazz) {
    EntityType type = context.getEntityType(clazz);
    if (null == type) {
      type = new EntityType(clazz);
    }
    return type;
  }
457806
public ClassMetadata add(Class<?> clazz) {
		ClassMetadata metadata = classMetadataFactory.createMetadata(clazz);
		log.debug("Adding persistent class " + metadata.getKind());
		metadata.validate();
		if (metadataByKind.get(metadata.getKind()) != null) {
			throw new DuplicateException("Two entities found with kind='" + metadata.getKind() + "': " + metadata.getPersistentClass().getName() + " and " + metadataByKind.get(metadata.getKind()).getPersistentClass().getName());
		}
		metadataByClass.put(metadata.getPersistentClass(), metadata);
		metadataByKind.put(metadata.getKind(), metadata);
		return metadata;
	}
794471
static <T> EntityInfo<T> get(Class<T> clazz) {
        return entityInfos.get(clazz);
    }
1313635
private List<Object> populate(Class<?> clazz, EntityMetadata metadata, Object rowId, List<String> relationNames,
        MetamodelImpl metaModel) {
        List<Object> result;
        if (isCql3Enabled(metadata)) {
            result = cqlClient.find(metaModel, metadata, rowId, relationNames);
        } else {
            result = (List<Object>) find(clazz, relationNames, relationNames != null, metadata, rowId);
        }
        return result;
    }
1206106
public static CassandraType getCassandraDataTypeClass(Class clazz)
    {
        if(clazz.isEnum()){
            return CassandraType.STRING;
        }
        return typeToClazz.get(clazz);
    }
461592
public <T extends BaseNlpEntity> List<T> getEntities(Class<T> clazz) {
    List<BaseNlpEntity> resultList = new ArrayList<>();
    for (BaseNlpEntity item : getEntities()) {
      if (item.getClass().equals(clazz)) {
        resultList.add(item);
      }
    }
    return (List<T>) resultList;
  }
582054
public <E> List<E> find(Class<E> entityClass, Map<String, String> superColumnMap,
        CassandraDataHandler dataHandler) {
        List<E> entities = null;
        String entityId = null;
        try {
            EntityMetadata entityMetadata =
                KunderaMetadataManager.getEntityMetadata(kunderaMetadata, getPersistenceUnit(), entityClass);
            entities = new ArrayList<E>();
            for (String superColumnName : superColumnMap.keySet()) {
                entityId = superColumnMap.get(superColumnName);
                List<SuperColumn> superColumnList =
                    loadSuperColumns(entityMetadata.getSchema(), entityMetadata.getTableName(), entityId,
                        new String[] { superColumnName.substring(0, superColumnName.indexOf("|")) });
                E e = (E) dataHandler.fromThriftRow(entityMetadata.getEntityClazz(), entityMetadata,
                    new DataRow<SuperColumn>(entityId, entityMetadata.getTableName(), superColumnList));
                if (e != null) {
                    entities.add(e);
                }
            }
        } catch (Exception e) {
            log.error("Error while retrieving records from database for entity {} and key {}, Caused by: . ",
                entityClass, entityId, e);
            throw new KunderaException(e);
        }
        return entities;
    }
967504
public Object populateEntity(ThriftRow tr, EntityMetadata m, Object entity, List<String> relationNames,
            boolean isWrapReq)
    {
        Map<String, Object> relations = new HashMap<String, Object>();
        try
        {
            boolean isCql3Enabled = clientBase.isCql3Enabled(m);
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());

            for (Column column : tr.getColumns())
            {
                if (column != null)
                {
                    String thriftColumnName = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());
                    if ((CassandraConstants.CQL_KEY.equalsIgnoreCase(thriftColumnName) || ((AbstractAttribute) m
                            .getIdAttribute()).getJPAColumnName().equals(thriftColumnName)) && tr.getId() == null)
                    {
                        entity = KunderaCoreUtils.initialize(m, entity, null);
                        setId(m, entity, column.getValue(), isCql3Enabled);
                    }
                    else
                    {
                        entity = onColumn(column, m, entity, entityType, relationNames, isWrapReq, relations,
                                isCql3Enabled);

                        String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
                        String discriminatorValue = ((AbstractManagedType) entityType).getDiscriminatorValue();

                        if (thriftColumnName != null
                                && thriftColumnName.equals(discriminatorColumn)
                                && column.getValue() != null
                                && !PropertyAccessorFactory.STRING.fromBytes(String.class, column.getValue()).equals(
                                        discriminatorValue))
                        {
                            entity = null;
                            break;
                        }
                    }
                }
            }

            // Add all super columns to entity
            Collection embeddedCollection = null;
            Field embeddedCollectionField = null;

            boolean mappingProcessed = false;
            Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
            Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();

            for (SuperColumn superColumn : tr.getSuperColumns())
            {
                if (superColumn != null)
                {

                    entity = KunderaCoreUtils.initialize(m, entity, tr.getId());
                    String scName = PropertyAccessorFactory.STRING.fromBytes(String.class, superColumn.getName());
                    String scNamePrefix = null;

                    // Map to hold property-name=>foreign-entity relations
                    Map<String, Set<String>> foreignKeysMap = new HashMap<String, Set<String>>();

                    // Get a name->field map for super-columns
                    if (!mappingProcessed)
                    {
                        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap,
                                superColumnNameToFieldMap, kunderaMetadata);
                        mappingProcessed = true;
                    }

                    if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)
                    {
                        scNamePrefix = MetadataUtils.getEmbeddedCollectionPrefix(scName);
                        embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);

                        if (embeddedCollection == null)
                        {
                            embeddedCollection = MetadataUtils.getEmbeddedCollectionInstance(embeddedCollectionField);
                        }

                        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance(embeddedCollectionField);

                        scrollOverSuperColumn(m, relationNames, isWrapReq, relations, entityType, superColumn,
                                embeddedObject, columnNameToFieldMap);

                        Collection collection = PropertyAccessorHelper.getCollectionInstance(embeddedCollectionField);
                        collection.add(embeddedObject);

                        PropertyAccessorHelper.set(entity, embeddedCollectionField, collection);

                        embeddedCollection.add(embeddedObject);

                        // Add this embedded object to cache
                        ElementCollectionCacheManager.getInstance().addElementCollectionCacheMapping(tr.getId(),
                                embeddedObject, scName);
                    }
                    else
                    {
                        if (superColumnNameToFieldMap.containsKey(scName))
                        {
                            Field field = superColumnNameToFieldMap.get(scName);

                            Object embeddedObj = PropertyAccessorHelper.getObject(entity, field);
                            if (embeddedObj == null)
                            {
                                embeddedObj = field.getType().newInstance();
                            }
                            // column
                            scrollOverSuperColumn(m, relationNames, isWrapReq, relations, entityType, superColumn,
                                    embeddedObj, columnNameToFieldMap);
                            PropertyAccessorHelper.set(entity, field, embeddedObj);
                        }
                        else
                        {
                            scrollOverSuperColumn(m, relationNames, isWrapReq, relations, entityType, superColumn,
                                    entity, isCql3Enabled);
                        }

                    }
                }
            }

            mappingProcessed = false;

            for (CounterColumn counterColumn : tr.getCounterColumns())
            {
                if (counterColumn != null)
                {
                    entity = KunderaCoreUtils.initialize(m, entity, tr.getId());
                    onCounterColumn(counterColumn, m, entity, entityType, relationNames, isWrapReq, relations,
                            isCql3Enabled);
                }
            }

            for (CounterSuperColumn counterSuperColumn : tr.getCounterSuperColumns())
            {
                if (counterSuperColumn != null)
                {
                    entity = KunderaCoreUtils.initialize(m, entity, tr.getId());
                    String scName = PropertyAccessorFactory.STRING
                            .fromBytes(String.class, counterSuperColumn.getName());
                    String scNamePrefix = null;

                    // Map to hold property-name=>foreign-entity relations
                    Map<String, Set<String>> foreignKeysMap = new HashMap<String, Set<String>>();

                    // Get a name->field map for super-columns
                    if (!mappingProcessed)
                    {
                        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap,
                                superColumnNameToFieldMap, kunderaMetadata);
                        mappingProcessed = true;
                    }

                    if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)
                    {
                        scNamePrefix = MetadataUtils.getEmbeddedCollectionPrefix(scName);
                        embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);

                        if (embeddedCollection == null)
                        {
                            embeddedCollection = MetadataUtils.getEmbeddedCollectionInstance(embeddedCollectionField);
                        }

                        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance(embeddedCollectionField);

                        scrollOverCounterSuperColumn(m, relationNames, isWrapReq, relations, entityType,
                                counterSuperColumn, embeddedObject, columnNameToFieldMap);
                        embeddedCollection.add(embeddedObject);

                        // Add this embedded object to cache
                        ElementCollectionCacheManager.getInstance().addElementCollectionCacheMapping(tr.getId(),
                                embeddedObject, scName);
                    }
                    else
                    {
                        if (superColumnNameToFieldMap.containsKey(scName))
                        {
                            Field field = superColumnNameToFieldMap.get(scName);
                            Object embeddedObj = field.getType().newInstance();
                            // column
                            scrollOverCounterSuperColumn(m, relationNames, isWrapReq, relations, entityType,
                                    counterSuperColumn, embeddedObj, columnNameToFieldMap);
                            PropertyAccessorHelper.set(entity, field, embeddedObj);
                        }
                        else
                        {
                            scrollOverCounterSuperColumn(m, relationNames, isWrapReq, relations, entityType,
                                    counterSuperColumn, entity, isCql3Enabled);
                        }
                    }
                }
            }

            if (embeddedCollection != null && !embeddedCollection.isEmpty())
            {
                PropertyAccessorHelper.set(entity, embeddedCollectionField, embeddedCollection);
            }

        }
        catch (Exception e)
        {
            log.error("Eror while retrieving data, Caused by: .", e);
            throw new PersistenceException(e);
        }

        if (entity != null && tr.getId() != null)
        {
            PropertyAccessorHelper.setId(entity, m, tr.getId());
        }
        return isWrapReq && relations != null && !relations.isEmpty() ? new EnhanceEntity(entity,
                PropertyAccessorHelper.getId(entity, m), relations) : entity;
    }