Return update query string for given entity intended for counter column family.

@param entityMetadata
the entity metadata
@param entity
the entity
@param cassandra_client
the cassandra_client
@param rlHolders
the rl holders
@return the list
963134
protected List<String> createUpdateQueryForCounter(EntityMetadata entityMetadata, Object entity,
        Cassandra.Client cassandra_client, List<RelationHolder> rlHolders) {
        Map<String, String> builders = new HashMap<String, String>();

        CQLTranslator translator = new CQLTranslator();

        Object rowId = PropertyAccessorHelper.getId(entity, entityMetadata);
        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(entityMetadata.getPersistenceUnit());

        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());

        Set<Attribute> attributes = entityType.getAttributes();

        for (Attribute attrib : attributes) {
            if (!entityMetadata.getIdAttribute().getName().equals(attrib.getName())
                && !metaModel.isEmbeddable(attrib.getJavaType()) && !attrib.isAssociation()) {
                String tableName = ((AbstractAttribute) attrib).getTableName() != null
                    ? ((AbstractAttribute) attrib).getTableName() : entityMetadata.getTableName();

                String queryString = builders.get(tableName);
                StringBuilder builder;
                if (queryString == null) {
                    builder = new StringBuilder();
                } else {
                    builder = new StringBuilder(queryString);
                }
                translator.buildSetClauseForCounters(builder, ((AbstractAttribute) attrib).getJPAColumnName(),
                    PropertyAccessorHelper.getObject(entity, attrib.getName()));
                builders.put(tableName, builder.toString());
            }
        }
        for (RelationHolder rl : rlHolders) {
            translator.buildSetClauseForCounters(new StringBuilder(builders.get(entityMetadata.getTableName())),
                rl.getRelationName(), rl.getRelationValue());
        }

        for (String tableName : builders.keySet()) {
            StringBuilder builder = new StringBuilder(builders.get(tableName));

            String update_Query = translator.UPDATE_QUERY;

            update_Query = StringUtils.replace(update_Query, CQLTranslator.COLUMN_FAMILY,
                translator.ensureCase(new StringBuilder(), tableName, false).toString());

            // strip last "," clause.
            builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length());

            builder.append(CQLTranslator.ADD_WHERE_CLAUSE);
            onWhereClause(entityMetadata, rowId, translator, builder, metaModel, entityMetadata.getIdAttribute());

            // strip last "AND" clause.
            builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());

            StringBuilder queryBuilder = new StringBuilder(update_Query);
            queryBuilder.append(CQLTranslator.ADD_SET_CLAUSE);
            queryBuilder.append(builder);

            if (log.isDebugEnabled()) {
                log.debug("Returning update query {}.", queryBuilder.toString());
            }

            builders.put(tableName, queryBuilder.toString());
        }
        return new ArrayList(builders.values());
    }
834704
public boolean updateEntity(Entity entity) {
        String entityName = entity.getName();
        checkEntityIsEmpty(entityName);
        QueryPart<Entity> queryPart = new Query<Entity>("entities")
                .path(entityName, true);
        return httpClientManager.updateMetaData(queryPart, patch(entity));
    }
957205
public int update(List<ENTITY> entities) {

        if (entities == null || entities.size() == 0) {
            recordLog(" param entity is null!");
            return 0;
        }

        final List<Query> queries = queryGenerator.getUpdateQuery(entities);
        String sql = queries.get(0).getSql();
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

            public void setValues(PreparedStatement stmt, int index) throws SQLException {
                int i = 1;
                List<Object> params = queries.get(index).getParams();
                for (Object o : params) {
                    stmt.setObject(i++, o);
                }
            }

            public int getBatchSize() {
                return queries.size();
            }
        });

        return entities.size();
    }
1206955
private void onQuery(EntityMetadata m, Client client)
    {
        String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());
        try
        {
            handler.readData(tableName, m, null, translator.getStartRow(), translator.getEndRow(), getColumnsToOuput(),
                    (FilterList) translator.getFilters());
        }
        catch (IOException e)
        {
            log.error(e.getMessage());
            throw new KunderaException("Error in connecting to database or some network problem. Caused by: ", e);
        }
    }
1231948
@PUT
    @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON})
    @Produces(Servlets.JSON_MEDIA_TYPE)
    public Response updateEntities(@Context HttpServletRequest request) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("==> EntityResource.updateEntities()");
        }

        String entityJson = null;
        AtlasPerfTracer perf = null;
        try {
            if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
                perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityResource.updateEntities()");
            }

            final String entities = Servlets.getRequestPayload(request);

            entityJson = AtlasClient.toString(new JSONArray(entities));

            if (LOG.isDebugEnabled()) {
                LOG.info("updating entities {} ", entityJson);
            }

            AtlasEntitiesWithExtInfo   entitiesInfo     = restAdapters.toAtlasEntities(entities);
            EntityMutationResponse     mutationResponse = entityREST.createOrUpdate(entitiesInfo);
            CreateUpdateEntitiesResult result           = restAdapters.toCreateUpdateEntitiesResult(mutationResponse);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Updated entities: {}", result.getEntityResult());
            }

            JSONObject response = getResponse(result);
            return Response.ok(response).build();
        } catch (AtlasBaseException e) {
            LOG.error("Unable to persist entity instance entityDef={}", entityJson, e);
            throw toWebApplicationException(e);
        } catch(EntityExistsException e) {
            LOG.error("Unique constraint violation for entityDef={}", entityJson, e);
            throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.CONFLICT));
        } catch (ValueConversionException ve) {
            LOG.error("Unable to persist entity instance due to a deserialization error entityDef={}", entityJson, ve);
            throw new WebApplicationException(Servlets.getErrorResponse(ve.getCause(), Response.Status.BAD_REQUEST));
        } catch (AtlasException | IllegalArgumentException e) {
            LOG.error("Unable to persist entity instance entityDef={}", entityJson, e);
            throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST));
        } catch (WebApplicationException e) {
            LOG.error("Unable to persist entity instance entityDef={}", entityJson, e);
            throw e;
        } catch (Throwable e) {
            LOG.error("Unable to persist entity instance entityDef={}", entityJson, e);
            throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
        } finally {
            AtlasPerfTracer.log(perf);

            if (LOG.isDebugEnabled()) {
                LOG.debug("<== EntityResource.updateEntities()");
            }
        }
    }
1286749
private void updateExistingColumnFamily(TableInfo tableInfo, KsDef ksDef, InvalidRequestException irex)
            throws Exception
    {
        StringBuilder builder = new StringBuilder("^Cannot add already existing (?:column family|table) .*$");

        if (irex.getWhy() != null && irex.getWhy().matches(builder.toString()))
        {
            SchemaOperationType operationType = SchemaOperationType.getInstance(operation);
            switch (operationType)
            {
            case create:
                handleCreate(tableInfo, ksDef);
                break;

            case createdrop:
                handleCreate(tableInfo, ksDef);
                break;

            case update:
                if (isCql3Enabled(tableInfo))
                {
                    for (ColumnInfo column : tableInfo.getColumnMetadatas())
                    {
                        addColumnToTable(tableInfo, column);
                    }
                    createIndexUsingCql(tableInfo);
                }
                else
                {
                    updateTable(ksDef, tableInfo);
                }
                break;

            default:
                break;
            }
        }
        else
        {
            log.error("Error occurred while creating table {}, Caused by: {}.", tableInfo.getTableName(), irex);
            throw new SchemaGenerationException("Error occurred while creating table " + tableInfo.getTableName(),
                    irex, "Cassandra", databaseName);
        }
    }
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;
    }
135246
@POST
    @Path("/bulk")
    @Consumes(Servlets.JSON_MEDIA_TYPE)
    @Produces(Servlets.JSON_MEDIA_TYPE)
    public EntityMutationResponse createOrUpdate(AtlasEntitiesWithExtInfo entities) throws AtlasBaseException {
        AtlasPerfTracer perf = null;

        try {
            if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
                perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.createOrUpdate(entityCount=" +
                                                               (CollectionUtils.isEmpty(entities.getEntities()) ? 0 : entities.getEntities().size()) + ")");
            }

            EntityStream entityStream = new AtlasEntityStream(entities);

            return entitiesStore.createOrUpdate(entityStream, false);
        } finally {
            AtlasPerfTracer.log(perf);
        }
    }
651575
private List populateData(EntityMetadata m, Map<Bytes, List<Column>> qResults, List<Object> entities,
            boolean isRelational, List<String> relationNames, CassandraDataHandler dataHandler)
    {
        if (m.getType().isSuperColumnFamilyMetadata())
        {
            Set<Bytes> primaryKeys = qResults.keySet();

            if (primaryKeys != null && !primaryKeys.isEmpty())
            {
                Object[] rowIds = new Object[primaryKeys.size()];
                int i = 0;
                for (Bytes b : primaryKeys)
                {
                    rowIds[i] = PropertyAccessorHelper.getObject(b, (Field) m.getIdAttribute().getJavaMember());
                    i++;
                }
                entities.addAll(findAll(m.getEntityClazz(), null, rowIds));
            }

        }
        else
        {
            Iterator<Bytes> rowIter = qResults.keySet().iterator();
            while (rowIter.hasNext())
            {
                Bytes rowKey = rowIter.next();
                List<Column> columns = qResults.get(rowKey);
                try
                {
                    Object id = PropertyAccessorHelper
                            .getObject(m.getIdAttribute().getJavaType(), rowKey.toByteArray());
                    Object e = null;
                    e = dataHandler.populateEntity(new ThriftRow(id, m.getTableName(), columns,
                            new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0),
                            new ArrayList<CounterSuperColumn>(0)), m, KunderaCoreUtils.getEntity(e), relationNames,
                            isRelational);
                    if (e != null)
                    {
                        entities.add(e);
                    }
                }
                catch (IllegalStateException e)
                {
                    log.error("Error while returning entities for {}, Caused by: .", m.getEntityClazz(), e);
                    throw new KunderaException(e);
                }
                catch (Exception e)
                {
                    log.error("Error while returning entities for {}, Caused by: .", m.getEntityClazz(), e);
                    throw new KunderaException(e);
                }
            }
        }
        return entities;
    }
1186616
protected <C extends CrudResponse, T extends UpdateEntity> List<C> handleMultipleUpdates(List<T> entityList) {

        if (entityList == null || entityList.isEmpty()) {
            return Collections.emptyList();
        }

        List<EntityUpdateWorker<C>> taskList = new ArrayList<EntityUpdateWorker<C>>();
        for (T entity : entityList) {
            taskList.add(new EntityUpdateWorker<C>(this, entity));
        }

        return concurrencyService.spinThreadsAndWaitForResult(taskList);

    }
869799
protected List populateEntitiesFromKeySlices(EntityMetadata m, boolean isWrapReq, List<String> relations,
        List<KeySlice> keys, CassandraDataHandler dataHandler) throws Exception {
        List results;
        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());

        Set<String> superColumnAttribs = metaModel.getEmbeddables(m.getEntityClazz()).keySet();
        results = new ArrayList(keys.size());

        ThriftDataResultHelper dataGenerator = new ThriftDataResultHelper();
        for (KeySlice key : keys) {
            List<ColumnOrSuperColumn> columns = key.getColumns();

            byte[] rowKey = key.getKey();

            Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), rowKey);

            Object e = null;
            Map<ByteBuffer, List<ColumnOrSuperColumn>> data = new HashMap<ByteBuffer, List<ColumnOrSuperColumn>>(1);
            data.put(ByteBuffer.wrap(rowKey), columns);
            ThriftRow tr = new ThriftRow();
            tr.setId(id);
            tr.setColumnFamilyName(m.getTableName());
            tr = dataGenerator.translateToThriftRow(data, m.isCounterColumnType(), m.getType(), tr);

            e = dataHandler.populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isWrapReq);

            if (e != null) {
                results.add(e);
            }
        }
        return results;
    }
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;
    }
153391
@Override
    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
            Object columnValue, Class entityClazz)
    {
        List<Object> rowKeys = new ArrayList<Object>();

        if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))
        {
            rowKeys = findIdsByColumnUsingCql(schemaName, tableName, pKeyName, columnName, columnValue, entityClazz);
        }
        else
        {
            Selector selector = clientFactory.getSelector(pool);
            SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, 10000);
            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);

            IndexClause ix = Selector.newIndexClause(Bytes.EMPTY, 10000, Selector.newIndexExpression(columnName
                    + Constants.JOIN_COLUMN_NAME_SEPARATOR + columnValue, IndexOperator.EQ,
                    Bytes.fromByteArray(PropertyAccessorHelper.getBytes(columnValue))));

            Map<Bytes, List<Column>> qResults = selector.getIndexedColumns(tableName, ix, slicePredicate,
                    getConsistencyLevel());

            // iterate through complete map and
            Iterator<Bytes> rowIter = qResults.keySet().iterator();
            while (rowIter.hasNext())
            {
                Bytes rowKey = rowIter.next();

                PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor((Field) metadata
                        .getIdAttribute().getJavaMember());
                Object value = accessor.fromBytes(metadata.getIdAttribute().getJavaType(), rowKey.toByteArray());

                rowKeys.add(value);
            }
        }
        if (rowKeys != null && !rowKeys.isEmpty())
        {
            return rowKeys.toArray(new Object[0]);
        }

        if (log.isInfoEnabled())
        {
            log.info("No row keys found, returning null.");
        }
        return null;
    }
56206
public List<EnhanceEntity> readFromIndexTable(EntityMetadata m, Client client,
            Map<Boolean, List<IndexClause>> indexClauseMap)
    {
        List<SearchResult> searchResults = new ArrayList<SearchResult>();
        List<Object> primaryKeys = new ArrayList<Object>();

        String columnFamilyName = m.getTableName() + Constants.INDEX_TABLE_SUFFIX;
        searchResults = ((CassandraClientBase) client).searchInInvertedIndex(columnFamilyName, m, indexClauseMap);

        Map<String, String> embeddedColumns = new HashMap<String, String>();
        for (SearchResult searchResult : searchResults)
        {
            if (searchResult.getEmbeddedColumnValues() != null)
            {
                for (String embeddedColVal : searchResult.getEmbeddedColumnValues())
                {
                    if (embeddedColVal != null)
                    {
                        StringBuilder strBuilder = new StringBuilder(embeddedColVal);
                        strBuilder.append("|");
                        strBuilder.append(searchResult.getPrimaryKey().toString());
                        embeddedColumns.put(strBuilder.toString(), searchResult.getPrimaryKey().toString());
                    }
                }
            }
        }
        List<EnhanceEntity> enhanceEntityList = new ArrayList<EnhanceEntity>();
        if (embeddedColumns != null && !embeddedColumns.isEmpty())
        {
            enhanceEntityList = client.find(m.getEntityClazz(), embeddedColumns);
        }
        else
        {
            for (SearchResult searchResult : searchResults)
            {
                primaryKeys.add(searchResult.getPrimaryKey());
            }
            enhanceEntityList = (List<EnhanceEntity>) ((CassandraClientBase) client).find(m.getEntityClazz(),
                    m.getRelationNames(), true, m, primaryKeys.toArray(new String[] {}));
        }

        return enhanceEntityList;
    }
874029
public Long countByQueryFieldQueryRepliesInAndData(QueryField queryField, Collection<QueryReply> queryReplies, Double data) {
    if (queryReplies == null || queryReplies.isEmpty()) {
      return 0l;
    }
    
    EntityManager entityManager = getEntityManager();

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class);
    Root<QueryQuestionNumericAnswer> root = criteria.from(QueryQuestionNumericAnswer.class);
    Join<QueryQuestionNumericAnswer, QueryReply> replyJoin = root.join(QueryQuestionNumericAnswer_.queryReply);
    
    criteria.select(criteriaBuilder.count(root));
    criteria.where(
      criteriaBuilder.and(
        criteriaBuilder.equal(root.get(QueryQuestionNumericAnswer_.queryField), queryField),
        root.get(QueryQuestionNumericAnswer_.queryReply).in(queryReplies),
        criteriaBuilder.equal(root.get(QueryQuestionNumericAnswer_.data), data),
        criteriaBuilder.equal(replyJoin.get(QueryReply_.archived), Boolean.FALSE)
      )
    );
    
    return entityManager.createQuery(criteria).getSingleResult();
  }
755739
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        return onQuery(m, client);
    }
1201862
public static List<Object> getRowKeys(List<KeySlice> keySlices, EntityMetadata metadata)
    {
        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor((Field) metadata.getIdAttribute()
                .getJavaMember());
        List<Object> rowKeys = new ArrayList<Object>();
        for (KeySlice keySlice : keySlices)
        {
            byte[] key = keySlice.getKey();
            Object rowKey = accessor.fromBytes(metadata.getIdAttribute().getJavaType(), key);
            rowKeys.add(rowKey);
        }
        return rowKeys;
    }